xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 74984dee51307779a3eab10a8cd6102be37e1081)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <deque>
108 #include <iterator>
109 #include <limits>
110 #include <optional>
111 #include <tuple>
112 
113 using namespace llvm;
114 using namespace PatternMatch;
115 using namespace SwitchCG;
116 
117 #define DEBUG_TYPE "isel"
118 
119 /// LimitFloatPrecision - Generate low-precision inline sequences for
120 /// some float libcalls (6, 8 or 12 bits).
121 static unsigned LimitFloatPrecision;
122 
123 static cl::opt<bool>
124     InsertAssertAlign("insert-assert-align", cl::init(true),
125                       cl::desc("Insert the experimental `assertalign` node."),
126                       cl::ReallyHidden);
127 
128 static cl::opt<unsigned, true>
129     LimitFPPrecision("limit-float-precision",
130                      cl::desc("Generate low-precision inline sequences "
131                               "for some float libcalls"),
132                      cl::location(LimitFloatPrecision), cl::Hidden,
133                      cl::init(0));
134 
135 static cl::opt<unsigned> SwitchPeelThreshold(
136     "switch-peel-threshold", cl::Hidden, cl::init(66),
137     cl::desc("Set the case probability threshold for peeling the case from a "
138              "switch statement. A value greater than 100 will void this "
139              "optimization"));
140 
141 // Limit the width of DAG chains. This is important in general to prevent
142 // DAG-based analysis from blowing up. For example, alias analysis and
143 // load clustering may not complete in reasonable time. It is difficult to
144 // recognize and avoid this situation within each individual analysis, and
145 // future analyses are likely to have the same behavior. Limiting DAG width is
146 // the safe approach and will be especially important with global DAGs.
147 //
148 // MaxParallelChains default is arbitrarily high to avoid affecting
149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150 // sequence over this should have been converted to llvm.memcpy by the
151 // frontend. It is easy to induce this behavior with .ll code such as:
152 // %buffer = alloca [4096 x i8]
153 // %data = load [4096 x i8]* %argPtr
154 // store [4096 x i8] %data, [4096 x i8]* %buffer
155 static const unsigned MaxParallelChains = 64;
156 
157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
158                                       const SDValue *Parts, unsigned NumParts,
159                                       MVT PartVT, EVT ValueVT, const Value *V,
160                                       SDValue InChain,
161                                       std::optional<CallingConv::ID> CC);
162 
163 /// getCopyFromParts - Create a value that contains the specified legal parts
164 /// combined into the value they represent.  If the parts combine to a type
165 /// larger than ValueVT then AssertOp can be used to specify whether the extra
166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167 /// (ISD::AssertSext).
168 static SDValue
169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171                  SDValue InChain,
172                  std::optional<CallingConv::ID> CC = std::nullopt,
173                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174   // Let the target assemble the parts if it wants to
175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
176   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177                                                    PartVT, ValueVT, CC))
178     return Val;
179 
180   if (ValueVT.isVector())
181     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182                                   InChain, CC);
183 
184   assert(NumParts > 0 && "No parts to assemble!");
185   SDValue Val = Parts[0];
186 
187   if (NumParts > 1) {
188     // Assemble the value from multiple parts.
189     if (ValueVT.isInteger()) {
190       unsigned PartBits = PartVT.getSizeInBits();
191       unsigned ValueBits = ValueVT.getSizeInBits();
192 
193       // Assemble the power of 2 part.
194       unsigned RoundParts = llvm::bit_floor(NumParts);
195       unsigned RoundBits = PartBits * RoundParts;
196       EVT RoundVT = RoundBits == ValueBits ?
197         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198       SDValue Lo, Hi;
199 
200       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201 
202       if (RoundParts > 2) {
203         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204                               InChain);
205         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206                               PartVT, HalfVT, V, InChain);
207       } else {
208         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210       }
211 
212       if (DAG.getDataLayout().isBigEndian())
213         std::swap(Lo, Hi);
214 
215       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216 
217       if (RoundParts < NumParts) {
218         // Assemble the trailing non-power-of-2 part.
219         unsigned OddParts = NumParts - RoundParts;
220         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222                               OddVT, V, InChain, CC);
223 
224         // Combine the round and odd parts.
225         Lo = Val;
226         if (DAG.getDataLayout().isBigEndian())
227           std::swap(Lo, Hi);
228         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
231                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
232                                          TLI.getShiftAmountTy(
233                                              TotalVT, DAG.getDataLayout())));
234         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236       }
237     } else if (PartVT.isFloatingPoint()) {
238       // FP split into multiple FP parts (for ppcf128)
239       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240              "Unexpected split");
241       SDValue Lo, Hi;
242       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245         std::swap(Lo, Hi);
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247     } else {
248       // FP split into integer parts (soft fp)
249       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250              !PartVT.isVector() && "Unexpected split");
251       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253                              InChain, CC);
254     }
255   }
256 
257   // There is now one part, held in Val.  Correct it to match ValueVT.
258   // PartEVT is the type of the register class that holds the value.
259   // ValueVT is the type of the inline asm operation.
260   EVT PartEVT = Val.getValueType();
261 
262   if (PartEVT == ValueVT)
263     return Val;
264 
265   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266       ValueVT.bitsLT(PartEVT)) {
267     // For an FP value in an integer part, we need to truncate to the right
268     // width first.
269     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
270     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271   }
272 
273   // Handle types that have the same size.
274   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276 
277   // Handle types with different sizes.
278   if (PartEVT.isInteger() && ValueVT.isInteger()) {
279     if (ValueVT.bitsLT(PartEVT)) {
280       // For a truncate, see if we have any information to
281       // indicate whether the truncated bits will always be
282       // zero or sign-extension.
283       if (AssertOp)
284         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285                           DAG.getValueType(ValueVT));
286       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287     }
288     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289   }
290 
291   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292     // FP_ROUND's are always exact here.
293     if (ValueVT.bitsLT(Val.getValueType())) {
294 
295       SDValue NoChange =
296           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297 
298       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299               llvm::Attribute::StrictFP)) {
300         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302                            NoChange);
303       }
304 
305       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306     }
307 
308     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309   }
310 
311   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312   // then truncating.
313   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314       ValueVT.bitsLT(PartEVT)) {
315     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317   }
318 
319   report_fatal_error("Unknown mismatch in getCopyFromParts!");
320 }
321 
322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
323                                               const Twine &ErrMsg) {
324   const Instruction *I = dyn_cast_or_null<Instruction>(V);
325   if (!V)
326     return Ctx.emitError(ErrMsg);
327 
328   const char *AsmError = ", possible invalid constraint for vector type";
329   if (const CallInst *CI = dyn_cast<CallInst>(I))
330     if (CI->isInlineAsm())
331       return Ctx.emitError(I, ErrMsg + AsmError);
332 
333   return Ctx.emitError(I, ErrMsg);
334 }
335 
336 /// getCopyFromPartsVector - Create a value that contains the specified legal
337 /// parts combined into the value they represent.  If the parts combine to a
338 /// type larger than ValueVT then AssertOp can be used to specify whether the
339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
340 /// ValueVT (ISD::AssertSext).
341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
342                                       const SDValue *Parts, unsigned NumParts,
343                                       MVT PartVT, EVT ValueVT, const Value *V,
344                                       SDValue InChain,
345                                       std::optional<CallingConv::ID> CallConv) {
346   assert(ValueVT.isVector() && "Not a vector value");
347   assert(NumParts > 0 && "No parts to assemble!");
348   const bool IsABIRegCopy = CallConv.has_value();
349 
350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
351   SDValue Val = Parts[0];
352 
353   // Handle a multi-element vector.
354   if (NumParts > 1) {
355     EVT IntermediateVT;
356     MVT RegisterVT;
357     unsigned NumIntermediates;
358     unsigned NumRegs;
359 
360     if (IsABIRegCopy) {
361       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
362           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
363           NumIntermediates, RegisterVT);
364     } else {
365       NumRegs =
366           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
367                                      NumIntermediates, RegisterVT);
368     }
369 
370     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
371     NumParts = NumRegs; // Silence a compiler warning.
372     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
373     assert(RegisterVT.getSizeInBits() ==
374            Parts[0].getSimpleValueType().getSizeInBits() &&
375            "Part type sizes don't match!");
376 
377     // Assemble the parts into intermediate operands.
378     SmallVector<SDValue, 8> Ops(NumIntermediates);
379     if (NumIntermediates == NumParts) {
380       // If the register was not expanded, truncate or copy the value,
381       // as appropriate.
382       for (unsigned i = 0; i != NumParts; ++i)
383         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
384                                   V, InChain, CallConv);
385     } else if (NumParts > 0) {
386       // If the intermediate type was expanded, build the intermediate
387       // operands from the parts.
388       assert(NumParts % NumIntermediates == 0 &&
389              "Must expand into a divisible number of parts!");
390       unsigned Factor = NumParts / NumIntermediates;
391       for (unsigned i = 0; i != NumIntermediates; ++i)
392         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
393                                   IntermediateVT, V, InChain, CallConv);
394     }
395 
396     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
397     // intermediate operands.
398     EVT BuiltVectorTy =
399         IntermediateVT.isVector()
400             ? EVT::getVectorVT(
401                   *DAG.getContext(), IntermediateVT.getScalarType(),
402                   IntermediateVT.getVectorElementCount() * NumParts)
403             : EVT::getVectorVT(*DAG.getContext(),
404                                IntermediateVT.getScalarType(),
405                                NumIntermediates);
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // Vector/Vector bitcast.
419     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
420       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421 
422     // If the parts vector has more elements than the value vector, then we
423     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
424     // Extract the elements we want.
425     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
427               ValueVT.getVectorElementCount().getKnownMinValue()) &&
428              (PartEVT.getVectorElementCount().isScalable() ==
429               ValueVT.getVectorElementCount().isScalable()) &&
430              "Cannot narrow, it would be a lossy transformation");
431       PartEVT =
432           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
433                            ValueVT.getVectorElementCount());
434       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
435                         DAG.getVectorIdxConstant(0, DL));
436       if (PartEVT == ValueVT)
437         return Val;
438       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440 
441       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
442       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444     }
445 
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448   }
449 
450   // Trivial bitcast if the types are the same size and the destination
451   // vector type is legal.
452   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
453       TLI.isTypeLegal(ValueVT))
454     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 
456   if (ValueVT.getVectorNumElements() != 1) {
457      // Certain ABIs require that vectors are passed as integers. For vectors
458      // are the same size, this is an obvious bitcast.
459      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
460        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461      } else if (ValueVT.bitsLT(PartEVT)) {
462        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
463        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
464        // Drop the extra bits.
465        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
466        return DAG.getBitcast(ValueVT, Val);
467      }
468 
469      diagnosePossiblyInvalidConstraint(
470          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
471      return DAG.getUNDEF(ValueVT);
472   }
473 
474   // Handle cases such as i8 -> <1 x i1>
475   EVT ValueSVT = ValueVT.getVectorElementType();
476   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
477     unsigned ValueSize = ValueSVT.getSizeInBits();
478     if (ValueSize == PartEVT.getSizeInBits()) {
479       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
480     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
481       // It's possible a scalar floating point type gets softened to integer and
482       // then promoted to a larger integer. If PartEVT is the larger integer
483       // we need to truncate it and then bitcast to the FP type.
484       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
485       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
486       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
487       Val = DAG.getBitcast(ValueSVT, Val);
488     } else {
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492     }
493   }
494 
495   return DAG.getBuildVector(ValueVT, DL, Val);
496 }
497 
498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V,
501                                  std::optional<CallingConv::ID> CallConv);
502 
503 /// getCopyToParts - Create a series of nodes that contain the specified value
504 /// split into legal parts.  If the parts contain more bits than Val, then, for
505 /// integers, ExtendKind can be used to specify how to generate the extra bits.
506 static void
507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
508                unsigned NumParts, MVT PartVT, const Value *V,
509                std::optional<CallingConv::ID> CallConv = std::nullopt,
510                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
511   // Let the target split the parts if it wants to
512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
513   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
514                                       CallConv))
515     return;
516   EVT ValueVT = Val.getValueType();
517 
518   // Handle the vector case separately.
519   if (ValueVT.isVector())
520     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
521                                 CallConv);
522 
523   unsigned OrigNumParts = NumParts;
524   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
525          "Copying to an illegal type!");
526 
527   if (NumParts == 0)
528     return;
529 
530   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
531   EVT PartEVT = PartVT;
532   if (PartEVT == ValueVT) {
533     assert(NumParts == 1 && "No-op copy with multiple parts!");
534     Parts[0] = Val;
535     return;
536   }
537 
538   unsigned PartBits = PartVT.getSizeInBits();
539   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540     // If the parts cover more bits than the value has, promote the value.
541     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542       assert(NumParts == 1 && "Do not know what to promote to!");
543       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
544     } else {
545       if (ValueVT.isFloatingPoint()) {
546         // FP values need to be bitcast, then extended if they are being put
547         // into a larger container.
548         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
549         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
550       }
551       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552              ValueVT.isInteger() &&
553              "Unknown mismatch!");
554       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
556       if (PartVT == MVT::x86mmx)
557         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559   } else if (PartBits == ValueVT.getSizeInBits()) {
560     // Different types of the same size.
561     assert(NumParts == 1 && PartEVT != ValueVT);
562     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
564     // If the parts cover less bits than value has, truncate the value.
565     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566            ValueVT.isInteger() &&
567            "Unknown mismatch!");
568     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
570     if (PartVT == MVT::x86mmx)
571       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   }
573 
574   // The value may have changed - recompute ValueVT.
575   ValueVT = Val.getValueType();
576   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
577          "Failed to tile the value with PartVT!");
578 
579   if (NumParts == 1) {
580     if (PartEVT != ValueVT) {
581       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
582                                         "scalar-to-vector conversion failed");
583       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584     }
585 
586     Parts[0] = Val;
587     return;
588   }
589 
590   // Expand the value into multiple parts.
591   if (NumParts & (NumParts - 1)) {
592     // The number of parts is not a power of 2.  Split off and copy the tail.
593     assert(PartVT.isInteger() && ValueVT.isInteger() &&
594            "Do not know what to expand to!");
595     unsigned RoundParts = llvm::bit_floor(NumParts);
596     unsigned RoundBits = RoundParts * PartBits;
597     unsigned OddParts = NumParts - RoundParts;
598     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
599       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
600 
601     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
602                    CallConv);
603 
604     if (DAG.getDataLayout().isBigEndian())
605       // The odd parts were reversed by getCopyToParts - unreverse them.
606       std::reverse(Parts + RoundParts, Parts + NumParts);
607 
608     NumParts = RoundParts;
609     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
610     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
611   }
612 
613   // The number of parts is a power of 2.  Repeatedly bisect the value using
614   // EXTRACT_ELEMENT.
615   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616                          EVT::getIntegerVT(*DAG.getContext(),
617                                            ValueVT.getSizeInBits()),
618                          Val);
619 
620   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
621     for (unsigned i = 0; i < NumParts; i += StepSize) {
622       unsigned ThisBits = StepSize * PartBits / 2;
623       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
624       SDValue &Part0 = Parts[i];
625       SDValue &Part1 = Parts[i+StepSize/2];
626 
627       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
629       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
630                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
631 
632       if (ThisBits == PartBits && ThisVT != PartVT) {
633         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
634         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
635       }
636     }
637   }
638 
639   if (DAG.getDataLayout().isBigEndian())
640     std::reverse(Parts, Parts + OrigNumParts);
641 }
642 
643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
644                                      const SDLoc &DL, EVT PartVT) {
645   if (!PartVT.isVector())
646     return SDValue();
647 
648   EVT ValueVT = Val.getValueType();
649   EVT PartEVT = PartVT.getVectorElementType();
650   EVT ValueEVT = ValueVT.getVectorElementType();
651   ElementCount PartNumElts = PartVT.getVectorElementCount();
652   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
653 
654   // We only support widening vectors with equivalent element types and
655   // fixed/scalable properties. If a target needs to widen a fixed-length type
656   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
657   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
658       PartNumElts.isScalable() != ValueNumElts.isScalable())
659     return SDValue();
660 
661   // Have a try for bf16 because some targets share its ABI with fp16.
662   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
664            "Cannot widen to illegal type");
665     Val = DAG.getNode(ISD::BITCAST, DL,
666                       ValueVT.changeVectorElementType(MVT::f16), Val);
667   } else if (PartEVT != ValueEVT) {
668     return SDValue();
669   }
670 
671   // Widening a scalable vector to another scalable vector is done by inserting
672   // the vector into a larger undef one.
673   if (PartNumElts.isScalable())
674     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675                        Val, DAG.getVectorIdxConstant(0, DL));
676 
677   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
678   // undef elements.
679   SmallVector<SDValue, 16> Ops;
680   DAG.ExtractVectorElements(Val, Ops);
681   SDValue EltUndef = DAG.getUNDEF(PartEVT);
682   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683 
684   // FIXME: Use CONCAT for 2x -> 4x.
685   return DAG.getBuildVector(PartVT, DL, Ops);
686 }
687 
688 /// getCopyToPartsVector - Create a series of nodes that contain the specified
689 /// value split into legal parts.
690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691                                  SDValue Val, SDValue *Parts, unsigned NumParts,
692                                  MVT PartVT, const Value *V,
693                                  std::optional<CallingConv::ID> CallConv) {
694   EVT ValueVT = Val.getValueType();
695   assert(ValueVT.isVector() && "Not a vector");
696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697   const bool IsABIRegCopy = CallConv.has_value();
698 
699   if (NumParts == 1) {
700     EVT PartEVT = PartVT;
701     if (PartEVT == ValueVT) {
702       // Nothing to do.
703     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704       // Bitconvert vector->vector case.
705       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707       Val = Widened;
708     } else if (PartVT.isVector() &&
709                PartEVT.getVectorElementType().bitsGE(
710                    ValueVT.getVectorElementType()) &&
711                PartEVT.getVectorElementCount() ==
712                    ValueVT.getVectorElementCount()) {
713 
714       // Promoted vector extract
715       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716     } else if (PartEVT.isVector() &&
717                PartEVT.getVectorElementType() !=
718                    ValueVT.getVectorElementType() &&
719                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720                    TargetLowering::TypeWidenVector) {
721       // Combination of widening and promotion.
722       EVT WidenVT =
723           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
724                            PartVT.getVectorElementCount());
725       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727     } else {
728       // Don't extract an integer from a float vector. This can happen if the
729       // FP type gets softened to integer and then promoted. The promotion
730       // prevents it from being picked up by the earlier bitcast case.
731       if (ValueVT.getVectorElementCount().isScalar() &&
732           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733         // If we reach this condition and PartVT is FP, this means that
734         // ValueVT is also FP and both have a different size, otherwise we
735         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736         // would be invalid since that would mean the smaller FP type has to
737         // be extended to the larger one.
738         if (PartVT.isFloatingPoint()) {
739           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741         } else
742           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743                             DAG.getVectorIdxConstant(0, DL));
744       } else {
745         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746         assert(PartVT.getFixedSizeInBits() > ValueSize &&
747                "lossy conversion of vector to scalar type");
748         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749         Val = DAG.getBitcast(IntermediateType, Val);
750         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751       }
752     }
753 
754     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755     Parts[0] = Val;
756     return;
757   }
758 
759   // Handle a multi-element vector.
760   EVT IntermediateVT;
761   MVT RegisterVT;
762   unsigned NumIntermediates;
763   unsigned NumRegs;
764   if (IsABIRegCopy) {
765     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
766         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767         RegisterVT);
768   } else {
769     NumRegs =
770         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771                                    NumIntermediates, RegisterVT);
772   }
773 
774   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775   NumParts = NumRegs; // Silence a compiler warning.
776   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777 
778   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779          "Mixing scalable and fixed vectors when copying in parts");
780 
781   std::optional<ElementCount> DestEltCnt;
782 
783   if (IntermediateVT.isVector())
784     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785   else
786     DestEltCnt = ElementCount::getFixed(NumIntermediates);
787 
788   EVT BuiltVectorTy = EVT::getVectorVT(
789       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790 
791   if (ValueVT == BuiltVectorTy) {
792     // Nothing to do.
793   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794     // Bitconvert vector->vector case.
795     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796   } else {
797     if (BuiltVectorTy.getVectorElementType().bitsGT(
798             ValueVT.getVectorElementType())) {
799       // Integer promotion.
800       ValueVT = EVT::getVectorVT(*DAG.getContext(),
801                                  BuiltVectorTy.getVectorElementType(),
802                                  ValueVT.getVectorElementCount());
803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804     }
805 
806     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807       Val = Widened;
808     }
809   }
810 
811   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812 
813   // Split the vector into intermediate operands.
814   SmallVector<SDValue, 8> Ops(NumIntermediates);
815   for (unsigned i = 0; i != NumIntermediates; ++i) {
816     if (IntermediateVT.isVector()) {
817       // This does something sensible for scalable vectors - see the
818       // definition of EXTRACT_SUBVECTOR for further details.
819       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820       Ops[i] =
821           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823     } else {
824       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825                            DAG.getVectorIdxConstant(i, DL));
826     }
827   }
828 
829   // Split the intermediate operands into legal parts.
830   if (NumParts == NumIntermediates) {
831     // If the register was not expanded, promote or copy the value,
832     // as appropriate.
833     for (unsigned i = 0; i != NumParts; ++i)
834       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835   } else if (NumParts > 0) {
836     // If the intermediate type was expanded, split each the value into
837     // legal parts.
838     assert(NumIntermediates != 0 && "division by zero");
839     assert(NumParts % NumIntermediates == 0 &&
840            "Must expand into a divisible number of parts!");
841     unsigned Factor = NumParts / NumIntermediates;
842     for (unsigned i = 0; i != NumIntermediates; ++i)
843       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844                      CallConv);
845   }
846 }
847 
848 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
849                            EVT valuevt, std::optional<CallingConv::ID> CC)
850     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
851       RegCount(1, regs.size()), CallConv(CC) {}
852 
853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
854                            const DataLayout &DL, unsigned Reg, Type *Ty,
855                            std::optional<CallingConv::ID> CC) {
856   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
857 
858   CallConv = CC;
859 
860   for (EVT ValueVT : ValueVTs) {
861     unsigned NumRegs =
862         isABIMangled()
863             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
864             : TLI.getNumRegisters(Context, ValueVT);
865     MVT RegisterVT =
866         isABIMangled()
867             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
868             : TLI.getRegisterType(Context, ValueVT);
869     for (unsigned i = 0; i != NumRegs; ++i)
870       Regs.push_back(Reg + i);
871     RegVTs.push_back(RegisterVT);
872     RegCount.push_back(NumRegs);
873     Reg += NumRegs;
874   }
875 }
876 
877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
878                                       FunctionLoweringInfo &FuncInfo,
879                                       const SDLoc &dl, SDValue &Chain,
880                                       SDValue *Glue, const Value *V) const {
881   // A Value with type {} or [0 x %t] needs no registers.
882   if (ValueVTs.empty())
883     return SDValue();
884 
885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
886 
887   // Assemble the legal parts into the final values.
888   SmallVector<SDValue, 4> Values(ValueVTs.size());
889   SmallVector<SDValue, 8> Parts;
890   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
891     // Copy the legal parts from the registers.
892     EVT ValueVT = ValueVTs[Value];
893     unsigned NumRegs = RegCount[Value];
894     MVT RegisterVT = isABIMangled()
895                          ? TLI.getRegisterTypeForCallingConv(
896                                *DAG.getContext(), *CallConv, RegVTs[Value])
897                          : RegVTs[Value];
898 
899     Parts.resize(NumRegs);
900     for (unsigned i = 0; i != NumRegs; ++i) {
901       SDValue P;
902       if (!Glue) {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
904       } else {
905         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
906         *Glue = P.getValue(2);
907       }
908 
909       Chain = P.getValue(1);
910       Parts[i] = P;
911 
912       // If the source register was virtual and if we know something about it,
913       // add an assert node.
914       if (!Register::isVirtualRegister(Regs[Part + i]) ||
915           !RegisterVT.isInteger())
916         continue;
917 
918       const FunctionLoweringInfo::LiveOutInfo *LOI =
919         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
920       if (!LOI)
921         continue;
922 
923       unsigned RegSize = RegisterVT.getScalarSizeInBits();
924       unsigned NumSignBits = LOI->NumSignBits;
925       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
926 
927       if (NumZeroBits == RegSize) {
928         // The current value is a zero.
929         // Explicitly express that as it would be easier for
930         // optimizations to kick in.
931         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
932         continue;
933       }
934 
935       // FIXME: We capture more information than the dag can represent.  For
936       // now, just use the tightest assertzext/assertsext possible.
937       bool isSExt;
938       EVT FromVT(MVT::Other);
939       if (NumZeroBits) {
940         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
941         isSExt = false;
942       } else if (NumSignBits > 1) {
943         FromVT =
944             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
945         isSExt = true;
946       } else {
947         continue;
948       }
949       // Add an assertion node.
950       assert(FromVT != MVT::Other);
951       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
952                              RegisterVT, P, DAG.getValueType(FromVT));
953     }
954 
955     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
956                                      RegisterVT, ValueVT, V, Chain, CallConv);
957     Part += NumRegs;
958     Parts.clear();
959   }
960 
961   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
962 }
963 
964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
965                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
966                                  const Value *V,
967                                  ISD::NodeType PreferredExtendType) const {
968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
969   ISD::NodeType ExtendKind = PreferredExtendType;
970 
971   // Get the list of the values's legal parts.
972   unsigned NumRegs = Regs.size();
973   SmallVector<SDValue, 8> Parts(NumRegs);
974   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumParts = RegCount[Value];
976 
977     MVT RegisterVT = isABIMangled()
978                          ? TLI.getRegisterTypeForCallingConv(
979                                *DAG.getContext(), *CallConv, RegVTs[Value])
980                          : RegVTs[Value];
981 
982     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
983       ExtendKind = ISD::ZERO_EXTEND;
984 
985     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
986                    NumParts, RegisterVT, V, CallConv, ExtendKind);
987     Part += NumParts;
988   }
989 
990   // Copy the parts into the registers.
991   SmallVector<SDValue, 8> Chains(NumRegs);
992   for (unsigned i = 0; i != NumRegs; ++i) {
993     SDValue Part;
994     if (!Glue) {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
996     } else {
997       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
998       *Glue = Part.getValue(1);
999     }
1000 
1001     Chains[i] = Part.getValue(0);
1002   }
1003 
1004   if (NumRegs == 1 || Glue)
1005     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1006     // flagged to it. That is the CopyToReg nodes and the user are considered
1007     // a single scheduling unit. If we create a TokenFactor and return it as
1008     // chain, then the TokenFactor is both a predecessor (operand) of the
1009     // user as well as a successor (the TF operands are flagged to the user).
1010     // c1, f1 = CopyToReg
1011     // c2, f2 = CopyToReg
1012     // c3     = TokenFactor c1, c2
1013     // ...
1014     //        = op c3, ..., f2
1015     Chain = Chains[NumRegs-1];
1016   else
1017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1018 }
1019 
1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1021                                         unsigned MatchingIdx, const SDLoc &dl,
1022                                         SelectionDAG &DAG,
1023                                         std::vector<SDValue> &Ops) const {
1024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1025 
1026   InlineAsm::Flag Flag(Code, Regs.size());
1027   if (HasMatching)
1028     Flag.setMatchingOp(MatchingIdx);
1029   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1030     // Put the register class of the virtual registers in the flag word.  That
1031     // way, later passes can recompute register class constraints for inline
1032     // assembly as well as normal instructions.
1033     // Don't do this for tied operands that can use the regclass information
1034     // from the def.
1035     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1036     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1037     Flag.setRegClass(RC->getID());
1038   }
1039 
1040   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1041   Ops.push_back(Res);
1042 
1043   if (Code == InlineAsm::Kind::Clobber) {
1044     // Clobbers should always have a 1:1 mapping with registers, and may
1045     // reference registers that have illegal (e.g. vector) types. Hence, we
1046     // shouldn't try to apply any sort of splitting logic to them.
1047     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1048            "No 1:1 mapping from clobbers to regs?");
1049     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1050     (void)SP;
1051     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1052       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1053       assert(
1054           (Regs[I] != SP ||
1055            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1056           "If we clobbered the stack pointer, MFI should know about it.");
1057     }
1058     return;
1059   }
1060 
1061   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1062     MVT RegisterVT = RegVTs[Value];
1063     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1064                                            RegisterVT);
1065     for (unsigned i = 0; i != NumRegs; ++i) {
1066       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1067       unsigned TheReg = Regs[Reg++];
1068       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1069     }
1070   }
1071 }
1072 
1073 SmallVector<std::pair<unsigned, TypeSize>, 4>
1074 RegsForValue::getRegsAndSizes() const {
1075   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1076   unsigned I = 0;
1077   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1078     unsigned RegCount = std::get<0>(CountAndVT);
1079     MVT RegisterVT = std::get<1>(CountAndVT);
1080     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1081     for (unsigned E = I + RegCount; I != E; ++I)
1082       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1083   }
1084   return OutVec;
1085 }
1086 
1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1088                                AssumptionCache *ac,
1089                                const TargetLibraryInfo *li) {
1090   AA = aa;
1091   AC = ac;
1092   GFI = gfi;
1093   LibInfo = li;
1094   Context = DAG.getContext();
1095   LPadToCallSiteMap.clear();
1096   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1097   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1098       *DAG.getMachineFunction().getFunction().getParent());
1099 }
1100 
1101 void SelectionDAGBuilder::clear() {
1102   NodeMap.clear();
1103   UnusedArgNodeMap.clear();
1104   PendingLoads.clear();
1105   PendingExports.clear();
1106   PendingConstrainedFP.clear();
1107   PendingConstrainedFPStrict.clear();
1108   CurInst = nullptr;
1109   HasTailCall = false;
1110   SDNodeOrder = LowestSDNodeOrder;
1111   StatepointLowering.clear();
1112 }
1113 
1114 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1115   DanglingDebugInfoMap.clear();
1116 }
1117 
1118 // Update DAG root to include dependencies on Pending chains.
1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1120   SDValue Root = DAG.getRoot();
1121 
1122   if (Pending.empty())
1123     return Root;
1124 
1125   // Add current root to PendingChains, unless we already indirectly
1126   // depend on it.
1127   if (Root.getOpcode() != ISD::EntryToken) {
1128     unsigned i = 0, e = Pending.size();
1129     for (; i != e; ++i) {
1130       assert(Pending[i].getNode()->getNumOperands() > 1);
1131       if (Pending[i].getNode()->getOperand(0) == Root)
1132         break;  // Don't add the root if we already indirectly depend on it.
1133     }
1134 
1135     if (i == e)
1136       Pending.push_back(Root);
1137   }
1138 
1139   if (Pending.size() == 1)
1140     Root = Pending[0];
1141   else
1142     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1143 
1144   DAG.setRoot(Root);
1145   Pending.clear();
1146   return Root;
1147 }
1148 
1149 SDValue SelectionDAGBuilder::getMemoryRoot() {
1150   return updateRoot(PendingLoads);
1151 }
1152 
1153 SDValue SelectionDAGBuilder::getRoot() {
1154   // Chain up all pending constrained intrinsics together with all
1155   // pending loads, by simply appending them to PendingLoads and
1156   // then calling getMemoryRoot().
1157   PendingLoads.reserve(PendingLoads.size() +
1158                        PendingConstrainedFP.size() +
1159                        PendingConstrainedFPStrict.size());
1160   PendingLoads.append(PendingConstrainedFP.begin(),
1161                       PendingConstrainedFP.end());
1162   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1163                       PendingConstrainedFPStrict.end());
1164   PendingConstrainedFP.clear();
1165   PendingConstrainedFPStrict.clear();
1166   return getMemoryRoot();
1167 }
1168 
1169 SDValue SelectionDAGBuilder::getControlRoot() {
1170   // We need to emit pending fpexcept.strict constrained intrinsics,
1171   // so append them to the PendingExports list.
1172   PendingExports.append(PendingConstrainedFPStrict.begin(),
1173                         PendingConstrainedFPStrict.end());
1174   PendingConstrainedFPStrict.clear();
1175   return updateRoot(PendingExports);
1176 }
1177 
1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1179                                              DILocalVariable *Variable,
1180                                              DIExpression *Expression,
1181                                              DebugLoc DL) {
1182   assert(Variable && "Missing variable");
1183 
1184   // Check if address has undef value.
1185   if (!Address || isa<UndefValue>(Address) ||
1186       (Address->use_empty() && !isa<Argument>(Address))) {
1187     LLVM_DEBUG(
1188         dbgs()
1189         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1190     return;
1191   }
1192 
1193   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1194 
1195   SDValue &N = NodeMap[Address];
1196   if (!N.getNode() && isa<Argument>(Address))
1197     // Check unused arguments map.
1198     N = UnusedArgNodeMap[Address];
1199   SDDbgValue *SDV;
1200   if (N.getNode()) {
1201     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1202       Address = BCI->getOperand(0);
1203     // Parameters are handled specially.
1204     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1205     if (IsParameter && FINode) {
1206       // Byval parameter. We have a frame index at this point.
1207       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1208                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1209     } else if (isa<Argument>(Address)) {
1210       // Address is an argument, so try to emit its dbg value using
1211       // virtual register info from the FuncInfo.ValueMap.
1212       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                FuncArgumentDbgValueKind::Declare, N);
1214       return;
1215     } else {
1216       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1217                             true, DL, SDNodeOrder);
1218     }
1219     DAG.AddDbgValue(SDV, IsParameter);
1220   } else {
1221     // If Address is an argument then try to emit its dbg value using
1222     // virtual register info from the FuncInfo.ValueMap.
1223     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1224                                   FuncArgumentDbgValueKind::Declare, N)) {
1225       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1226                         << " (could not emit func-arg dbg_value)\n");
1227     }
1228   }
1229   return;
1230 }
1231 
1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1233   // Add SDDbgValue nodes for any var locs here. Do so before updating
1234   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1236     // Add SDDbgValue nodes for any var locs here. Do so before updating
1237     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1238     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1239          It != End; ++It) {
1240       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1241       dropDanglingDebugInfo(Var, It->Expr);
1242       if (It->Values.isKillLocation(It->Expr)) {
1243         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1244         continue;
1245       }
1246       SmallVector<Value *> Values(It->Values.location_ops());
1247       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1248                             It->Values.hasArgList())) {
1249         SmallVector<Value *, 4> Vals;
1250         for (Value *V : It->Values.location_ops())
1251           Vals.push_back(V);
1252         addDanglingDebugInfo(Vals,
1253                              FnVarLocs->getDILocalVariable(It->VariableID),
1254                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1255       }
1256     }
1257   }
1258 
1259   // We must skip DbgVariableRecords if they've already been processed above as
1260   // we have just emitted the debug values resulting from assignment tracking
1261   // analysis, making any existing DbgVariableRecords redundant (and probably
1262   // less correct). We still need to process DbgLabelRecords. This does sink
1263   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1264   // be important as it does so deterministcally and ordering between
1265   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1266   // printing).
1267   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1268   // Is there is any debug-info attached to this instruction, in the form of
1269   // DbgRecord non-instruction debug-info records.
1270   for (DbgRecord &DR : I.getDbgRecordRange()) {
1271     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1272       assert(DLR->getLabel() && "Missing label");
1273       SDDbgLabel *SDV =
1274           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1275       DAG.AddDbgLabel(SDV);
1276       continue;
1277     }
1278 
1279     if (SkipDbgVariableRecords)
1280       continue;
1281     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1282     DILocalVariable *Variable = DVR.getVariable();
1283     DIExpression *Expression = DVR.getExpression();
1284     dropDanglingDebugInfo(Variable, Expression);
1285 
1286     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1287       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1288         continue;
1289       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1290                         << "\n");
1291       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1292                          DVR.getDebugLoc());
1293       continue;
1294     }
1295 
1296     // A DbgVariableRecord with no locations is a kill location.
1297     SmallVector<Value *, 4> Values(DVR.location_ops());
1298     if (Values.empty()) {
1299       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1300                            SDNodeOrder);
1301       continue;
1302     }
1303 
1304     // A DbgVariableRecord with an undef or absent location is also a kill
1305     // location.
1306     if (llvm::any_of(Values,
1307                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1308       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1309                            SDNodeOrder);
1310       continue;
1311     }
1312 
1313     bool IsVariadic = DVR.hasArgList();
1314     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1315                           SDNodeOrder, IsVariadic)) {
1316       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1317                            DVR.getDebugLoc(), SDNodeOrder);
1318     }
1319   }
1320 }
1321 
1322 void SelectionDAGBuilder::visit(const Instruction &I) {
1323   visitDbgInfo(I);
1324 
1325   // Set up outgoing PHI node register values before emitting the terminator.
1326   if (I.isTerminator()) {
1327     HandlePHINodesInSuccessorBlocks(I.getParent());
1328   }
1329 
1330   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1331   if (!isa<DbgInfoIntrinsic>(I))
1332     ++SDNodeOrder;
1333 
1334   CurInst = &I;
1335 
1336   // Set inserted listener only if required.
1337   bool NodeInserted = false;
1338   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1339   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1340   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1341   if (PCSectionsMD || MMRA) {
1342     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1343         DAG, [&](SDNode *) { NodeInserted = true; });
1344   }
1345 
1346   visit(I.getOpcode(), I);
1347 
1348   if (!I.isTerminator() && !HasTailCall &&
1349       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1350     CopyToExportRegsIfNeeded(&I);
1351 
1352   // Handle metadata.
1353   if (PCSectionsMD || MMRA) {
1354     auto It = NodeMap.find(&I);
1355     if (It != NodeMap.end()) {
1356       if (PCSectionsMD)
1357         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1358       if (MMRA)
1359         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1360     } else if (NodeInserted) {
1361       // This should not happen; if it does, don't let it go unnoticed so we can
1362       // fix it. Relevant visit*() function is probably missing a setValue().
1363       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1364              << I.getModule()->getName() << "]\n";
1365       LLVM_DEBUG(I.dump());
1366       assert(false);
1367     }
1368   }
1369 
1370   CurInst = nullptr;
1371 }
1372 
1373 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1374   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1375 }
1376 
1377 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1378   // Note: this doesn't use InstVisitor, because it has to work with
1379   // ConstantExpr's in addition to instructions.
1380   switch (Opcode) {
1381   default: llvm_unreachable("Unknown instruction type encountered!");
1382     // Build the switch statement using the Instruction.def file.
1383 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1384     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1385 #include "llvm/IR/Instruction.def"
1386   }
1387 }
1388 
1389 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1390                                             DILocalVariable *Variable,
1391                                             DebugLoc DL, unsigned Order,
1392                                             SmallVectorImpl<Value *> &Values,
1393                                             DIExpression *Expression) {
1394   // For variadic dbg_values we will now insert an undef.
1395   // FIXME: We can potentially recover these!
1396   SmallVector<SDDbgOperand, 2> Locs;
1397   for (const Value *V : Values) {
1398     auto *Undef = UndefValue::get(V->getType());
1399     Locs.push_back(SDDbgOperand::fromConst(Undef));
1400   }
1401   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1402                                         /*IsIndirect=*/false, DL, Order,
1403                                         /*IsVariadic=*/true);
1404   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1405   return true;
1406 }
1407 
1408 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1409                                                DILocalVariable *Var,
1410                                                DIExpression *Expr,
1411                                                bool IsVariadic, DebugLoc DL,
1412                                                unsigned Order) {
1413   if (IsVariadic) {
1414     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1415     return;
1416   }
1417   // TODO: Dangling debug info will eventually either be resolved or produce
1418   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1419   // between the original dbg.value location and its resolved DBG_VALUE,
1420   // which we should ideally fill with an extra Undef DBG_VALUE.
1421   assert(Values.size() == 1);
1422   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1423 }
1424 
1425 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1426                                                 const DIExpression *Expr) {
1427   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1428     DIVariable *DanglingVariable = DDI.getVariable();
1429     DIExpression *DanglingExpr = DDI.getExpression();
1430     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1431       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1432                         << printDDI(nullptr, DDI) << "\n");
1433       return true;
1434     }
1435     return false;
1436   };
1437 
1438   for (auto &DDIMI : DanglingDebugInfoMap) {
1439     DanglingDebugInfoVector &DDIV = DDIMI.second;
1440 
1441     // If debug info is to be dropped, run it through final checks to see
1442     // whether it can be salvaged.
1443     for (auto &DDI : DDIV)
1444       if (isMatchingDbgValue(DDI))
1445         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1446 
1447     erase_if(DDIV, isMatchingDbgValue);
1448   }
1449 }
1450 
1451 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1452 // generate the debug data structures now that we've seen its definition.
1453 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1454                                                    SDValue Val) {
1455   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1456   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1457     return;
1458 
1459   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1460   for (auto &DDI : DDIV) {
1461     DebugLoc DL = DDI.getDebugLoc();
1462     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1463     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1464     DILocalVariable *Variable = DDI.getVariable();
1465     DIExpression *Expr = DDI.getExpression();
1466     assert(Variable->isValidLocationForIntrinsic(DL) &&
1467            "Expected inlined-at fields to agree");
1468     SDDbgValue *SDV;
1469     if (Val.getNode()) {
1470       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1471       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1472       // we couldn't resolve it directly when examining the DbgValue intrinsic
1473       // in the first place we should not be more successful here). Unless we
1474       // have some test case that prove this to be correct we should avoid
1475       // calling EmitFuncArgumentDbgValue here.
1476       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1477                                     FuncArgumentDbgValueKind::Value, Val)) {
1478         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1479                           << printDDI(V, DDI) << "\n");
1480         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1481         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1482         // inserted after the definition of Val when emitting the instructions
1483         // after ISel. An alternative could be to teach
1484         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1485         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1486                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1487                    << ValSDNodeOrder << "\n");
1488         SDV = getDbgValue(Val, Variable, Expr, DL,
1489                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1490         DAG.AddDbgValue(SDV, false);
1491       } else
1492         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1493                           << printDDI(V, DDI)
1494                           << " in EmitFuncArgumentDbgValue\n");
1495     } else {
1496       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1497                         << "\n");
1498       auto Undef = UndefValue::get(V->getType());
1499       auto SDV =
1500           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1501       DAG.AddDbgValue(SDV, false);
1502     }
1503   }
1504   DDIV.clear();
1505 }
1506 
1507 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1508                                                     DanglingDebugInfo &DDI) {
1509   // TODO: For the variadic implementation, instead of only checking the fail
1510   // state of `handleDebugValue`, we need know specifically which values were
1511   // invalid, so that we attempt to salvage only those values when processing
1512   // a DIArgList.
1513   const Value *OrigV = V;
1514   DILocalVariable *Var = DDI.getVariable();
1515   DIExpression *Expr = DDI.getExpression();
1516   DebugLoc DL = DDI.getDebugLoc();
1517   unsigned SDOrder = DDI.getSDNodeOrder();
1518 
1519   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1520   // that DW_OP_stack_value is desired.
1521   bool StackValue = true;
1522 
1523   // Can this Value can be encoded without any further work?
1524   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1525     return;
1526 
1527   // Attempt to salvage back through as many instructions as possible. Bail if
1528   // a non-instruction is seen, such as a constant expression or global
1529   // variable. FIXME: Further work could recover those too.
1530   while (isa<Instruction>(V)) {
1531     const Instruction &VAsInst = *cast<const Instruction>(V);
1532     // Temporary "0", awaiting real implementation.
1533     SmallVector<uint64_t, 16> Ops;
1534     SmallVector<Value *, 4> AdditionalValues;
1535     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1536                              Expr->getNumLocationOperands(), Ops,
1537                              AdditionalValues);
1538     // If we cannot salvage any further, and haven't yet found a suitable debug
1539     // expression, bail out.
1540     if (!V)
1541       break;
1542 
1543     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1544     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1545     // here for variadic dbg_values, remove that condition.
1546     if (!AdditionalValues.empty())
1547       break;
1548 
1549     // New value and expr now represent this debuginfo.
1550     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1551 
1552     // Some kind of simplification occurred: check whether the operand of the
1553     // salvaged debug expression can be encoded in this DAG.
1554     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1555       LLVM_DEBUG(
1556           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1557                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1558       return;
1559     }
1560   }
1561 
1562   // This was the final opportunity to salvage this debug information, and it
1563   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1564   // any earlier variable location.
1565   assert(OrigV && "V shouldn't be null");
1566   auto *Undef = UndefValue::get(OrigV->getType());
1567   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1568   DAG.AddDbgValue(SDV, false);
1569   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1570                     << printDDI(OrigV, DDI) << "\n");
1571 }
1572 
1573 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1574                                                DIExpression *Expr,
1575                                                DebugLoc DbgLoc,
1576                                                unsigned Order) {
1577   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1578   DIExpression *NewExpr =
1579       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1580   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1581                    /*IsVariadic*/ false);
1582 }
1583 
1584 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1585                                            DILocalVariable *Var,
1586                                            DIExpression *Expr, DebugLoc DbgLoc,
1587                                            unsigned Order, bool IsVariadic) {
1588   if (Values.empty())
1589     return true;
1590 
1591   // Filter EntryValue locations out early.
1592   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1593     return true;
1594 
1595   SmallVector<SDDbgOperand> LocationOps;
1596   SmallVector<SDNode *> Dependencies;
1597   for (const Value *V : Values) {
1598     // Constant value.
1599     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1600         isa<ConstantPointerNull>(V)) {
1601       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1602       continue;
1603     }
1604 
1605     // Look through IntToPtr constants.
1606     if (auto *CE = dyn_cast<ConstantExpr>(V))
1607       if (CE->getOpcode() == Instruction::IntToPtr) {
1608         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1609         continue;
1610       }
1611 
1612     // If the Value is a frame index, we can create a FrameIndex debug value
1613     // without relying on the DAG at all.
1614     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1615       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1616       if (SI != FuncInfo.StaticAllocaMap.end()) {
1617         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1618         continue;
1619       }
1620     }
1621 
1622     // Do not use getValue() in here; we don't want to generate code at
1623     // this point if it hasn't been done yet.
1624     SDValue N = NodeMap[V];
1625     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1626       N = UnusedArgNodeMap[V];
1627     if (N.getNode()) {
1628       // Only emit func arg dbg value for non-variadic dbg.values for now.
1629       if (!IsVariadic &&
1630           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1631                                    FuncArgumentDbgValueKind::Value, N))
1632         return true;
1633       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1634         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1635         // describe stack slot locations.
1636         //
1637         // Consider "int x = 0; int *px = &x;". There are two kinds of
1638         // interesting debug values here after optimization:
1639         //
1640         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1641         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1642         //
1643         // Both describe the direct values of their associated variables.
1644         Dependencies.push_back(N.getNode());
1645         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1646         continue;
1647       }
1648       LocationOps.emplace_back(
1649           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1650       continue;
1651     }
1652 
1653     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1654     // Special rules apply for the first dbg.values of parameter variables in a
1655     // function. Identify them by the fact they reference Argument Values, that
1656     // they're parameters, and they are parameters of the current function. We
1657     // need to let them dangle until they get an SDNode.
1658     bool IsParamOfFunc =
1659         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1660     if (IsParamOfFunc)
1661       return false;
1662 
1663     // The value is not used in this block yet (or it would have an SDNode).
1664     // We still want the value to appear for the user if possible -- if it has
1665     // an associated VReg, we can refer to that instead.
1666     auto VMI = FuncInfo.ValueMap.find(V);
1667     if (VMI != FuncInfo.ValueMap.end()) {
1668       unsigned Reg = VMI->second;
1669       // If this is a PHI node, it may be split up into several MI PHI nodes
1670       // (in FunctionLoweringInfo::set).
1671       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1672                        V->getType(), std::nullopt);
1673       if (RFV.occupiesMultipleRegs()) {
1674         // FIXME: We could potentially support variadic dbg_values here.
1675         if (IsVariadic)
1676           return false;
1677         unsigned Offset = 0;
1678         unsigned BitsToDescribe = 0;
1679         if (auto VarSize = Var->getSizeInBits())
1680           BitsToDescribe = *VarSize;
1681         if (auto Fragment = Expr->getFragmentInfo())
1682           BitsToDescribe = Fragment->SizeInBits;
1683         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1684           // Bail out if all bits are described already.
1685           if (Offset >= BitsToDescribe)
1686             break;
1687           // TODO: handle scalable vectors.
1688           unsigned RegisterSize = RegAndSize.second;
1689           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1690                                       ? BitsToDescribe - Offset
1691                                       : RegisterSize;
1692           auto FragmentExpr = DIExpression::createFragmentExpression(
1693               Expr, Offset, FragmentSize);
1694           if (!FragmentExpr)
1695             continue;
1696           SDDbgValue *SDV = DAG.getVRegDbgValue(
1697               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1698           DAG.AddDbgValue(SDV, false);
1699           Offset += RegisterSize;
1700         }
1701         return true;
1702       }
1703       // We can use simple vreg locations for variadic dbg_values as well.
1704       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1705       continue;
1706     }
1707     // We failed to create a SDDbgOperand for V.
1708     return false;
1709   }
1710 
1711   // We have created a SDDbgOperand for each Value in Values.
1712   assert(!LocationOps.empty());
1713   SDDbgValue *SDV =
1714       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1715                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1716   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1717   return true;
1718 }
1719 
1720 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1721   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1722   for (auto &Pair : DanglingDebugInfoMap)
1723     for (auto &DDI : Pair.second)
1724       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1725   clearDanglingDebugInfo();
1726 }
1727 
1728 /// getCopyFromRegs - If there was virtual register allocated for the value V
1729 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1730 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1731   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1732   SDValue Result;
1733 
1734   if (It != FuncInfo.ValueMap.end()) {
1735     Register InReg = It->second;
1736 
1737     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1738                      DAG.getDataLayout(), InReg, Ty,
1739                      std::nullopt); // This is not an ABI copy.
1740     SDValue Chain = DAG.getEntryNode();
1741     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1742                                  V);
1743     resolveDanglingDebugInfo(V, Result);
1744   }
1745 
1746   return Result;
1747 }
1748 
1749 /// getValue - Return an SDValue for the given Value.
1750 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1751   // If we already have an SDValue for this value, use it. It's important
1752   // to do this first, so that we don't create a CopyFromReg if we already
1753   // have a regular SDValue.
1754   SDValue &N = NodeMap[V];
1755   if (N.getNode()) return N;
1756 
1757   // If there's a virtual register allocated and initialized for this
1758   // value, use it.
1759   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1760     return copyFromReg;
1761 
1762   // Otherwise create a new SDValue and remember it.
1763   SDValue Val = getValueImpl(V);
1764   NodeMap[V] = Val;
1765   resolveDanglingDebugInfo(V, Val);
1766   return Val;
1767 }
1768 
1769 /// getNonRegisterValue - Return an SDValue for the given Value, but
1770 /// don't look in FuncInfo.ValueMap for a virtual register.
1771 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1772   // If we already have an SDValue for this value, use it.
1773   SDValue &N = NodeMap[V];
1774   if (N.getNode()) {
1775     if (isIntOrFPConstant(N)) {
1776       // Remove the debug location from the node as the node is about to be used
1777       // in a location which may differ from the original debug location.  This
1778       // is relevant to Constant and ConstantFP nodes because they can appear
1779       // as constant expressions inside PHI nodes.
1780       N->setDebugLoc(DebugLoc());
1781     }
1782     return N;
1783   }
1784 
1785   // Otherwise create a new SDValue and remember it.
1786   SDValue Val = getValueImpl(V);
1787   NodeMap[V] = Val;
1788   resolveDanglingDebugInfo(V, Val);
1789   return Val;
1790 }
1791 
1792 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1793 /// Create an SDValue for the given value.
1794 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796 
1797   if (const Constant *C = dyn_cast<Constant>(V)) {
1798     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1799 
1800     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1801       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1802 
1803     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1804       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1805 
1806     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1807       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1808                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1809                          getValue(CPA->getAddrDiscriminator()),
1810                          getValue(CPA->getDiscriminator()));
1811     }
1812 
1813     if (isa<ConstantPointerNull>(C)) {
1814       unsigned AS = V->getType()->getPointerAddressSpace();
1815       return DAG.getConstant(0, getCurSDLoc(),
1816                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1817     }
1818 
1819     if (match(C, m_VScale()))
1820       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1821 
1822     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1823       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1824 
1825     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1826       return DAG.getUNDEF(VT);
1827 
1828     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1829       visit(CE->getOpcode(), *CE);
1830       SDValue N1 = NodeMap[V];
1831       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1832       return N1;
1833     }
1834 
1835     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1836       SmallVector<SDValue, 4> Constants;
1837       for (const Use &U : C->operands()) {
1838         SDNode *Val = getValue(U).getNode();
1839         // If the operand is an empty aggregate, there are no values.
1840         if (!Val) continue;
1841         // Add each leaf value from the operand to the Constants list
1842         // to form a flattened list of all the values.
1843         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1844           Constants.push_back(SDValue(Val, i));
1845       }
1846 
1847       return DAG.getMergeValues(Constants, getCurSDLoc());
1848     }
1849 
1850     if (const ConstantDataSequential *CDS =
1851           dyn_cast<ConstantDataSequential>(C)) {
1852       SmallVector<SDValue, 4> Ops;
1853       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1854         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1855         // Add each leaf value from the operand to the Constants list
1856         // to form a flattened list of all the values.
1857         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1858           Ops.push_back(SDValue(Val, i));
1859       }
1860 
1861       if (isa<ArrayType>(CDS->getType()))
1862         return DAG.getMergeValues(Ops, getCurSDLoc());
1863       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1864     }
1865 
1866     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1867       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1868              "Unknown struct or array constant!");
1869 
1870       SmallVector<EVT, 4> ValueVTs;
1871       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1872       unsigned NumElts = ValueVTs.size();
1873       if (NumElts == 0)
1874         return SDValue(); // empty struct
1875       SmallVector<SDValue, 4> Constants(NumElts);
1876       for (unsigned i = 0; i != NumElts; ++i) {
1877         EVT EltVT = ValueVTs[i];
1878         if (isa<UndefValue>(C))
1879           Constants[i] = DAG.getUNDEF(EltVT);
1880         else if (EltVT.isFloatingPoint())
1881           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1882         else
1883           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1884       }
1885 
1886       return DAG.getMergeValues(Constants, getCurSDLoc());
1887     }
1888 
1889     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1890       return DAG.getBlockAddress(BA, VT);
1891 
1892     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1893       return getValue(Equiv->getGlobalValue());
1894 
1895     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1896       return getValue(NC->getGlobalValue());
1897 
1898     if (VT == MVT::aarch64svcount) {
1899       assert(C->isNullValue() && "Can only zero this target type!");
1900       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1901                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1902     }
1903 
1904     VectorType *VecTy = cast<VectorType>(V->getType());
1905 
1906     // Now that we know the number and type of the elements, get that number of
1907     // elements into the Ops array based on what kind of constant it is.
1908     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1909       SmallVector<SDValue, 16> Ops;
1910       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1911       for (unsigned i = 0; i != NumElements; ++i)
1912         Ops.push_back(getValue(CV->getOperand(i)));
1913 
1914       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1915     }
1916 
1917     if (isa<ConstantAggregateZero>(C)) {
1918       EVT EltVT =
1919           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1920 
1921       SDValue Op;
1922       if (EltVT.isFloatingPoint())
1923         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1924       else
1925         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1926 
1927       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1928     }
1929 
1930     llvm_unreachable("Unknown vector constant");
1931   }
1932 
1933   // If this is a static alloca, generate it as the frameindex instead of
1934   // computation.
1935   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1936     DenseMap<const AllocaInst*, int>::iterator SI =
1937       FuncInfo.StaticAllocaMap.find(AI);
1938     if (SI != FuncInfo.StaticAllocaMap.end())
1939       return DAG.getFrameIndex(
1940           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1941   }
1942 
1943   // If this is an instruction which fast-isel has deferred, select it now.
1944   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1945     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1946 
1947     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1948                      Inst->getType(), std::nullopt);
1949     SDValue Chain = DAG.getEntryNode();
1950     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1951   }
1952 
1953   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1954     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1955 
1956   if (const auto *BB = dyn_cast<BasicBlock>(V))
1957     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1958 
1959   llvm_unreachable("Can't get register for value!");
1960 }
1961 
1962 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1963   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1964   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1965   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1966   bool IsSEH = isAsynchronousEHPersonality(Pers);
1967   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1968   if (!IsSEH)
1969     CatchPadMBB->setIsEHScopeEntry();
1970   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1971   if (IsMSVCCXX || IsCoreCLR)
1972     CatchPadMBB->setIsEHFuncletEntry();
1973 }
1974 
1975 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1976   // Update machine-CFG edge.
1977   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1978   FuncInfo.MBB->addSuccessor(TargetMBB);
1979   TargetMBB->setIsEHCatchretTarget(true);
1980   DAG.getMachineFunction().setHasEHCatchret(true);
1981 
1982   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1983   bool IsSEH = isAsynchronousEHPersonality(Pers);
1984   if (IsSEH) {
1985     // If this is not a fall-through branch or optimizations are switched off,
1986     // emit the branch.
1987     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1988         TM.getOptLevel() == CodeGenOptLevel::None)
1989       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1990                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1991     return;
1992   }
1993 
1994   // Figure out the funclet membership for the catchret's successor.
1995   // This will be used by the FuncletLayout pass to determine how to order the
1996   // BB's.
1997   // A 'catchret' returns to the outer scope's color.
1998   Value *ParentPad = I.getCatchSwitchParentPad();
1999   const BasicBlock *SuccessorColor;
2000   if (isa<ConstantTokenNone>(ParentPad))
2001     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2002   else
2003     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2004   assert(SuccessorColor && "No parent funclet for catchret!");
2005   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
2006   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2007 
2008   // Create the terminator node.
2009   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2010                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2011                             DAG.getBasicBlock(SuccessorColorMBB));
2012   DAG.setRoot(Ret);
2013 }
2014 
2015 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2016   // Don't emit any special code for the cleanuppad instruction. It just marks
2017   // the start of an EH scope/funclet.
2018   FuncInfo.MBB->setIsEHScopeEntry();
2019   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2020   if (Pers != EHPersonality::Wasm_CXX) {
2021     FuncInfo.MBB->setIsEHFuncletEntry();
2022     FuncInfo.MBB->setIsCleanupFuncletEntry();
2023   }
2024 }
2025 
2026 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2027 // not match, it is OK to add only the first unwind destination catchpad to the
2028 // successors, because there will be at least one invoke instruction within the
2029 // catch scope that points to the next unwind destination, if one exists, so
2030 // CFGSort cannot mess up with BB sorting order.
2031 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2032 // call within them, and catchpads only consisting of 'catch (...)' have a
2033 // '__cxa_end_catch' call within them, both of which generate invokes in case
2034 // the next unwind destination exists, i.e., the next unwind destination is not
2035 // the caller.)
2036 //
2037 // Having at most one EH pad successor is also simpler and helps later
2038 // transformations.
2039 //
2040 // For example,
2041 // current:
2042 //   invoke void @foo to ... unwind label %catch.dispatch
2043 // catch.dispatch:
2044 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2045 // catch.start:
2046 //   ...
2047 //   ... in this BB or some other child BB dominated by this BB there will be an
2048 //   invoke that points to 'next' BB as an unwind destination
2049 //
2050 // next: ; We don't need to add this to 'current' BB's successor
2051 //   ...
2052 static void findWasmUnwindDestinations(
2053     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2054     BranchProbability Prob,
2055     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2056         &UnwindDests) {
2057   while (EHPadBB) {
2058     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2059     if (isa<CleanupPadInst>(Pad)) {
2060       // Stop on cleanup pads.
2061       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2062       UnwindDests.back().first->setIsEHScopeEntry();
2063       break;
2064     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2065       // Add the catchpad handlers to the possible destinations. We don't
2066       // continue to the unwind destination of the catchswitch for wasm.
2067       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2068         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2069         UnwindDests.back().first->setIsEHScopeEntry();
2070       }
2071       break;
2072     } else {
2073       continue;
2074     }
2075   }
2076 }
2077 
2078 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2079 /// many places it could ultimately go. In the IR, we have a single unwind
2080 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2081 /// This function skips over imaginary basic blocks that hold catchswitch
2082 /// instructions, and finds all the "real" machine
2083 /// basic block destinations. As those destinations may not be successors of
2084 /// EHPadBB, here we also calculate the edge probability to those destinations.
2085 /// The passed-in Prob is the edge probability to EHPadBB.
2086 static void findUnwindDestinations(
2087     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2088     BranchProbability Prob,
2089     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2090         &UnwindDests) {
2091   EHPersonality Personality =
2092     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2093   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2094   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2095   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2096   bool IsSEH = isAsynchronousEHPersonality(Personality);
2097 
2098   if (IsWasmCXX) {
2099     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2100     assert(UnwindDests.size() <= 1 &&
2101            "There should be at most one unwind destination for wasm");
2102     return;
2103   }
2104 
2105   while (EHPadBB) {
2106     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2107     BasicBlock *NewEHPadBB = nullptr;
2108     if (isa<LandingPadInst>(Pad)) {
2109       // Stop on landingpads. They are not funclets.
2110       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2111       break;
2112     } else if (isa<CleanupPadInst>(Pad)) {
2113       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2114       // personalities.
2115       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2116       UnwindDests.back().first->setIsEHScopeEntry();
2117       UnwindDests.back().first->setIsEHFuncletEntry();
2118       break;
2119     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2120       // Add the catchpad handlers to the possible destinations.
2121       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2122         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2123         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2124         if (IsMSVCCXX || IsCoreCLR)
2125           UnwindDests.back().first->setIsEHFuncletEntry();
2126         if (!IsSEH)
2127           UnwindDests.back().first->setIsEHScopeEntry();
2128       }
2129       NewEHPadBB = CatchSwitch->getUnwindDest();
2130     } else {
2131       continue;
2132     }
2133 
2134     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2135     if (BPI && NewEHPadBB)
2136       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2137     EHPadBB = NewEHPadBB;
2138   }
2139 }
2140 
2141 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2142   // Update successor info.
2143   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2144   auto UnwindDest = I.getUnwindDest();
2145   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2146   BranchProbability UnwindDestProb =
2147       (BPI && UnwindDest)
2148           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2149           : BranchProbability::getZero();
2150   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2151   for (auto &UnwindDest : UnwindDests) {
2152     UnwindDest.first->setIsEHPad();
2153     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2154   }
2155   FuncInfo.MBB->normalizeSuccProbs();
2156 
2157   // Create the terminator node.
2158   SDValue Ret =
2159       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2160   DAG.setRoot(Ret);
2161 }
2162 
2163 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2164   report_fatal_error("visitCatchSwitch not yet implemented!");
2165 }
2166 
2167 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2169   auto &DL = DAG.getDataLayout();
2170   SDValue Chain = getControlRoot();
2171   SmallVector<ISD::OutputArg, 8> Outs;
2172   SmallVector<SDValue, 8> OutVals;
2173 
2174   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2175   // lower
2176   //
2177   //   %val = call <ty> @llvm.experimental.deoptimize()
2178   //   ret <ty> %val
2179   //
2180   // differently.
2181   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2182     LowerDeoptimizingReturn();
2183     return;
2184   }
2185 
2186   if (!FuncInfo.CanLowerReturn) {
2187     unsigned DemoteReg = FuncInfo.DemoteRegister;
2188     const Function *F = I.getParent()->getParent();
2189 
2190     // Emit a store of the return value through the virtual register.
2191     // Leave Outs empty so that LowerReturn won't try to load return
2192     // registers the usual way.
2193     SmallVector<EVT, 1> PtrValueVTs;
2194     ComputeValueVTs(TLI, DL,
2195                     PointerType::get(F->getContext(),
2196                                      DAG.getDataLayout().getAllocaAddrSpace()),
2197                     PtrValueVTs);
2198 
2199     SDValue RetPtr =
2200         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2201     SDValue RetOp = getValue(I.getOperand(0));
2202 
2203     SmallVector<EVT, 4> ValueVTs, MemVTs;
2204     SmallVector<uint64_t, 4> Offsets;
2205     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2206                     &Offsets, 0);
2207     unsigned NumValues = ValueVTs.size();
2208 
2209     SmallVector<SDValue, 4> Chains(NumValues);
2210     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2211     for (unsigned i = 0; i != NumValues; ++i) {
2212       // An aggregate return value cannot wrap around the address space, so
2213       // offsets to its parts don't wrap either.
2214       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2215                                            TypeSize::getFixed(Offsets[i]));
2216 
2217       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2218       if (MemVTs[i] != ValueVTs[i])
2219         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2220       Chains[i] = DAG.getStore(
2221           Chain, getCurSDLoc(), Val,
2222           // FIXME: better loc info would be nice.
2223           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2224           commonAlignment(BaseAlign, Offsets[i]));
2225     }
2226 
2227     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2228                         MVT::Other, Chains);
2229   } else if (I.getNumOperands() != 0) {
2230     SmallVector<EVT, 4> ValueVTs;
2231     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2232     unsigned NumValues = ValueVTs.size();
2233     if (NumValues) {
2234       SDValue RetOp = getValue(I.getOperand(0));
2235 
2236       const Function *F = I.getParent()->getParent();
2237 
2238       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2239           I.getOperand(0)->getType(), F->getCallingConv(),
2240           /*IsVarArg*/ false, DL);
2241 
2242       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2243       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2244         ExtendKind = ISD::SIGN_EXTEND;
2245       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2246         ExtendKind = ISD::ZERO_EXTEND;
2247 
2248       LLVMContext &Context = F->getContext();
2249       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2250 
2251       for (unsigned j = 0; j != NumValues; ++j) {
2252         EVT VT = ValueVTs[j];
2253 
2254         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2255           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2256 
2257         CallingConv::ID CC = F->getCallingConv();
2258 
2259         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2260         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2261         SmallVector<SDValue, 4> Parts(NumParts);
2262         getCopyToParts(DAG, getCurSDLoc(),
2263                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2264                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2265 
2266         // 'inreg' on function refers to return value
2267         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2268         if (RetInReg)
2269           Flags.setInReg();
2270 
2271         if (I.getOperand(0)->getType()->isPointerTy()) {
2272           Flags.setPointer();
2273           Flags.setPointerAddrSpace(
2274               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2275         }
2276 
2277         if (NeedsRegBlock) {
2278           Flags.setInConsecutiveRegs();
2279           if (j == NumValues - 1)
2280             Flags.setInConsecutiveRegsLast();
2281         }
2282 
2283         // Propagate extension type if any
2284         if (ExtendKind == ISD::SIGN_EXTEND)
2285           Flags.setSExt();
2286         else if (ExtendKind == ISD::ZERO_EXTEND)
2287           Flags.setZExt();
2288 
2289         for (unsigned i = 0; i < NumParts; ++i) {
2290           Outs.push_back(ISD::OutputArg(Flags,
2291                                         Parts[i].getValueType().getSimpleVT(),
2292                                         VT, /*isfixed=*/true, 0, 0));
2293           OutVals.push_back(Parts[i]);
2294         }
2295       }
2296     }
2297   }
2298 
2299   // Push in swifterror virtual register as the last element of Outs. This makes
2300   // sure swifterror virtual register will be returned in the swifterror
2301   // physical register.
2302   const Function *F = I.getParent()->getParent();
2303   if (TLI.supportSwiftError() &&
2304       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2305     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2306     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2307     Flags.setSwiftError();
2308     Outs.push_back(ISD::OutputArg(
2309         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2310         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2311     // Create SDNode for the swifterror virtual register.
2312     OutVals.push_back(
2313         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2314                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2315                         EVT(TLI.getPointerTy(DL))));
2316   }
2317 
2318   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2319   CallingConv::ID CallConv =
2320     DAG.getMachineFunction().getFunction().getCallingConv();
2321   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2322       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2323 
2324   // Verify that the target's LowerReturn behaved as expected.
2325   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2326          "LowerReturn didn't return a valid chain!");
2327 
2328   // Update the DAG with the new chain value resulting from return lowering.
2329   DAG.setRoot(Chain);
2330 }
2331 
2332 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2333 /// created for it, emit nodes to copy the value into the virtual
2334 /// registers.
2335 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2336   // Skip empty types
2337   if (V->getType()->isEmptyTy())
2338     return;
2339 
2340   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2341   if (VMI != FuncInfo.ValueMap.end()) {
2342     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2343            "Unused value assigned virtual registers!");
2344     CopyValueToVirtualRegister(V, VMI->second);
2345   }
2346 }
2347 
2348 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2349 /// the current basic block, add it to ValueMap now so that we'll get a
2350 /// CopyTo/FromReg.
2351 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2352   // No need to export constants.
2353   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2354 
2355   // Already exported?
2356   if (FuncInfo.isExportedInst(V)) return;
2357 
2358   Register Reg = FuncInfo.InitializeRegForValue(V);
2359   CopyValueToVirtualRegister(V, Reg);
2360 }
2361 
2362 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2363                                                      const BasicBlock *FromBB) {
2364   // The operands of the setcc have to be in this block.  We don't know
2365   // how to export them from some other block.
2366   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2367     // Can export from current BB.
2368     if (VI->getParent() == FromBB)
2369       return true;
2370 
2371     // Is already exported, noop.
2372     return FuncInfo.isExportedInst(V);
2373   }
2374 
2375   // If this is an argument, we can export it if the BB is the entry block or
2376   // if it is already exported.
2377   if (isa<Argument>(V)) {
2378     if (FromBB->isEntryBlock())
2379       return true;
2380 
2381     // Otherwise, can only export this if it is already exported.
2382     return FuncInfo.isExportedInst(V);
2383   }
2384 
2385   // Otherwise, constants can always be exported.
2386   return true;
2387 }
2388 
2389 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2390 BranchProbability
2391 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2392                                         const MachineBasicBlock *Dst) const {
2393   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2394   const BasicBlock *SrcBB = Src->getBasicBlock();
2395   const BasicBlock *DstBB = Dst->getBasicBlock();
2396   if (!BPI) {
2397     // If BPI is not available, set the default probability as 1 / N, where N is
2398     // the number of successors.
2399     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2400     return BranchProbability(1, SuccSize);
2401   }
2402   return BPI->getEdgeProbability(SrcBB, DstBB);
2403 }
2404 
2405 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2406                                                MachineBasicBlock *Dst,
2407                                                BranchProbability Prob) {
2408   if (!FuncInfo.BPI)
2409     Src->addSuccessorWithoutProb(Dst);
2410   else {
2411     if (Prob.isUnknown())
2412       Prob = getEdgeProbability(Src, Dst);
2413     Src->addSuccessor(Dst, Prob);
2414   }
2415 }
2416 
2417 static bool InBlock(const Value *V, const BasicBlock *BB) {
2418   if (const Instruction *I = dyn_cast<Instruction>(V))
2419     return I->getParent() == BB;
2420   return true;
2421 }
2422 
2423 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2424 /// This function emits a branch and is used at the leaves of an OR or an
2425 /// AND operator tree.
2426 void
2427 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2428                                                   MachineBasicBlock *TBB,
2429                                                   MachineBasicBlock *FBB,
2430                                                   MachineBasicBlock *CurBB,
2431                                                   MachineBasicBlock *SwitchBB,
2432                                                   BranchProbability TProb,
2433                                                   BranchProbability FProb,
2434                                                   bool InvertCond) {
2435   const BasicBlock *BB = CurBB->getBasicBlock();
2436 
2437   // If the leaf of the tree is a comparison, merge the condition into
2438   // the caseblock.
2439   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2440     // The operands of the cmp have to be in this block.  We don't know
2441     // how to export them from some other block.  If this is the first block
2442     // of the sequence, no exporting is needed.
2443     if (CurBB == SwitchBB ||
2444         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2445          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2446       ISD::CondCode Condition;
2447       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2448         ICmpInst::Predicate Pred =
2449             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2450         Condition = getICmpCondCode(Pred);
2451       } else {
2452         const FCmpInst *FC = cast<FCmpInst>(Cond);
2453         FCmpInst::Predicate Pred =
2454             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2455         Condition = getFCmpCondCode(Pred);
2456         if (TM.Options.NoNaNsFPMath)
2457           Condition = getFCmpCodeWithoutNaN(Condition);
2458       }
2459 
2460       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2461                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2462       SL->SwitchCases.push_back(CB);
2463       return;
2464     }
2465   }
2466 
2467   // Create a CaseBlock record representing this branch.
2468   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2469   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2470                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2471   SL->SwitchCases.push_back(CB);
2472 }
2473 
2474 // Collect dependencies on V recursively. This is used for the cost analysis in
2475 // `shouldKeepJumpConditionsTogether`.
2476 static bool collectInstructionDeps(
2477     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2478     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2479     unsigned Depth = 0) {
2480   // Return false if we have an incomplete count.
2481   if (Depth >= SelectionDAG::MaxRecursionDepth)
2482     return false;
2483 
2484   auto *I = dyn_cast<Instruction>(V);
2485   if (I == nullptr)
2486     return true;
2487 
2488   if (Necessary != nullptr) {
2489     // This instruction is necessary for the other side of the condition so
2490     // don't count it.
2491     if (Necessary->contains(I))
2492       return true;
2493   }
2494 
2495   // Already added this dep.
2496   if (!Deps->try_emplace(I, false).second)
2497     return true;
2498 
2499   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2500     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2501                                 Depth + 1))
2502       return false;
2503   return true;
2504 }
2505 
2506 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2507     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2508     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2509     TargetLoweringBase::CondMergingParams Params) const {
2510   if (I.getNumSuccessors() != 2)
2511     return false;
2512 
2513   if (!I.isConditional())
2514     return false;
2515 
2516   if (Params.BaseCost < 0)
2517     return false;
2518 
2519   // Baseline cost.
2520   InstructionCost CostThresh = Params.BaseCost;
2521 
2522   BranchProbabilityInfo *BPI = nullptr;
2523   if (Params.LikelyBias || Params.UnlikelyBias)
2524     BPI = FuncInfo.BPI;
2525   if (BPI != nullptr) {
2526     // See if we are either likely to get an early out or compute both lhs/rhs
2527     // of the condition.
2528     BasicBlock *IfFalse = I.getSuccessor(0);
2529     BasicBlock *IfTrue = I.getSuccessor(1);
2530 
2531     std::optional<bool> Likely;
2532     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2533       Likely = true;
2534     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2535       Likely = false;
2536 
2537     if (Likely) {
2538       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2539         // Its likely we will have to compute both lhs and rhs of condition
2540         CostThresh += Params.LikelyBias;
2541       else {
2542         if (Params.UnlikelyBias < 0)
2543           return false;
2544         // Its likely we will get an early out.
2545         CostThresh -= Params.UnlikelyBias;
2546       }
2547     }
2548   }
2549 
2550   if (CostThresh <= 0)
2551     return false;
2552 
2553   // Collect "all" instructions that lhs condition is dependent on.
2554   // Use map for stable iteration (to avoid non-determanism of iteration of
2555   // SmallPtrSet). The `bool` value is just a dummy.
2556   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2557   collectInstructionDeps(&LhsDeps, Lhs);
2558   // Collect "all" instructions that rhs condition is dependent on AND are
2559   // dependencies of lhs. This gives us an estimate on which instructions we
2560   // stand to save by splitting the condition.
2561   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2562     return false;
2563   // Add the compare instruction itself unless its a dependency on the LHS.
2564   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2565     if (!LhsDeps.contains(RhsI))
2566       RhsDeps.try_emplace(RhsI, false);
2567 
2568   const auto &TLI = DAG.getTargetLoweringInfo();
2569   const auto &TTI =
2570       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2571 
2572   InstructionCost CostOfIncluding = 0;
2573   // See if this instruction will need to computed independently of whether RHS
2574   // is.
2575   Value *BrCond = I.getCondition();
2576   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2577     for (const auto *U : Ins->users()) {
2578       // If user is independent of RHS calculation we don't need to count it.
2579       if (auto *UIns = dyn_cast<Instruction>(U))
2580         if (UIns != BrCond && !RhsDeps.contains(UIns))
2581           return false;
2582     }
2583     return true;
2584   };
2585 
2586   // Prune instructions from RHS Deps that are dependencies of unrelated
2587   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2588   // arbitrary and just meant to cap the how much time we spend in the pruning
2589   // loop. Its highly unlikely to come into affect.
2590   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2591   // Stop after a certain point. No incorrectness from including too many
2592   // instructions.
2593   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2594     const Instruction *ToDrop = nullptr;
2595     for (const auto &InsPair : RhsDeps) {
2596       if (!ShouldCountInsn(InsPair.first)) {
2597         ToDrop = InsPair.first;
2598         break;
2599       }
2600     }
2601     if (ToDrop == nullptr)
2602       break;
2603     RhsDeps.erase(ToDrop);
2604   }
2605 
2606   for (const auto &InsPair : RhsDeps) {
2607     // Finally accumulate latency that we can only attribute to computing the
2608     // RHS condition. Use latency because we are essentially trying to calculate
2609     // the cost of the dependency chain.
2610     // Possible TODO: We could try to estimate ILP and make this more precise.
2611     CostOfIncluding +=
2612         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2613 
2614     if (CostOfIncluding > CostThresh)
2615       return false;
2616   }
2617   return true;
2618 }
2619 
2620 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2621                                                MachineBasicBlock *TBB,
2622                                                MachineBasicBlock *FBB,
2623                                                MachineBasicBlock *CurBB,
2624                                                MachineBasicBlock *SwitchBB,
2625                                                Instruction::BinaryOps Opc,
2626                                                BranchProbability TProb,
2627                                                BranchProbability FProb,
2628                                                bool InvertCond) {
2629   // Skip over not part of the tree and remember to invert op and operands at
2630   // next level.
2631   Value *NotCond;
2632   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2633       InBlock(NotCond, CurBB->getBasicBlock())) {
2634     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2635                          !InvertCond);
2636     return;
2637   }
2638 
2639   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2640   const Value *BOpOp0, *BOpOp1;
2641   // Compute the effective opcode for Cond, taking into account whether it needs
2642   // to be inverted, e.g.
2643   //   and (not (or A, B)), C
2644   // gets lowered as
2645   //   and (and (not A, not B), C)
2646   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2647   if (BOp) {
2648     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2649                ? Instruction::And
2650                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2651                       ? Instruction::Or
2652                       : (Instruction::BinaryOps)0);
2653     if (InvertCond) {
2654       if (BOpc == Instruction::And)
2655         BOpc = Instruction::Or;
2656       else if (BOpc == Instruction::Or)
2657         BOpc = Instruction::And;
2658     }
2659   }
2660 
2661   // If this node is not part of the or/and tree, emit it as a branch.
2662   // Note that all nodes in the tree should have same opcode.
2663   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2664   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2665       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2666       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2667     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2668                                  TProb, FProb, InvertCond);
2669     return;
2670   }
2671 
2672   //  Create TmpBB after CurBB.
2673   MachineFunction::iterator BBI(CurBB);
2674   MachineFunction &MF = DAG.getMachineFunction();
2675   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2676   CurBB->getParent()->insert(++BBI, TmpBB);
2677 
2678   if (Opc == Instruction::Or) {
2679     // Codegen X | Y as:
2680     // BB1:
2681     //   jmp_if_X TBB
2682     //   jmp TmpBB
2683     // TmpBB:
2684     //   jmp_if_Y TBB
2685     //   jmp FBB
2686     //
2687 
2688     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2689     // The requirement is that
2690     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2691     //     = TrueProb for original BB.
2692     // Assuming the original probabilities are A and B, one choice is to set
2693     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2694     // A/(1+B) and 2B/(1+B). This choice assumes that
2695     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2696     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2697     // TmpBB, but the math is more complicated.
2698 
2699     auto NewTrueProb = TProb / 2;
2700     auto NewFalseProb = TProb / 2 + FProb;
2701     // Emit the LHS condition.
2702     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2703                          NewFalseProb, InvertCond);
2704 
2705     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2706     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2707     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2708     // Emit the RHS condition into TmpBB.
2709     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2710                          Probs[1], InvertCond);
2711   } else {
2712     assert(Opc == Instruction::And && "Unknown merge op!");
2713     // Codegen X & Y as:
2714     // BB1:
2715     //   jmp_if_X TmpBB
2716     //   jmp FBB
2717     // TmpBB:
2718     //   jmp_if_Y TBB
2719     //   jmp FBB
2720     //
2721     //  This requires creation of TmpBB after CurBB.
2722 
2723     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2724     // The requirement is that
2725     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2726     //     = FalseProb for original BB.
2727     // Assuming the original probabilities are A and B, one choice is to set
2728     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2729     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2730     // TrueProb for BB1 * FalseProb for TmpBB.
2731 
2732     auto NewTrueProb = TProb + FProb / 2;
2733     auto NewFalseProb = FProb / 2;
2734     // Emit the LHS condition.
2735     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2736                          NewFalseProb, InvertCond);
2737 
2738     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2739     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2740     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2741     // Emit the RHS condition into TmpBB.
2742     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2743                          Probs[1], InvertCond);
2744   }
2745 }
2746 
2747 /// If the set of cases should be emitted as a series of branches, return true.
2748 /// If we should emit this as a bunch of and/or'd together conditions, return
2749 /// false.
2750 bool
2751 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2752   if (Cases.size() != 2) return true;
2753 
2754   // If this is two comparisons of the same values or'd or and'd together, they
2755   // will get folded into a single comparison, so don't emit two blocks.
2756   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2757        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2758       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2759        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2760     return false;
2761   }
2762 
2763   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2764   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2765   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2766       Cases[0].CC == Cases[1].CC &&
2767       isa<Constant>(Cases[0].CmpRHS) &&
2768       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2769     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2770       return false;
2771     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2772       return false;
2773   }
2774 
2775   return true;
2776 }
2777 
2778 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2779   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2780 
2781   // Update machine-CFG edges.
2782   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2783 
2784   if (I.isUnconditional()) {
2785     // Update machine-CFG edges.
2786     BrMBB->addSuccessor(Succ0MBB);
2787 
2788     // If this is not a fall-through branch or optimizations are switched off,
2789     // emit the branch.
2790     if (Succ0MBB != NextBlock(BrMBB) ||
2791         TM.getOptLevel() == CodeGenOptLevel::None) {
2792       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2793                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2794       setValue(&I, Br);
2795       DAG.setRoot(Br);
2796     }
2797 
2798     return;
2799   }
2800 
2801   // If this condition is one of the special cases we handle, do special stuff
2802   // now.
2803   const Value *CondVal = I.getCondition();
2804   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2805 
2806   // If this is a series of conditions that are or'd or and'd together, emit
2807   // this as a sequence of branches instead of setcc's with and/or operations.
2808   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2809   // unpredictable branches, and vector extracts because those jumps are likely
2810   // expensive for any target), this should improve performance.
2811   // For example, instead of something like:
2812   //     cmp A, B
2813   //     C = seteq
2814   //     cmp D, E
2815   //     F = setle
2816   //     or C, F
2817   //     jnz foo
2818   // Emit:
2819   //     cmp A, B
2820   //     je foo
2821   //     cmp D, E
2822   //     jle foo
2823   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2824   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2825       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2826     Value *Vec;
2827     const Value *BOp0, *BOp1;
2828     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2829     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2830       Opcode = Instruction::And;
2831     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::Or;
2833 
2834     if (Opcode &&
2835         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2836           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2837         !shouldKeepJumpConditionsTogether(
2838             FuncInfo, I, Opcode, BOp0, BOp1,
2839             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2840                 Opcode, BOp0, BOp1))) {
2841       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2842                            getEdgeProbability(BrMBB, Succ0MBB),
2843                            getEdgeProbability(BrMBB, Succ1MBB),
2844                            /*InvertCond=*/false);
2845       // If the compares in later blocks need to use values not currently
2846       // exported from this block, export them now.  This block should always
2847       // be the first entry.
2848       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2849 
2850       // Allow some cases to be rejected.
2851       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2852         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2854           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2855         }
2856 
2857         // Emit the branch for this block.
2858         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2859         SL->SwitchCases.erase(SL->SwitchCases.begin());
2860         return;
2861       }
2862 
2863       // Okay, we decided not to do this, remove any inserted MBB's and clear
2864       // SwitchCases.
2865       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2866         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2867 
2868       SL->SwitchCases.clear();
2869     }
2870   }
2871 
2872   // Create a CaseBlock record representing this branch.
2873   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2874                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2875 
2876   // Use visitSwitchCase to actually insert the fast branch sequence for this
2877   // cond branch.
2878   visitSwitchCase(CB, BrMBB);
2879 }
2880 
2881 /// visitSwitchCase - Emits the necessary code to represent a single node in
2882 /// the binary search tree resulting from lowering a switch instruction.
2883 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2884                                           MachineBasicBlock *SwitchBB) {
2885   SDValue Cond;
2886   SDValue CondLHS = getValue(CB.CmpLHS);
2887   SDLoc dl = CB.DL;
2888 
2889   if (CB.CC == ISD::SETTRUE) {
2890     // Branch or fall through to TrueBB.
2891     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2892     SwitchBB->normalizeSuccProbs();
2893     if (CB.TrueBB != NextBlock(SwitchBB)) {
2894       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2895                               DAG.getBasicBlock(CB.TrueBB)));
2896     }
2897     return;
2898   }
2899 
2900   auto &TLI = DAG.getTargetLoweringInfo();
2901   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2902 
2903   // Build the setcc now.
2904   if (!CB.CmpMHS) {
2905     // Fold "(X == true)" to X and "(X == false)" to !X to
2906     // handle common cases produced by branch lowering.
2907     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2908         CB.CC == ISD::SETEQ)
2909       Cond = CondLHS;
2910     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2911              CB.CC == ISD::SETEQ) {
2912       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2913       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2914     } else {
2915       SDValue CondRHS = getValue(CB.CmpRHS);
2916 
2917       // If a pointer's DAG type is larger than its memory type then the DAG
2918       // values are zero-extended. This breaks signed comparisons so truncate
2919       // back to the underlying type before doing the compare.
2920       if (CondLHS.getValueType() != MemVT) {
2921         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2922         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2923       }
2924       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2925     }
2926   } else {
2927     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2928 
2929     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2930     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2931 
2932     SDValue CmpOp = getValue(CB.CmpMHS);
2933     EVT VT = CmpOp.getValueType();
2934 
2935     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2936       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2937                           ISD::SETLE);
2938     } else {
2939       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2940                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2941       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2942                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2943     }
2944   }
2945 
2946   // Update successor info
2947   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2948   // TrueBB and FalseBB are always different unless the incoming IR is
2949   // degenerate. This only happens when running llc on weird IR.
2950   if (CB.TrueBB != CB.FalseBB)
2951     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2952   SwitchBB->normalizeSuccProbs();
2953 
2954   // If the lhs block is the next block, invert the condition so that we can
2955   // fall through to the lhs instead of the rhs block.
2956   if (CB.TrueBB == NextBlock(SwitchBB)) {
2957     std::swap(CB.TrueBB, CB.FalseBB);
2958     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2959     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2960   }
2961 
2962   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2963                                MVT::Other, getControlRoot(), Cond,
2964                                DAG.getBasicBlock(CB.TrueBB));
2965 
2966   setValue(CurInst, BrCond);
2967 
2968   // Insert the false branch. Do this even if it's a fall through branch,
2969   // this makes it easier to do DAG optimizations which require inverting
2970   // the branch condition.
2971   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2972                        DAG.getBasicBlock(CB.FalseBB));
2973 
2974   DAG.setRoot(BrCond);
2975 }
2976 
2977 /// visitJumpTable - Emit JumpTable node in the current MBB
2978 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2979   // Emit the code for the jump table
2980   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2981   assert(JT.Reg != -1U && "Should lower JT Header first!");
2982   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2983   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2984   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2985   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2986                                     Index.getValue(1), Table, Index);
2987   DAG.setRoot(BrJumpTable);
2988 }
2989 
2990 /// visitJumpTableHeader - This function emits necessary code to produce index
2991 /// in the JumpTable from switch case.
2992 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2993                                                JumpTableHeader &JTH,
2994                                                MachineBasicBlock *SwitchBB) {
2995   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2996   const SDLoc &dl = *JT.SL;
2997 
2998   // Subtract the lowest switch case value from the value being switched on.
2999   SDValue SwitchOp = getValue(JTH.SValue);
3000   EVT VT = SwitchOp.getValueType();
3001   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3002                             DAG.getConstant(JTH.First, dl, VT));
3003 
3004   // The SDNode we just created, which holds the value being switched on minus
3005   // the smallest case value, needs to be copied to a virtual register so it
3006   // can be used as an index into the jump table in a subsequent basic block.
3007   // This value may be smaller or larger than the target's pointer type, and
3008   // therefore require extension or truncating.
3009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3010   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
3011 
3012   unsigned JumpTableReg =
3013       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
3014   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
3015                                     JumpTableReg, SwitchOp);
3016   JT.Reg = JumpTableReg;
3017 
3018   if (!JTH.FallthroughUnreachable) {
3019     // Emit the range check for the jump table, and branch to the default block
3020     // for the switch statement if the value being switched on exceeds the
3021     // largest case in the switch.
3022     SDValue CMP = DAG.getSetCC(
3023         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3024                                    Sub.getValueType()),
3025         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3026 
3027     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3028                                  MVT::Other, CopyTo, CMP,
3029                                  DAG.getBasicBlock(JT.Default));
3030 
3031     // Avoid emitting unnecessary branches to the next block.
3032     if (JT.MBB != NextBlock(SwitchBB))
3033       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3034                            DAG.getBasicBlock(JT.MBB));
3035 
3036     DAG.setRoot(BrCond);
3037   } else {
3038     // Avoid emitting unnecessary branches to the next block.
3039     if (JT.MBB != NextBlock(SwitchBB))
3040       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3041                               DAG.getBasicBlock(JT.MBB)));
3042     else
3043       DAG.setRoot(CopyTo);
3044   }
3045 }
3046 
3047 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3048 /// variable if there exists one.
3049 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3050                                  SDValue &Chain) {
3051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3052   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3053   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3054   MachineFunction &MF = DAG.getMachineFunction();
3055   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3056   MachineSDNode *Node =
3057       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3058   if (Global) {
3059     MachinePointerInfo MPInfo(Global);
3060     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3061                  MachineMemOperand::MODereferenceable;
3062     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3063         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3064         DAG.getEVTAlign(PtrTy));
3065     DAG.setNodeMemRefs(Node, {MemRef});
3066   }
3067   if (PtrTy != PtrMemTy)
3068     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3069   return SDValue(Node, 0);
3070 }
3071 
3072 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3073 /// tail spliced into a stack protector check success bb.
3074 ///
3075 /// For a high level explanation of how this fits into the stack protector
3076 /// generation see the comment on the declaration of class
3077 /// StackProtectorDescriptor.
3078 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3079                                                   MachineBasicBlock *ParentBB) {
3080 
3081   // First create the loads to the guard/stack slot for the comparison.
3082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3083   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3084   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3085 
3086   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3087   int FI = MFI.getStackProtectorIndex();
3088 
3089   SDValue Guard;
3090   SDLoc dl = getCurSDLoc();
3091   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3092   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3093   Align Align =
3094       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3095 
3096   // Generate code to load the content of the guard slot.
3097   SDValue GuardVal = DAG.getLoad(
3098       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3099       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3100       MachineMemOperand::MOVolatile);
3101 
3102   if (TLI.useStackGuardXorFP())
3103     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3104 
3105   // Retrieve guard check function, nullptr if instrumentation is inlined.
3106   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3107     // The target provides a guard check function to validate the guard value.
3108     // Generate a call to that function with the content of the guard slot as
3109     // argument.
3110     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3111     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3112 
3113     TargetLowering::ArgListTy Args;
3114     TargetLowering::ArgListEntry Entry;
3115     Entry.Node = GuardVal;
3116     Entry.Ty = FnTy->getParamType(0);
3117     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3118       Entry.IsInReg = true;
3119     Args.push_back(Entry);
3120 
3121     TargetLowering::CallLoweringInfo CLI(DAG);
3122     CLI.setDebugLoc(getCurSDLoc())
3123         .setChain(DAG.getEntryNode())
3124         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3125                    getValue(GuardCheckFn), std::move(Args));
3126 
3127     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3128     DAG.setRoot(Result.second);
3129     return;
3130   }
3131 
3132   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3133   // Otherwise, emit a volatile load to retrieve the stack guard value.
3134   SDValue Chain = DAG.getEntryNode();
3135   if (TLI.useLoadStackGuardNode()) {
3136     Guard = getLoadStackGuard(DAG, dl, Chain);
3137   } else {
3138     const Value *IRGuard = TLI.getSDagStackGuard(M);
3139     SDValue GuardPtr = getValue(IRGuard);
3140 
3141     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3142                         MachinePointerInfo(IRGuard, 0), Align,
3143                         MachineMemOperand::MOVolatile);
3144   }
3145 
3146   // Perform the comparison via a getsetcc.
3147   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3148                                                         *DAG.getContext(),
3149                                                         Guard.getValueType()),
3150                              Guard, GuardVal, ISD::SETNE);
3151 
3152   // If the guard/stackslot do not equal, branch to failure MBB.
3153   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3154                                MVT::Other, GuardVal.getOperand(0),
3155                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3156   // Otherwise branch to success MBB.
3157   SDValue Br = DAG.getNode(ISD::BR, dl,
3158                            MVT::Other, BrCond,
3159                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3160 
3161   DAG.setRoot(Br);
3162 }
3163 
3164 /// Codegen the failure basic block for a stack protector check.
3165 ///
3166 /// A failure stack protector machine basic block consists simply of a call to
3167 /// __stack_chk_fail().
3168 ///
3169 /// For a high level explanation of how this fits into the stack protector
3170 /// generation see the comment on the declaration of class
3171 /// StackProtectorDescriptor.
3172 void
3173 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3175   TargetLowering::MakeLibCallOptions CallOptions;
3176   CallOptions.setDiscardResult(true);
3177   SDValue Chain =
3178       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3179                       std::nullopt, CallOptions, getCurSDLoc())
3180           .second;
3181   // On PS4/PS5, the "return address" must still be within the calling
3182   // function, even if it's at the very end, so emit an explicit TRAP here.
3183   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3184   if (TM.getTargetTriple().isPS())
3185     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3186   // WebAssembly needs an unreachable instruction after a non-returning call,
3187   // because the function return type can be different from __stack_chk_fail's
3188   // return type (void).
3189   if (TM.getTargetTriple().isWasm())
3190     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3191 
3192   DAG.setRoot(Chain);
3193 }
3194 
3195 /// visitBitTestHeader - This function emits necessary code to produce value
3196 /// suitable for "bit tests"
3197 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3198                                              MachineBasicBlock *SwitchBB) {
3199   SDLoc dl = getCurSDLoc();
3200 
3201   // Subtract the minimum value.
3202   SDValue SwitchOp = getValue(B.SValue);
3203   EVT VT = SwitchOp.getValueType();
3204   SDValue RangeSub =
3205       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3206 
3207   // Determine the type of the test operands.
3208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3209   bool UsePtrType = false;
3210   if (!TLI.isTypeLegal(VT)) {
3211     UsePtrType = true;
3212   } else {
3213     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3214       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3215         // Switch table case range are encoded into series of masks.
3216         // Just use pointer type, it's guaranteed to fit.
3217         UsePtrType = true;
3218         break;
3219       }
3220   }
3221   SDValue Sub = RangeSub;
3222   if (UsePtrType) {
3223     VT = TLI.getPointerTy(DAG.getDataLayout());
3224     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3225   }
3226 
3227   B.RegVT = VT.getSimpleVT();
3228   B.Reg = FuncInfo.CreateReg(B.RegVT);
3229   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3230 
3231   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3232 
3233   if (!B.FallthroughUnreachable)
3234     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3235   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3236   SwitchBB->normalizeSuccProbs();
3237 
3238   SDValue Root = CopyTo;
3239   if (!B.FallthroughUnreachable) {
3240     // Conditional branch to the default block.
3241     SDValue RangeCmp = DAG.getSetCC(dl,
3242         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3243                                RangeSub.getValueType()),
3244         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3245         ISD::SETUGT);
3246 
3247     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3248                        DAG.getBasicBlock(B.Default));
3249   }
3250 
3251   // Avoid emitting unnecessary branches to the next block.
3252   if (MBB != NextBlock(SwitchBB))
3253     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3254 
3255   DAG.setRoot(Root);
3256 }
3257 
3258 /// visitBitTestCase - this function produces one "bit test"
3259 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3260                                            MachineBasicBlock* NextMBB,
3261                                            BranchProbability BranchProbToNext,
3262                                            unsigned Reg,
3263                                            BitTestCase &B,
3264                                            MachineBasicBlock *SwitchBB) {
3265   SDLoc dl = getCurSDLoc();
3266   MVT VT = BB.RegVT;
3267   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3268   SDValue Cmp;
3269   unsigned PopCount = llvm::popcount(B.Mask);
3270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3271   if (PopCount == 1) {
3272     // Testing for a single bit; just compare the shift count with what it
3273     // would need to be to shift a 1 bit in that position.
3274     Cmp = DAG.getSetCC(
3275         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3276         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3277         ISD::SETEQ);
3278   } else if (PopCount == BB.Range) {
3279     // There is only one zero bit in the range, test for it directly.
3280     Cmp = DAG.getSetCC(
3281         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3282         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3283   } else {
3284     // Make desired shift
3285     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3286                                     DAG.getConstant(1, dl, VT), ShiftOp);
3287 
3288     // Emit bit tests and jumps
3289     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3290                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3291     Cmp = DAG.getSetCC(
3292         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3293         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3294   }
3295 
3296   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3297   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3298   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3299   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3300   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3301   // one as they are relative probabilities (and thus work more like weights),
3302   // and hence we need to normalize them to let the sum of them become one.
3303   SwitchBB->normalizeSuccProbs();
3304 
3305   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3306                               MVT::Other, getControlRoot(),
3307                               Cmp, DAG.getBasicBlock(B.TargetBB));
3308 
3309   // Avoid emitting unnecessary branches to the next block.
3310   if (NextMBB != NextBlock(SwitchBB))
3311     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3312                         DAG.getBasicBlock(NextMBB));
3313 
3314   DAG.setRoot(BrAnd);
3315 }
3316 
3317 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3318   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3319 
3320   // Retrieve successors. Look through artificial IR level blocks like
3321   // catchswitch for successors.
3322   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3323   const BasicBlock *EHPadBB = I.getSuccessor(1);
3324   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3325 
3326   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3327   // have to do anything here to lower funclet bundles.
3328   assert(!I.hasOperandBundlesOtherThan(
3329              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3330               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3331               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3332               LLVMContext::OB_clang_arc_attachedcall}) &&
3333          "Cannot lower invokes with arbitrary operand bundles yet!");
3334 
3335   const Value *Callee(I.getCalledOperand());
3336   const Function *Fn = dyn_cast<Function>(Callee);
3337   if (isa<InlineAsm>(Callee))
3338     visitInlineAsm(I, EHPadBB);
3339   else if (Fn && Fn->isIntrinsic()) {
3340     switch (Fn->getIntrinsicID()) {
3341     default:
3342       llvm_unreachable("Cannot invoke this intrinsic");
3343     case Intrinsic::donothing:
3344       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3345     case Intrinsic::seh_try_begin:
3346     case Intrinsic::seh_scope_begin:
3347     case Intrinsic::seh_try_end:
3348     case Intrinsic::seh_scope_end:
3349       if (EHPadMBB)
3350           // a block referenced by EH table
3351           // so dtor-funclet not removed by opts
3352           EHPadMBB->setMachineBlockAddressTaken();
3353       break;
3354     case Intrinsic::experimental_patchpoint_void:
3355     case Intrinsic::experimental_patchpoint:
3356       visitPatchpoint(I, EHPadBB);
3357       break;
3358     case Intrinsic::experimental_gc_statepoint:
3359       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3360       break;
3361     case Intrinsic::wasm_rethrow: {
3362       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3363       // special because it can be invoked, so we manually lower it to a DAG
3364       // node here.
3365       SmallVector<SDValue, 8> Ops;
3366       Ops.push_back(getControlRoot()); // inchain for the terminator node
3367       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3368       Ops.push_back(
3369           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3370                                 TLI.getPointerTy(DAG.getDataLayout())));
3371       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3372       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3373       break;
3374     }
3375     }
3376   } else if (I.hasDeoptState()) {
3377     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3378     // Eventually we will support lowering the @llvm.experimental.deoptimize
3379     // intrinsic, and right now there are no plans to support other intrinsics
3380     // with deopt state.
3381     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3382   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3383     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3384   } else {
3385     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3386   }
3387 
3388   // If the value of the invoke is used outside of its defining block, make it
3389   // available as a virtual register.
3390   // We already took care of the exported value for the statepoint instruction
3391   // during call to the LowerStatepoint.
3392   if (!isa<GCStatepointInst>(I)) {
3393     CopyToExportRegsIfNeeded(&I);
3394   }
3395 
3396   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3397   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3398   BranchProbability EHPadBBProb =
3399       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3400           : BranchProbability::getZero();
3401   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3402 
3403   // Update successor info.
3404   addSuccessorWithProb(InvokeMBB, Return);
3405   for (auto &UnwindDest : UnwindDests) {
3406     UnwindDest.first->setIsEHPad();
3407     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3408   }
3409   InvokeMBB->normalizeSuccProbs();
3410 
3411   // Drop into normal successor.
3412   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3413                           DAG.getBasicBlock(Return)));
3414 }
3415 
3416 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3417   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3418 
3419   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3420   // have to do anything here to lower funclet bundles.
3421   assert(!I.hasOperandBundlesOtherThan(
3422              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3423          "Cannot lower callbrs with arbitrary operand bundles yet!");
3424 
3425   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3426   visitInlineAsm(I);
3427   CopyToExportRegsIfNeeded(&I);
3428 
3429   // Retrieve successors.
3430   SmallPtrSet<BasicBlock *, 8> Dests;
3431   Dests.insert(I.getDefaultDest());
3432   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3433 
3434   // Update successor info.
3435   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3436   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3437     BasicBlock *Dest = I.getIndirectDest(i);
3438     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3439     Target->setIsInlineAsmBrIndirectTarget();
3440     Target->setMachineBlockAddressTaken();
3441     Target->setLabelMustBeEmitted();
3442     // Don't add duplicate machine successors.
3443     if (Dests.insert(Dest).second)
3444       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3445   }
3446   CallBrMBB->normalizeSuccProbs();
3447 
3448   // Drop into default successor.
3449   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3450                           MVT::Other, getControlRoot(),
3451                           DAG.getBasicBlock(Return)));
3452 }
3453 
3454 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3455   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3456 }
3457 
3458 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3459   assert(FuncInfo.MBB->isEHPad() &&
3460          "Call to landingpad not in landing pad!");
3461 
3462   // If there aren't registers to copy the values into (e.g., during SjLj
3463   // exceptions), then don't bother to create these DAG nodes.
3464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3465   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3466   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3467       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3468     return;
3469 
3470   // If landingpad's return type is token type, we don't create DAG nodes
3471   // for its exception pointer and selector value. The extraction of exception
3472   // pointer or selector value from token type landingpads is not currently
3473   // supported.
3474   if (LP.getType()->isTokenTy())
3475     return;
3476 
3477   SmallVector<EVT, 2> ValueVTs;
3478   SDLoc dl = getCurSDLoc();
3479   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3480   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3481 
3482   // Get the two live-in registers as SDValues. The physregs have already been
3483   // copied into virtual registers.
3484   SDValue Ops[2];
3485   if (FuncInfo.ExceptionPointerVirtReg) {
3486     Ops[0] = DAG.getZExtOrTrunc(
3487         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3488                            FuncInfo.ExceptionPointerVirtReg,
3489                            TLI.getPointerTy(DAG.getDataLayout())),
3490         dl, ValueVTs[0]);
3491   } else {
3492     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3493   }
3494   Ops[1] = DAG.getZExtOrTrunc(
3495       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3496                          FuncInfo.ExceptionSelectorVirtReg,
3497                          TLI.getPointerTy(DAG.getDataLayout())),
3498       dl, ValueVTs[1]);
3499 
3500   // Merge into one.
3501   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3502                             DAG.getVTList(ValueVTs), Ops);
3503   setValue(&LP, Res);
3504 }
3505 
3506 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3507                                            MachineBasicBlock *Last) {
3508   // Update JTCases.
3509   for (JumpTableBlock &JTB : SL->JTCases)
3510     if (JTB.first.HeaderBB == First)
3511       JTB.first.HeaderBB = Last;
3512 
3513   // Update BitTestCases.
3514   for (BitTestBlock &BTB : SL->BitTestCases)
3515     if (BTB.Parent == First)
3516       BTB.Parent = Last;
3517 }
3518 
3519 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3520   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3521 
3522   // Update machine-CFG edges with unique successors.
3523   SmallSet<BasicBlock*, 32> Done;
3524   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3525     BasicBlock *BB = I.getSuccessor(i);
3526     bool Inserted = Done.insert(BB).second;
3527     if (!Inserted)
3528         continue;
3529 
3530     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3531     addSuccessorWithProb(IndirectBrMBB, Succ);
3532   }
3533   IndirectBrMBB->normalizeSuccProbs();
3534 
3535   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3536                           MVT::Other, getControlRoot(),
3537                           getValue(I.getAddress())));
3538 }
3539 
3540 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3541   if (!DAG.getTarget().Options.TrapUnreachable)
3542     return;
3543 
3544   // We may be able to ignore unreachable behind a noreturn call.
3545   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3546       Call && Call->doesNotReturn()) {
3547     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3548       return;
3549     // Do not emit an additional trap instruction.
3550     if (Call->isNonContinuableTrap())
3551       return;
3552   }
3553 
3554   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3555 }
3556 
3557 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3558   SDNodeFlags Flags;
3559   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3560     Flags.copyFMF(*FPOp);
3561 
3562   SDValue Op = getValue(I.getOperand(0));
3563   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3564                                     Op, Flags);
3565   setValue(&I, UnNodeValue);
3566 }
3567 
3568 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3569   SDNodeFlags Flags;
3570   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3571     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3572     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3573   }
3574   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3575     Flags.setExact(ExactOp->isExact());
3576   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3577     Flags.setDisjoint(DisjointOp->isDisjoint());
3578   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3579     Flags.copyFMF(*FPOp);
3580 
3581   SDValue Op1 = getValue(I.getOperand(0));
3582   SDValue Op2 = getValue(I.getOperand(1));
3583   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3584                                      Op1, Op2, Flags);
3585   setValue(&I, BinNodeValue);
3586 }
3587 
3588 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3589   SDValue Op1 = getValue(I.getOperand(0));
3590   SDValue Op2 = getValue(I.getOperand(1));
3591 
3592   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3593       Op1.getValueType(), DAG.getDataLayout());
3594 
3595   // Coerce the shift amount to the right type if we can. This exposes the
3596   // truncate or zext to optimization early.
3597   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3598     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3599            "Unexpected shift type");
3600     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3601   }
3602 
3603   bool nuw = false;
3604   bool nsw = false;
3605   bool exact = false;
3606 
3607   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3608 
3609     if (const OverflowingBinaryOperator *OFBinOp =
3610             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3611       nuw = OFBinOp->hasNoUnsignedWrap();
3612       nsw = OFBinOp->hasNoSignedWrap();
3613     }
3614     if (const PossiblyExactOperator *ExactOp =
3615             dyn_cast<const PossiblyExactOperator>(&I))
3616       exact = ExactOp->isExact();
3617   }
3618   SDNodeFlags Flags;
3619   Flags.setExact(exact);
3620   Flags.setNoSignedWrap(nsw);
3621   Flags.setNoUnsignedWrap(nuw);
3622   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3623                             Flags);
3624   setValue(&I, Res);
3625 }
3626 
3627 void SelectionDAGBuilder::visitSDiv(const User &I) {
3628   SDValue Op1 = getValue(I.getOperand(0));
3629   SDValue Op2 = getValue(I.getOperand(1));
3630 
3631   SDNodeFlags Flags;
3632   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3633                  cast<PossiblyExactOperator>(&I)->isExact());
3634   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3635                            Op2, Flags));
3636 }
3637 
3638 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3639   ICmpInst::Predicate predicate = I.getPredicate();
3640   SDValue Op1 = getValue(I.getOperand(0));
3641   SDValue Op2 = getValue(I.getOperand(1));
3642   ISD::CondCode Opcode = getICmpCondCode(predicate);
3643 
3644   auto &TLI = DAG.getTargetLoweringInfo();
3645   EVT MemVT =
3646       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3647 
3648   // If a pointer's DAG type is larger than its memory type then the DAG values
3649   // are zero-extended. This breaks signed comparisons so truncate back to the
3650   // underlying type before doing the compare.
3651   if (Op1.getValueType() != MemVT) {
3652     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3653     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3654   }
3655 
3656   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3657                                                         I.getType());
3658   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3659 }
3660 
3661 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3662   FCmpInst::Predicate predicate = I.getPredicate();
3663   SDValue Op1 = getValue(I.getOperand(0));
3664   SDValue Op2 = getValue(I.getOperand(1));
3665 
3666   ISD::CondCode Condition = getFCmpCondCode(predicate);
3667   auto *FPMO = cast<FPMathOperator>(&I);
3668   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3669     Condition = getFCmpCodeWithoutNaN(Condition);
3670 
3671   SDNodeFlags Flags;
3672   Flags.copyFMF(*FPMO);
3673   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3674 
3675   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3676                                                         I.getType());
3677   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3678 }
3679 
3680 // Check if the condition of the select has one use or two users that are both
3681 // selects with the same condition.
3682 static bool hasOnlySelectUsers(const Value *Cond) {
3683   return llvm::all_of(Cond->users(), [](const Value *V) {
3684     return isa<SelectInst>(V);
3685   });
3686 }
3687 
3688 void SelectionDAGBuilder::visitSelect(const User &I) {
3689   SmallVector<EVT, 4> ValueVTs;
3690   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3691                   ValueVTs);
3692   unsigned NumValues = ValueVTs.size();
3693   if (NumValues == 0) return;
3694 
3695   SmallVector<SDValue, 4> Values(NumValues);
3696   SDValue Cond     = getValue(I.getOperand(0));
3697   SDValue LHSVal   = getValue(I.getOperand(1));
3698   SDValue RHSVal   = getValue(I.getOperand(2));
3699   SmallVector<SDValue, 1> BaseOps(1, Cond);
3700   ISD::NodeType OpCode =
3701       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3702 
3703   bool IsUnaryAbs = false;
3704   bool Negate = false;
3705 
3706   SDNodeFlags Flags;
3707   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3708     Flags.copyFMF(*FPOp);
3709 
3710   Flags.setUnpredictable(
3711       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3712 
3713   // Min/max matching is only viable if all output VTs are the same.
3714   if (all_equal(ValueVTs)) {
3715     EVT VT = ValueVTs[0];
3716     LLVMContext &Ctx = *DAG.getContext();
3717     auto &TLI = DAG.getTargetLoweringInfo();
3718 
3719     // We care about the legality of the operation after it has been type
3720     // legalized.
3721     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3722       VT = TLI.getTypeToTransformTo(Ctx, VT);
3723 
3724     // If the vselect is legal, assume we want to leave this as a vector setcc +
3725     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3726     // min/max is legal on the scalar type.
3727     bool UseScalarMinMax = VT.isVector() &&
3728       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3729 
3730     // ValueTracking's select pattern matching does not account for -0.0,
3731     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3732     // -0.0 is less than +0.0.
3733     Value *LHS, *RHS;
3734     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3735     ISD::NodeType Opc = ISD::DELETED_NODE;
3736     switch (SPR.Flavor) {
3737     case SPF_UMAX:    Opc = ISD::UMAX; break;
3738     case SPF_UMIN:    Opc = ISD::UMIN; break;
3739     case SPF_SMAX:    Opc = ISD::SMAX; break;
3740     case SPF_SMIN:    Opc = ISD::SMIN; break;
3741     case SPF_FMINNUM:
3742       switch (SPR.NaNBehavior) {
3743       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3744       case SPNB_RETURNS_NAN: break;
3745       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3746       case SPNB_RETURNS_ANY:
3747         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3748             (UseScalarMinMax &&
3749              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3750           Opc = ISD::FMINNUM;
3751         break;
3752       }
3753       break;
3754     case SPF_FMAXNUM:
3755       switch (SPR.NaNBehavior) {
3756       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3757       case SPNB_RETURNS_NAN: break;
3758       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3759       case SPNB_RETURNS_ANY:
3760         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3761             (UseScalarMinMax &&
3762              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3763           Opc = ISD::FMAXNUM;
3764         break;
3765       }
3766       break;
3767     case SPF_NABS:
3768       Negate = true;
3769       [[fallthrough]];
3770     case SPF_ABS:
3771       IsUnaryAbs = true;
3772       Opc = ISD::ABS;
3773       break;
3774     default: break;
3775     }
3776 
3777     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3778         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3779          (UseScalarMinMax &&
3780           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3781         // If the underlying comparison instruction is used by any other
3782         // instruction, the consumed instructions won't be destroyed, so it is
3783         // not profitable to convert to a min/max.
3784         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3785       OpCode = Opc;
3786       LHSVal = getValue(LHS);
3787       RHSVal = getValue(RHS);
3788       BaseOps.clear();
3789     }
3790 
3791     if (IsUnaryAbs) {
3792       OpCode = Opc;
3793       LHSVal = getValue(LHS);
3794       BaseOps.clear();
3795     }
3796   }
3797 
3798   if (IsUnaryAbs) {
3799     for (unsigned i = 0; i != NumValues; ++i) {
3800       SDLoc dl = getCurSDLoc();
3801       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3802       Values[i] =
3803           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3804       if (Negate)
3805         Values[i] = DAG.getNegative(Values[i], dl, VT);
3806     }
3807   } else {
3808     for (unsigned i = 0; i != NumValues; ++i) {
3809       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3810       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3811       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3812       Values[i] = DAG.getNode(
3813           OpCode, getCurSDLoc(),
3814           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3815     }
3816   }
3817 
3818   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3819                            DAG.getVTList(ValueVTs), Values));
3820 }
3821 
3822 void SelectionDAGBuilder::visitTrunc(const User &I) {
3823   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3824   SDValue N = getValue(I.getOperand(0));
3825   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3826                                                         I.getType());
3827   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3828 }
3829 
3830 void SelectionDAGBuilder::visitZExt(const User &I) {
3831   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3832   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3833   SDValue N = getValue(I.getOperand(0));
3834   auto &TLI = DAG.getTargetLoweringInfo();
3835   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3836 
3837   SDNodeFlags Flags;
3838   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3839     Flags.setNonNeg(PNI->hasNonNeg());
3840 
3841   // Eagerly use nonneg information to canonicalize towards sign_extend if
3842   // that is the target's preference.
3843   // TODO: Let the target do this later.
3844   if (Flags.hasNonNeg() &&
3845       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3846     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3847     return;
3848   }
3849 
3850   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3851 }
3852 
3853 void SelectionDAGBuilder::visitSExt(const User &I) {
3854   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3855   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3856   SDValue N = getValue(I.getOperand(0));
3857   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3858                                                         I.getType());
3859   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3860 }
3861 
3862 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3863   // FPTrunc is never a no-op cast, no need to check
3864   SDValue N = getValue(I.getOperand(0));
3865   SDLoc dl = getCurSDLoc();
3866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3867   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3868   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3869                            DAG.getTargetConstant(
3870                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3871 }
3872 
3873 void SelectionDAGBuilder::visitFPExt(const User &I) {
3874   // FPExt is never a no-op cast, no need to check
3875   SDValue N = getValue(I.getOperand(0));
3876   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3877                                                         I.getType());
3878   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3879 }
3880 
3881 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3882   // FPToUI is never a no-op cast, no need to check
3883   SDValue N = getValue(I.getOperand(0));
3884   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3885                                                         I.getType());
3886   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3887 }
3888 
3889 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3890   // FPToSI is never a no-op cast, no need to check
3891   SDValue N = getValue(I.getOperand(0));
3892   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3893                                                         I.getType());
3894   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3895 }
3896 
3897 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3898   // UIToFP is never a no-op cast, no need to check
3899   SDValue N = getValue(I.getOperand(0));
3900   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3901                                                         I.getType());
3902   SDNodeFlags Flags;
3903   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3904     Flags.setNonNeg(PNI->hasNonNeg());
3905 
3906   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3907 }
3908 
3909 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3910   // SIToFP is never a no-op cast, no need to check
3911   SDValue N = getValue(I.getOperand(0));
3912   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3913                                                         I.getType());
3914   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3915 }
3916 
3917 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3918   // What to do depends on the size of the integer and the size of the pointer.
3919   // We can either truncate, zero extend, or no-op, accordingly.
3920   SDValue N = getValue(I.getOperand(0));
3921   auto &TLI = DAG.getTargetLoweringInfo();
3922   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3923                                                         I.getType());
3924   EVT PtrMemVT =
3925       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3926   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3927   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3928   setValue(&I, N);
3929 }
3930 
3931 void SelectionDAGBuilder::visitIntToPtr(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 = TLI.getValueType(DAG.getDataLayout(), I.getType());
3937   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3938   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3939   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3940   setValue(&I, N);
3941 }
3942 
3943 void SelectionDAGBuilder::visitBitCast(const User &I) {
3944   SDValue N = getValue(I.getOperand(0));
3945   SDLoc dl = getCurSDLoc();
3946   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3947                                                         I.getType());
3948 
3949   // BitCast assures us that source and destination are the same size so this is
3950   // either a BITCAST or a no-op.
3951   if (DestVT != N.getValueType())
3952     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3953                              DestVT, N)); // convert types.
3954   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3955   // might fold any kind of constant expression to an integer constant and that
3956   // is not what we are looking for. Only recognize a bitcast of a genuine
3957   // constant integer as an opaque constant.
3958   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3959     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3960                                  /*isOpaque*/true));
3961   else
3962     setValue(&I, N);            // noop cast.
3963 }
3964 
3965 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3967   const Value *SV = I.getOperand(0);
3968   SDValue N = getValue(SV);
3969   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3970 
3971   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3972   unsigned DestAS = I.getType()->getPointerAddressSpace();
3973 
3974   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3975     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3976 
3977   setValue(&I, N);
3978 }
3979 
3980 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3982   SDValue InVec = getValue(I.getOperand(0));
3983   SDValue InVal = getValue(I.getOperand(1));
3984   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3985                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3986   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3987                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3988                            InVec, InVal, InIdx));
3989 }
3990 
3991 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3993   SDValue InVec = getValue(I.getOperand(0));
3994   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3995                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3996   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3997                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3998                            InVec, InIdx));
3999 }
4000 
4001 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4002   SDValue Src1 = getValue(I.getOperand(0));
4003   SDValue Src2 = getValue(I.getOperand(1));
4004   ArrayRef<int> Mask;
4005   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4006     Mask = SVI->getShuffleMask();
4007   else
4008     Mask = cast<ConstantExpr>(I).getShuffleMask();
4009   SDLoc DL = getCurSDLoc();
4010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4011   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4012   EVT SrcVT = Src1.getValueType();
4013 
4014   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4015       VT.isScalableVector()) {
4016     // Canonical splat form of first element of first input vector.
4017     SDValue FirstElt =
4018         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4019                     DAG.getVectorIdxConstant(0, DL));
4020     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4021     return;
4022   }
4023 
4024   // For now, we only handle splats for scalable vectors.
4025   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4026   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4027   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4028 
4029   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4030   unsigned MaskNumElts = Mask.size();
4031 
4032   if (SrcNumElts == MaskNumElts) {
4033     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4034     return;
4035   }
4036 
4037   // Normalize the shuffle vector since mask and vector length don't match.
4038   if (SrcNumElts < MaskNumElts) {
4039     // Mask is longer than the source vectors. We can use concatenate vector to
4040     // make the mask and vectors lengths match.
4041 
4042     if (MaskNumElts % SrcNumElts == 0) {
4043       // Mask length is a multiple of the source vector length.
4044       // Check if the shuffle is some kind of concatenation of the input
4045       // vectors.
4046       unsigned NumConcat = MaskNumElts / SrcNumElts;
4047       bool IsConcat = true;
4048       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4049       for (unsigned i = 0; i != MaskNumElts; ++i) {
4050         int Idx = Mask[i];
4051         if (Idx < 0)
4052           continue;
4053         // Ensure the indices in each SrcVT sized piece are sequential and that
4054         // the same source is used for the whole piece.
4055         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4056             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4057              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4058           IsConcat = false;
4059           break;
4060         }
4061         // Remember which source this index came from.
4062         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4063       }
4064 
4065       // The shuffle is concatenating multiple vectors together. Just emit
4066       // a CONCAT_VECTORS operation.
4067       if (IsConcat) {
4068         SmallVector<SDValue, 8> ConcatOps;
4069         for (auto Src : ConcatSrcs) {
4070           if (Src < 0)
4071             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4072           else if (Src == 0)
4073             ConcatOps.push_back(Src1);
4074           else
4075             ConcatOps.push_back(Src2);
4076         }
4077         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4078         return;
4079       }
4080     }
4081 
4082     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4083     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4084     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4085                                     PaddedMaskNumElts);
4086 
4087     // Pad both vectors with undefs to make them the same length as the mask.
4088     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4089 
4090     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4091     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4092     MOps1[0] = Src1;
4093     MOps2[0] = Src2;
4094 
4095     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4096     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4097 
4098     // Readjust mask for new input vector length.
4099     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4100     for (unsigned i = 0; i != MaskNumElts; ++i) {
4101       int Idx = Mask[i];
4102       if (Idx >= (int)SrcNumElts)
4103         Idx -= SrcNumElts - PaddedMaskNumElts;
4104       MappedOps[i] = Idx;
4105     }
4106 
4107     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4108 
4109     // If the concatenated vector was padded, extract a subvector with the
4110     // correct number of elements.
4111     if (MaskNumElts != PaddedMaskNumElts)
4112       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4113                            DAG.getVectorIdxConstant(0, DL));
4114 
4115     setValue(&I, Result);
4116     return;
4117   }
4118 
4119   if (SrcNumElts > MaskNumElts) {
4120     // Analyze the access pattern of the vector to see if we can extract
4121     // two subvectors and do the shuffle.
4122     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4123     bool CanExtract = true;
4124     for (int Idx : Mask) {
4125       unsigned Input = 0;
4126       if (Idx < 0)
4127         continue;
4128 
4129       if (Idx >= (int)SrcNumElts) {
4130         Input = 1;
4131         Idx -= SrcNumElts;
4132       }
4133 
4134       // If all the indices come from the same MaskNumElts sized portion of
4135       // the sources we can use extract. Also make sure the extract wouldn't
4136       // extract past the end of the source.
4137       int NewStartIdx = alignDown(Idx, MaskNumElts);
4138       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4139           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4140         CanExtract = false;
4141       // Make sure we always update StartIdx as we use it to track if all
4142       // elements are undef.
4143       StartIdx[Input] = NewStartIdx;
4144     }
4145 
4146     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4147       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4148       return;
4149     }
4150     if (CanExtract) {
4151       // Extract appropriate subvector and generate a vector shuffle
4152       for (unsigned Input = 0; Input < 2; ++Input) {
4153         SDValue &Src = Input == 0 ? Src1 : Src2;
4154         if (StartIdx[Input] < 0)
4155           Src = DAG.getUNDEF(VT);
4156         else {
4157           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4158                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4159         }
4160       }
4161 
4162       // Calculate new mask.
4163       SmallVector<int, 8> MappedOps(Mask);
4164       for (int &Idx : MappedOps) {
4165         if (Idx >= (int)SrcNumElts)
4166           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4167         else if (Idx >= 0)
4168           Idx -= StartIdx[0];
4169       }
4170 
4171       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4172       return;
4173     }
4174   }
4175 
4176   // We can't use either concat vectors or extract subvectors so fall back to
4177   // replacing the shuffle with extract and build vector.
4178   // to insert and build vector.
4179   EVT EltVT = VT.getVectorElementType();
4180   SmallVector<SDValue,8> Ops;
4181   for (int Idx : Mask) {
4182     SDValue Res;
4183 
4184     if (Idx < 0) {
4185       Res = DAG.getUNDEF(EltVT);
4186     } else {
4187       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4188       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4189 
4190       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4191                         DAG.getVectorIdxConstant(Idx, DL));
4192     }
4193 
4194     Ops.push_back(Res);
4195   }
4196 
4197   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4198 }
4199 
4200 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4201   ArrayRef<unsigned> Indices = I.getIndices();
4202   const Value *Op0 = I.getOperand(0);
4203   const Value *Op1 = I.getOperand(1);
4204   Type *AggTy = I.getType();
4205   Type *ValTy = Op1->getType();
4206   bool IntoUndef = isa<UndefValue>(Op0);
4207   bool FromUndef = isa<UndefValue>(Op1);
4208 
4209   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4210 
4211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4212   SmallVector<EVT, 4> AggValueVTs;
4213   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4214   SmallVector<EVT, 4> ValValueVTs;
4215   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4216 
4217   unsigned NumAggValues = AggValueVTs.size();
4218   unsigned NumValValues = ValValueVTs.size();
4219   SmallVector<SDValue, 4> Values(NumAggValues);
4220 
4221   // Ignore an insertvalue that produces an empty object
4222   if (!NumAggValues) {
4223     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4224     return;
4225   }
4226 
4227   SDValue Agg = getValue(Op0);
4228   unsigned i = 0;
4229   // Copy the beginning value(s) from the original aggregate.
4230   for (; i != LinearIndex; ++i)
4231     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4232                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4233   // Copy values from the inserted value(s).
4234   if (NumValValues) {
4235     SDValue Val = getValue(Op1);
4236     for (; i != LinearIndex + NumValValues; ++i)
4237       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4238                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4239   }
4240   // Copy remaining value(s) from the original aggregate.
4241   for (; i != NumAggValues; ++i)
4242     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4243                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4244 
4245   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4246                            DAG.getVTList(AggValueVTs), Values));
4247 }
4248 
4249 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4250   ArrayRef<unsigned> Indices = I.getIndices();
4251   const Value *Op0 = I.getOperand(0);
4252   Type *AggTy = Op0->getType();
4253   Type *ValTy = I.getType();
4254   bool OutOfUndef = isa<UndefValue>(Op0);
4255 
4256   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4257 
4258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4259   SmallVector<EVT, 4> ValValueVTs;
4260   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4261 
4262   unsigned NumValValues = ValValueVTs.size();
4263 
4264   // Ignore a extractvalue that produces an empty object
4265   if (!NumValValues) {
4266     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4267     return;
4268   }
4269 
4270   SmallVector<SDValue, 4> Values(NumValValues);
4271 
4272   SDValue Agg = getValue(Op0);
4273   // Copy out the selected value(s).
4274   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4275     Values[i - LinearIndex] =
4276       OutOfUndef ?
4277         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4278         SDValue(Agg.getNode(), Agg.getResNo() + i);
4279 
4280   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4281                            DAG.getVTList(ValValueVTs), Values));
4282 }
4283 
4284 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4285   Value *Op0 = I.getOperand(0);
4286   // Note that the pointer operand may be a vector of pointers. Take the scalar
4287   // element which holds a pointer.
4288   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4289   SDValue N = getValue(Op0);
4290   SDLoc dl = getCurSDLoc();
4291   auto &TLI = DAG.getTargetLoweringInfo();
4292 
4293   // Normalize Vector GEP - all scalar operands should be converted to the
4294   // splat vector.
4295   bool IsVectorGEP = I.getType()->isVectorTy();
4296   ElementCount VectorElementCount =
4297       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4298                   : ElementCount::getFixed(0);
4299 
4300   if (IsVectorGEP && !N.getValueType().isVector()) {
4301     LLVMContext &Context = *DAG.getContext();
4302     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4303     N = DAG.getSplat(VT, dl, N);
4304   }
4305 
4306   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4307        GTI != E; ++GTI) {
4308     const Value *Idx = GTI.getOperand();
4309     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4310       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4311       if (Field) {
4312         // N = N + Offset
4313         uint64_t Offset =
4314             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4315 
4316         // In an inbounds GEP with an offset that is nonnegative even when
4317         // interpreted as signed, assume there is no unsigned overflow.
4318         SDNodeFlags Flags;
4319         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4320           Flags.setNoUnsignedWrap(true);
4321 
4322         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4323                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4324       }
4325     } else {
4326       // IdxSize is the width of the arithmetic according to IR semantics.
4327       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4328       // (and fix up the result later).
4329       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4330       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4331       TypeSize ElementSize =
4332           GTI.getSequentialElementStride(DAG.getDataLayout());
4333       // We intentionally mask away the high bits here; ElementSize may not
4334       // fit in IdxTy.
4335       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4336       bool ElementScalable = ElementSize.isScalable();
4337 
4338       // If this is a scalar constant or a splat vector of constants,
4339       // handle it quickly.
4340       const auto *C = dyn_cast<Constant>(Idx);
4341       if (C && isa<VectorType>(C->getType()))
4342         C = C->getSplatValue();
4343 
4344       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4345       if (CI && CI->isZero())
4346         continue;
4347       if (CI && !ElementScalable) {
4348         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4349         LLVMContext &Context = *DAG.getContext();
4350         SDValue OffsVal;
4351         if (IsVectorGEP)
4352           OffsVal = DAG.getConstant(
4353               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4354         else
4355           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4356 
4357         // In an inbounds GEP with an offset that is nonnegative even when
4358         // interpreted as signed, assume there is no unsigned overflow.
4359         SDNodeFlags Flags;
4360         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4361           Flags.setNoUnsignedWrap(true);
4362 
4363         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4364 
4365         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4366         continue;
4367       }
4368 
4369       // N = N + Idx * ElementMul;
4370       SDValue IdxN = getValue(Idx);
4371 
4372       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4373         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4374                                   VectorElementCount);
4375         IdxN = DAG.getSplat(VT, dl, IdxN);
4376       }
4377 
4378       // If the index is smaller or larger than intptr_t, truncate or extend
4379       // it.
4380       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4381 
4382       if (ElementScalable) {
4383         EVT VScaleTy = N.getValueType().getScalarType();
4384         SDValue VScale = DAG.getNode(
4385             ISD::VSCALE, dl, VScaleTy,
4386             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4387         if (IsVectorGEP)
4388           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4389         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4390       } else {
4391         // If this is a multiply by a power of two, turn it into a shl
4392         // immediately.  This is a very common case.
4393         if (ElementMul != 1) {
4394           if (ElementMul.isPowerOf2()) {
4395             unsigned Amt = ElementMul.logBase2();
4396             IdxN = DAG.getNode(ISD::SHL, dl,
4397                                N.getValueType(), IdxN,
4398                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4399           } else {
4400             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4401                                             IdxN.getValueType());
4402             IdxN = DAG.getNode(ISD::MUL, dl,
4403                                N.getValueType(), IdxN, Scale);
4404           }
4405         }
4406       }
4407 
4408       N = DAG.getNode(ISD::ADD, dl,
4409                       N.getValueType(), N, IdxN);
4410     }
4411   }
4412 
4413   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4414   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4415   if (IsVectorGEP) {
4416     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4417     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4418   }
4419 
4420   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4421     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4422 
4423   setValue(&I, N);
4424 }
4425 
4426 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4427   // If this is a fixed sized alloca in the entry block of the function,
4428   // allocate it statically on the stack.
4429   if (FuncInfo.StaticAllocaMap.count(&I))
4430     return;   // getValue will auto-populate this.
4431 
4432   SDLoc dl = getCurSDLoc();
4433   Type *Ty = I.getAllocatedType();
4434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4435   auto &DL = DAG.getDataLayout();
4436   TypeSize TySize = DL.getTypeAllocSize(Ty);
4437   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4438 
4439   SDValue AllocSize = getValue(I.getArraySize());
4440 
4441   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4442   if (AllocSize.getValueType() != IntPtr)
4443     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4444 
4445   if (TySize.isScalable())
4446     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4447                             DAG.getVScale(dl, IntPtr,
4448                                           APInt(IntPtr.getScalarSizeInBits(),
4449                                                 TySize.getKnownMinValue())));
4450   else {
4451     SDValue TySizeValue =
4452         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4453     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4454                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4455   }
4456 
4457   // Handle alignment.  If the requested alignment is less than or equal to
4458   // the stack alignment, ignore it.  If the size is greater than or equal to
4459   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4460   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4461   if (*Alignment <= StackAlign)
4462     Alignment = std::nullopt;
4463 
4464   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4465   // Round the size of the allocation up to the stack alignment size
4466   // by add SA-1 to the size. This doesn't overflow because we're computing
4467   // an address inside an alloca.
4468   SDNodeFlags Flags;
4469   Flags.setNoUnsignedWrap(true);
4470   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4471                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4472 
4473   // Mask out the low bits for alignment purposes.
4474   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4475                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4476 
4477   SDValue Ops[] = {
4478       getRoot(), AllocSize,
4479       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4480   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4481   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4482   setValue(&I, DSA);
4483   DAG.setRoot(DSA.getValue(1));
4484 
4485   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4486 }
4487 
4488 static const MDNode *getRangeMetadata(const Instruction &I) {
4489   // If !noundef is not present, then !range violation results in a poison
4490   // value rather than immediate undefined behavior. In theory, transferring
4491   // these annotations to SDAG is fine, but in practice there are key SDAG
4492   // transforms that are known not to be poison-safe, such as folding logical
4493   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4494   // also present.
4495   if (!I.hasMetadata(LLVMContext::MD_noundef))
4496     return nullptr;
4497   return I.getMetadata(LLVMContext::MD_range);
4498 }
4499 
4500 static std::optional<ConstantRange> getRange(const Instruction &I) {
4501   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4502     // see comment in getRangeMetadata about this check
4503     if (CB->hasRetAttr(Attribute::NoUndef))
4504       return CB->getRange();
4505   }
4506   if (const MDNode *Range = getRangeMetadata(I))
4507     return getConstantRangeFromMetadata(*Range);
4508   return std::nullopt;
4509 }
4510 
4511 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4512   if (I.isAtomic())
4513     return visitAtomicLoad(I);
4514 
4515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4516   const Value *SV = I.getOperand(0);
4517   if (TLI.supportSwiftError()) {
4518     // Swifterror values can come from either a function parameter with
4519     // swifterror attribute or an alloca with swifterror attribute.
4520     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4521       if (Arg->hasSwiftErrorAttr())
4522         return visitLoadFromSwiftError(I);
4523     }
4524 
4525     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4526       if (Alloca->isSwiftError())
4527         return visitLoadFromSwiftError(I);
4528     }
4529   }
4530 
4531   SDValue Ptr = getValue(SV);
4532 
4533   Type *Ty = I.getType();
4534   SmallVector<EVT, 4> ValueVTs, MemVTs;
4535   SmallVector<TypeSize, 4> Offsets;
4536   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4537   unsigned NumValues = ValueVTs.size();
4538   if (NumValues == 0)
4539     return;
4540 
4541   Align Alignment = I.getAlign();
4542   AAMDNodes AAInfo = I.getAAMetadata();
4543   const MDNode *Ranges = getRangeMetadata(I);
4544   bool isVolatile = I.isVolatile();
4545   MachineMemOperand::Flags MMOFlags =
4546       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4547 
4548   SDValue Root;
4549   bool ConstantMemory = false;
4550   if (isVolatile)
4551     // Serialize volatile loads with other side effects.
4552     Root = getRoot();
4553   else if (NumValues > MaxParallelChains)
4554     Root = getMemoryRoot();
4555   else if (AA &&
4556            AA->pointsToConstantMemory(MemoryLocation(
4557                SV,
4558                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4559                AAInfo))) {
4560     // Do not serialize (non-volatile) loads of constant memory with anything.
4561     Root = DAG.getEntryNode();
4562     ConstantMemory = true;
4563     MMOFlags |= MachineMemOperand::MOInvariant;
4564   } else {
4565     // Do not serialize non-volatile loads against each other.
4566     Root = DAG.getRoot();
4567   }
4568 
4569   SDLoc dl = getCurSDLoc();
4570 
4571   if (isVolatile)
4572     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4573 
4574   SmallVector<SDValue, 4> Values(NumValues);
4575   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4576 
4577   unsigned ChainI = 0;
4578   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4579     // Serializing loads here may result in excessive register pressure, and
4580     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4581     // could recover a bit by hoisting nodes upward in the chain by recognizing
4582     // they are side-effect free or do not alias. The optimizer should really
4583     // avoid this case by converting large object/array copies to llvm.memcpy
4584     // (MaxParallelChains should always remain as failsafe).
4585     if (ChainI == MaxParallelChains) {
4586       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4587       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4588                                   ArrayRef(Chains.data(), ChainI));
4589       Root = Chain;
4590       ChainI = 0;
4591     }
4592 
4593     // TODO: MachinePointerInfo only supports a fixed length offset.
4594     MachinePointerInfo PtrInfo =
4595         !Offsets[i].isScalable() || Offsets[i].isZero()
4596             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4597             : MachinePointerInfo();
4598 
4599     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4600     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4601                             MMOFlags, AAInfo, Ranges);
4602     Chains[ChainI] = L.getValue(1);
4603 
4604     if (MemVTs[i] != ValueVTs[i])
4605       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4606 
4607     Values[i] = L;
4608   }
4609 
4610   if (!ConstantMemory) {
4611     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4612                                 ArrayRef(Chains.data(), ChainI));
4613     if (isVolatile)
4614       DAG.setRoot(Chain);
4615     else
4616       PendingLoads.push_back(Chain);
4617   }
4618 
4619   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4620                            DAG.getVTList(ValueVTs), Values));
4621 }
4622 
4623 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4624   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4625          "call visitStoreToSwiftError when backend supports swifterror");
4626 
4627   SmallVector<EVT, 4> ValueVTs;
4628   SmallVector<uint64_t, 4> Offsets;
4629   const Value *SrcV = I.getOperand(0);
4630   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4631                   SrcV->getType(), ValueVTs, &Offsets, 0);
4632   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4633          "expect a single EVT for swifterror");
4634 
4635   SDValue Src = getValue(SrcV);
4636   // Create a virtual register, then update the virtual register.
4637   Register VReg =
4638       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4639   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4640   // Chain can be getRoot or getControlRoot.
4641   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4642                                       SDValue(Src.getNode(), Src.getResNo()));
4643   DAG.setRoot(CopyNode);
4644 }
4645 
4646 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4647   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4648          "call visitLoadFromSwiftError when backend supports swifterror");
4649 
4650   assert(!I.isVolatile() &&
4651          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4652          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4653          "Support volatile, non temporal, invariant for load_from_swift_error");
4654 
4655   const Value *SV = I.getOperand(0);
4656   Type *Ty = I.getType();
4657   assert(
4658       (!AA ||
4659        !AA->pointsToConstantMemory(MemoryLocation(
4660            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4661            I.getAAMetadata()))) &&
4662       "load_from_swift_error should not be constant memory");
4663 
4664   SmallVector<EVT, 4> ValueVTs;
4665   SmallVector<uint64_t, 4> Offsets;
4666   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4667                   ValueVTs, &Offsets, 0);
4668   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4669          "expect a single EVT for swifterror");
4670 
4671   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4672   SDValue L = DAG.getCopyFromReg(
4673       getRoot(), getCurSDLoc(),
4674       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4675 
4676   setValue(&I, L);
4677 }
4678 
4679 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4680   if (I.isAtomic())
4681     return visitAtomicStore(I);
4682 
4683   const Value *SrcV = I.getOperand(0);
4684   const Value *PtrV = I.getOperand(1);
4685 
4686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4687   if (TLI.supportSwiftError()) {
4688     // Swifterror values can come from either a function parameter with
4689     // swifterror attribute or an alloca with swifterror attribute.
4690     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4691       if (Arg->hasSwiftErrorAttr())
4692         return visitStoreToSwiftError(I);
4693     }
4694 
4695     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4696       if (Alloca->isSwiftError())
4697         return visitStoreToSwiftError(I);
4698     }
4699   }
4700 
4701   SmallVector<EVT, 4> ValueVTs, MemVTs;
4702   SmallVector<TypeSize, 4> Offsets;
4703   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4704                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4705   unsigned NumValues = ValueVTs.size();
4706   if (NumValues == 0)
4707     return;
4708 
4709   // Get the lowered operands. Note that we do this after
4710   // checking if NumResults is zero, because with zero results
4711   // the operands won't have values in the map.
4712   SDValue Src = getValue(SrcV);
4713   SDValue Ptr = getValue(PtrV);
4714 
4715   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4716   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4717   SDLoc dl = getCurSDLoc();
4718   Align Alignment = I.getAlign();
4719   AAMDNodes AAInfo = I.getAAMetadata();
4720 
4721   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4722 
4723   unsigned ChainI = 0;
4724   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4725     // See visitLoad comments.
4726     if (ChainI == MaxParallelChains) {
4727       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4728                                   ArrayRef(Chains.data(), ChainI));
4729       Root = Chain;
4730       ChainI = 0;
4731     }
4732 
4733     // TODO: MachinePointerInfo only supports a fixed length offset.
4734     MachinePointerInfo PtrInfo =
4735         !Offsets[i].isScalable() || Offsets[i].isZero()
4736             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4737             : MachinePointerInfo();
4738 
4739     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4740     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4741     if (MemVTs[i] != ValueVTs[i])
4742       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4743     SDValue St =
4744         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4745     Chains[ChainI] = St;
4746   }
4747 
4748   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4749                                   ArrayRef(Chains.data(), ChainI));
4750   setValue(&I, StoreNode);
4751   DAG.setRoot(StoreNode);
4752 }
4753 
4754 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4755                                            bool IsCompressing) {
4756   SDLoc sdl = getCurSDLoc();
4757 
4758   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4759                                Align &Alignment) {
4760     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4761     Src0 = I.getArgOperand(0);
4762     Ptr = I.getArgOperand(1);
4763     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4764     Mask = I.getArgOperand(3);
4765   };
4766   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4767                                     Align &Alignment) {
4768     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4769     Src0 = I.getArgOperand(0);
4770     Ptr = I.getArgOperand(1);
4771     Mask = I.getArgOperand(2);
4772     Alignment = I.getParamAlign(1).valueOrOne();
4773   };
4774 
4775   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4776   Align Alignment;
4777   if (IsCompressing)
4778     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4779   else
4780     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4781 
4782   SDValue Ptr = getValue(PtrOperand);
4783   SDValue Src0 = getValue(Src0Operand);
4784   SDValue Mask = getValue(MaskOperand);
4785   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4786 
4787   EVT VT = Src0.getValueType();
4788 
4789   auto MMOFlags = MachineMemOperand::MOStore;
4790   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4791     MMOFlags |= MachineMemOperand::MONonTemporal;
4792 
4793   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4794       MachinePointerInfo(PtrOperand), MMOFlags,
4795       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4796 
4797   const auto &TLI = DAG.getTargetLoweringInfo();
4798   const auto &TTI =
4799       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4800   SDValue StoreNode =
4801       !IsCompressing &&
4802               cast<FixedVectorType>(I.getArgOperand(0)->getType())
4803                       ->getNumElements() == 1 &&
4804               TTI.hasConditionalLoadStoreForType(
4805                   I.getArgOperand(0)->getType()->getScalarType())
4806           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4807                                  Mask)
4808           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4809                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4810                                IsCompressing);
4811   DAG.setRoot(StoreNode);
4812   setValue(&I, StoreNode);
4813 }
4814 
4815 // Get a uniform base for the Gather/Scatter intrinsic.
4816 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4817 // We try to represent it as a base pointer + vector of indices.
4818 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4819 // The first operand of the GEP may be a single pointer or a vector of pointers
4820 // Example:
4821 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4822 //  or
4823 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4824 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4825 //
4826 // When the first GEP operand is a single pointer - it is the uniform base we
4827 // are looking for. If first operand of the GEP is a splat vector - we
4828 // extract the splat value and use it as a uniform base.
4829 // In all other cases the function returns 'false'.
4830 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4831                            ISD::MemIndexType &IndexType, SDValue &Scale,
4832                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4833                            uint64_t ElemSize) {
4834   SelectionDAG& DAG = SDB->DAG;
4835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4836   const DataLayout &DL = DAG.getDataLayout();
4837 
4838   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4839 
4840   // Handle splat constant pointer.
4841   if (auto *C = dyn_cast<Constant>(Ptr)) {
4842     C = C->getSplatValue();
4843     if (!C)
4844       return false;
4845 
4846     Base = SDB->getValue(C);
4847 
4848     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4849     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4850     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4851     IndexType = ISD::SIGNED_SCALED;
4852     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4853     return true;
4854   }
4855 
4856   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4857   if (!GEP || GEP->getParent() != CurBB)
4858     return false;
4859 
4860   if (GEP->getNumOperands() != 2)
4861     return false;
4862 
4863   const Value *BasePtr = GEP->getPointerOperand();
4864   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4865 
4866   // Make sure the base is scalar and the index is a vector.
4867   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4868     return false;
4869 
4870   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4871   if (ScaleVal.isScalable())
4872     return false;
4873 
4874   // Target may not support the required addressing mode.
4875   if (ScaleVal != 1 &&
4876       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4877     return false;
4878 
4879   Base = SDB->getValue(BasePtr);
4880   Index = SDB->getValue(IndexVal);
4881   IndexType = ISD::SIGNED_SCALED;
4882 
4883   Scale =
4884       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4885   return true;
4886 }
4887 
4888 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4889   SDLoc sdl = getCurSDLoc();
4890 
4891   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4892   const Value *Ptr = I.getArgOperand(1);
4893   SDValue Src0 = getValue(I.getArgOperand(0));
4894   SDValue Mask = getValue(I.getArgOperand(3));
4895   EVT VT = Src0.getValueType();
4896   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4897                         ->getMaybeAlignValue()
4898                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4899   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4900 
4901   SDValue Base;
4902   SDValue Index;
4903   ISD::MemIndexType IndexType;
4904   SDValue Scale;
4905   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4906                                     I.getParent(), VT.getScalarStoreSize());
4907 
4908   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4909   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4910       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4911       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4912   if (!UniformBase) {
4913     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4914     Index = getValue(Ptr);
4915     IndexType = ISD::SIGNED_SCALED;
4916     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4917   }
4918 
4919   EVT IdxVT = Index.getValueType();
4920   EVT EltTy = IdxVT.getVectorElementType();
4921   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4922     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4923     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4924   }
4925 
4926   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4927   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4928                                          Ops, MMO, IndexType, false);
4929   DAG.setRoot(Scatter);
4930   setValue(&I, Scatter);
4931 }
4932 
4933 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4934   SDLoc sdl = getCurSDLoc();
4935 
4936   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4937                               Align &Alignment) {
4938     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4939     Ptr = I.getArgOperand(0);
4940     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4941     Mask = I.getArgOperand(2);
4942     Src0 = I.getArgOperand(3);
4943   };
4944   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4945                                  Align &Alignment) {
4946     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4947     Ptr = I.getArgOperand(0);
4948     Alignment = I.getParamAlign(0).valueOrOne();
4949     Mask = I.getArgOperand(1);
4950     Src0 = I.getArgOperand(2);
4951   };
4952 
4953   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4954   Align Alignment;
4955   if (IsExpanding)
4956     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4957   else
4958     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4959 
4960   SDValue Ptr = getValue(PtrOperand);
4961   SDValue Src0 = getValue(Src0Operand);
4962   SDValue Mask = getValue(MaskOperand);
4963   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4964 
4965   EVT VT = Src0.getValueType();
4966   AAMDNodes AAInfo = I.getAAMetadata();
4967   const MDNode *Ranges = getRangeMetadata(I);
4968 
4969   // Do not serialize masked loads of constant memory with anything.
4970   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4971   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4972 
4973   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4974 
4975   auto MMOFlags = MachineMemOperand::MOLoad;
4976   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4977     MMOFlags |= MachineMemOperand::MONonTemporal;
4978 
4979   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4980       MachinePointerInfo(PtrOperand), MMOFlags,
4981       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4982 
4983   const auto &TLI = DAG.getTargetLoweringInfo();
4984   const auto &TTI =
4985       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4986   // The Load/Res may point to different values and both of them are output
4987   // variables.
4988   SDValue Load;
4989   SDValue Res;
4990   if (!IsExpanding &&
4991       cast<FixedVectorType>(Src0Operand->getType())->getNumElements() == 1 &&
4992       TTI.hasConditionalLoadStoreForType(
4993           Src0Operand->getType()->getScalarType()))
4994     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4995   else
4996     Res = Load =
4997         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4998                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4999   if (AddToChain)
5000     PendingLoads.push_back(Load.getValue(1));
5001   setValue(&I, Res);
5002 }
5003 
5004 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5005   SDLoc sdl = getCurSDLoc();
5006 
5007   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5008   const Value *Ptr = I.getArgOperand(0);
5009   SDValue Src0 = getValue(I.getArgOperand(3));
5010   SDValue Mask = getValue(I.getArgOperand(2));
5011 
5012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5013   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5014   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5015                         ->getMaybeAlignValue()
5016                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5017 
5018   const MDNode *Ranges = getRangeMetadata(I);
5019 
5020   SDValue Root = DAG.getRoot();
5021   SDValue Base;
5022   SDValue Index;
5023   ISD::MemIndexType IndexType;
5024   SDValue Scale;
5025   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5026                                     I.getParent(), VT.getScalarStoreSize());
5027   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5028   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5029       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5030       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5031       Ranges);
5032 
5033   if (!UniformBase) {
5034     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5035     Index = getValue(Ptr);
5036     IndexType = ISD::SIGNED_SCALED;
5037     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5038   }
5039 
5040   EVT IdxVT = Index.getValueType();
5041   EVT EltTy = IdxVT.getVectorElementType();
5042   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5043     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5044     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5045   }
5046 
5047   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5048   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5049                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5050 
5051   PendingLoads.push_back(Gather.getValue(1));
5052   setValue(&I, Gather);
5053 }
5054 
5055 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5056   SDLoc dl = getCurSDLoc();
5057   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5058   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5059   SyncScope::ID SSID = I.getSyncScopeID();
5060 
5061   SDValue InChain = getRoot();
5062 
5063   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5064   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5065 
5066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5067   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5068 
5069   MachineFunction &MF = DAG.getMachineFunction();
5070   MachineMemOperand *MMO = MF.getMachineMemOperand(
5071       MachinePointerInfo(I.getPointerOperand()), Flags,
5072       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5073       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5074 
5075   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5076                                    dl, MemVT, VTs, InChain,
5077                                    getValue(I.getPointerOperand()),
5078                                    getValue(I.getCompareOperand()),
5079                                    getValue(I.getNewValOperand()), MMO);
5080 
5081   SDValue OutChain = L.getValue(2);
5082 
5083   setValue(&I, L);
5084   DAG.setRoot(OutChain);
5085 }
5086 
5087 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5088   SDLoc dl = getCurSDLoc();
5089   ISD::NodeType NT;
5090   switch (I.getOperation()) {
5091   default: llvm_unreachable("Unknown atomicrmw operation");
5092   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5093   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5094   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5095   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5096   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5097   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5098   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5099   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5100   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5101   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5102   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5103   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5104   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5105   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5106   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5107   case AtomicRMWInst::UIncWrap:
5108     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5109     break;
5110   case AtomicRMWInst::UDecWrap:
5111     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5112     break;
5113   }
5114   AtomicOrdering Ordering = I.getOrdering();
5115   SyncScope::ID SSID = I.getSyncScopeID();
5116 
5117   SDValue InChain = getRoot();
5118 
5119   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5121   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5122 
5123   MachineFunction &MF = DAG.getMachineFunction();
5124   MachineMemOperand *MMO = MF.getMachineMemOperand(
5125       MachinePointerInfo(I.getPointerOperand()), Flags,
5126       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5127       AAMDNodes(), nullptr, SSID, Ordering);
5128 
5129   SDValue L =
5130     DAG.getAtomic(NT, dl, MemVT, InChain,
5131                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5132                   MMO);
5133 
5134   SDValue OutChain = L.getValue(1);
5135 
5136   setValue(&I, L);
5137   DAG.setRoot(OutChain);
5138 }
5139 
5140 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5141   SDLoc dl = getCurSDLoc();
5142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5143   SDValue Ops[3];
5144   Ops[0] = getRoot();
5145   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5146                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5147   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5148                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5149   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5150   setValue(&I, N);
5151   DAG.setRoot(N);
5152 }
5153 
5154 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5155   SDLoc dl = getCurSDLoc();
5156   AtomicOrdering Order = I.getOrdering();
5157   SyncScope::ID SSID = I.getSyncScopeID();
5158 
5159   SDValue InChain = getRoot();
5160 
5161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5162   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5163   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5164 
5165   if (!TLI.supportsUnalignedAtomics() &&
5166       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5167     report_fatal_error("Cannot generate unaligned atomic load");
5168 
5169   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5170 
5171   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5172       MachinePointerInfo(I.getPointerOperand()), Flags,
5173       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5174       nullptr, SSID, Order);
5175 
5176   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5177 
5178   SDValue Ptr = getValue(I.getPointerOperand());
5179   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5180                             Ptr, MMO);
5181 
5182   SDValue OutChain = L.getValue(1);
5183   if (MemVT != VT)
5184     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5185 
5186   setValue(&I, L);
5187   DAG.setRoot(OutChain);
5188 }
5189 
5190 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5191   SDLoc dl = getCurSDLoc();
5192 
5193   AtomicOrdering Ordering = I.getOrdering();
5194   SyncScope::ID SSID = I.getSyncScopeID();
5195 
5196   SDValue InChain = getRoot();
5197 
5198   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5199   EVT MemVT =
5200       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5201 
5202   if (!TLI.supportsUnalignedAtomics() &&
5203       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5204     report_fatal_error("Cannot generate unaligned atomic store");
5205 
5206   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5207 
5208   MachineFunction &MF = DAG.getMachineFunction();
5209   MachineMemOperand *MMO = MF.getMachineMemOperand(
5210       MachinePointerInfo(I.getPointerOperand()), Flags,
5211       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5212       nullptr, SSID, Ordering);
5213 
5214   SDValue Val = getValue(I.getValueOperand());
5215   if (Val.getValueType() != MemVT)
5216     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5217   SDValue Ptr = getValue(I.getPointerOperand());
5218 
5219   SDValue OutChain =
5220       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5221 
5222   setValue(&I, OutChain);
5223   DAG.setRoot(OutChain);
5224 }
5225 
5226 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5227 /// node.
5228 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5229                                                unsigned Intrinsic) {
5230   // Ignore the callsite's attributes. A specific call site may be marked with
5231   // readnone, but the lowering code will expect the chain based on the
5232   // definition.
5233   const Function *F = I.getCalledFunction();
5234   bool HasChain = !F->doesNotAccessMemory();
5235   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5236 
5237   // Build the operand list.
5238   SmallVector<SDValue, 8> Ops;
5239   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5240     if (OnlyLoad) {
5241       // We don't need to serialize loads against other loads.
5242       Ops.push_back(DAG.getRoot());
5243     } else {
5244       Ops.push_back(getRoot());
5245     }
5246   }
5247 
5248   // Info is set by getTgtMemIntrinsic
5249   TargetLowering::IntrinsicInfo Info;
5250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5251   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5252                                                DAG.getMachineFunction(),
5253                                                Intrinsic);
5254 
5255   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5256   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5257       Info.opc == ISD::INTRINSIC_W_CHAIN)
5258     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5259                                         TLI.getPointerTy(DAG.getDataLayout())));
5260 
5261   // Add all operands of the call to the operand list.
5262   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5263     const Value *Arg = I.getArgOperand(i);
5264     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5265       Ops.push_back(getValue(Arg));
5266       continue;
5267     }
5268 
5269     // Use TargetConstant instead of a regular constant for immarg.
5270     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5271     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5272       assert(CI->getBitWidth() <= 64 &&
5273              "large intrinsic immediates not handled");
5274       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5275     } else {
5276       Ops.push_back(
5277           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5278     }
5279   }
5280 
5281   SmallVector<EVT, 4> ValueVTs;
5282   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5283 
5284   if (HasChain)
5285     ValueVTs.push_back(MVT::Other);
5286 
5287   SDVTList VTs = DAG.getVTList(ValueVTs);
5288 
5289   // Propagate fast-math-flags from IR to node(s).
5290   SDNodeFlags Flags;
5291   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5292     Flags.copyFMF(*FPMO);
5293   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5294 
5295   // Create the node.
5296   SDValue Result;
5297 
5298   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5299     auto *Token = Bundle->Inputs[0].get();
5300     SDValue ConvControlToken = getValue(Token);
5301     assert(Ops.back().getValueType() != MVT::Glue &&
5302            "Did not expected another glue node here.");
5303     ConvControlToken =
5304         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5305     Ops.push_back(ConvControlToken);
5306   }
5307 
5308   // In some cases, custom collection of operands from CallInst I may be needed.
5309   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5310   if (IsTgtIntrinsic) {
5311     // This is target intrinsic that touches memory
5312     //
5313     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5314     //       didn't yield anything useful.
5315     MachinePointerInfo MPI;
5316     if (Info.ptrVal)
5317       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5318     else if (Info.fallbackAddressSpace)
5319       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5320     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5321                                      Info.memVT, MPI, Info.align, Info.flags,
5322                                      Info.size, I.getAAMetadata());
5323   } else if (!HasChain) {
5324     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5325   } else if (!I.getType()->isVoidTy()) {
5326     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5327   } else {
5328     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5329   }
5330 
5331   if (HasChain) {
5332     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5333     if (OnlyLoad)
5334       PendingLoads.push_back(Chain);
5335     else
5336       DAG.setRoot(Chain);
5337   }
5338 
5339   if (!I.getType()->isVoidTy()) {
5340     if (!isa<VectorType>(I.getType()))
5341       Result = lowerRangeToAssertZExt(DAG, I, Result);
5342 
5343     MaybeAlign Alignment = I.getRetAlign();
5344 
5345     // Insert `assertalign` node if there's an alignment.
5346     if (InsertAssertAlign && Alignment) {
5347       Result =
5348           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5349     }
5350   }
5351 
5352   setValue(&I, Result);
5353 }
5354 
5355 /// GetSignificand - Get the significand and build it into a floating-point
5356 /// number with exponent of 1:
5357 ///
5358 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5359 ///
5360 /// where Op is the hexadecimal representation of floating point value.
5361 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5362   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5363                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5364   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5365                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5366   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5367 }
5368 
5369 /// GetExponent - Get the exponent:
5370 ///
5371 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5372 ///
5373 /// where Op is the hexadecimal representation of floating point value.
5374 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5375                            const TargetLowering &TLI, const SDLoc &dl) {
5376   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5377                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5378   SDValue t1 = DAG.getNode(
5379       ISD::SRL, dl, MVT::i32, t0,
5380       DAG.getConstant(23, dl,
5381                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5382   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5383                            DAG.getConstant(127, dl, MVT::i32));
5384   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5385 }
5386 
5387 /// getF32Constant - Get 32-bit floating point constant.
5388 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5389                               const SDLoc &dl) {
5390   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5391                            MVT::f32);
5392 }
5393 
5394 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5395                                        SelectionDAG &DAG) {
5396   // TODO: What fast-math-flags should be set on the floating-point nodes?
5397 
5398   //   IntegerPartOfX = ((int32_t)(t0);
5399   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5400 
5401   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5402   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5403   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5404 
5405   //   IntegerPartOfX <<= 23;
5406   IntegerPartOfX =
5407       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5408                   DAG.getConstant(23, dl,
5409                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5410                                       MVT::i32, DAG.getDataLayout())));
5411 
5412   SDValue TwoToFractionalPartOfX;
5413   if (LimitFloatPrecision <= 6) {
5414     // For floating-point precision of 6:
5415     //
5416     //   TwoToFractionalPartOfX =
5417     //     0.997535578f +
5418     //       (0.735607626f + 0.252464424f * x) * x;
5419     //
5420     // error 0.0144103317, which is 6 bits
5421     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5422                              getF32Constant(DAG, 0x3e814304, dl));
5423     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5424                              getF32Constant(DAG, 0x3f3c50c8, dl));
5425     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5426     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5427                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5428   } else if (LimitFloatPrecision <= 12) {
5429     // For floating-point precision of 12:
5430     //
5431     //   TwoToFractionalPartOfX =
5432     //     0.999892986f +
5433     //       (0.696457318f +
5434     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5435     //
5436     // error 0.000107046256, which is 13 to 14 bits
5437     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5438                              getF32Constant(DAG, 0x3da235e3, dl));
5439     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5440                              getF32Constant(DAG, 0x3e65b8f3, dl));
5441     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5442     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5443                              getF32Constant(DAG, 0x3f324b07, dl));
5444     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5445     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5446                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5447   } else { // LimitFloatPrecision <= 18
5448     // For floating-point precision of 18:
5449     //
5450     //   TwoToFractionalPartOfX =
5451     //     0.999999982f +
5452     //       (0.693148872f +
5453     //         (0.240227044f +
5454     //           (0.554906021e-1f +
5455     //             (0.961591928e-2f +
5456     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5457     // error 2.47208000*10^(-7), which is better than 18 bits
5458     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5459                              getF32Constant(DAG, 0x3924b03e, dl));
5460     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5461                              getF32Constant(DAG, 0x3ab24b87, dl));
5462     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5463     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5464                              getF32Constant(DAG, 0x3c1d8c17, dl));
5465     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5466     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5467                              getF32Constant(DAG, 0x3d634a1d, dl));
5468     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5469     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5470                              getF32Constant(DAG, 0x3e75fe14, dl));
5471     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5472     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5473                               getF32Constant(DAG, 0x3f317234, dl));
5474     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5475     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5476                                          getF32Constant(DAG, 0x3f800000, dl));
5477   }
5478 
5479   // Add the exponent into the result in integer domain.
5480   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5481   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5482                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5483 }
5484 
5485 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5486 /// limited-precision mode.
5487 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5488                          const TargetLowering &TLI, SDNodeFlags Flags) {
5489   if (Op.getValueType() == MVT::f32 &&
5490       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5491 
5492     // Put the exponent in the right bit position for later addition to the
5493     // final result:
5494     //
5495     // t0 = Op * log2(e)
5496 
5497     // TODO: What fast-math-flags should be set here?
5498     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5499                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5500     return getLimitedPrecisionExp2(t0, dl, DAG);
5501   }
5502 
5503   // No special expansion.
5504   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5505 }
5506 
5507 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5508 /// limited-precision mode.
5509 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5510                          const TargetLowering &TLI, SDNodeFlags Flags) {
5511   // TODO: What fast-math-flags should be set on the floating-point nodes?
5512 
5513   if (Op.getValueType() == MVT::f32 &&
5514       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5515     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5516 
5517     // Scale the exponent by log(2).
5518     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5519     SDValue LogOfExponent =
5520         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5521                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5522 
5523     // Get the significand and build it into a floating-point number with
5524     // exponent of 1.
5525     SDValue X = GetSignificand(DAG, Op1, dl);
5526 
5527     SDValue LogOfMantissa;
5528     if (LimitFloatPrecision <= 6) {
5529       // For floating-point precision of 6:
5530       //
5531       //   LogofMantissa =
5532       //     -1.1609546f +
5533       //       (1.4034025f - 0.23903021f * x) * x;
5534       //
5535       // error 0.0034276066, which is better than 8 bits
5536       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5537                                getF32Constant(DAG, 0xbe74c456, dl));
5538       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5539                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5540       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5541       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5542                                   getF32Constant(DAG, 0x3f949a29, dl));
5543     } else if (LimitFloatPrecision <= 12) {
5544       // For floating-point precision of 12:
5545       //
5546       //   LogOfMantissa =
5547       //     -1.7417939f +
5548       //       (2.8212026f +
5549       //         (-1.4699568f +
5550       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5551       //
5552       // error 0.000061011436, which is 14 bits
5553       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5554                                getF32Constant(DAG, 0xbd67b6d6, dl));
5555       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5556                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5557       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5558       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5559                                getF32Constant(DAG, 0x3fbc278b, dl));
5560       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5561       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5562                                getF32Constant(DAG, 0x40348e95, dl));
5563       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5564       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5565                                   getF32Constant(DAG, 0x3fdef31a, dl));
5566     } else { // LimitFloatPrecision <= 18
5567       // For floating-point precision of 18:
5568       //
5569       //   LogOfMantissa =
5570       //     -2.1072184f +
5571       //       (4.2372794f +
5572       //         (-3.7029485f +
5573       //           (2.2781945f +
5574       //             (-0.87823314f +
5575       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5576       //
5577       // error 0.0000023660568, which is better than 18 bits
5578       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5579                                getF32Constant(DAG, 0xbc91e5ac, dl));
5580       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5581                                getF32Constant(DAG, 0x3e4350aa, dl));
5582       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5583       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5584                                getF32Constant(DAG, 0x3f60d3e3, dl));
5585       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5586       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5587                                getF32Constant(DAG, 0x4011cdf0, dl));
5588       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5589       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5590                                getF32Constant(DAG, 0x406cfd1c, dl));
5591       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5592       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5593                                getF32Constant(DAG, 0x408797cb, dl));
5594       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5595       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5596                                   getF32Constant(DAG, 0x4006dcab, dl));
5597     }
5598 
5599     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5600   }
5601 
5602   // No special expansion.
5603   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5604 }
5605 
5606 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5607 /// limited-precision mode.
5608 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5609                           const TargetLowering &TLI, SDNodeFlags Flags) {
5610   // TODO: What fast-math-flags should be set on the floating-point nodes?
5611 
5612   if (Op.getValueType() == MVT::f32 &&
5613       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5614     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5615 
5616     // Get the exponent.
5617     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5618 
5619     // Get the significand and build it into a floating-point number with
5620     // exponent of 1.
5621     SDValue X = GetSignificand(DAG, Op1, dl);
5622 
5623     // Different possible minimax approximations of significand in
5624     // floating-point for various degrees of accuracy over [1,2].
5625     SDValue Log2ofMantissa;
5626     if (LimitFloatPrecision <= 6) {
5627       // For floating-point precision of 6:
5628       //
5629       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5630       //
5631       // error 0.0049451742, which is more than 7 bits
5632       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5633                                getF32Constant(DAG, 0xbeb08fe0, dl));
5634       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5635                                getF32Constant(DAG, 0x40019463, dl));
5636       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5637       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5638                                    getF32Constant(DAG, 0x3fd6633d, dl));
5639     } else if (LimitFloatPrecision <= 12) {
5640       // For floating-point precision of 12:
5641       //
5642       //   Log2ofMantissa =
5643       //     -2.51285454f +
5644       //       (4.07009056f +
5645       //         (-2.12067489f +
5646       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5647       //
5648       // error 0.0000876136000, which is better than 13 bits
5649       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5650                                getF32Constant(DAG, 0xbda7262e, dl));
5651       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5652                                getF32Constant(DAG, 0x3f25280b, dl));
5653       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5654       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5655                                getF32Constant(DAG, 0x4007b923, dl));
5656       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5657       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5658                                getF32Constant(DAG, 0x40823e2f, dl));
5659       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5660       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5661                                    getF32Constant(DAG, 0x4020d29c, dl));
5662     } else { // LimitFloatPrecision <= 18
5663       // For floating-point precision of 18:
5664       //
5665       //   Log2ofMantissa =
5666       //     -3.0400495f +
5667       //       (6.1129976f +
5668       //         (-5.3420409f +
5669       //           (3.2865683f +
5670       //             (-1.2669343f +
5671       //               (0.27515199f -
5672       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5673       //
5674       // error 0.0000018516, which is better than 18 bits
5675       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5676                                getF32Constant(DAG, 0xbcd2769e, dl));
5677       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5678                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5679       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5680       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5681                                getF32Constant(DAG, 0x3fa22ae7, dl));
5682       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5683       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5684                                getF32Constant(DAG, 0x40525723, dl));
5685       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5686       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5687                                getF32Constant(DAG, 0x40aaf200, dl));
5688       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5689       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5690                                getF32Constant(DAG, 0x40c39dad, dl));
5691       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5692       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5693                                    getF32Constant(DAG, 0x4042902c, dl));
5694     }
5695 
5696     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5697   }
5698 
5699   // No special expansion.
5700   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5701 }
5702 
5703 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5704 /// limited-precision mode.
5705 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5706                            const TargetLowering &TLI, SDNodeFlags Flags) {
5707   // TODO: What fast-math-flags should be set on the floating-point nodes?
5708 
5709   if (Op.getValueType() == MVT::f32 &&
5710       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5711     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5712 
5713     // Scale the exponent by log10(2) [0.30102999f].
5714     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5715     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5716                                         getF32Constant(DAG, 0x3e9a209a, dl));
5717 
5718     // Get the significand and build it into a floating-point number with
5719     // exponent of 1.
5720     SDValue X = GetSignificand(DAG, Op1, dl);
5721 
5722     SDValue Log10ofMantissa;
5723     if (LimitFloatPrecision <= 6) {
5724       // For floating-point precision of 6:
5725       //
5726       //   Log10ofMantissa =
5727       //     -0.50419619f +
5728       //       (0.60948995f - 0.10380950f * x) * x;
5729       //
5730       // error 0.0014886165, which is 6 bits
5731       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5732                                getF32Constant(DAG, 0xbdd49a13, dl));
5733       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5734                                getF32Constant(DAG, 0x3f1c0789, dl));
5735       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5736       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5737                                     getF32Constant(DAG, 0x3f011300, dl));
5738     } else if (LimitFloatPrecision <= 12) {
5739       // For floating-point precision of 12:
5740       //
5741       //   Log10ofMantissa =
5742       //     -0.64831180f +
5743       //       (0.91751397f +
5744       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5745       //
5746       // error 0.00019228036, which is better than 12 bits
5747       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5748                                getF32Constant(DAG, 0x3d431f31, dl));
5749       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5750                                getF32Constant(DAG, 0x3ea21fb2, dl));
5751       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5752       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5753                                getF32Constant(DAG, 0x3f6ae232, dl));
5754       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5755       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5756                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5757     } else { // LimitFloatPrecision <= 18
5758       // For floating-point precision of 18:
5759       //
5760       //   Log10ofMantissa =
5761       //     -0.84299375f +
5762       //       (1.5327582f +
5763       //         (-1.0688956f +
5764       //           (0.49102474f +
5765       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5766       //
5767       // error 0.0000037995730, which is better than 18 bits
5768       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5769                                getF32Constant(DAG, 0x3c5d51ce, dl));
5770       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5771                                getF32Constant(DAG, 0x3e00685a, dl));
5772       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5773       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5774                                getF32Constant(DAG, 0x3efb6798, dl));
5775       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5776       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5777                                getF32Constant(DAG, 0x3f88d192, dl));
5778       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5779       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5780                                getF32Constant(DAG, 0x3fc4316c, dl));
5781       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5782       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5783                                     getF32Constant(DAG, 0x3f57ce70, dl));
5784     }
5785 
5786     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5787   }
5788 
5789   // No special expansion.
5790   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5791 }
5792 
5793 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5794 /// limited-precision mode.
5795 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5796                           const TargetLowering &TLI, SDNodeFlags Flags) {
5797   if (Op.getValueType() == MVT::f32 &&
5798       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5799     return getLimitedPrecisionExp2(Op, dl, DAG);
5800 
5801   // No special expansion.
5802   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5803 }
5804 
5805 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5806 /// limited-precision mode with x == 10.0f.
5807 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5808                          SelectionDAG &DAG, const TargetLowering &TLI,
5809                          SDNodeFlags Flags) {
5810   bool IsExp10 = false;
5811   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5812       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5813     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5814       APFloat Ten(10.0f);
5815       IsExp10 = LHSC->isExactlyValue(Ten);
5816     }
5817   }
5818 
5819   // TODO: What fast-math-flags should be set on the FMUL node?
5820   if (IsExp10) {
5821     // Put the exponent in the right bit position for later addition to the
5822     // final result:
5823     //
5824     //   #define LOG2OF10 3.3219281f
5825     //   t0 = Op * LOG2OF10;
5826     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5827                              getF32Constant(DAG, 0x40549a78, dl));
5828     return getLimitedPrecisionExp2(t0, dl, DAG);
5829   }
5830 
5831   // No special expansion.
5832   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5833 }
5834 
5835 /// ExpandPowI - Expand a llvm.powi intrinsic.
5836 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5837                           SelectionDAG &DAG) {
5838   // If RHS is a constant, we can expand this out to a multiplication tree if
5839   // it's beneficial on the target, otherwise we end up lowering to a call to
5840   // __powidf2 (for example).
5841   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5842     unsigned Val = RHSC->getSExtValue();
5843 
5844     // powi(x, 0) -> 1.0
5845     if (Val == 0)
5846       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5847 
5848     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5849             Val, DAG.shouldOptForSize())) {
5850       // Get the exponent as a positive value.
5851       if ((int)Val < 0)
5852         Val = -Val;
5853       // We use the simple binary decomposition method to generate the multiply
5854       // sequence.  There are more optimal ways to do this (for example,
5855       // powi(x,15) generates one more multiply than it should), but this has
5856       // the benefit of being both really simple and much better than a libcall.
5857       SDValue Res; // Logically starts equal to 1.0
5858       SDValue CurSquare = LHS;
5859       // TODO: Intrinsics should have fast-math-flags that propagate to these
5860       // nodes.
5861       while (Val) {
5862         if (Val & 1) {
5863           if (Res.getNode())
5864             Res =
5865                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5866           else
5867             Res = CurSquare; // 1.0*CurSquare.
5868         }
5869 
5870         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5871                                 CurSquare, CurSquare);
5872         Val >>= 1;
5873       }
5874 
5875       // If the original was negative, invert the result, producing 1/(x*x*x).
5876       if (RHSC->getSExtValue() < 0)
5877         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5878                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5879       return Res;
5880     }
5881   }
5882 
5883   // Otherwise, expand to a libcall.
5884   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5885 }
5886 
5887 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5888                             SDValue LHS, SDValue RHS, SDValue Scale,
5889                             SelectionDAG &DAG, const TargetLowering &TLI) {
5890   EVT VT = LHS.getValueType();
5891   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5892   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5893   LLVMContext &Ctx = *DAG.getContext();
5894 
5895   // If the type is legal but the operation isn't, this node might survive all
5896   // the way to operation legalization. If we end up there and we do not have
5897   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5898   // node.
5899 
5900   // Coax the legalizer into expanding the node during type legalization instead
5901   // by bumping the size by one bit. This will force it to Promote, enabling the
5902   // early expansion and avoiding the need to expand later.
5903 
5904   // We don't have to do this if Scale is 0; that can always be expanded, unless
5905   // it's a saturating signed operation. Those can experience true integer
5906   // division overflow, a case which we must avoid.
5907 
5908   // FIXME: We wouldn't have to do this (or any of the early
5909   // expansion/promotion) if it was possible to expand a libcall of an
5910   // illegal type during operation legalization. But it's not, so things
5911   // get a bit hacky.
5912   unsigned ScaleInt = Scale->getAsZExtVal();
5913   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5914       (TLI.isTypeLegal(VT) ||
5915        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5916     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5917         Opcode, VT, ScaleInt);
5918     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5919       EVT PromVT;
5920       if (VT.isScalarInteger())
5921         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5922       else if (VT.isVector()) {
5923         PromVT = VT.getVectorElementType();
5924         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5925         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5926       } else
5927         llvm_unreachable("Wrong VT for DIVFIX?");
5928       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5929       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5930       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5931       // For saturating operations, we need to shift up the LHS to get the
5932       // proper saturation width, and then shift down again afterwards.
5933       if (Saturating)
5934         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5935                           DAG.getConstant(1, DL, ShiftTy));
5936       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5937       if (Saturating)
5938         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5939                           DAG.getConstant(1, DL, ShiftTy));
5940       return DAG.getZExtOrTrunc(Res, DL, VT);
5941     }
5942   }
5943 
5944   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5945 }
5946 
5947 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5948 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5949 static void
5950 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5951                      const SDValue &N) {
5952   switch (N.getOpcode()) {
5953   case ISD::CopyFromReg: {
5954     SDValue Op = N.getOperand(1);
5955     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5956                       Op.getValueType().getSizeInBits());
5957     return;
5958   }
5959   case ISD::BITCAST:
5960   case ISD::AssertZext:
5961   case ISD::AssertSext:
5962   case ISD::TRUNCATE:
5963     getUnderlyingArgRegs(Regs, N.getOperand(0));
5964     return;
5965   case ISD::BUILD_PAIR:
5966   case ISD::BUILD_VECTOR:
5967   case ISD::CONCAT_VECTORS:
5968     for (SDValue Op : N->op_values())
5969       getUnderlyingArgRegs(Regs, Op);
5970     return;
5971   default:
5972     return;
5973   }
5974 }
5975 
5976 /// If the DbgValueInst is a dbg_value of a function argument, create the
5977 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5978 /// instruction selection, they will be inserted to the entry BB.
5979 /// We don't currently support this for variadic dbg_values, as they shouldn't
5980 /// appear for function arguments or in the prologue.
5981 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5982     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5983     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5984   const Argument *Arg = dyn_cast<Argument>(V);
5985   if (!Arg)
5986     return false;
5987 
5988   MachineFunction &MF = DAG.getMachineFunction();
5989   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5990 
5991   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5992   // we've been asked to pursue.
5993   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5994                               bool Indirect) {
5995     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5996       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5997       // pointing at the VReg, which will be patched up later.
5998       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5999       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6000           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6001           /* isKill */ false, /* isDead */ false,
6002           /* isUndef */ false, /* isEarlyClobber */ false,
6003           /* SubReg */ 0, /* isDebug */ true)});
6004 
6005       auto *NewDIExpr = FragExpr;
6006       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6007       // the DIExpression.
6008       if (Indirect)
6009         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6010       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6011       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6012       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6013     } else {
6014       // Create a completely standard DBG_VALUE.
6015       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6016       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6017     }
6018   };
6019 
6020   if (Kind == FuncArgumentDbgValueKind::Value) {
6021     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6022     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6023     // the entry block.
6024     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6025     if (!IsInEntryBlock)
6026       return false;
6027 
6028     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6029     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6030     // variable that also is a param.
6031     //
6032     // Although, if we are at the top of the entry block already, we can still
6033     // emit using ArgDbgValue. This might catch some situations when the
6034     // dbg.value refers to an argument that isn't used in the entry block, so
6035     // any CopyToReg node would be optimized out and the only way to express
6036     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6037     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6038     // we should only emit as ArgDbgValue if the Variable is an argument to the
6039     // current function, and the dbg.value intrinsic is found in the entry
6040     // block.
6041     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6042         !DL->getInlinedAt();
6043     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6044     if (!IsInPrologue && !VariableIsFunctionInputArg)
6045       return false;
6046 
6047     // Here we assume that a function argument on IR level only can be used to
6048     // describe one input parameter on source level. If we for example have
6049     // source code like this
6050     //
6051     //    struct A { long x, y; };
6052     //    void foo(struct A a, long b) {
6053     //      ...
6054     //      b = a.x;
6055     //      ...
6056     //    }
6057     //
6058     // and IR like this
6059     //
6060     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6061     //  entry:
6062     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6063     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6064     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6065     //    ...
6066     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6067     //    ...
6068     //
6069     // then the last dbg.value is describing a parameter "b" using a value that
6070     // is an argument. But since we already has used %a1 to describe a parameter
6071     // we should not handle that last dbg.value here (that would result in an
6072     // incorrect hoisting of the DBG_VALUE to the function entry).
6073     // Notice that we allow one dbg.value per IR level argument, to accommodate
6074     // for the situation with fragments above.
6075     // If there is no node for the value being handled, we return true to skip
6076     // the normal generation of debug info, as it would kill existing debug
6077     // info for the parameter in case of duplicates.
6078     if (VariableIsFunctionInputArg) {
6079       unsigned ArgNo = Arg->getArgNo();
6080       if (ArgNo >= FuncInfo.DescribedArgs.size())
6081         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6082       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6083         return !NodeMap[V].getNode();
6084       FuncInfo.DescribedArgs.set(ArgNo);
6085     }
6086   }
6087 
6088   bool IsIndirect = false;
6089   std::optional<MachineOperand> Op;
6090   // Some arguments' frame index is recorded during argument lowering.
6091   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6092   if (FI != std::numeric_limits<int>::max())
6093     Op = MachineOperand::CreateFI(FI);
6094 
6095   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6096   if (!Op && N.getNode()) {
6097     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6098     Register Reg;
6099     if (ArgRegsAndSizes.size() == 1)
6100       Reg = ArgRegsAndSizes.front().first;
6101 
6102     if (Reg && Reg.isVirtual()) {
6103       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6104       Register PR = RegInfo.getLiveInPhysReg(Reg);
6105       if (PR)
6106         Reg = PR;
6107     }
6108     if (Reg) {
6109       Op = MachineOperand::CreateReg(Reg, false);
6110       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6111     }
6112   }
6113 
6114   if (!Op && N.getNode()) {
6115     // Check if frame index is available.
6116     SDValue LCandidate = peekThroughBitcasts(N);
6117     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6118       if (FrameIndexSDNode *FINode =
6119           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6120         Op = MachineOperand::CreateFI(FINode->getIndex());
6121   }
6122 
6123   if (!Op) {
6124     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6125     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6126                                          SplitRegs) {
6127       unsigned Offset = 0;
6128       for (const auto &RegAndSize : SplitRegs) {
6129         // If the expression is already a fragment, the current register
6130         // offset+size might extend beyond the fragment. In this case, only
6131         // the register bits that are inside the fragment are relevant.
6132         int RegFragmentSizeInBits = RegAndSize.second;
6133         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6134           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6135           // The register is entirely outside the expression fragment,
6136           // so is irrelevant for debug info.
6137           if (Offset >= ExprFragmentSizeInBits)
6138             break;
6139           // The register is partially outside the expression fragment, only
6140           // the low bits within the fragment are relevant for debug info.
6141           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6142             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6143           }
6144         }
6145 
6146         auto FragmentExpr = DIExpression::createFragmentExpression(
6147             Expr, Offset, RegFragmentSizeInBits);
6148         Offset += RegAndSize.second;
6149         // If a valid fragment expression cannot be created, the variable's
6150         // correct value cannot be determined and so it is set as Undef.
6151         if (!FragmentExpr) {
6152           SDDbgValue *SDV = DAG.getConstantDbgValue(
6153               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6154           DAG.AddDbgValue(SDV, false);
6155           continue;
6156         }
6157         MachineInstr *NewMI =
6158             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6159                              Kind != FuncArgumentDbgValueKind::Value);
6160         FuncInfo.ArgDbgValues.push_back(NewMI);
6161       }
6162     };
6163 
6164     // Check if ValueMap has reg number.
6165     DenseMap<const Value *, Register>::const_iterator
6166       VMI = FuncInfo.ValueMap.find(V);
6167     if (VMI != FuncInfo.ValueMap.end()) {
6168       const auto &TLI = DAG.getTargetLoweringInfo();
6169       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6170                        V->getType(), std::nullopt);
6171       if (RFV.occupiesMultipleRegs()) {
6172         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6173         return true;
6174       }
6175 
6176       Op = MachineOperand::CreateReg(VMI->second, false);
6177       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6178     } else if (ArgRegsAndSizes.size() > 1) {
6179       // This was split due to the calling convention, and no virtual register
6180       // mapping exists for the value.
6181       splitMultiRegDbgValue(ArgRegsAndSizes);
6182       return true;
6183     }
6184   }
6185 
6186   if (!Op)
6187     return false;
6188 
6189   assert(Variable->isValidLocationForIntrinsic(DL) &&
6190          "Expected inlined-at fields to agree");
6191   MachineInstr *NewMI = nullptr;
6192 
6193   if (Op->isReg())
6194     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6195   else
6196     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6197                     Variable, Expr);
6198 
6199   // Otherwise, use ArgDbgValues.
6200   FuncInfo.ArgDbgValues.push_back(NewMI);
6201   return true;
6202 }
6203 
6204 /// Return the appropriate SDDbgValue based on N.
6205 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6206                                              DILocalVariable *Variable,
6207                                              DIExpression *Expr,
6208                                              const DebugLoc &dl,
6209                                              unsigned DbgSDNodeOrder) {
6210   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6211     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6212     // stack slot locations.
6213     //
6214     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6215     // debug values here after optimization:
6216     //
6217     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6218     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6219     //
6220     // Both describe the direct values of their associated variables.
6221     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6222                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6223   }
6224   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6225                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6226 }
6227 
6228 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6229   switch (Intrinsic) {
6230   case Intrinsic::smul_fix:
6231     return ISD::SMULFIX;
6232   case Intrinsic::umul_fix:
6233     return ISD::UMULFIX;
6234   case Intrinsic::smul_fix_sat:
6235     return ISD::SMULFIXSAT;
6236   case Intrinsic::umul_fix_sat:
6237     return ISD::UMULFIXSAT;
6238   case Intrinsic::sdiv_fix:
6239     return ISD::SDIVFIX;
6240   case Intrinsic::udiv_fix:
6241     return ISD::UDIVFIX;
6242   case Intrinsic::sdiv_fix_sat:
6243     return ISD::SDIVFIXSAT;
6244   case Intrinsic::udiv_fix_sat:
6245     return ISD::UDIVFIXSAT;
6246   default:
6247     llvm_unreachable("Unhandled fixed point intrinsic");
6248   }
6249 }
6250 
6251 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6252                                            const char *FunctionName) {
6253   assert(FunctionName && "FunctionName must not be nullptr");
6254   SDValue Callee = DAG.getExternalSymbol(
6255       FunctionName,
6256       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6257   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6258 }
6259 
6260 /// Given a @llvm.call.preallocated.setup, return the corresponding
6261 /// preallocated call.
6262 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6263   assert(cast<CallBase>(PreallocatedSetup)
6264                  ->getCalledFunction()
6265                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6266          "expected call_preallocated_setup Value");
6267   for (const auto *U : PreallocatedSetup->users()) {
6268     auto *UseCall = cast<CallBase>(U);
6269     const Function *Fn = UseCall->getCalledFunction();
6270     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6271       return UseCall;
6272     }
6273   }
6274   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6275 }
6276 
6277 /// If DI is a debug value with an EntryValue expression, lower it using the
6278 /// corresponding physical register of the associated Argument value
6279 /// (guaranteed to exist by the verifier).
6280 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6281     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6282     DIExpression *Expr, DebugLoc DbgLoc) {
6283   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6284     return false;
6285 
6286   // These properties are guaranteed by the verifier.
6287   const Argument *Arg = cast<Argument>(Values[0]);
6288   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6289 
6290   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6291   if (ArgIt == FuncInfo.ValueMap.end()) {
6292     LLVM_DEBUG(
6293         dbgs() << "Dropping dbg.value: expression is entry_value but "
6294                   "couldn't find an associated register for the Argument\n");
6295     return true;
6296   }
6297   Register ArgVReg = ArgIt->getSecond();
6298 
6299   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6300     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6301       SDDbgValue *SDV = DAG.getVRegDbgValue(
6302           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6303       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6304       return true;
6305     }
6306   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6307                        "couldn't find a physical register\n");
6308   return true;
6309 }
6310 
6311 /// Lower the call to the specified intrinsic function.
6312 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6313                                                   unsigned Intrinsic) {
6314   SDLoc sdl = getCurSDLoc();
6315   switch (Intrinsic) {
6316   case Intrinsic::experimental_convergence_anchor:
6317     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6318     break;
6319   case Intrinsic::experimental_convergence_entry:
6320     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6321     break;
6322   case Intrinsic::experimental_convergence_loop: {
6323     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6324     auto *Token = Bundle->Inputs[0].get();
6325     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6326                              getValue(Token)));
6327     break;
6328   }
6329   }
6330 }
6331 
6332 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6333                                                unsigned IntrinsicID) {
6334   // For now, we're only lowering an 'add' histogram.
6335   // We can add others later, e.g. saturating adds, min/max.
6336   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6337          "Tried to lower unsupported histogram type");
6338   SDLoc sdl = getCurSDLoc();
6339   Value *Ptr = I.getOperand(0);
6340   SDValue Inc = getValue(I.getOperand(1));
6341   SDValue Mask = getValue(I.getOperand(2));
6342 
6343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6344   DataLayout TargetDL = DAG.getDataLayout();
6345   EVT VT = Inc.getValueType();
6346   Align Alignment = DAG.getEVTAlign(VT);
6347 
6348   const MDNode *Ranges = getRangeMetadata(I);
6349 
6350   SDValue Root = DAG.getRoot();
6351   SDValue Base;
6352   SDValue Index;
6353   ISD::MemIndexType IndexType;
6354   SDValue Scale;
6355   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6356                                     I.getParent(), VT.getScalarStoreSize());
6357 
6358   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6359 
6360   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6361       MachinePointerInfo(AS),
6362       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6363       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6364 
6365   if (!UniformBase) {
6366     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6367     Index = getValue(Ptr);
6368     IndexType = ISD::SIGNED_SCALED;
6369     Scale =
6370         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6371   }
6372 
6373   EVT IdxVT = Index.getValueType();
6374   EVT EltTy = IdxVT.getVectorElementType();
6375   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6376     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6377     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6378   }
6379 
6380   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6381 
6382   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6383   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6384                                              Ops, MMO, IndexType);
6385 
6386   setValue(&I, Histogram);
6387   DAG.setRoot(Histogram);
6388 }
6389 
6390 /// Lower the call to the specified intrinsic function.
6391 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6392                                              unsigned Intrinsic) {
6393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6394   SDLoc sdl = getCurSDLoc();
6395   DebugLoc dl = getCurDebugLoc();
6396   SDValue Res;
6397 
6398   SDNodeFlags Flags;
6399   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6400     Flags.copyFMF(*FPOp);
6401 
6402   switch (Intrinsic) {
6403   default:
6404     // By default, turn this into a target intrinsic node.
6405     visitTargetIntrinsic(I, Intrinsic);
6406     return;
6407   case Intrinsic::vscale: {
6408     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6409     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6410     return;
6411   }
6412   case Intrinsic::vastart:  visitVAStart(I); return;
6413   case Intrinsic::vaend:    visitVAEnd(I); return;
6414   case Intrinsic::vacopy:   visitVACopy(I); return;
6415   case Intrinsic::returnaddress:
6416     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6417                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6418                              getValue(I.getArgOperand(0))));
6419     return;
6420   case Intrinsic::addressofreturnaddress:
6421     setValue(&I,
6422              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6423                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6424     return;
6425   case Intrinsic::sponentry:
6426     setValue(&I,
6427              DAG.getNode(ISD::SPONENTRY, sdl,
6428                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6429     return;
6430   case Intrinsic::frameaddress:
6431     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6432                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6433                              getValue(I.getArgOperand(0))));
6434     return;
6435   case Intrinsic::read_volatile_register:
6436   case Intrinsic::read_register: {
6437     Value *Reg = I.getArgOperand(0);
6438     SDValue Chain = getRoot();
6439     SDValue RegName =
6440         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6441     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6442     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6443       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6444     setValue(&I, Res);
6445     DAG.setRoot(Res.getValue(1));
6446     return;
6447   }
6448   case Intrinsic::write_register: {
6449     Value *Reg = I.getArgOperand(0);
6450     Value *RegValue = I.getArgOperand(1);
6451     SDValue Chain = getRoot();
6452     SDValue RegName =
6453         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6454     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6455                             RegName, getValue(RegValue)));
6456     return;
6457   }
6458   case Intrinsic::memcpy: {
6459     const auto &MCI = cast<MemCpyInst>(I);
6460     SDValue Op1 = getValue(I.getArgOperand(0));
6461     SDValue Op2 = getValue(I.getArgOperand(1));
6462     SDValue Op3 = getValue(I.getArgOperand(2));
6463     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6464     Align DstAlign = MCI.getDestAlign().valueOrOne();
6465     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6466     Align Alignment = std::min(DstAlign, SrcAlign);
6467     bool isVol = MCI.isVolatile();
6468     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6469     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6470     // node.
6471     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6472     SDValue MC = DAG.getMemcpy(
6473         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6474         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6475         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6476     updateDAGForMaybeTailCall(MC);
6477     return;
6478   }
6479   case Intrinsic::memcpy_inline: {
6480     const auto &MCI = cast<MemCpyInlineInst>(I);
6481     SDValue Dst = getValue(I.getArgOperand(0));
6482     SDValue Src = getValue(I.getArgOperand(1));
6483     SDValue Size = getValue(I.getArgOperand(2));
6484     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6485     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6486     Align DstAlign = MCI.getDestAlign().valueOrOne();
6487     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6488     Align Alignment = std::min(DstAlign, SrcAlign);
6489     bool isVol = MCI.isVolatile();
6490     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6491     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6492     // node.
6493     SDValue MC = DAG.getMemcpy(
6494         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6495         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6496         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6497     updateDAGForMaybeTailCall(MC);
6498     return;
6499   }
6500   case Intrinsic::memset: {
6501     const auto &MSI = cast<MemSetInst>(I);
6502     SDValue Op1 = getValue(I.getArgOperand(0));
6503     SDValue Op2 = getValue(I.getArgOperand(1));
6504     SDValue Op3 = getValue(I.getArgOperand(2));
6505     // @llvm.memset defines 0 and 1 to both mean no alignment.
6506     Align Alignment = MSI.getDestAlign().valueOrOne();
6507     bool isVol = MSI.isVolatile();
6508     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6509     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6510     SDValue MS = DAG.getMemset(
6511         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6512         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6513     updateDAGForMaybeTailCall(MS);
6514     return;
6515   }
6516   case Intrinsic::memset_inline: {
6517     const auto &MSII = cast<MemSetInlineInst>(I);
6518     SDValue Dst = getValue(I.getArgOperand(0));
6519     SDValue Value = getValue(I.getArgOperand(1));
6520     SDValue Size = getValue(I.getArgOperand(2));
6521     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6522     // @llvm.memset defines 0 and 1 to both mean no alignment.
6523     Align DstAlign = MSII.getDestAlign().valueOrOne();
6524     bool isVol = MSII.isVolatile();
6525     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6526     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6527     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6528                                /* AlwaysInline */ true, isTC,
6529                                MachinePointerInfo(I.getArgOperand(0)),
6530                                I.getAAMetadata());
6531     updateDAGForMaybeTailCall(MC);
6532     return;
6533   }
6534   case Intrinsic::memmove: {
6535     const auto &MMI = cast<MemMoveInst>(I);
6536     SDValue Op1 = getValue(I.getArgOperand(0));
6537     SDValue Op2 = getValue(I.getArgOperand(1));
6538     SDValue Op3 = getValue(I.getArgOperand(2));
6539     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6540     Align DstAlign = MMI.getDestAlign().valueOrOne();
6541     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6542     Align Alignment = std::min(DstAlign, SrcAlign);
6543     bool isVol = MMI.isVolatile();
6544     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6545     // FIXME: Support passing different dest/src alignments to the memmove DAG
6546     // node.
6547     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6548     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6549                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6550                                 MachinePointerInfo(I.getArgOperand(1)),
6551                                 I.getAAMetadata(), AA);
6552     updateDAGForMaybeTailCall(MM);
6553     return;
6554   }
6555   case Intrinsic::memcpy_element_unordered_atomic: {
6556     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6557     SDValue Dst = getValue(MI.getRawDest());
6558     SDValue Src = getValue(MI.getRawSource());
6559     SDValue Length = getValue(MI.getLength());
6560 
6561     Type *LengthTy = MI.getLength()->getType();
6562     unsigned ElemSz = MI.getElementSizeInBytes();
6563     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6564     SDValue MC =
6565         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6566                             isTC, MachinePointerInfo(MI.getRawDest()),
6567                             MachinePointerInfo(MI.getRawSource()));
6568     updateDAGForMaybeTailCall(MC);
6569     return;
6570   }
6571   case Intrinsic::memmove_element_unordered_atomic: {
6572     auto &MI = cast<AtomicMemMoveInst>(I);
6573     SDValue Dst = getValue(MI.getRawDest());
6574     SDValue Src = getValue(MI.getRawSource());
6575     SDValue Length = getValue(MI.getLength());
6576 
6577     Type *LengthTy = MI.getLength()->getType();
6578     unsigned ElemSz = MI.getElementSizeInBytes();
6579     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6580     SDValue MC =
6581         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6582                              isTC, MachinePointerInfo(MI.getRawDest()),
6583                              MachinePointerInfo(MI.getRawSource()));
6584     updateDAGForMaybeTailCall(MC);
6585     return;
6586   }
6587   case Intrinsic::memset_element_unordered_atomic: {
6588     auto &MI = cast<AtomicMemSetInst>(I);
6589     SDValue Dst = getValue(MI.getRawDest());
6590     SDValue Val = getValue(MI.getValue());
6591     SDValue Length = getValue(MI.getLength());
6592 
6593     Type *LengthTy = MI.getLength()->getType();
6594     unsigned ElemSz = MI.getElementSizeInBytes();
6595     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6596     SDValue MC =
6597         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6598                             isTC, MachinePointerInfo(MI.getRawDest()));
6599     updateDAGForMaybeTailCall(MC);
6600     return;
6601   }
6602   case Intrinsic::call_preallocated_setup: {
6603     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6604     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6605     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6606                               getRoot(), SrcValue);
6607     setValue(&I, Res);
6608     DAG.setRoot(Res);
6609     return;
6610   }
6611   case Intrinsic::call_preallocated_arg: {
6612     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6613     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6614     SDValue Ops[3];
6615     Ops[0] = getRoot();
6616     Ops[1] = SrcValue;
6617     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6618                                    MVT::i32); // arg index
6619     SDValue Res = DAG.getNode(
6620         ISD::PREALLOCATED_ARG, sdl,
6621         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6622     setValue(&I, Res);
6623     DAG.setRoot(Res.getValue(1));
6624     return;
6625   }
6626   case Intrinsic::dbg_declare: {
6627     const auto &DI = cast<DbgDeclareInst>(I);
6628     // Debug intrinsics are handled separately in assignment tracking mode.
6629     // Some intrinsics are handled right after Argument lowering.
6630     if (AssignmentTrackingEnabled ||
6631         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6632       return;
6633     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6634     DILocalVariable *Variable = DI.getVariable();
6635     DIExpression *Expression = DI.getExpression();
6636     dropDanglingDebugInfo(Variable, Expression);
6637     // Assume dbg.declare can not currently use DIArgList, i.e.
6638     // it is non-variadic.
6639     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6640     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6641                        DI.getDebugLoc());
6642     return;
6643   }
6644   case Intrinsic::dbg_label: {
6645     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6646     DILabel *Label = DI.getLabel();
6647     assert(Label && "Missing label");
6648 
6649     SDDbgLabel *SDV;
6650     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6651     DAG.AddDbgLabel(SDV);
6652     return;
6653   }
6654   case Intrinsic::dbg_assign: {
6655     // Debug intrinsics are handled separately in assignment tracking mode.
6656     if (AssignmentTrackingEnabled)
6657       return;
6658     // If assignment tracking hasn't been enabled then fall through and treat
6659     // the dbg.assign as a dbg.value.
6660     [[fallthrough]];
6661   }
6662   case Intrinsic::dbg_value: {
6663     // Debug intrinsics are handled separately in assignment tracking mode.
6664     if (AssignmentTrackingEnabled)
6665       return;
6666     const DbgValueInst &DI = cast<DbgValueInst>(I);
6667     assert(DI.getVariable() && "Missing variable");
6668 
6669     DILocalVariable *Variable = DI.getVariable();
6670     DIExpression *Expression = DI.getExpression();
6671     dropDanglingDebugInfo(Variable, Expression);
6672 
6673     if (DI.isKillLocation()) {
6674       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6675       return;
6676     }
6677 
6678     SmallVector<Value *, 4> Values(DI.getValues());
6679     if (Values.empty())
6680       return;
6681 
6682     bool IsVariadic = DI.hasArgList();
6683     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6684                           SDNodeOrder, IsVariadic))
6685       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6686                            DI.getDebugLoc(), SDNodeOrder);
6687     return;
6688   }
6689 
6690   case Intrinsic::eh_typeid_for: {
6691     // Find the type id for the given typeinfo.
6692     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6693     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6694     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6695     setValue(&I, Res);
6696     return;
6697   }
6698 
6699   case Intrinsic::eh_return_i32:
6700   case Intrinsic::eh_return_i64:
6701     DAG.getMachineFunction().setCallsEHReturn(true);
6702     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6703                             MVT::Other,
6704                             getControlRoot(),
6705                             getValue(I.getArgOperand(0)),
6706                             getValue(I.getArgOperand(1))));
6707     return;
6708   case Intrinsic::eh_unwind_init:
6709     DAG.getMachineFunction().setCallsUnwindInit(true);
6710     return;
6711   case Intrinsic::eh_dwarf_cfa:
6712     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6713                              TLI.getPointerTy(DAG.getDataLayout()),
6714                              getValue(I.getArgOperand(0))));
6715     return;
6716   case Intrinsic::eh_sjlj_callsite: {
6717     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6718     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6719     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6720 
6721     MMI.setCurrentCallSite(CI->getZExtValue());
6722     return;
6723   }
6724   case Intrinsic::eh_sjlj_functioncontext: {
6725     // Get and store the index of the function context.
6726     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6727     AllocaInst *FnCtx =
6728       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6729     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6730     MFI.setFunctionContextIndex(FI);
6731     return;
6732   }
6733   case Intrinsic::eh_sjlj_setjmp: {
6734     SDValue Ops[2];
6735     Ops[0] = getRoot();
6736     Ops[1] = getValue(I.getArgOperand(0));
6737     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6738                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6739     setValue(&I, Op.getValue(0));
6740     DAG.setRoot(Op.getValue(1));
6741     return;
6742   }
6743   case Intrinsic::eh_sjlj_longjmp:
6744     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6745                             getRoot(), getValue(I.getArgOperand(0))));
6746     return;
6747   case Intrinsic::eh_sjlj_setup_dispatch:
6748     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6749                             getRoot()));
6750     return;
6751   case Intrinsic::masked_gather:
6752     visitMaskedGather(I);
6753     return;
6754   case Intrinsic::masked_load:
6755     visitMaskedLoad(I);
6756     return;
6757   case Intrinsic::masked_scatter:
6758     visitMaskedScatter(I);
6759     return;
6760   case Intrinsic::masked_store:
6761     visitMaskedStore(I);
6762     return;
6763   case Intrinsic::masked_expandload:
6764     visitMaskedLoad(I, true /* IsExpanding */);
6765     return;
6766   case Intrinsic::masked_compressstore:
6767     visitMaskedStore(I, true /* IsCompressing */);
6768     return;
6769   case Intrinsic::powi:
6770     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6771                             getValue(I.getArgOperand(1)), DAG));
6772     return;
6773   case Intrinsic::log:
6774     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6775     return;
6776   case Intrinsic::log2:
6777     setValue(&I,
6778              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6779     return;
6780   case Intrinsic::log10:
6781     setValue(&I,
6782              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6783     return;
6784   case Intrinsic::exp:
6785     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6786     return;
6787   case Intrinsic::exp2:
6788     setValue(&I,
6789              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6790     return;
6791   case Intrinsic::pow:
6792     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6793                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6794     return;
6795   case Intrinsic::sqrt:
6796   case Intrinsic::fabs:
6797   case Intrinsic::sin:
6798   case Intrinsic::cos:
6799   case Intrinsic::tan:
6800   case Intrinsic::exp10:
6801   case Intrinsic::floor:
6802   case Intrinsic::ceil:
6803   case Intrinsic::trunc:
6804   case Intrinsic::rint:
6805   case Intrinsic::nearbyint:
6806   case Intrinsic::round:
6807   case Intrinsic::roundeven:
6808   case Intrinsic::canonicalize: {
6809     unsigned Opcode;
6810     // clang-format off
6811     switch (Intrinsic) {
6812     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6813     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6814     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6815     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6816     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6817     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6818     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6819     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6820     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6821     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6822     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6823     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6824     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6825     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6826     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6827     }
6828     // clang-format on
6829 
6830     setValue(&I, DAG.getNode(Opcode, sdl,
6831                              getValue(I.getArgOperand(0)).getValueType(),
6832                              getValue(I.getArgOperand(0)), Flags));
6833     return;
6834   }
6835   case Intrinsic::lround:
6836   case Intrinsic::llround:
6837   case Intrinsic::lrint:
6838   case Intrinsic::llrint: {
6839     unsigned Opcode;
6840     // clang-format off
6841     switch (Intrinsic) {
6842     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6843     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6844     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6845     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6846     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6847     }
6848     // clang-format on
6849 
6850     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6851     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6852                              getValue(I.getArgOperand(0))));
6853     return;
6854   }
6855   case Intrinsic::minnum:
6856     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6857                              getValue(I.getArgOperand(0)).getValueType(),
6858                              getValue(I.getArgOperand(0)),
6859                              getValue(I.getArgOperand(1)), Flags));
6860     return;
6861   case Intrinsic::maxnum:
6862     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6863                              getValue(I.getArgOperand(0)).getValueType(),
6864                              getValue(I.getArgOperand(0)),
6865                              getValue(I.getArgOperand(1)), Flags));
6866     return;
6867   case Intrinsic::minimum:
6868     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6869                              getValue(I.getArgOperand(0)).getValueType(),
6870                              getValue(I.getArgOperand(0)),
6871                              getValue(I.getArgOperand(1)), Flags));
6872     return;
6873   case Intrinsic::maximum:
6874     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6875                              getValue(I.getArgOperand(0)).getValueType(),
6876                              getValue(I.getArgOperand(0)),
6877                              getValue(I.getArgOperand(1)), Flags));
6878     return;
6879   case Intrinsic::copysign:
6880     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6881                              getValue(I.getArgOperand(0)).getValueType(),
6882                              getValue(I.getArgOperand(0)),
6883                              getValue(I.getArgOperand(1)), Flags));
6884     return;
6885   case Intrinsic::ldexp:
6886     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6887                              getValue(I.getArgOperand(0)).getValueType(),
6888                              getValue(I.getArgOperand(0)),
6889                              getValue(I.getArgOperand(1)), Flags));
6890     return;
6891   case Intrinsic::frexp: {
6892     SmallVector<EVT, 2> ValueVTs;
6893     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6894     SDVTList VTs = DAG.getVTList(ValueVTs);
6895     setValue(&I,
6896              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6897     return;
6898   }
6899   case Intrinsic::arithmetic_fence: {
6900     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6901                              getValue(I.getArgOperand(0)).getValueType(),
6902                              getValue(I.getArgOperand(0)), Flags));
6903     return;
6904   }
6905   case Intrinsic::fma:
6906     setValue(&I, DAG.getNode(
6907                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6908                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6909                      getValue(I.getArgOperand(2)), Flags));
6910     return;
6911 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6912   case Intrinsic::INTRINSIC:
6913 #include "llvm/IR/ConstrainedOps.def"
6914     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6915     return;
6916 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6917 #include "llvm/IR/VPIntrinsics.def"
6918     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6919     return;
6920   case Intrinsic::fptrunc_round: {
6921     // Get the last argument, the metadata and convert it to an integer in the
6922     // call
6923     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6924     std::optional<RoundingMode> RoundMode =
6925         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6926 
6927     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6928 
6929     // Propagate fast-math-flags from IR to node(s).
6930     SDNodeFlags Flags;
6931     Flags.copyFMF(*cast<FPMathOperator>(&I));
6932     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6933 
6934     SDValue Result;
6935     Result = DAG.getNode(
6936         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6937         DAG.getTargetConstant((int)*RoundMode, sdl,
6938                               TLI.getPointerTy(DAG.getDataLayout())));
6939     setValue(&I, Result);
6940 
6941     return;
6942   }
6943   case Intrinsic::fmuladd: {
6944     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6945     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6946         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6947       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6948                                getValue(I.getArgOperand(0)).getValueType(),
6949                                getValue(I.getArgOperand(0)),
6950                                getValue(I.getArgOperand(1)),
6951                                getValue(I.getArgOperand(2)), Flags));
6952     } else {
6953       // TODO: Intrinsic calls should have fast-math-flags.
6954       SDValue Mul = DAG.getNode(
6955           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6956           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6957       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6958                                 getValue(I.getArgOperand(0)).getValueType(),
6959                                 Mul, getValue(I.getArgOperand(2)), Flags);
6960       setValue(&I, Add);
6961     }
6962     return;
6963   }
6964   case Intrinsic::convert_to_fp16:
6965     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6966                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6967                                          getValue(I.getArgOperand(0)),
6968                                          DAG.getTargetConstant(0, sdl,
6969                                                                MVT::i32))));
6970     return;
6971   case Intrinsic::convert_from_fp16:
6972     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6973                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6974                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6975                                          getValue(I.getArgOperand(0)))));
6976     return;
6977   case Intrinsic::fptosi_sat: {
6978     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6979     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6980                              getValue(I.getArgOperand(0)),
6981                              DAG.getValueType(VT.getScalarType())));
6982     return;
6983   }
6984   case Intrinsic::fptoui_sat: {
6985     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6986     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6987                              getValue(I.getArgOperand(0)),
6988                              DAG.getValueType(VT.getScalarType())));
6989     return;
6990   }
6991   case Intrinsic::set_rounding:
6992     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6993                       {getRoot(), getValue(I.getArgOperand(0))});
6994     setValue(&I, Res);
6995     DAG.setRoot(Res.getValue(0));
6996     return;
6997   case Intrinsic::is_fpclass: {
6998     const DataLayout DLayout = DAG.getDataLayout();
6999     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7000     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7001     FPClassTest Test = static_cast<FPClassTest>(
7002         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7003     MachineFunction &MF = DAG.getMachineFunction();
7004     const Function &F = MF.getFunction();
7005     SDValue Op = getValue(I.getArgOperand(0));
7006     SDNodeFlags Flags;
7007     Flags.setNoFPExcept(
7008         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7009     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7010     // expansion can use illegal types. Making expansion early allows
7011     // legalizing these types prior to selection.
7012     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
7013       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7014       setValue(&I, Result);
7015       return;
7016     }
7017 
7018     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7019     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7020     setValue(&I, V);
7021     return;
7022   }
7023   case Intrinsic::get_fpenv: {
7024     const DataLayout DLayout = DAG.getDataLayout();
7025     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7026     Align TempAlign = DAG.getEVTAlign(EnvVT);
7027     SDValue Chain = getRoot();
7028     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7029     // and temporary storage in stack.
7030     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7031       Res = DAG.getNode(
7032           ISD::GET_FPENV, sdl,
7033           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7034                         MVT::Other),
7035           Chain);
7036     } else {
7037       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7038       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7039       auto MPI =
7040           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7041       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7042           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7043           TempAlign);
7044       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7045       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7046     }
7047     setValue(&I, Res);
7048     DAG.setRoot(Res.getValue(1));
7049     return;
7050   }
7051   case Intrinsic::set_fpenv: {
7052     const DataLayout DLayout = DAG.getDataLayout();
7053     SDValue Env = getValue(I.getArgOperand(0));
7054     EVT EnvVT = Env.getValueType();
7055     Align TempAlign = DAG.getEVTAlign(EnvVT);
7056     SDValue Chain = getRoot();
7057     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7058     // environment from memory.
7059     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7060       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7061     } else {
7062       // Allocate space in stack, copy environment bits into it and use this
7063       // memory in SET_FPENV_MEM.
7064       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7065       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7066       auto MPI =
7067           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7068       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7069                            MachineMemOperand::MOStore);
7070       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7071           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7072           TempAlign);
7073       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7074     }
7075     DAG.setRoot(Chain);
7076     return;
7077   }
7078   case Intrinsic::reset_fpenv:
7079     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7080     return;
7081   case Intrinsic::get_fpmode:
7082     Res = DAG.getNode(
7083         ISD::GET_FPMODE, sdl,
7084         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7085                       MVT::Other),
7086         DAG.getRoot());
7087     setValue(&I, Res);
7088     DAG.setRoot(Res.getValue(1));
7089     return;
7090   case Intrinsic::set_fpmode:
7091     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7092                       getValue(I.getArgOperand(0)));
7093     DAG.setRoot(Res);
7094     return;
7095   case Intrinsic::reset_fpmode: {
7096     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7097     DAG.setRoot(Res);
7098     return;
7099   }
7100   case Intrinsic::pcmarker: {
7101     SDValue Tmp = getValue(I.getArgOperand(0));
7102     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7103     return;
7104   }
7105   case Intrinsic::readcyclecounter: {
7106     SDValue Op = getRoot();
7107     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7108                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7109     setValue(&I, Res);
7110     DAG.setRoot(Res.getValue(1));
7111     return;
7112   }
7113   case Intrinsic::readsteadycounter: {
7114     SDValue Op = getRoot();
7115     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7116                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7117     setValue(&I, Res);
7118     DAG.setRoot(Res.getValue(1));
7119     return;
7120   }
7121   case Intrinsic::bitreverse:
7122     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7123                              getValue(I.getArgOperand(0)).getValueType(),
7124                              getValue(I.getArgOperand(0))));
7125     return;
7126   case Intrinsic::bswap:
7127     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7128                              getValue(I.getArgOperand(0)).getValueType(),
7129                              getValue(I.getArgOperand(0))));
7130     return;
7131   case Intrinsic::cttz: {
7132     SDValue Arg = getValue(I.getArgOperand(0));
7133     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7134     EVT Ty = Arg.getValueType();
7135     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7136                              sdl, Ty, Arg));
7137     return;
7138   }
7139   case Intrinsic::ctlz: {
7140     SDValue Arg = getValue(I.getArgOperand(0));
7141     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7142     EVT Ty = Arg.getValueType();
7143     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7144                              sdl, Ty, Arg));
7145     return;
7146   }
7147   case Intrinsic::ctpop: {
7148     SDValue Arg = getValue(I.getArgOperand(0));
7149     EVT Ty = Arg.getValueType();
7150     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7151     return;
7152   }
7153   case Intrinsic::fshl:
7154   case Intrinsic::fshr: {
7155     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7156     SDValue X = getValue(I.getArgOperand(0));
7157     SDValue Y = getValue(I.getArgOperand(1));
7158     SDValue Z = getValue(I.getArgOperand(2));
7159     EVT VT = X.getValueType();
7160 
7161     if (X == Y) {
7162       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7163       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7164     } else {
7165       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7166       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7167     }
7168     return;
7169   }
7170   case Intrinsic::sadd_sat: {
7171     SDValue Op1 = getValue(I.getArgOperand(0));
7172     SDValue Op2 = getValue(I.getArgOperand(1));
7173     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7174     return;
7175   }
7176   case Intrinsic::uadd_sat: {
7177     SDValue Op1 = getValue(I.getArgOperand(0));
7178     SDValue Op2 = getValue(I.getArgOperand(1));
7179     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7180     return;
7181   }
7182   case Intrinsic::ssub_sat: {
7183     SDValue Op1 = getValue(I.getArgOperand(0));
7184     SDValue Op2 = getValue(I.getArgOperand(1));
7185     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7186     return;
7187   }
7188   case Intrinsic::usub_sat: {
7189     SDValue Op1 = getValue(I.getArgOperand(0));
7190     SDValue Op2 = getValue(I.getArgOperand(1));
7191     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7192     return;
7193   }
7194   case Intrinsic::sshl_sat: {
7195     SDValue Op1 = getValue(I.getArgOperand(0));
7196     SDValue Op2 = getValue(I.getArgOperand(1));
7197     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7198     return;
7199   }
7200   case Intrinsic::ushl_sat: {
7201     SDValue Op1 = getValue(I.getArgOperand(0));
7202     SDValue Op2 = getValue(I.getArgOperand(1));
7203     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7204     return;
7205   }
7206   case Intrinsic::smul_fix:
7207   case Intrinsic::umul_fix:
7208   case Intrinsic::smul_fix_sat:
7209   case Intrinsic::umul_fix_sat: {
7210     SDValue Op1 = getValue(I.getArgOperand(0));
7211     SDValue Op2 = getValue(I.getArgOperand(1));
7212     SDValue Op3 = getValue(I.getArgOperand(2));
7213     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7214                              Op1.getValueType(), Op1, Op2, Op3));
7215     return;
7216   }
7217   case Intrinsic::sdiv_fix:
7218   case Intrinsic::udiv_fix:
7219   case Intrinsic::sdiv_fix_sat:
7220   case Intrinsic::udiv_fix_sat: {
7221     SDValue Op1 = getValue(I.getArgOperand(0));
7222     SDValue Op2 = getValue(I.getArgOperand(1));
7223     SDValue Op3 = getValue(I.getArgOperand(2));
7224     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7225                               Op1, Op2, Op3, DAG, TLI));
7226     return;
7227   }
7228   case Intrinsic::smax: {
7229     SDValue Op1 = getValue(I.getArgOperand(0));
7230     SDValue Op2 = getValue(I.getArgOperand(1));
7231     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7232     return;
7233   }
7234   case Intrinsic::smin: {
7235     SDValue Op1 = getValue(I.getArgOperand(0));
7236     SDValue Op2 = getValue(I.getArgOperand(1));
7237     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7238     return;
7239   }
7240   case Intrinsic::umax: {
7241     SDValue Op1 = getValue(I.getArgOperand(0));
7242     SDValue Op2 = getValue(I.getArgOperand(1));
7243     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7244     return;
7245   }
7246   case Intrinsic::umin: {
7247     SDValue Op1 = getValue(I.getArgOperand(0));
7248     SDValue Op2 = getValue(I.getArgOperand(1));
7249     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7250     return;
7251   }
7252   case Intrinsic::abs: {
7253     // TODO: Preserve "int min is poison" arg in SDAG?
7254     SDValue Op1 = getValue(I.getArgOperand(0));
7255     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7256     return;
7257   }
7258   case Intrinsic::scmp: {
7259     SDValue Op1 = getValue(I.getArgOperand(0));
7260     SDValue Op2 = getValue(I.getArgOperand(1));
7261     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7262     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7263     break;
7264   }
7265   case Intrinsic::ucmp: {
7266     SDValue Op1 = getValue(I.getArgOperand(0));
7267     SDValue Op2 = getValue(I.getArgOperand(1));
7268     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7269     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7270     break;
7271   }
7272   case Intrinsic::stacksave: {
7273     SDValue Op = getRoot();
7274     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7275     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7276     setValue(&I, Res);
7277     DAG.setRoot(Res.getValue(1));
7278     return;
7279   }
7280   case Intrinsic::stackrestore:
7281     Res = getValue(I.getArgOperand(0));
7282     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7283     return;
7284   case Intrinsic::get_dynamic_area_offset: {
7285     SDValue Op = getRoot();
7286     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7287     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7288     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7289     // target.
7290     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7291       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7292                          " intrinsic!");
7293     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7294                       Op);
7295     DAG.setRoot(Op);
7296     setValue(&I, Res);
7297     return;
7298   }
7299   case Intrinsic::stackguard: {
7300     MachineFunction &MF = DAG.getMachineFunction();
7301     const Module &M = *MF.getFunction().getParent();
7302     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7303     SDValue Chain = getRoot();
7304     if (TLI.useLoadStackGuardNode()) {
7305       Res = getLoadStackGuard(DAG, sdl, Chain);
7306       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7307     } else {
7308       const Value *Global = TLI.getSDagStackGuard(M);
7309       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7310       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7311                         MachinePointerInfo(Global, 0), Align,
7312                         MachineMemOperand::MOVolatile);
7313     }
7314     if (TLI.useStackGuardXorFP())
7315       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7316     DAG.setRoot(Chain);
7317     setValue(&I, Res);
7318     return;
7319   }
7320   case Intrinsic::stackprotector: {
7321     // Emit code into the DAG to store the stack guard onto the stack.
7322     MachineFunction &MF = DAG.getMachineFunction();
7323     MachineFrameInfo &MFI = MF.getFrameInfo();
7324     SDValue Src, Chain = getRoot();
7325 
7326     if (TLI.useLoadStackGuardNode())
7327       Src = getLoadStackGuard(DAG, sdl, Chain);
7328     else
7329       Src = getValue(I.getArgOperand(0));   // The guard's value.
7330 
7331     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7332 
7333     int FI = FuncInfo.StaticAllocaMap[Slot];
7334     MFI.setStackProtectorIndex(FI);
7335     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7336 
7337     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7338 
7339     // Store the stack protector onto the stack.
7340     Res = DAG.getStore(
7341         Chain, sdl, Src, FIN,
7342         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7343         MaybeAlign(), MachineMemOperand::MOVolatile);
7344     setValue(&I, Res);
7345     DAG.setRoot(Res);
7346     return;
7347   }
7348   case Intrinsic::objectsize:
7349     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7350 
7351   case Intrinsic::is_constant:
7352     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7353 
7354   case Intrinsic::annotation:
7355   case Intrinsic::ptr_annotation:
7356   case Intrinsic::launder_invariant_group:
7357   case Intrinsic::strip_invariant_group:
7358     // Drop the intrinsic, but forward the value
7359     setValue(&I, getValue(I.getOperand(0)));
7360     return;
7361 
7362   case Intrinsic::assume:
7363   case Intrinsic::experimental_noalias_scope_decl:
7364   case Intrinsic::var_annotation:
7365   case Intrinsic::sideeffect:
7366     // Discard annotate attributes, noalias scope declarations, assumptions, and
7367     // artificial side-effects.
7368     return;
7369 
7370   case Intrinsic::codeview_annotation: {
7371     // Emit a label associated with this metadata.
7372     MachineFunction &MF = DAG.getMachineFunction();
7373     MCSymbol *Label =
7374         MF.getMMI().getContext().createTempSymbol("annotation", true);
7375     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7376     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7377     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7378     DAG.setRoot(Res);
7379     return;
7380   }
7381 
7382   case Intrinsic::init_trampoline: {
7383     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7384 
7385     SDValue Ops[6];
7386     Ops[0] = getRoot();
7387     Ops[1] = getValue(I.getArgOperand(0));
7388     Ops[2] = getValue(I.getArgOperand(1));
7389     Ops[3] = getValue(I.getArgOperand(2));
7390     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7391     Ops[5] = DAG.getSrcValue(F);
7392 
7393     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7394 
7395     DAG.setRoot(Res);
7396     return;
7397   }
7398   case Intrinsic::adjust_trampoline:
7399     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7400                              TLI.getPointerTy(DAG.getDataLayout()),
7401                              getValue(I.getArgOperand(0))));
7402     return;
7403   case Intrinsic::gcroot: {
7404     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7405            "only valid in functions with gc specified, enforced by Verifier");
7406     assert(GFI && "implied by previous");
7407     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7408     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7409 
7410     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7411     GFI->addStackRoot(FI->getIndex(), TypeMap);
7412     return;
7413   }
7414   case Intrinsic::gcread:
7415   case Intrinsic::gcwrite:
7416     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7417   case Intrinsic::get_rounding:
7418     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7419     setValue(&I, Res);
7420     DAG.setRoot(Res.getValue(1));
7421     return;
7422 
7423   case Intrinsic::expect:
7424     // Just replace __builtin_expect(exp, c) with EXP.
7425     setValue(&I, getValue(I.getArgOperand(0)));
7426     return;
7427 
7428   case Intrinsic::ubsantrap:
7429   case Intrinsic::debugtrap:
7430   case Intrinsic::trap: {
7431     StringRef TrapFuncName =
7432         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7433     if (TrapFuncName.empty()) {
7434       switch (Intrinsic) {
7435       case Intrinsic::trap:
7436         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7437         break;
7438       case Intrinsic::debugtrap:
7439         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7440         break;
7441       case Intrinsic::ubsantrap:
7442         DAG.setRoot(DAG.getNode(
7443             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7444             DAG.getTargetConstant(
7445                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7446                 MVT::i32)));
7447         break;
7448       default: llvm_unreachable("unknown trap intrinsic");
7449       }
7450       return;
7451     }
7452     TargetLowering::ArgListTy Args;
7453     if (Intrinsic == Intrinsic::ubsantrap) {
7454       Args.push_back(TargetLoweringBase::ArgListEntry());
7455       Args[0].Val = I.getArgOperand(0);
7456       Args[0].Node = getValue(Args[0].Val);
7457       Args[0].Ty = Args[0].Val->getType();
7458     }
7459 
7460     TargetLowering::CallLoweringInfo CLI(DAG);
7461     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7462         CallingConv::C, I.getType(),
7463         DAG.getExternalSymbol(TrapFuncName.data(),
7464                               TLI.getPointerTy(DAG.getDataLayout())),
7465         std::move(Args));
7466 
7467     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7468     DAG.setRoot(Result.second);
7469     return;
7470   }
7471 
7472   case Intrinsic::allow_runtime_check:
7473   case Intrinsic::allow_ubsan_check:
7474     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7475     return;
7476 
7477   case Intrinsic::uadd_with_overflow:
7478   case Intrinsic::sadd_with_overflow:
7479   case Intrinsic::usub_with_overflow:
7480   case Intrinsic::ssub_with_overflow:
7481   case Intrinsic::umul_with_overflow:
7482   case Intrinsic::smul_with_overflow: {
7483     ISD::NodeType Op;
7484     switch (Intrinsic) {
7485     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7486     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7487     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7488     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7489     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7490     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7491     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7492     }
7493     SDValue Op1 = getValue(I.getArgOperand(0));
7494     SDValue Op2 = getValue(I.getArgOperand(1));
7495 
7496     EVT ResultVT = Op1.getValueType();
7497     EVT OverflowVT = MVT::i1;
7498     if (ResultVT.isVector())
7499       OverflowVT = EVT::getVectorVT(
7500           *Context, OverflowVT, ResultVT.getVectorElementCount());
7501 
7502     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7503     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7504     return;
7505   }
7506   case Intrinsic::prefetch: {
7507     SDValue Ops[5];
7508     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7509     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7510     Ops[0] = DAG.getRoot();
7511     Ops[1] = getValue(I.getArgOperand(0));
7512     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7513                                    MVT::i32);
7514     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7515                                    MVT::i32);
7516     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7517                                    MVT::i32);
7518     SDValue Result = DAG.getMemIntrinsicNode(
7519         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7520         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7521         /* align */ std::nullopt, Flags);
7522 
7523     // Chain the prefetch in parallel with any pending loads, to stay out of
7524     // the way of later optimizations.
7525     PendingLoads.push_back(Result);
7526     Result = getRoot();
7527     DAG.setRoot(Result);
7528     return;
7529   }
7530   case Intrinsic::lifetime_start:
7531   case Intrinsic::lifetime_end: {
7532     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7533     // Stack coloring is not enabled in O0, discard region information.
7534     if (TM.getOptLevel() == CodeGenOptLevel::None)
7535       return;
7536 
7537     const int64_t ObjectSize =
7538         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7539     Value *const ObjectPtr = I.getArgOperand(1);
7540     SmallVector<const Value *, 4> Allocas;
7541     getUnderlyingObjects(ObjectPtr, Allocas);
7542 
7543     for (const Value *Alloca : Allocas) {
7544       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7545 
7546       // Could not find an Alloca.
7547       if (!LifetimeObject)
7548         continue;
7549 
7550       // First check that the Alloca is static, otherwise it won't have a
7551       // valid frame index.
7552       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7553       if (SI == FuncInfo.StaticAllocaMap.end())
7554         return;
7555 
7556       const int FrameIndex = SI->second;
7557       int64_t Offset;
7558       if (GetPointerBaseWithConstantOffset(
7559               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7560         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7561       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7562                                 Offset);
7563       DAG.setRoot(Res);
7564     }
7565     return;
7566   }
7567   case Intrinsic::pseudoprobe: {
7568     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7569     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7570     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7571     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7572     DAG.setRoot(Res);
7573     return;
7574   }
7575   case Intrinsic::invariant_start:
7576     // Discard region information.
7577     setValue(&I,
7578              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7579     return;
7580   case Intrinsic::invariant_end:
7581     // Discard region information.
7582     return;
7583   case Intrinsic::clear_cache: {
7584     SDValue InputChain = DAG.getRoot();
7585     SDValue StartVal = getValue(I.getArgOperand(0));
7586     SDValue EndVal = getValue(I.getArgOperand(1));
7587     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7588                       {InputChain, StartVal, EndVal});
7589     setValue(&I, Res);
7590     DAG.setRoot(Res);
7591     return;
7592   }
7593   case Intrinsic::donothing:
7594   case Intrinsic::seh_try_begin:
7595   case Intrinsic::seh_scope_begin:
7596   case Intrinsic::seh_try_end:
7597   case Intrinsic::seh_scope_end:
7598     // ignore
7599     return;
7600   case Intrinsic::experimental_stackmap:
7601     visitStackmap(I);
7602     return;
7603   case Intrinsic::experimental_patchpoint_void:
7604   case Intrinsic::experimental_patchpoint:
7605     visitPatchpoint(I);
7606     return;
7607   case Intrinsic::experimental_gc_statepoint:
7608     LowerStatepoint(cast<GCStatepointInst>(I));
7609     return;
7610   case Intrinsic::experimental_gc_result:
7611     visitGCResult(cast<GCResultInst>(I));
7612     return;
7613   case Intrinsic::experimental_gc_relocate:
7614     visitGCRelocate(cast<GCRelocateInst>(I));
7615     return;
7616   case Intrinsic::instrprof_cover:
7617     llvm_unreachable("instrprof failed to lower a cover");
7618   case Intrinsic::instrprof_increment:
7619     llvm_unreachable("instrprof failed to lower an increment");
7620   case Intrinsic::instrprof_timestamp:
7621     llvm_unreachable("instrprof failed to lower a timestamp");
7622   case Intrinsic::instrprof_value_profile:
7623     llvm_unreachable("instrprof failed to lower a value profiling call");
7624   case Intrinsic::instrprof_mcdc_parameters:
7625     llvm_unreachable("instrprof failed to lower mcdc parameters");
7626   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7627     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7628   case Intrinsic::localescape: {
7629     MachineFunction &MF = DAG.getMachineFunction();
7630     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7631 
7632     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7633     // is the same on all targets.
7634     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7635       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7636       if (isa<ConstantPointerNull>(Arg))
7637         continue; // Skip null pointers. They represent a hole in index space.
7638       AllocaInst *Slot = cast<AllocaInst>(Arg);
7639       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7640              "can only escape static allocas");
7641       int FI = FuncInfo.StaticAllocaMap[Slot];
7642       MCSymbol *FrameAllocSym =
7643           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7644               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7645       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7646               TII->get(TargetOpcode::LOCAL_ESCAPE))
7647           .addSym(FrameAllocSym)
7648           .addFrameIndex(FI);
7649     }
7650 
7651     return;
7652   }
7653 
7654   case Intrinsic::localrecover: {
7655     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7656     MachineFunction &MF = DAG.getMachineFunction();
7657 
7658     // Get the symbol that defines the frame offset.
7659     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7660     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7661     unsigned IdxVal =
7662         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7663     MCSymbol *FrameAllocSym =
7664         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7665             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7666 
7667     Value *FP = I.getArgOperand(1);
7668     SDValue FPVal = getValue(FP);
7669     EVT PtrVT = FPVal.getValueType();
7670 
7671     // Create a MCSymbol for the label to avoid any target lowering
7672     // that would make this PC relative.
7673     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7674     SDValue OffsetVal =
7675         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7676 
7677     // Add the offset to the FP.
7678     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7679     setValue(&I, Add);
7680 
7681     return;
7682   }
7683 
7684   case Intrinsic::eh_exceptionpointer:
7685   case Intrinsic::eh_exceptioncode: {
7686     // Get the exception pointer vreg, copy from it, and resize it to fit.
7687     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7688     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7689     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7690     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7691     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7692     if (Intrinsic == Intrinsic::eh_exceptioncode)
7693       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7694     setValue(&I, N);
7695     return;
7696   }
7697   case Intrinsic::xray_customevent: {
7698     // Here we want to make sure that the intrinsic behaves as if it has a
7699     // specific calling convention.
7700     const auto &Triple = DAG.getTarget().getTargetTriple();
7701     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7702       return;
7703 
7704     SmallVector<SDValue, 8> Ops;
7705 
7706     // We want to say that we always want the arguments in registers.
7707     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7708     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7709     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7710     SDValue Chain = getRoot();
7711     Ops.push_back(LogEntryVal);
7712     Ops.push_back(StrSizeVal);
7713     Ops.push_back(Chain);
7714 
7715     // We need to enforce the calling convention for the callsite, so that
7716     // argument ordering is enforced correctly, and that register allocation can
7717     // see that some registers may be assumed clobbered and have to preserve
7718     // them across calls to the intrinsic.
7719     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7720                                            sdl, NodeTys, Ops);
7721     SDValue patchableNode = SDValue(MN, 0);
7722     DAG.setRoot(patchableNode);
7723     setValue(&I, patchableNode);
7724     return;
7725   }
7726   case Intrinsic::xray_typedevent: {
7727     // Here we want to make sure that the intrinsic behaves as if it has a
7728     // specific calling convention.
7729     const auto &Triple = DAG.getTarget().getTargetTriple();
7730     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7731       return;
7732 
7733     SmallVector<SDValue, 8> Ops;
7734 
7735     // We want to say that we always want the arguments in registers.
7736     // It's unclear to me how manipulating the selection DAG here forces callers
7737     // to provide arguments in registers instead of on the stack.
7738     SDValue LogTypeId = getValue(I.getArgOperand(0));
7739     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7740     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7741     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7742     SDValue Chain = getRoot();
7743     Ops.push_back(LogTypeId);
7744     Ops.push_back(LogEntryVal);
7745     Ops.push_back(StrSizeVal);
7746     Ops.push_back(Chain);
7747 
7748     // We need to enforce the calling convention for the callsite, so that
7749     // argument ordering is enforced correctly, and that register allocation can
7750     // see that some registers may be assumed clobbered and have to preserve
7751     // them across calls to the intrinsic.
7752     MachineSDNode *MN = DAG.getMachineNode(
7753         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7754     SDValue patchableNode = SDValue(MN, 0);
7755     DAG.setRoot(patchableNode);
7756     setValue(&I, patchableNode);
7757     return;
7758   }
7759   case Intrinsic::experimental_deoptimize:
7760     LowerDeoptimizeCall(&I);
7761     return;
7762   case Intrinsic::experimental_stepvector:
7763     visitStepVector(I);
7764     return;
7765   case Intrinsic::vector_reduce_fadd:
7766   case Intrinsic::vector_reduce_fmul:
7767   case Intrinsic::vector_reduce_add:
7768   case Intrinsic::vector_reduce_mul:
7769   case Intrinsic::vector_reduce_and:
7770   case Intrinsic::vector_reduce_or:
7771   case Intrinsic::vector_reduce_xor:
7772   case Intrinsic::vector_reduce_smax:
7773   case Intrinsic::vector_reduce_smin:
7774   case Intrinsic::vector_reduce_umax:
7775   case Intrinsic::vector_reduce_umin:
7776   case Intrinsic::vector_reduce_fmax:
7777   case Intrinsic::vector_reduce_fmin:
7778   case Intrinsic::vector_reduce_fmaximum:
7779   case Intrinsic::vector_reduce_fminimum:
7780     visitVectorReduce(I, Intrinsic);
7781     return;
7782 
7783   case Intrinsic::icall_branch_funnel: {
7784     SmallVector<SDValue, 16> Ops;
7785     Ops.push_back(getValue(I.getArgOperand(0)));
7786 
7787     int64_t Offset;
7788     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7789         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7790     if (!Base)
7791       report_fatal_error(
7792           "llvm.icall.branch.funnel operand must be a GlobalValue");
7793     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7794 
7795     struct BranchFunnelTarget {
7796       int64_t Offset;
7797       SDValue Target;
7798     };
7799     SmallVector<BranchFunnelTarget, 8> Targets;
7800 
7801     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7802       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7803           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7804       if (ElemBase != Base)
7805         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7806                            "to the same GlobalValue");
7807 
7808       SDValue Val = getValue(I.getArgOperand(Op + 1));
7809       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7810       if (!GA)
7811         report_fatal_error(
7812             "llvm.icall.branch.funnel operand must be a GlobalValue");
7813       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7814                                      GA->getGlobal(), sdl, Val.getValueType(),
7815                                      GA->getOffset())});
7816     }
7817     llvm::sort(Targets,
7818                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7819                  return T1.Offset < T2.Offset;
7820                });
7821 
7822     for (auto &T : Targets) {
7823       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7824       Ops.push_back(T.Target);
7825     }
7826 
7827     Ops.push_back(DAG.getRoot()); // Chain
7828     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7829                                  MVT::Other, Ops),
7830               0);
7831     DAG.setRoot(N);
7832     setValue(&I, N);
7833     HasTailCall = true;
7834     return;
7835   }
7836 
7837   case Intrinsic::wasm_landingpad_index:
7838     // Information this intrinsic contained has been transferred to
7839     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7840     // delete it now.
7841     return;
7842 
7843   case Intrinsic::aarch64_settag:
7844   case Intrinsic::aarch64_settag_zero: {
7845     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7846     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7847     SDValue Val = TSI.EmitTargetCodeForSetTag(
7848         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7849         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7850         ZeroMemory);
7851     DAG.setRoot(Val);
7852     setValue(&I, Val);
7853     return;
7854   }
7855   case Intrinsic::amdgcn_cs_chain: {
7856     assert(I.arg_size() == 5 && "Additional args not supported yet");
7857     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7858            "Non-zero flags not supported yet");
7859 
7860     // At this point we don't care if it's amdgpu_cs_chain or
7861     // amdgpu_cs_chain_preserve.
7862     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7863 
7864     Type *RetTy = I.getType();
7865     assert(RetTy->isVoidTy() && "Should not return");
7866 
7867     SDValue Callee = getValue(I.getOperand(0));
7868 
7869     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7870     // We'll also tack the value of the EXEC mask at the end.
7871     TargetLowering::ArgListTy Args;
7872     Args.reserve(3);
7873 
7874     for (unsigned Idx : {2, 3, 1}) {
7875       TargetLowering::ArgListEntry Arg;
7876       Arg.Node = getValue(I.getOperand(Idx));
7877       Arg.Ty = I.getOperand(Idx)->getType();
7878       Arg.setAttributes(&I, Idx);
7879       Args.push_back(Arg);
7880     }
7881 
7882     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7883     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7884     Args[2].IsInReg = true; // EXEC should be inreg
7885 
7886     TargetLowering::CallLoweringInfo CLI(DAG);
7887     CLI.setDebugLoc(getCurSDLoc())
7888         .setChain(getRoot())
7889         .setCallee(CC, RetTy, Callee, std::move(Args))
7890         .setNoReturn(true)
7891         .setTailCall(true)
7892         .setConvergent(I.isConvergent());
7893     CLI.CB = &I;
7894     std::pair<SDValue, SDValue> Result =
7895         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7896     (void)Result;
7897     assert(!Result.first.getNode() && !Result.second.getNode() &&
7898            "Should've lowered as tail call");
7899 
7900     HasTailCall = true;
7901     return;
7902   }
7903   case Intrinsic::ptrmask: {
7904     SDValue Ptr = getValue(I.getOperand(0));
7905     SDValue Mask = getValue(I.getOperand(1));
7906 
7907     // On arm64_32, pointers are 32 bits when stored in memory, but
7908     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7909     // match the index type, but the pointer is 64 bits, so the the mask must be
7910     // zero-extended up to 64 bits to match the pointer.
7911     EVT PtrVT =
7912         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7913     EVT MemVT =
7914         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7915     assert(PtrVT == Ptr.getValueType());
7916     assert(MemVT == Mask.getValueType());
7917     if (MemVT != PtrVT)
7918       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7919 
7920     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7921     return;
7922   }
7923   case Intrinsic::threadlocal_address: {
7924     setValue(&I, getValue(I.getOperand(0)));
7925     return;
7926   }
7927   case Intrinsic::get_active_lane_mask: {
7928     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7929     SDValue Index = getValue(I.getOperand(0));
7930     EVT ElementVT = Index.getValueType();
7931 
7932     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7933       visitTargetIntrinsic(I, Intrinsic);
7934       return;
7935     }
7936 
7937     SDValue TripCount = getValue(I.getOperand(1));
7938     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7939                                  CCVT.getVectorElementCount());
7940 
7941     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7942     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7943     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7944     SDValue VectorInduction = DAG.getNode(
7945         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7946     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7947                                  VectorTripCount, ISD::CondCode::SETULT);
7948     setValue(&I, SetCC);
7949     return;
7950   }
7951   case Intrinsic::experimental_get_vector_length: {
7952     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7953            "Expected positive VF");
7954     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7955     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7956 
7957     SDValue Count = getValue(I.getOperand(0));
7958     EVT CountVT = Count.getValueType();
7959 
7960     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7961       visitTargetIntrinsic(I, Intrinsic);
7962       return;
7963     }
7964 
7965     // Expand to a umin between the trip count and the maximum elements the type
7966     // can hold.
7967     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7968 
7969     // Extend the trip count to at least the result VT.
7970     if (CountVT.bitsLT(VT)) {
7971       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7972       CountVT = VT;
7973     }
7974 
7975     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7976                                          ElementCount::get(VF, IsScalable));
7977 
7978     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7979     // Clip to the result type if needed.
7980     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7981 
7982     setValue(&I, Trunc);
7983     return;
7984   }
7985   case Intrinsic::experimental_vector_partial_reduce_add: {
7986     SDValue OpNode = getValue(I.getOperand(1));
7987     EVT ReducedTy = EVT::getEVT(I.getType());
7988     EVT FullTy = OpNode.getValueType();
7989 
7990     unsigned Stride = ReducedTy.getVectorMinNumElements();
7991     unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride;
7992 
7993     // Collect all of the subvectors
7994     std::deque<SDValue> Subvectors;
7995     Subvectors.push_back(getValue(I.getOperand(0)));
7996     for (unsigned i = 0; i < ScaleFactor; i++) {
7997       auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl);
7998       Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy,
7999                                        {OpNode, SourceIndex}));
8000     }
8001 
8002     // Flatten the subvector tree
8003     while (Subvectors.size() > 1) {
8004       Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy,
8005                                        {Subvectors[0], Subvectors[1]}));
8006       Subvectors.pop_front();
8007       Subvectors.pop_front();
8008     }
8009 
8010     assert(Subvectors.size() == 1 &&
8011            "There should only be one subvector after tree flattening");
8012 
8013     setValue(&I, Subvectors[0]);
8014     return;
8015   }
8016   case Intrinsic::experimental_cttz_elts: {
8017     auto DL = getCurSDLoc();
8018     SDValue Op = getValue(I.getOperand(0));
8019     EVT OpVT = Op.getValueType();
8020 
8021     if (!TLI.shouldExpandCttzElements(OpVT)) {
8022       visitTargetIntrinsic(I, Intrinsic);
8023       return;
8024     }
8025 
8026     if (OpVT.getScalarType() != MVT::i1) {
8027       // Compare the input vector elements to zero & use to count trailing zeros
8028       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8029       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8030                               OpVT.getVectorElementCount());
8031       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8032     }
8033 
8034     // If the zero-is-poison flag is set, we can assume the upper limit
8035     // of the result is VF-1.
8036     bool ZeroIsPoison =
8037         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8038     ConstantRange VScaleRange(1, true); // Dummy value.
8039     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8040       VScaleRange = getVScaleRange(I.getCaller(), 64);
8041     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8042         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8043 
8044     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8045 
8046     // Create the new vector type & get the vector length
8047     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8048                                  OpVT.getVectorElementCount());
8049 
8050     SDValue VL =
8051         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8052 
8053     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8054     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8055     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8056     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8057     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8058     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8059     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8060 
8061     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8062     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8063 
8064     setValue(&I, Ret);
8065     return;
8066   }
8067   case Intrinsic::vector_insert: {
8068     SDValue Vec = getValue(I.getOperand(0));
8069     SDValue SubVec = getValue(I.getOperand(1));
8070     SDValue Index = getValue(I.getOperand(2));
8071 
8072     // The intrinsic's index type is i64, but the SDNode requires an index type
8073     // suitable for the target. Convert the index as required.
8074     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8075     if (Index.getValueType() != VectorIdxTy)
8076       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8077 
8078     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8079     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8080                              Index));
8081     return;
8082   }
8083   case Intrinsic::vector_extract: {
8084     SDValue Vec = getValue(I.getOperand(0));
8085     SDValue Index = getValue(I.getOperand(1));
8086     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8087 
8088     // The intrinsic's index type is i64, but the SDNode requires an index type
8089     // suitable for the target. Convert the index as required.
8090     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8091     if (Index.getValueType() != VectorIdxTy)
8092       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8093 
8094     setValue(&I,
8095              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8096     return;
8097   }
8098   case Intrinsic::vector_reverse:
8099     visitVectorReverse(I);
8100     return;
8101   case Intrinsic::vector_splice:
8102     visitVectorSplice(I);
8103     return;
8104   case Intrinsic::callbr_landingpad:
8105     visitCallBrLandingPad(I);
8106     return;
8107   case Intrinsic::vector_interleave2:
8108     visitVectorInterleave(I);
8109     return;
8110   case Intrinsic::vector_deinterleave2:
8111     visitVectorDeinterleave(I);
8112     return;
8113   case Intrinsic::experimental_convergence_anchor:
8114   case Intrinsic::experimental_convergence_entry:
8115   case Intrinsic::experimental_convergence_loop:
8116     visitConvergenceControl(I, Intrinsic);
8117     return;
8118   case Intrinsic::experimental_vector_histogram_add: {
8119     visitVectorHistogram(I, Intrinsic);
8120     return;
8121   }
8122   }
8123 }
8124 
8125 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8126     const ConstrainedFPIntrinsic &FPI) {
8127   SDLoc sdl = getCurSDLoc();
8128 
8129   // We do not need to serialize constrained FP intrinsics against
8130   // each other or against (nonvolatile) loads, so they can be
8131   // chained like loads.
8132   SDValue Chain = DAG.getRoot();
8133   SmallVector<SDValue, 4> Opers;
8134   Opers.push_back(Chain);
8135   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8136     Opers.push_back(getValue(FPI.getArgOperand(I)));
8137 
8138   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8139     assert(Result.getNode()->getNumValues() == 2);
8140 
8141     // Push node to the appropriate list so that future instructions can be
8142     // chained up correctly.
8143     SDValue OutChain = Result.getValue(1);
8144     switch (EB) {
8145     case fp::ExceptionBehavior::ebIgnore:
8146       // The only reason why ebIgnore nodes still need to be chained is that
8147       // they might depend on the current rounding mode, and therefore must
8148       // not be moved across instruction that may change that mode.
8149       [[fallthrough]];
8150     case fp::ExceptionBehavior::ebMayTrap:
8151       // These must not be moved across calls or instructions that may change
8152       // floating-point exception masks.
8153       PendingConstrainedFP.push_back(OutChain);
8154       break;
8155     case fp::ExceptionBehavior::ebStrict:
8156       // These must not be moved across calls or instructions that may change
8157       // floating-point exception masks or read floating-point exception flags.
8158       // In addition, they cannot be optimized out even if unused.
8159       PendingConstrainedFPStrict.push_back(OutChain);
8160       break;
8161     }
8162   };
8163 
8164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8165   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8166   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8167   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8168 
8169   SDNodeFlags Flags;
8170   if (EB == fp::ExceptionBehavior::ebIgnore)
8171     Flags.setNoFPExcept(true);
8172 
8173   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8174     Flags.copyFMF(*FPOp);
8175 
8176   unsigned Opcode;
8177   switch (FPI.getIntrinsicID()) {
8178   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8179 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8180   case Intrinsic::INTRINSIC:                                                   \
8181     Opcode = ISD::STRICT_##DAGN;                                               \
8182     break;
8183 #include "llvm/IR/ConstrainedOps.def"
8184   case Intrinsic::experimental_constrained_fmuladd: {
8185     Opcode = ISD::STRICT_FMA;
8186     // Break fmuladd into fmul and fadd.
8187     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8188         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8189       Opers.pop_back();
8190       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8191       pushOutChain(Mul, EB);
8192       Opcode = ISD::STRICT_FADD;
8193       Opers.clear();
8194       Opers.push_back(Mul.getValue(1));
8195       Opers.push_back(Mul.getValue(0));
8196       Opers.push_back(getValue(FPI.getArgOperand(2)));
8197     }
8198     break;
8199   }
8200   }
8201 
8202   // A few strict DAG nodes carry additional operands that are not
8203   // set up by the default code above.
8204   switch (Opcode) {
8205   default: break;
8206   case ISD::STRICT_FP_ROUND:
8207     Opers.push_back(
8208         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8209     break;
8210   case ISD::STRICT_FSETCC:
8211   case ISD::STRICT_FSETCCS: {
8212     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8213     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8214     if (TM.Options.NoNaNsFPMath)
8215       Condition = getFCmpCodeWithoutNaN(Condition);
8216     Opers.push_back(DAG.getCondCode(Condition));
8217     break;
8218   }
8219   }
8220 
8221   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8222   pushOutChain(Result, EB);
8223 
8224   SDValue FPResult = Result.getValue(0);
8225   setValue(&FPI, FPResult);
8226 }
8227 
8228 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8229   std::optional<unsigned> ResOPC;
8230   switch (VPIntrin.getIntrinsicID()) {
8231   case Intrinsic::vp_ctlz: {
8232     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8233     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8234     break;
8235   }
8236   case Intrinsic::vp_cttz: {
8237     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8238     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8239     break;
8240   }
8241   case Intrinsic::vp_cttz_elts: {
8242     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8243     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8244     break;
8245   }
8246 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8247   case Intrinsic::VPID:                                                        \
8248     ResOPC = ISD::VPSD;                                                        \
8249     break;
8250 #include "llvm/IR/VPIntrinsics.def"
8251   }
8252 
8253   if (!ResOPC)
8254     llvm_unreachable(
8255         "Inconsistency: no SDNode available for this VPIntrinsic!");
8256 
8257   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8258       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8259     if (VPIntrin.getFastMathFlags().allowReassoc())
8260       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8261                                                 : ISD::VP_REDUCE_FMUL;
8262   }
8263 
8264   return *ResOPC;
8265 }
8266 
8267 void SelectionDAGBuilder::visitVPLoad(
8268     const VPIntrinsic &VPIntrin, EVT VT,
8269     const SmallVectorImpl<SDValue> &OpValues) {
8270   SDLoc DL = getCurSDLoc();
8271   Value *PtrOperand = VPIntrin.getArgOperand(0);
8272   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8273   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8274   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8275   SDValue LD;
8276   // Do not serialize variable-length loads of constant memory with
8277   // anything.
8278   if (!Alignment)
8279     Alignment = DAG.getEVTAlign(VT);
8280   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8281   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8282   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8283   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8284       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8285       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8286   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8287                      MMO, false /*IsExpanding */);
8288   if (AddToChain)
8289     PendingLoads.push_back(LD.getValue(1));
8290   setValue(&VPIntrin, LD);
8291 }
8292 
8293 void SelectionDAGBuilder::visitVPGather(
8294     const VPIntrinsic &VPIntrin, EVT VT,
8295     const SmallVectorImpl<SDValue> &OpValues) {
8296   SDLoc DL = getCurSDLoc();
8297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8298   Value *PtrOperand = VPIntrin.getArgOperand(0);
8299   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8300   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8301   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8302   SDValue LD;
8303   if (!Alignment)
8304     Alignment = DAG.getEVTAlign(VT.getScalarType());
8305   unsigned AS =
8306     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8307   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8308       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8309       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8310   SDValue Base, Index, Scale;
8311   ISD::MemIndexType IndexType;
8312   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8313                                     this, VPIntrin.getParent(),
8314                                     VT.getScalarStoreSize());
8315   if (!UniformBase) {
8316     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8317     Index = getValue(PtrOperand);
8318     IndexType = ISD::SIGNED_SCALED;
8319     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8320   }
8321   EVT IdxVT = Index.getValueType();
8322   EVT EltTy = IdxVT.getVectorElementType();
8323   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8324     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8325     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8326   }
8327   LD = DAG.getGatherVP(
8328       DAG.getVTList(VT, MVT::Other), VT, DL,
8329       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8330       IndexType);
8331   PendingLoads.push_back(LD.getValue(1));
8332   setValue(&VPIntrin, LD);
8333 }
8334 
8335 void SelectionDAGBuilder::visitVPStore(
8336     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8337   SDLoc DL = getCurSDLoc();
8338   Value *PtrOperand = VPIntrin.getArgOperand(1);
8339   EVT VT = OpValues[0].getValueType();
8340   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8341   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8342   SDValue ST;
8343   if (!Alignment)
8344     Alignment = DAG.getEVTAlign(VT);
8345   SDValue Ptr = OpValues[1];
8346   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8347   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8348       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8349       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8350   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8351                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8352                       /* IsTruncating */ false, /*IsCompressing*/ false);
8353   DAG.setRoot(ST);
8354   setValue(&VPIntrin, ST);
8355 }
8356 
8357 void SelectionDAGBuilder::visitVPScatter(
8358     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8359   SDLoc DL = getCurSDLoc();
8360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8361   Value *PtrOperand = VPIntrin.getArgOperand(1);
8362   EVT VT = OpValues[0].getValueType();
8363   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8364   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8365   SDValue ST;
8366   if (!Alignment)
8367     Alignment = DAG.getEVTAlign(VT.getScalarType());
8368   unsigned AS =
8369       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8370   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8371       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8372       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8373   SDValue Base, Index, Scale;
8374   ISD::MemIndexType IndexType;
8375   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8376                                     this, VPIntrin.getParent(),
8377                                     VT.getScalarStoreSize());
8378   if (!UniformBase) {
8379     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8380     Index = getValue(PtrOperand);
8381     IndexType = ISD::SIGNED_SCALED;
8382     Scale =
8383       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8384   }
8385   EVT IdxVT = Index.getValueType();
8386   EVT EltTy = IdxVT.getVectorElementType();
8387   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8388     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8389     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8390   }
8391   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8392                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8393                          OpValues[2], OpValues[3]},
8394                         MMO, IndexType);
8395   DAG.setRoot(ST);
8396   setValue(&VPIntrin, ST);
8397 }
8398 
8399 void SelectionDAGBuilder::visitVPStridedLoad(
8400     const VPIntrinsic &VPIntrin, EVT VT,
8401     const SmallVectorImpl<SDValue> &OpValues) {
8402   SDLoc DL = getCurSDLoc();
8403   Value *PtrOperand = VPIntrin.getArgOperand(0);
8404   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8405   if (!Alignment)
8406     Alignment = DAG.getEVTAlign(VT.getScalarType());
8407   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8408   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8409   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8410   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8411   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8412   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8413   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8414       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8415       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8416 
8417   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8418                                     OpValues[2], OpValues[3], MMO,
8419                                     false /*IsExpanding*/);
8420 
8421   if (AddToChain)
8422     PendingLoads.push_back(LD.getValue(1));
8423   setValue(&VPIntrin, LD);
8424 }
8425 
8426 void SelectionDAGBuilder::visitVPStridedStore(
8427     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8428   SDLoc DL = getCurSDLoc();
8429   Value *PtrOperand = VPIntrin.getArgOperand(1);
8430   EVT VT = OpValues[0].getValueType();
8431   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8432   if (!Alignment)
8433     Alignment = DAG.getEVTAlign(VT.getScalarType());
8434   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8435   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8436   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8437       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8438       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8439 
8440   SDValue ST = DAG.getStridedStoreVP(
8441       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8442       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8443       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8444       /*IsCompressing*/ false);
8445 
8446   DAG.setRoot(ST);
8447   setValue(&VPIntrin, ST);
8448 }
8449 
8450 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8452   SDLoc DL = getCurSDLoc();
8453 
8454   ISD::CondCode Condition;
8455   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8456   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8457   if (IsFP) {
8458     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8459     // flags, but calls that don't return floating-point types can't be
8460     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8461     Condition = getFCmpCondCode(CondCode);
8462     if (TM.Options.NoNaNsFPMath)
8463       Condition = getFCmpCodeWithoutNaN(Condition);
8464   } else {
8465     Condition = getICmpCondCode(CondCode);
8466   }
8467 
8468   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8469   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8470   // #2 is the condition code
8471   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8472   SDValue EVL = getValue(VPIntrin.getOperand(4));
8473   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8474   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8475          "Unexpected target EVL type");
8476   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8477 
8478   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8479                                                         VPIntrin.getType());
8480   setValue(&VPIntrin,
8481            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8482 }
8483 
8484 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8485     const VPIntrinsic &VPIntrin) {
8486   SDLoc DL = getCurSDLoc();
8487   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8488 
8489   auto IID = VPIntrin.getIntrinsicID();
8490 
8491   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8492     return visitVPCmp(*CmpI);
8493 
8494   SmallVector<EVT, 4> ValueVTs;
8495   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8496   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8497   SDVTList VTs = DAG.getVTList(ValueVTs);
8498 
8499   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8500 
8501   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8502   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8503          "Unexpected target EVL type");
8504 
8505   // Request operands.
8506   SmallVector<SDValue, 7> OpValues;
8507   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8508     auto Op = getValue(VPIntrin.getArgOperand(I));
8509     if (I == EVLParamPos)
8510       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8511     OpValues.push_back(Op);
8512   }
8513 
8514   switch (Opcode) {
8515   default: {
8516     SDNodeFlags SDFlags;
8517     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8518       SDFlags.copyFMF(*FPMO);
8519     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8520     setValue(&VPIntrin, Result);
8521     break;
8522   }
8523   case ISD::VP_LOAD:
8524     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8525     break;
8526   case ISD::VP_GATHER:
8527     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8528     break;
8529   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8530     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8531     break;
8532   case ISD::VP_STORE:
8533     visitVPStore(VPIntrin, OpValues);
8534     break;
8535   case ISD::VP_SCATTER:
8536     visitVPScatter(VPIntrin, OpValues);
8537     break;
8538   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8539     visitVPStridedStore(VPIntrin, OpValues);
8540     break;
8541   case ISD::VP_FMULADD: {
8542     assert(OpValues.size() == 5 && "Unexpected number of operands");
8543     SDNodeFlags SDFlags;
8544     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8545       SDFlags.copyFMF(*FPMO);
8546     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8547         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8548       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8549     } else {
8550       SDValue Mul = DAG.getNode(
8551           ISD::VP_FMUL, DL, VTs,
8552           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8553       SDValue Add =
8554           DAG.getNode(ISD::VP_FADD, DL, VTs,
8555                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8556       setValue(&VPIntrin, Add);
8557     }
8558     break;
8559   }
8560   case ISD::VP_IS_FPCLASS: {
8561     const DataLayout DLayout = DAG.getDataLayout();
8562     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8563     auto Constant = OpValues[1]->getAsZExtVal();
8564     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8565     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8566                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8567     setValue(&VPIntrin, V);
8568     return;
8569   }
8570   case ISD::VP_INTTOPTR: {
8571     SDValue N = OpValues[0];
8572     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8573     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8574     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8575                                OpValues[2]);
8576     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8577                              OpValues[2]);
8578     setValue(&VPIntrin, N);
8579     break;
8580   }
8581   case ISD::VP_PTRTOINT: {
8582     SDValue N = OpValues[0];
8583     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8584                                                           VPIntrin.getType());
8585     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8586                                        VPIntrin.getOperand(0)->getType());
8587     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8588                                OpValues[2]);
8589     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8590                              OpValues[2]);
8591     setValue(&VPIntrin, N);
8592     break;
8593   }
8594   case ISD::VP_ABS:
8595   case ISD::VP_CTLZ:
8596   case ISD::VP_CTLZ_ZERO_UNDEF:
8597   case ISD::VP_CTTZ:
8598   case ISD::VP_CTTZ_ZERO_UNDEF:
8599   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8600   case ISD::VP_CTTZ_ELTS: {
8601     SDValue Result =
8602         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8603     setValue(&VPIntrin, Result);
8604     break;
8605   }
8606   }
8607 }
8608 
8609 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8610                                           const BasicBlock *EHPadBB,
8611                                           MCSymbol *&BeginLabel) {
8612   MachineFunction &MF = DAG.getMachineFunction();
8613   MachineModuleInfo &MMI = MF.getMMI();
8614 
8615   // Insert a label before the invoke call to mark the try range.  This can be
8616   // used to detect deletion of the invoke via the MachineModuleInfo.
8617   BeginLabel = MMI.getContext().createTempSymbol();
8618 
8619   // For SjLj, keep track of which landing pads go with which invokes
8620   // so as to maintain the ordering of pads in the LSDA.
8621   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8622   if (CallSiteIndex) {
8623     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8624     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8625 
8626     // Now that the call site is handled, stop tracking it.
8627     MMI.setCurrentCallSite(0);
8628   }
8629 
8630   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8631 }
8632 
8633 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8634                                         const BasicBlock *EHPadBB,
8635                                         MCSymbol *BeginLabel) {
8636   assert(BeginLabel && "BeginLabel should've been set");
8637 
8638   MachineFunction &MF = DAG.getMachineFunction();
8639   MachineModuleInfo &MMI = MF.getMMI();
8640 
8641   // Insert a label at the end of the invoke call to mark the try range.  This
8642   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8643   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8644   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8645 
8646   // Inform MachineModuleInfo of range.
8647   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8648   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8649   // actually use outlined funclets and their LSDA info style.
8650   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8651     assert(II && "II should've been set");
8652     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8653     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8654   } else if (!isScopedEHPersonality(Pers)) {
8655     assert(EHPadBB);
8656     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8657   }
8658 
8659   return Chain;
8660 }
8661 
8662 std::pair<SDValue, SDValue>
8663 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8664                                     const BasicBlock *EHPadBB) {
8665   MCSymbol *BeginLabel = nullptr;
8666 
8667   if (EHPadBB) {
8668     // Both PendingLoads and PendingExports must be flushed here;
8669     // this call might not return.
8670     (void)getRoot();
8671     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8672     CLI.setChain(getRoot());
8673   }
8674 
8675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8676   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8677 
8678   assert((CLI.IsTailCall || Result.second.getNode()) &&
8679          "Non-null chain expected with non-tail call!");
8680   assert((Result.second.getNode() || !Result.first.getNode()) &&
8681          "Null value expected with tail call!");
8682 
8683   if (!Result.second.getNode()) {
8684     // As a special case, a null chain means that a tail call has been emitted
8685     // and the DAG root is already updated.
8686     HasTailCall = true;
8687 
8688     // Since there's no actual continuation from this block, nothing can be
8689     // relying on us setting vregs for them.
8690     PendingExports.clear();
8691   } else {
8692     DAG.setRoot(Result.second);
8693   }
8694 
8695   if (EHPadBB) {
8696     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8697                            BeginLabel));
8698     Result.second = getRoot();
8699   }
8700 
8701   return Result;
8702 }
8703 
8704 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8705                                       bool isTailCall, bool isMustTailCall,
8706                                       const BasicBlock *EHPadBB,
8707                                       const TargetLowering::PtrAuthInfo *PAI) {
8708   auto &DL = DAG.getDataLayout();
8709   FunctionType *FTy = CB.getFunctionType();
8710   Type *RetTy = CB.getType();
8711 
8712   TargetLowering::ArgListTy Args;
8713   Args.reserve(CB.arg_size());
8714 
8715   const Value *SwiftErrorVal = nullptr;
8716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8717 
8718   if (isTailCall) {
8719     // Avoid emitting tail calls in functions with the disable-tail-calls
8720     // attribute.
8721     auto *Caller = CB.getParent()->getParent();
8722     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8723         "true" && !isMustTailCall)
8724       isTailCall = false;
8725 
8726     // We can't tail call inside a function with a swifterror argument. Lowering
8727     // does not support this yet. It would have to move into the swifterror
8728     // register before the call.
8729     if (TLI.supportSwiftError() &&
8730         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8731       isTailCall = false;
8732   }
8733 
8734   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8735     TargetLowering::ArgListEntry Entry;
8736     const Value *V = *I;
8737 
8738     // Skip empty types
8739     if (V->getType()->isEmptyTy())
8740       continue;
8741 
8742     SDValue ArgNode = getValue(V);
8743     Entry.Node = ArgNode; Entry.Ty = V->getType();
8744 
8745     Entry.setAttributes(&CB, I - CB.arg_begin());
8746 
8747     // Use swifterror virtual register as input to the call.
8748     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8749       SwiftErrorVal = V;
8750       // We find the virtual register for the actual swifterror argument.
8751       // Instead of using the Value, we use the virtual register instead.
8752       Entry.Node =
8753           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8754                           EVT(TLI.getPointerTy(DL)));
8755     }
8756 
8757     Args.push_back(Entry);
8758 
8759     // If we have an explicit sret argument that is an Instruction, (i.e., it
8760     // might point to function-local memory), we can't meaningfully tail-call.
8761     if (Entry.IsSRet && isa<Instruction>(V))
8762       isTailCall = false;
8763   }
8764 
8765   // If call site has a cfguardtarget operand bundle, create and add an
8766   // additional ArgListEntry.
8767   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8768     TargetLowering::ArgListEntry Entry;
8769     Value *V = Bundle->Inputs[0];
8770     SDValue ArgNode = getValue(V);
8771     Entry.Node = ArgNode;
8772     Entry.Ty = V->getType();
8773     Entry.IsCFGuardTarget = true;
8774     Args.push_back(Entry);
8775   }
8776 
8777   // Check if target-independent constraints permit a tail call here.
8778   // Target-dependent constraints are checked within TLI->LowerCallTo.
8779   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8780     isTailCall = false;
8781 
8782   // Disable tail calls if there is an swifterror argument. Targets have not
8783   // been updated to support tail calls.
8784   if (TLI.supportSwiftError() && SwiftErrorVal)
8785     isTailCall = false;
8786 
8787   ConstantInt *CFIType = nullptr;
8788   if (CB.isIndirectCall()) {
8789     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8790       if (!TLI.supportKCFIBundles())
8791         report_fatal_error(
8792             "Target doesn't support calls with kcfi operand bundles.");
8793       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8794       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8795     }
8796   }
8797 
8798   SDValue ConvControlToken;
8799   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8800     auto *Token = Bundle->Inputs[0].get();
8801     ConvControlToken = getValue(Token);
8802   }
8803 
8804   TargetLowering::CallLoweringInfo CLI(DAG);
8805   CLI.setDebugLoc(getCurSDLoc())
8806       .setChain(getRoot())
8807       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8808       .setTailCall(isTailCall)
8809       .setConvergent(CB.isConvergent())
8810       .setIsPreallocated(
8811           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8812       .setCFIType(CFIType)
8813       .setConvergenceControlToken(ConvControlToken);
8814 
8815   // Set the pointer authentication info if we have it.
8816   if (PAI) {
8817     if (!TLI.supportPtrAuthBundles())
8818       report_fatal_error(
8819           "This target doesn't support calls with ptrauth operand bundles.");
8820     CLI.setPtrAuth(*PAI);
8821   }
8822 
8823   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8824 
8825   if (Result.first.getNode()) {
8826     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8827     setValue(&CB, Result.first);
8828   }
8829 
8830   // The last element of CLI.InVals has the SDValue for swifterror return.
8831   // Here we copy it to a virtual register and update SwiftErrorMap for
8832   // book-keeping.
8833   if (SwiftErrorVal && TLI.supportSwiftError()) {
8834     // Get the last element of InVals.
8835     SDValue Src = CLI.InVals.back();
8836     Register VReg =
8837         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8838     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8839     DAG.setRoot(CopyNode);
8840   }
8841 }
8842 
8843 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8844                              SelectionDAGBuilder &Builder) {
8845   // Check to see if this load can be trivially constant folded, e.g. if the
8846   // input is from a string literal.
8847   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8848     // Cast pointer to the type we really want to load.
8849     Type *LoadTy =
8850         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8851     if (LoadVT.isVector())
8852       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8853 
8854     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8855                                          PointerType::getUnqual(LoadTy));
8856 
8857     if (const Constant *LoadCst =
8858             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8859                                          LoadTy, Builder.DAG.getDataLayout()))
8860       return Builder.getValue(LoadCst);
8861   }
8862 
8863   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8864   // still constant memory, the input chain can be the entry node.
8865   SDValue Root;
8866   bool ConstantMemory = false;
8867 
8868   // Do not serialize (non-volatile) loads of constant memory with anything.
8869   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8870     Root = Builder.DAG.getEntryNode();
8871     ConstantMemory = true;
8872   } else {
8873     // Do not serialize non-volatile loads against each other.
8874     Root = Builder.DAG.getRoot();
8875   }
8876 
8877   SDValue Ptr = Builder.getValue(PtrVal);
8878   SDValue LoadVal =
8879       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8880                           MachinePointerInfo(PtrVal), Align(1));
8881 
8882   if (!ConstantMemory)
8883     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8884   return LoadVal;
8885 }
8886 
8887 /// Record the value for an instruction that produces an integer result,
8888 /// converting the type where necessary.
8889 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8890                                                   SDValue Value,
8891                                                   bool IsSigned) {
8892   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8893                                                     I.getType(), true);
8894   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8895   setValue(&I, Value);
8896 }
8897 
8898 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8899 /// true and lower it. Otherwise return false, and it will be lowered like a
8900 /// normal call.
8901 /// The caller already checked that \p I calls the appropriate LibFunc with a
8902 /// correct prototype.
8903 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8904   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8905   const Value *Size = I.getArgOperand(2);
8906   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8907   if (CSize && CSize->getZExtValue() == 0) {
8908     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8909                                                           I.getType(), true);
8910     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8911     return true;
8912   }
8913 
8914   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8915   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8916       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8917       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8918   if (Res.first.getNode()) {
8919     processIntegerCallValue(I, Res.first, true);
8920     PendingLoads.push_back(Res.second);
8921     return true;
8922   }
8923 
8924   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8925   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8926   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8927     return false;
8928 
8929   // If the target has a fast compare for the given size, it will return a
8930   // preferred load type for that size. Require that the load VT is legal and
8931   // that the target supports unaligned loads of that type. Otherwise, return
8932   // INVALID.
8933   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8934     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8935     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8936     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8937       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8938       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8939       // TODO: Check alignment of src and dest ptrs.
8940       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8941       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8942       if (!TLI.isTypeLegal(LVT) ||
8943           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8944           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8945         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8946     }
8947 
8948     return LVT;
8949   };
8950 
8951   // This turns into unaligned loads. We only do this if the target natively
8952   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8953   // we'll only produce a small number of byte loads.
8954   MVT LoadVT;
8955   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8956   switch (NumBitsToCompare) {
8957   default:
8958     return false;
8959   case 16:
8960     LoadVT = MVT::i16;
8961     break;
8962   case 32:
8963     LoadVT = MVT::i32;
8964     break;
8965   case 64:
8966   case 128:
8967   case 256:
8968     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8969     break;
8970   }
8971 
8972   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8973     return false;
8974 
8975   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8976   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8977 
8978   // Bitcast to a wide integer type if the loads are vectors.
8979   if (LoadVT.isVector()) {
8980     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8981     LoadL = DAG.getBitcast(CmpVT, LoadL);
8982     LoadR = DAG.getBitcast(CmpVT, LoadR);
8983   }
8984 
8985   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8986   processIntegerCallValue(I, Cmp, false);
8987   return true;
8988 }
8989 
8990 /// See if we can lower a memchr call into an optimized form. If so, return
8991 /// true and lower it. Otherwise return false, and it will be lowered like a
8992 /// normal call.
8993 /// The caller already checked that \p I calls the appropriate LibFunc with a
8994 /// correct prototype.
8995 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8996   const Value *Src = I.getArgOperand(0);
8997   const Value *Char = I.getArgOperand(1);
8998   const Value *Length = I.getArgOperand(2);
8999 
9000   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9001   std::pair<SDValue, SDValue> Res =
9002     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9003                                 getValue(Src), getValue(Char), getValue(Length),
9004                                 MachinePointerInfo(Src));
9005   if (Res.first.getNode()) {
9006     setValue(&I, Res.first);
9007     PendingLoads.push_back(Res.second);
9008     return true;
9009   }
9010 
9011   return false;
9012 }
9013 
9014 /// See if we can lower a mempcpy call into an optimized form. If so, return
9015 /// true and lower it. Otherwise return false, and it will be lowered like a
9016 /// normal call.
9017 /// The caller already checked that \p I calls the appropriate LibFunc with a
9018 /// correct prototype.
9019 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9020   SDValue Dst = getValue(I.getArgOperand(0));
9021   SDValue Src = getValue(I.getArgOperand(1));
9022   SDValue Size = getValue(I.getArgOperand(2));
9023 
9024   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9025   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9026   // DAG::getMemcpy needs Alignment to be defined.
9027   Align Alignment = std::min(DstAlign, SrcAlign);
9028 
9029   SDLoc sdl = getCurSDLoc();
9030 
9031   // In the mempcpy context we need to pass in a false value for isTailCall
9032   // because the return pointer needs to be adjusted by the size of
9033   // the copied memory.
9034   SDValue Root = getMemoryRoot();
9035   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
9036                              /*isTailCall=*/false,
9037                              MachinePointerInfo(I.getArgOperand(0)),
9038                              MachinePointerInfo(I.getArgOperand(1)),
9039                              I.getAAMetadata());
9040   assert(MC.getNode() != nullptr &&
9041          "** memcpy should not be lowered as TailCall in mempcpy context **");
9042   DAG.setRoot(MC);
9043 
9044   // Check if Size needs to be truncated or extended.
9045   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9046 
9047   // Adjust return pointer to point just past the last dst byte.
9048   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9049                                     Dst, Size);
9050   setValue(&I, DstPlusSize);
9051   return true;
9052 }
9053 
9054 /// See if we can lower a strcpy call into an optimized form.  If so, return
9055 /// true and lower it, otherwise return false and it will be lowered like a
9056 /// normal call.
9057 /// The caller already checked that \p I calls the appropriate LibFunc with a
9058 /// correct prototype.
9059 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9060   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9061 
9062   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9063   std::pair<SDValue, SDValue> Res =
9064     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9065                                 getValue(Arg0), getValue(Arg1),
9066                                 MachinePointerInfo(Arg0),
9067                                 MachinePointerInfo(Arg1), isStpcpy);
9068   if (Res.first.getNode()) {
9069     setValue(&I, Res.first);
9070     DAG.setRoot(Res.second);
9071     return true;
9072   }
9073 
9074   return false;
9075 }
9076 
9077 /// See if we can lower a strcmp call into an optimized form.  If so, return
9078 /// true and lower it, otherwise return false and it will be lowered like a
9079 /// normal call.
9080 /// The caller already checked that \p I calls the appropriate LibFunc with a
9081 /// correct prototype.
9082 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9083   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9084 
9085   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9086   std::pair<SDValue, SDValue> Res =
9087     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9088                                 getValue(Arg0), getValue(Arg1),
9089                                 MachinePointerInfo(Arg0),
9090                                 MachinePointerInfo(Arg1));
9091   if (Res.first.getNode()) {
9092     processIntegerCallValue(I, Res.first, true);
9093     PendingLoads.push_back(Res.second);
9094     return true;
9095   }
9096 
9097   return false;
9098 }
9099 
9100 /// See if we can lower a strlen call into an optimized form.  If so, return
9101 /// true and lower it, otherwise return false and it will be lowered like a
9102 /// normal call.
9103 /// The caller already checked that \p I calls the appropriate LibFunc with a
9104 /// correct prototype.
9105 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9106   const Value *Arg0 = I.getArgOperand(0);
9107 
9108   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9109   std::pair<SDValue, SDValue> Res =
9110     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9111                                 getValue(Arg0), MachinePointerInfo(Arg0));
9112   if (Res.first.getNode()) {
9113     processIntegerCallValue(I, Res.first, false);
9114     PendingLoads.push_back(Res.second);
9115     return true;
9116   }
9117 
9118   return false;
9119 }
9120 
9121 /// See if we can lower a strnlen call into an optimized form.  If so, return
9122 /// true and lower it, otherwise return false and it will be lowered like a
9123 /// normal call.
9124 /// The caller already checked that \p I calls the appropriate LibFunc with a
9125 /// correct prototype.
9126 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9127   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9128 
9129   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9130   std::pair<SDValue, SDValue> Res =
9131     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9132                                  getValue(Arg0), getValue(Arg1),
9133                                  MachinePointerInfo(Arg0));
9134   if (Res.first.getNode()) {
9135     processIntegerCallValue(I, Res.first, false);
9136     PendingLoads.push_back(Res.second);
9137     return true;
9138   }
9139 
9140   return false;
9141 }
9142 
9143 /// See if we can lower a unary floating-point operation into an SDNode with
9144 /// the specified Opcode.  If so, return true and lower it, otherwise return
9145 /// false and it will be lowered like a normal call.
9146 /// The caller already checked that \p I calls the appropriate LibFunc with a
9147 /// correct prototype.
9148 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9149                                               unsigned Opcode) {
9150   // We already checked this call's prototype; verify it doesn't modify errno.
9151   if (!I.onlyReadsMemory())
9152     return false;
9153 
9154   SDNodeFlags Flags;
9155   Flags.copyFMF(cast<FPMathOperator>(I));
9156 
9157   SDValue Tmp = getValue(I.getArgOperand(0));
9158   setValue(&I,
9159            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9160   return true;
9161 }
9162 
9163 /// See if we can lower a binary floating-point operation into an SDNode with
9164 /// the specified Opcode. If so, return true and lower it. Otherwise return
9165 /// false, and it will be lowered like a normal call.
9166 /// The caller already checked that \p I calls the appropriate LibFunc with a
9167 /// correct prototype.
9168 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9169                                                unsigned Opcode) {
9170   // We already checked this call's prototype; verify it doesn't modify errno.
9171   if (!I.onlyReadsMemory())
9172     return false;
9173 
9174   SDNodeFlags Flags;
9175   Flags.copyFMF(cast<FPMathOperator>(I));
9176 
9177   SDValue Tmp0 = getValue(I.getArgOperand(0));
9178   SDValue Tmp1 = getValue(I.getArgOperand(1));
9179   EVT VT = Tmp0.getValueType();
9180   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9181   return true;
9182 }
9183 
9184 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9185   // Handle inline assembly differently.
9186   if (I.isInlineAsm()) {
9187     visitInlineAsm(I);
9188     return;
9189   }
9190 
9191   diagnoseDontCall(I);
9192 
9193   if (Function *F = I.getCalledFunction()) {
9194     if (F->isDeclaration()) {
9195       // Is this an LLVM intrinsic or a target-specific intrinsic?
9196       unsigned IID = F->getIntrinsicID();
9197       if (!IID)
9198         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9199           IID = II->getIntrinsicID(F);
9200 
9201       if (IID) {
9202         visitIntrinsicCall(I, IID);
9203         return;
9204       }
9205     }
9206 
9207     // Check for well-known libc/libm calls.  If the function is internal, it
9208     // can't be a library call.  Don't do the check if marked as nobuiltin for
9209     // some reason or the call site requires strict floating point semantics.
9210     LibFunc Func;
9211     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9212         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9213         LibInfo->hasOptimizedCodeGen(Func)) {
9214       switch (Func) {
9215       default: break;
9216       case LibFunc_bcmp:
9217         if (visitMemCmpBCmpCall(I))
9218           return;
9219         break;
9220       case LibFunc_copysign:
9221       case LibFunc_copysignf:
9222       case LibFunc_copysignl:
9223         // We already checked this call's prototype; verify it doesn't modify
9224         // errno.
9225         if (I.onlyReadsMemory()) {
9226           SDValue LHS = getValue(I.getArgOperand(0));
9227           SDValue RHS = getValue(I.getArgOperand(1));
9228           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9229                                    LHS.getValueType(), LHS, RHS));
9230           return;
9231         }
9232         break;
9233       case LibFunc_fabs:
9234       case LibFunc_fabsf:
9235       case LibFunc_fabsl:
9236         if (visitUnaryFloatCall(I, ISD::FABS))
9237           return;
9238         break;
9239       case LibFunc_fmin:
9240       case LibFunc_fminf:
9241       case LibFunc_fminl:
9242         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9243           return;
9244         break;
9245       case LibFunc_fmax:
9246       case LibFunc_fmaxf:
9247       case LibFunc_fmaxl:
9248         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9249           return;
9250         break;
9251       case LibFunc_sin:
9252       case LibFunc_sinf:
9253       case LibFunc_sinl:
9254         if (visitUnaryFloatCall(I, ISD::FSIN))
9255           return;
9256         break;
9257       case LibFunc_cos:
9258       case LibFunc_cosf:
9259       case LibFunc_cosl:
9260         if (visitUnaryFloatCall(I, ISD::FCOS))
9261           return;
9262         break;
9263       case LibFunc_tan:
9264       case LibFunc_tanf:
9265       case LibFunc_tanl:
9266         if (visitUnaryFloatCall(I, ISD::FTAN))
9267           return;
9268         break;
9269       case LibFunc_sqrt:
9270       case LibFunc_sqrtf:
9271       case LibFunc_sqrtl:
9272       case LibFunc_sqrt_finite:
9273       case LibFunc_sqrtf_finite:
9274       case LibFunc_sqrtl_finite:
9275         if (visitUnaryFloatCall(I, ISD::FSQRT))
9276           return;
9277         break;
9278       case LibFunc_floor:
9279       case LibFunc_floorf:
9280       case LibFunc_floorl:
9281         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9282           return;
9283         break;
9284       case LibFunc_nearbyint:
9285       case LibFunc_nearbyintf:
9286       case LibFunc_nearbyintl:
9287         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9288           return;
9289         break;
9290       case LibFunc_ceil:
9291       case LibFunc_ceilf:
9292       case LibFunc_ceill:
9293         if (visitUnaryFloatCall(I, ISD::FCEIL))
9294           return;
9295         break;
9296       case LibFunc_rint:
9297       case LibFunc_rintf:
9298       case LibFunc_rintl:
9299         if (visitUnaryFloatCall(I, ISD::FRINT))
9300           return;
9301         break;
9302       case LibFunc_round:
9303       case LibFunc_roundf:
9304       case LibFunc_roundl:
9305         if (visitUnaryFloatCall(I, ISD::FROUND))
9306           return;
9307         break;
9308       case LibFunc_trunc:
9309       case LibFunc_truncf:
9310       case LibFunc_truncl:
9311         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9312           return;
9313         break;
9314       case LibFunc_log2:
9315       case LibFunc_log2f:
9316       case LibFunc_log2l:
9317         if (visitUnaryFloatCall(I, ISD::FLOG2))
9318           return;
9319         break;
9320       case LibFunc_exp2:
9321       case LibFunc_exp2f:
9322       case LibFunc_exp2l:
9323         if (visitUnaryFloatCall(I, ISD::FEXP2))
9324           return;
9325         break;
9326       case LibFunc_exp10:
9327       case LibFunc_exp10f:
9328       case LibFunc_exp10l:
9329         if (visitUnaryFloatCall(I, ISD::FEXP10))
9330           return;
9331         break;
9332       case LibFunc_ldexp:
9333       case LibFunc_ldexpf:
9334       case LibFunc_ldexpl:
9335         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9336           return;
9337         break;
9338       case LibFunc_memcmp:
9339         if (visitMemCmpBCmpCall(I))
9340           return;
9341         break;
9342       case LibFunc_mempcpy:
9343         if (visitMemPCpyCall(I))
9344           return;
9345         break;
9346       case LibFunc_memchr:
9347         if (visitMemChrCall(I))
9348           return;
9349         break;
9350       case LibFunc_strcpy:
9351         if (visitStrCpyCall(I, false))
9352           return;
9353         break;
9354       case LibFunc_stpcpy:
9355         if (visitStrCpyCall(I, true))
9356           return;
9357         break;
9358       case LibFunc_strcmp:
9359         if (visitStrCmpCall(I))
9360           return;
9361         break;
9362       case LibFunc_strlen:
9363         if (visitStrLenCall(I))
9364           return;
9365         break;
9366       case LibFunc_strnlen:
9367         if (visitStrNLenCall(I))
9368           return;
9369         break;
9370       }
9371     }
9372   }
9373 
9374   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9375     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9376     return;
9377   }
9378 
9379   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9380   // have to do anything here to lower funclet bundles.
9381   // CFGuardTarget bundles are lowered in LowerCallTo.
9382   assert(!I.hasOperandBundlesOtherThan(
9383              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9384               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9385               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9386               LLVMContext::OB_convergencectrl}) &&
9387          "Cannot lower calls with arbitrary operand bundles!");
9388 
9389   SDValue Callee = getValue(I.getCalledOperand());
9390 
9391   if (I.hasDeoptState())
9392     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9393   else
9394     // Check if we can potentially perform a tail call. More detailed checking
9395     // is be done within LowerCallTo, after more information about the call is
9396     // known.
9397     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9398 }
9399 
9400 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9401     const CallBase &CB, const BasicBlock *EHPadBB) {
9402   auto PAB = CB.getOperandBundle("ptrauth");
9403   const Value *CalleeV = CB.getCalledOperand();
9404 
9405   // Gather the call ptrauth data from the operand bundle:
9406   //   [ i32 <key>, i64 <discriminator> ]
9407   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9408   const Value *Discriminator = PAB->Inputs[1];
9409 
9410   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9411   assert(Discriminator->getType()->isIntegerTy(64) &&
9412          "Invalid ptrauth discriminator");
9413 
9414   // Functions should never be ptrauth-called directly.
9415   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9416 
9417   // Otherwise, do an authenticated indirect call.
9418   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9419                                      getValue(Discriminator)};
9420 
9421   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9422               EHPadBB, &PAI);
9423 }
9424 
9425 namespace {
9426 
9427 /// AsmOperandInfo - This contains information for each constraint that we are
9428 /// lowering.
9429 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9430 public:
9431   /// CallOperand - If this is the result output operand or a clobber
9432   /// this is null, otherwise it is the incoming operand to the CallInst.
9433   /// This gets modified as the asm is processed.
9434   SDValue CallOperand;
9435 
9436   /// AssignedRegs - If this is a register or register class operand, this
9437   /// contains the set of register corresponding to the operand.
9438   RegsForValue AssignedRegs;
9439 
9440   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9441     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9442   }
9443 
9444   /// Whether or not this operand accesses memory
9445   bool hasMemory(const TargetLowering &TLI) const {
9446     // Indirect operand accesses access memory.
9447     if (isIndirect)
9448       return true;
9449 
9450     for (const auto &Code : Codes)
9451       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9452         return true;
9453 
9454     return false;
9455   }
9456 };
9457 
9458 
9459 } // end anonymous namespace
9460 
9461 /// Make sure that the output operand \p OpInfo and its corresponding input
9462 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9463 /// out).
9464 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9465                                SDISelAsmOperandInfo &MatchingOpInfo,
9466                                SelectionDAG &DAG) {
9467   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9468     return;
9469 
9470   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9471   const auto &TLI = DAG.getTargetLoweringInfo();
9472 
9473   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9474       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9475                                        OpInfo.ConstraintVT);
9476   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9477       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9478                                        MatchingOpInfo.ConstraintVT);
9479   if ((OpInfo.ConstraintVT.isInteger() !=
9480        MatchingOpInfo.ConstraintVT.isInteger()) ||
9481       (MatchRC.second != InputRC.second)) {
9482     // FIXME: error out in a more elegant fashion
9483     report_fatal_error("Unsupported asm: input constraint"
9484                        " with a matching output constraint of"
9485                        " incompatible type!");
9486   }
9487   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9488 }
9489 
9490 /// Get a direct memory input to behave well as an indirect operand.
9491 /// This may introduce stores, hence the need for a \p Chain.
9492 /// \return The (possibly updated) chain.
9493 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9494                                         SDISelAsmOperandInfo &OpInfo,
9495                                         SelectionDAG &DAG) {
9496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9497 
9498   // If we don't have an indirect input, put it in the constpool if we can,
9499   // otherwise spill it to a stack slot.
9500   // TODO: This isn't quite right. We need to handle these according to
9501   // the addressing mode that the constraint wants. Also, this may take
9502   // an additional register for the computation and we don't want that
9503   // either.
9504 
9505   // If the operand is a float, integer, or vector constant, spill to a
9506   // constant pool entry to get its address.
9507   const Value *OpVal = OpInfo.CallOperandVal;
9508   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9509       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9510     OpInfo.CallOperand = DAG.getConstantPool(
9511         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9512     return Chain;
9513   }
9514 
9515   // Otherwise, create a stack slot and emit a store to it before the asm.
9516   Type *Ty = OpVal->getType();
9517   auto &DL = DAG.getDataLayout();
9518   uint64_t TySize = DL.getTypeAllocSize(Ty);
9519   MachineFunction &MF = DAG.getMachineFunction();
9520   int SSFI = MF.getFrameInfo().CreateStackObject(
9521       TySize, DL.getPrefTypeAlign(Ty), false);
9522   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9523   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9524                             MachinePointerInfo::getFixedStack(MF, SSFI),
9525                             TLI.getMemValueType(DL, Ty));
9526   OpInfo.CallOperand = StackSlot;
9527 
9528   return Chain;
9529 }
9530 
9531 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9532 /// specified operand.  We prefer to assign virtual registers, to allow the
9533 /// register allocator to handle the assignment process.  However, if the asm
9534 /// uses features that we can't model on machineinstrs, we have SDISel do the
9535 /// allocation.  This produces generally horrible, but correct, code.
9536 ///
9537 ///   OpInfo describes the operand
9538 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9539 static std::optional<unsigned>
9540 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9541                      SDISelAsmOperandInfo &OpInfo,
9542                      SDISelAsmOperandInfo &RefOpInfo) {
9543   LLVMContext &Context = *DAG.getContext();
9544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9545 
9546   MachineFunction &MF = DAG.getMachineFunction();
9547   SmallVector<unsigned, 4> Regs;
9548   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9549 
9550   // No work to do for memory/address operands.
9551   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9552       OpInfo.ConstraintType == TargetLowering::C_Address)
9553     return std::nullopt;
9554 
9555   // If this is a constraint for a single physreg, or a constraint for a
9556   // register class, find it.
9557   unsigned AssignedReg;
9558   const TargetRegisterClass *RC;
9559   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9560       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9561   // RC is unset only on failure. Return immediately.
9562   if (!RC)
9563     return std::nullopt;
9564 
9565   // Get the actual register value type.  This is important, because the user
9566   // may have asked for (e.g.) the AX register in i32 type.  We need to
9567   // remember that AX is actually i16 to get the right extension.
9568   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9569 
9570   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9571     // If this is an FP operand in an integer register (or visa versa), or more
9572     // generally if the operand value disagrees with the register class we plan
9573     // to stick it in, fix the operand type.
9574     //
9575     // If this is an input value, the bitcast to the new type is done now.
9576     // Bitcast for output value is done at the end of visitInlineAsm().
9577     if ((OpInfo.Type == InlineAsm::isOutput ||
9578          OpInfo.Type == InlineAsm::isInput) &&
9579         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9580       // Try to convert to the first EVT that the reg class contains.  If the
9581       // types are identical size, use a bitcast to convert (e.g. two differing
9582       // vector types).  Note: output bitcast is done at the end of
9583       // visitInlineAsm().
9584       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9585         // Exclude indirect inputs while they are unsupported because the code
9586         // to perform the load is missing and thus OpInfo.CallOperand still
9587         // refers to the input address rather than the pointed-to value.
9588         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9589           OpInfo.CallOperand =
9590               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9591         OpInfo.ConstraintVT = RegVT;
9592         // If the operand is an FP value and we want it in integer registers,
9593         // use the corresponding integer type. This turns an f64 value into
9594         // i64, which can be passed with two i32 values on a 32-bit machine.
9595       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9596         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9597         if (OpInfo.Type == InlineAsm::isInput)
9598           OpInfo.CallOperand =
9599               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9600         OpInfo.ConstraintVT = VT;
9601       }
9602     }
9603   }
9604 
9605   // No need to allocate a matching input constraint since the constraint it's
9606   // matching to has already been allocated.
9607   if (OpInfo.isMatchingInputConstraint())
9608     return std::nullopt;
9609 
9610   EVT ValueVT = OpInfo.ConstraintVT;
9611   if (OpInfo.ConstraintVT == MVT::Other)
9612     ValueVT = RegVT;
9613 
9614   // Initialize NumRegs.
9615   unsigned NumRegs = 1;
9616   if (OpInfo.ConstraintVT != MVT::Other)
9617     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9618 
9619   // If this is a constraint for a specific physical register, like {r17},
9620   // assign it now.
9621 
9622   // If this associated to a specific register, initialize iterator to correct
9623   // place. If virtual, make sure we have enough registers
9624 
9625   // Initialize iterator if necessary
9626   TargetRegisterClass::iterator I = RC->begin();
9627   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9628 
9629   // Do not check for single registers.
9630   if (AssignedReg) {
9631     I = std::find(I, RC->end(), AssignedReg);
9632     if (I == RC->end()) {
9633       // RC does not contain the selected register, which indicates a
9634       // mismatch between the register and the required type/bitwidth.
9635       return {AssignedReg};
9636     }
9637   }
9638 
9639   for (; NumRegs; --NumRegs, ++I) {
9640     assert(I != RC->end() && "Ran out of registers to allocate!");
9641     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9642     Regs.push_back(R);
9643   }
9644 
9645   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9646   return std::nullopt;
9647 }
9648 
9649 static unsigned
9650 findMatchingInlineAsmOperand(unsigned OperandNo,
9651                              const std::vector<SDValue> &AsmNodeOperands) {
9652   // Scan until we find the definition we already emitted of this operand.
9653   unsigned CurOp = InlineAsm::Op_FirstOperand;
9654   for (; OperandNo; --OperandNo) {
9655     // Advance to the next operand.
9656     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9657     const InlineAsm::Flag F(OpFlag);
9658     assert(
9659         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9660         "Skipped past definitions?");
9661     CurOp += F.getNumOperandRegisters() + 1;
9662   }
9663   return CurOp;
9664 }
9665 
9666 namespace {
9667 
9668 class ExtraFlags {
9669   unsigned Flags = 0;
9670 
9671 public:
9672   explicit ExtraFlags(const CallBase &Call) {
9673     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9674     if (IA->hasSideEffects())
9675       Flags |= InlineAsm::Extra_HasSideEffects;
9676     if (IA->isAlignStack())
9677       Flags |= InlineAsm::Extra_IsAlignStack;
9678     if (Call.isConvergent())
9679       Flags |= InlineAsm::Extra_IsConvergent;
9680     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9681   }
9682 
9683   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9684     // Ideally, we would only check against memory constraints.  However, the
9685     // meaning of an Other constraint can be target-specific and we can't easily
9686     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9687     // for Other constraints as well.
9688     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9689         OpInfo.ConstraintType == TargetLowering::C_Other) {
9690       if (OpInfo.Type == InlineAsm::isInput)
9691         Flags |= InlineAsm::Extra_MayLoad;
9692       else if (OpInfo.Type == InlineAsm::isOutput)
9693         Flags |= InlineAsm::Extra_MayStore;
9694       else if (OpInfo.Type == InlineAsm::isClobber)
9695         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9696     }
9697   }
9698 
9699   unsigned get() const { return Flags; }
9700 };
9701 
9702 } // end anonymous namespace
9703 
9704 static bool isFunction(SDValue Op) {
9705   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9706     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9707       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9708 
9709       // In normal "call dllimport func" instruction (non-inlineasm) it force
9710       // indirect access by specifing call opcode. And usually specially print
9711       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9712       // not do in this way now. (In fact, this is similar with "Data Access"
9713       // action). So here we ignore dllimport function.
9714       if (Fn && !Fn->hasDLLImportStorageClass())
9715         return true;
9716     }
9717   }
9718   return false;
9719 }
9720 
9721 /// visitInlineAsm - Handle a call to an InlineAsm object.
9722 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9723                                          const BasicBlock *EHPadBB) {
9724   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9725 
9726   /// ConstraintOperands - Information about all of the constraints.
9727   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9728 
9729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9730   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9731       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9732 
9733   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9734   // AsmDialect, MayLoad, MayStore).
9735   bool HasSideEffect = IA->hasSideEffects();
9736   ExtraFlags ExtraInfo(Call);
9737 
9738   for (auto &T : TargetConstraints) {
9739     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9740     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9741 
9742     if (OpInfo.CallOperandVal)
9743       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9744 
9745     if (!HasSideEffect)
9746       HasSideEffect = OpInfo.hasMemory(TLI);
9747 
9748     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9749     // FIXME: Could we compute this on OpInfo rather than T?
9750 
9751     // Compute the constraint code and ConstraintType to use.
9752     TLI.ComputeConstraintToUse(T, SDValue());
9753 
9754     if (T.ConstraintType == TargetLowering::C_Immediate &&
9755         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9756       // We've delayed emitting a diagnostic like the "n" constraint because
9757       // inlining could cause an integer showing up.
9758       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9759                                           "' expects an integer constant "
9760                                           "expression");
9761 
9762     ExtraInfo.update(T);
9763   }
9764 
9765   // We won't need to flush pending loads if this asm doesn't touch
9766   // memory and is nonvolatile.
9767   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9768 
9769   bool EmitEHLabels = isa<InvokeInst>(Call);
9770   if (EmitEHLabels) {
9771     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9772   }
9773   bool IsCallBr = isa<CallBrInst>(Call);
9774 
9775   if (IsCallBr || EmitEHLabels) {
9776     // If this is a callbr or invoke we need to flush pending exports since
9777     // inlineasm_br and invoke are terminators.
9778     // We need to do this before nodes are glued to the inlineasm_br node.
9779     Chain = getControlRoot();
9780   }
9781 
9782   MCSymbol *BeginLabel = nullptr;
9783   if (EmitEHLabels) {
9784     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9785   }
9786 
9787   int OpNo = -1;
9788   SmallVector<StringRef> AsmStrs;
9789   IA->collectAsmStrs(AsmStrs);
9790 
9791   // Second pass over the constraints: compute which constraint option to use.
9792   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9793     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9794       OpNo++;
9795 
9796     // If this is an output operand with a matching input operand, look up the
9797     // matching input. If their types mismatch, e.g. one is an integer, the
9798     // other is floating point, or their sizes are different, flag it as an
9799     // error.
9800     if (OpInfo.hasMatchingInput()) {
9801       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9802       patchMatchingInput(OpInfo, Input, DAG);
9803     }
9804 
9805     // Compute the constraint code and ConstraintType to use.
9806     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9807 
9808     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9809          OpInfo.Type == InlineAsm::isClobber) ||
9810         OpInfo.ConstraintType == TargetLowering::C_Address)
9811       continue;
9812 
9813     // In Linux PIC model, there are 4 cases about value/label addressing:
9814     //
9815     // 1: Function call or Label jmp inside the module.
9816     // 2: Data access (such as global variable, static variable) inside module.
9817     // 3: Function call or Label jmp outside the module.
9818     // 4: Data access (such as global variable) outside the module.
9819     //
9820     // Due to current llvm inline asm architecture designed to not "recognize"
9821     // the asm code, there are quite troubles for us to treat mem addressing
9822     // differently for same value/adress used in different instuctions.
9823     // For example, in pic model, call a func may in plt way or direclty
9824     // pc-related, but lea/mov a function adress may use got.
9825     //
9826     // Here we try to "recognize" function call for the case 1 and case 3 in
9827     // inline asm. And try to adjust the constraint for them.
9828     //
9829     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9830     // label, so here we don't handle jmp function label now, but we need to
9831     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9832     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9833         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9834         TM.getCodeModel() != CodeModel::Large) {
9835       OpInfo.isIndirect = false;
9836       OpInfo.ConstraintType = TargetLowering::C_Address;
9837     }
9838 
9839     // If this is a memory input, and if the operand is not indirect, do what we
9840     // need to provide an address for the memory input.
9841     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9842         !OpInfo.isIndirect) {
9843       assert((OpInfo.isMultipleAlternative ||
9844               (OpInfo.Type == InlineAsm::isInput)) &&
9845              "Can only indirectify direct input operands!");
9846 
9847       // Memory operands really want the address of the value.
9848       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9849 
9850       // There is no longer a Value* corresponding to this operand.
9851       OpInfo.CallOperandVal = nullptr;
9852 
9853       // It is now an indirect operand.
9854       OpInfo.isIndirect = true;
9855     }
9856 
9857   }
9858 
9859   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9860   std::vector<SDValue> AsmNodeOperands;
9861   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9862   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9863       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9864 
9865   // If we have a !srcloc metadata node associated with it, we want to attach
9866   // this to the ultimately generated inline asm machineinstr.  To do this, we
9867   // pass in the third operand as this (potentially null) inline asm MDNode.
9868   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9869   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9870 
9871   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9872   // bits as operand 3.
9873   AsmNodeOperands.push_back(DAG.getTargetConstant(
9874       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9875 
9876   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9877   // this, assign virtual and physical registers for inputs and otput.
9878   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9879     // Assign Registers.
9880     SDISelAsmOperandInfo &RefOpInfo =
9881         OpInfo.isMatchingInputConstraint()
9882             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9883             : OpInfo;
9884     const auto RegError =
9885         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9886     if (RegError) {
9887       const MachineFunction &MF = DAG.getMachineFunction();
9888       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9889       const char *RegName = TRI.getName(*RegError);
9890       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9891                                    "' allocated for constraint '" +
9892                                    Twine(OpInfo.ConstraintCode) +
9893                                    "' does not match required type");
9894       return;
9895     }
9896 
9897     auto DetectWriteToReservedRegister = [&]() {
9898       const MachineFunction &MF = DAG.getMachineFunction();
9899       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9900       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9901         if (Register::isPhysicalRegister(Reg) &&
9902             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9903           const char *RegName = TRI.getName(Reg);
9904           emitInlineAsmError(Call, "write to reserved register '" +
9905                                        Twine(RegName) + "'");
9906           return true;
9907         }
9908       }
9909       return false;
9910     };
9911     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9912             (OpInfo.Type == InlineAsm::isInput &&
9913              !OpInfo.isMatchingInputConstraint())) &&
9914            "Only address as input operand is allowed.");
9915 
9916     switch (OpInfo.Type) {
9917     case InlineAsm::isOutput:
9918       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9919         const InlineAsm::ConstraintCode ConstraintID =
9920             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9921         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9922                "Failed to convert memory constraint code to constraint id.");
9923 
9924         // Add information to the INLINEASM node to know about this output.
9925         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9926         OpFlags.setMemConstraint(ConstraintID);
9927         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9928                                                         MVT::i32));
9929         AsmNodeOperands.push_back(OpInfo.CallOperand);
9930       } else {
9931         // Otherwise, this outputs to a register (directly for C_Register /
9932         // C_RegisterClass, and a target-defined fashion for
9933         // C_Immediate/C_Other). Find a register that we can use.
9934         if (OpInfo.AssignedRegs.Regs.empty()) {
9935           emitInlineAsmError(
9936               Call, "couldn't allocate output register for constraint '" +
9937                         Twine(OpInfo.ConstraintCode) + "'");
9938           return;
9939         }
9940 
9941         if (DetectWriteToReservedRegister())
9942           return;
9943 
9944         // Add information to the INLINEASM node to know that this register is
9945         // set.
9946         OpInfo.AssignedRegs.AddInlineAsmOperands(
9947             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9948                                   : InlineAsm::Kind::RegDef,
9949             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9950       }
9951       break;
9952 
9953     case InlineAsm::isInput:
9954     case InlineAsm::isLabel: {
9955       SDValue InOperandVal = OpInfo.CallOperand;
9956 
9957       if (OpInfo.isMatchingInputConstraint()) {
9958         // If this is required to match an output register we have already set,
9959         // just use its register.
9960         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9961                                                   AsmNodeOperands);
9962         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9963         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9964           if (OpInfo.isIndirect) {
9965             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9966             emitInlineAsmError(Call, "inline asm not supported yet: "
9967                                      "don't know how to handle tied "
9968                                      "indirect register inputs");
9969             return;
9970           }
9971 
9972           SmallVector<unsigned, 4> Regs;
9973           MachineFunction &MF = DAG.getMachineFunction();
9974           MachineRegisterInfo &MRI = MF.getRegInfo();
9975           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9976           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9977           Register TiedReg = R->getReg();
9978           MVT RegVT = R->getSimpleValueType(0);
9979           const TargetRegisterClass *RC =
9980               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9981               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9982                                       : TRI.getMinimalPhysRegClass(TiedReg);
9983           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9984             Regs.push_back(MRI.createVirtualRegister(RC));
9985 
9986           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9987 
9988           SDLoc dl = getCurSDLoc();
9989           // Use the produced MatchedRegs object to
9990           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9991           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9992                                            OpInfo.getMatchedOperand(), dl, DAG,
9993                                            AsmNodeOperands);
9994           break;
9995         }
9996 
9997         assert(Flag.isMemKind() && "Unknown matching constraint!");
9998         assert(Flag.getNumOperandRegisters() == 1 &&
9999                "Unexpected number of operands");
10000         // Add information to the INLINEASM node to know about this input.
10001         // See InlineAsm.h isUseOperandTiedToDef.
10002         Flag.clearMemConstraint();
10003         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10004         AsmNodeOperands.push_back(DAG.getTargetConstant(
10005             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10006         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10007         break;
10008       }
10009 
10010       // Treat indirect 'X' constraint as memory.
10011       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10012           OpInfo.isIndirect)
10013         OpInfo.ConstraintType = TargetLowering::C_Memory;
10014 
10015       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10016           OpInfo.ConstraintType == TargetLowering::C_Other) {
10017         std::vector<SDValue> Ops;
10018         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10019                                           Ops, DAG);
10020         if (Ops.empty()) {
10021           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10022             if (isa<ConstantSDNode>(InOperandVal)) {
10023               emitInlineAsmError(Call, "value out of range for constraint '" +
10024                                            Twine(OpInfo.ConstraintCode) + "'");
10025               return;
10026             }
10027 
10028           emitInlineAsmError(Call,
10029                              "invalid operand for inline asm constraint '" +
10030                                  Twine(OpInfo.ConstraintCode) + "'");
10031           return;
10032         }
10033 
10034         // Add information to the INLINEASM node to know about this input.
10035         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10036         AsmNodeOperands.push_back(DAG.getTargetConstant(
10037             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10038         llvm::append_range(AsmNodeOperands, Ops);
10039         break;
10040       }
10041 
10042       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10043         assert((OpInfo.isIndirect ||
10044                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10045                "Operand must be indirect to be a mem!");
10046         assert(InOperandVal.getValueType() ==
10047                    TLI.getPointerTy(DAG.getDataLayout()) &&
10048                "Memory operands expect pointer values");
10049 
10050         const InlineAsm::ConstraintCode ConstraintID =
10051             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10052         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10053                "Failed to convert memory constraint code to constraint id.");
10054 
10055         // Add information to the INLINEASM node to know about this input.
10056         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10057         ResOpType.setMemConstraint(ConstraintID);
10058         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10059                                                         getCurSDLoc(),
10060                                                         MVT::i32));
10061         AsmNodeOperands.push_back(InOperandVal);
10062         break;
10063       }
10064 
10065       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10066         const InlineAsm::ConstraintCode ConstraintID =
10067             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10068         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10069                "Failed to convert memory constraint code to constraint id.");
10070 
10071         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10072 
10073         SDValue AsmOp = InOperandVal;
10074         if (isFunction(InOperandVal)) {
10075           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10076           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10077           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10078                                              InOperandVal.getValueType(),
10079                                              GA->getOffset());
10080         }
10081 
10082         // Add information to the INLINEASM node to know about this input.
10083         ResOpType.setMemConstraint(ConstraintID);
10084 
10085         AsmNodeOperands.push_back(
10086             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10087 
10088         AsmNodeOperands.push_back(AsmOp);
10089         break;
10090       }
10091 
10092       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10093           OpInfo.ConstraintType != TargetLowering::C_Register) {
10094         emitInlineAsmError(Call, "unknown asm constraint '" +
10095                                      Twine(OpInfo.ConstraintCode) + "'");
10096         return;
10097       }
10098 
10099       // TODO: Support this.
10100       if (OpInfo.isIndirect) {
10101         emitInlineAsmError(
10102             Call, "Don't know how to handle indirect register inputs yet "
10103                   "for constraint '" +
10104                       Twine(OpInfo.ConstraintCode) + "'");
10105         return;
10106       }
10107 
10108       // Copy the input into the appropriate registers.
10109       if (OpInfo.AssignedRegs.Regs.empty()) {
10110         emitInlineAsmError(Call,
10111                            "couldn't allocate input reg for constraint '" +
10112                                Twine(OpInfo.ConstraintCode) + "'");
10113         return;
10114       }
10115 
10116       if (DetectWriteToReservedRegister())
10117         return;
10118 
10119       SDLoc dl = getCurSDLoc();
10120 
10121       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10122                                         &Call);
10123 
10124       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10125                                                0, dl, DAG, AsmNodeOperands);
10126       break;
10127     }
10128     case InlineAsm::isClobber:
10129       // Add the clobbered value to the operand list, so that the register
10130       // allocator is aware that the physreg got clobbered.
10131       if (!OpInfo.AssignedRegs.Regs.empty())
10132         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10133                                                  false, 0, getCurSDLoc(), DAG,
10134                                                  AsmNodeOperands);
10135       break;
10136     }
10137   }
10138 
10139   // Finish up input operands.  Set the input chain and add the flag last.
10140   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10141   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10142 
10143   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10144   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10145                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10146   Glue = Chain.getValue(1);
10147 
10148   // Do additional work to generate outputs.
10149 
10150   SmallVector<EVT, 1> ResultVTs;
10151   SmallVector<SDValue, 1> ResultValues;
10152   SmallVector<SDValue, 8> OutChains;
10153 
10154   llvm::Type *CallResultType = Call.getType();
10155   ArrayRef<Type *> ResultTypes;
10156   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10157     ResultTypes = StructResult->elements();
10158   else if (!CallResultType->isVoidTy())
10159     ResultTypes = ArrayRef(CallResultType);
10160 
10161   auto CurResultType = ResultTypes.begin();
10162   auto handleRegAssign = [&](SDValue V) {
10163     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10164     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10165     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10166     ++CurResultType;
10167     // If the type of the inline asm call site return value is different but has
10168     // same size as the type of the asm output bitcast it.  One example of this
10169     // is for vectors with different width / number of elements.  This can
10170     // happen for register classes that can contain multiple different value
10171     // types.  The preg or vreg allocated may not have the same VT as was
10172     // expected.
10173     //
10174     // This can also happen for a return value that disagrees with the register
10175     // class it is put in, eg. a double in a general-purpose register on a
10176     // 32-bit machine.
10177     if (ResultVT != V.getValueType() &&
10178         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10179       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10180     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10181              V.getValueType().isInteger()) {
10182       // If a result value was tied to an input value, the computed result
10183       // may have a wider width than the expected result.  Extract the
10184       // relevant portion.
10185       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10186     }
10187     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10188     ResultVTs.push_back(ResultVT);
10189     ResultValues.push_back(V);
10190   };
10191 
10192   // Deal with output operands.
10193   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10194     if (OpInfo.Type == InlineAsm::isOutput) {
10195       SDValue Val;
10196       // Skip trivial output operands.
10197       if (OpInfo.AssignedRegs.Regs.empty())
10198         continue;
10199 
10200       switch (OpInfo.ConstraintType) {
10201       case TargetLowering::C_Register:
10202       case TargetLowering::C_RegisterClass:
10203         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10204                                                   Chain, &Glue, &Call);
10205         break;
10206       case TargetLowering::C_Immediate:
10207       case TargetLowering::C_Other:
10208         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10209                                               OpInfo, DAG);
10210         break;
10211       case TargetLowering::C_Memory:
10212         break; // Already handled.
10213       case TargetLowering::C_Address:
10214         break; // Silence warning.
10215       case TargetLowering::C_Unknown:
10216         assert(false && "Unexpected unknown constraint");
10217       }
10218 
10219       // Indirect output manifest as stores. Record output chains.
10220       if (OpInfo.isIndirect) {
10221         const Value *Ptr = OpInfo.CallOperandVal;
10222         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10223         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10224                                      MachinePointerInfo(Ptr));
10225         OutChains.push_back(Store);
10226       } else {
10227         // generate CopyFromRegs to associated registers.
10228         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10229         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10230           for (const SDValue &V : Val->op_values())
10231             handleRegAssign(V);
10232         } else
10233           handleRegAssign(Val);
10234       }
10235     }
10236   }
10237 
10238   // Set results.
10239   if (!ResultValues.empty()) {
10240     assert(CurResultType == ResultTypes.end() &&
10241            "Mismatch in number of ResultTypes");
10242     assert(ResultValues.size() == ResultTypes.size() &&
10243            "Mismatch in number of output operands in asm result");
10244 
10245     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10246                             DAG.getVTList(ResultVTs), ResultValues);
10247     setValue(&Call, V);
10248   }
10249 
10250   // Collect store chains.
10251   if (!OutChains.empty())
10252     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10253 
10254   if (EmitEHLabels) {
10255     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10256   }
10257 
10258   // Only Update Root if inline assembly has a memory effect.
10259   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10260       EmitEHLabels)
10261     DAG.setRoot(Chain);
10262 }
10263 
10264 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10265                                              const Twine &Message) {
10266   LLVMContext &Ctx = *DAG.getContext();
10267   Ctx.emitError(&Call, Message);
10268 
10269   // Make sure we leave the DAG in a valid state
10270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10271   SmallVector<EVT, 1> ValueVTs;
10272   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10273 
10274   if (ValueVTs.empty())
10275     return;
10276 
10277   SmallVector<SDValue, 1> Ops;
10278   for (const EVT &VT : ValueVTs)
10279     Ops.push_back(DAG.getUNDEF(VT));
10280 
10281   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10282 }
10283 
10284 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10285   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10286                           MVT::Other, getRoot(),
10287                           getValue(I.getArgOperand(0)),
10288                           DAG.getSrcValue(I.getArgOperand(0))));
10289 }
10290 
10291 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10292   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10293   const DataLayout &DL = DAG.getDataLayout();
10294   SDValue V = DAG.getVAArg(
10295       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10296       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10297       DL.getABITypeAlign(I.getType()).value());
10298   DAG.setRoot(V.getValue(1));
10299 
10300   if (I.getType()->isPointerTy())
10301     V = DAG.getPtrExtOrTrunc(
10302         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10303   setValue(&I, V);
10304 }
10305 
10306 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10307   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10308                           MVT::Other, getRoot(),
10309                           getValue(I.getArgOperand(0)),
10310                           DAG.getSrcValue(I.getArgOperand(0))));
10311 }
10312 
10313 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10314   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10315                           MVT::Other, getRoot(),
10316                           getValue(I.getArgOperand(0)),
10317                           getValue(I.getArgOperand(1)),
10318                           DAG.getSrcValue(I.getArgOperand(0)),
10319                           DAG.getSrcValue(I.getArgOperand(1))));
10320 }
10321 
10322 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10323                                                     const Instruction &I,
10324                                                     SDValue Op) {
10325   std::optional<ConstantRange> CR = getRange(I);
10326 
10327   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10328     return Op;
10329 
10330   APInt Lo = CR->getUnsignedMin();
10331   if (!Lo.isMinValue())
10332     return Op;
10333 
10334   APInt Hi = CR->getUnsignedMax();
10335   unsigned Bits = std::max(Hi.getActiveBits(),
10336                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10337 
10338   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10339 
10340   SDLoc SL = getCurSDLoc();
10341 
10342   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10343                              DAG.getValueType(SmallVT));
10344   unsigned NumVals = Op.getNode()->getNumValues();
10345   if (NumVals == 1)
10346     return ZExt;
10347 
10348   SmallVector<SDValue, 4> Ops;
10349 
10350   Ops.push_back(ZExt);
10351   for (unsigned I = 1; I != NumVals; ++I)
10352     Ops.push_back(Op.getValue(I));
10353 
10354   return DAG.getMergeValues(Ops, SL);
10355 }
10356 
10357 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10358 /// the call being lowered.
10359 ///
10360 /// This is a helper for lowering intrinsics that follow a target calling
10361 /// convention or require stack pointer adjustment. Only a subset of the
10362 /// intrinsic's operands need to participate in the calling convention.
10363 void SelectionDAGBuilder::populateCallLoweringInfo(
10364     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10365     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10366     AttributeSet RetAttrs, bool IsPatchPoint) {
10367   TargetLowering::ArgListTy Args;
10368   Args.reserve(NumArgs);
10369 
10370   // Populate the argument list.
10371   // Attributes for args start at offset 1, after the return attribute.
10372   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10373        ArgI != ArgE; ++ArgI) {
10374     const Value *V = Call->getOperand(ArgI);
10375 
10376     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10377 
10378     TargetLowering::ArgListEntry Entry;
10379     Entry.Node = getValue(V);
10380     Entry.Ty = V->getType();
10381     Entry.setAttributes(Call, ArgI);
10382     Args.push_back(Entry);
10383   }
10384 
10385   CLI.setDebugLoc(getCurSDLoc())
10386       .setChain(getRoot())
10387       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10388                  RetAttrs)
10389       .setDiscardResult(Call->use_empty())
10390       .setIsPatchPoint(IsPatchPoint)
10391       .setIsPreallocated(
10392           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10393 }
10394 
10395 /// Add a stack map intrinsic call's live variable operands to a stackmap
10396 /// or patchpoint target node's operand list.
10397 ///
10398 /// Constants are converted to TargetConstants purely as an optimization to
10399 /// avoid constant materialization and register allocation.
10400 ///
10401 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10402 /// generate addess computation nodes, and so FinalizeISel can convert the
10403 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10404 /// address materialization and register allocation, but may also be required
10405 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10406 /// alloca in the entry block, then the runtime may assume that the alloca's
10407 /// StackMap location can be read immediately after compilation and that the
10408 /// location is valid at any point during execution (this is similar to the
10409 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10410 /// only available in a register, then the runtime would need to trap when
10411 /// execution reaches the StackMap in order to read the alloca's location.
10412 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10413                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10414                                 SelectionDAGBuilder &Builder) {
10415   SelectionDAG &DAG = Builder.DAG;
10416   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10417     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10418 
10419     // Things on the stack are pointer-typed, meaning that they are already
10420     // legal and can be emitted directly to target nodes.
10421     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10422       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10423     } else {
10424       // Otherwise emit a target independent node to be legalised.
10425       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10426     }
10427   }
10428 }
10429 
10430 /// Lower llvm.experimental.stackmap.
10431 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10432   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10433   //                                  [live variables...])
10434 
10435   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10436 
10437   SDValue Chain, InGlue, Callee;
10438   SmallVector<SDValue, 32> Ops;
10439 
10440   SDLoc DL = getCurSDLoc();
10441   Callee = getValue(CI.getCalledOperand());
10442 
10443   // The stackmap intrinsic only records the live variables (the arguments
10444   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10445   // intrinsic, this won't be lowered to a function call. This means we don't
10446   // have to worry about calling conventions and target specific lowering code.
10447   // Instead we perform the call lowering right here.
10448   //
10449   // chain, flag = CALLSEQ_START(chain, 0, 0)
10450   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10451   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10452   //
10453   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10454   InGlue = Chain.getValue(1);
10455 
10456   // Add the STACKMAP operands, starting with DAG house-keeping.
10457   Ops.push_back(Chain);
10458   Ops.push_back(InGlue);
10459 
10460   // Add the <id>, <numShadowBytes> operands.
10461   //
10462   // These do not require legalisation, and can be emitted directly to target
10463   // constant nodes.
10464   SDValue ID = getValue(CI.getArgOperand(0));
10465   assert(ID.getValueType() == MVT::i64);
10466   SDValue IDConst =
10467       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10468   Ops.push_back(IDConst);
10469 
10470   SDValue Shad = getValue(CI.getArgOperand(1));
10471   assert(Shad.getValueType() == MVT::i32);
10472   SDValue ShadConst =
10473       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10474   Ops.push_back(ShadConst);
10475 
10476   // Add the live variables.
10477   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10478 
10479   // Create the STACKMAP node.
10480   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10481   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10482   InGlue = Chain.getValue(1);
10483 
10484   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10485 
10486   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10487 
10488   // Set the root to the target-lowered call chain.
10489   DAG.setRoot(Chain);
10490 
10491   // Inform the Frame Information that we have a stackmap in this function.
10492   FuncInfo.MF->getFrameInfo().setHasStackMap();
10493 }
10494 
10495 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10496 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10497                                           const BasicBlock *EHPadBB) {
10498   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10499   //                                         i32 <numBytes>,
10500   //                                         i8* <target>,
10501   //                                         i32 <numArgs>,
10502   //                                         [Args...],
10503   //                                         [live variables...])
10504 
10505   CallingConv::ID CC = CB.getCallingConv();
10506   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10507   bool HasDef = !CB.getType()->isVoidTy();
10508   SDLoc dl = getCurSDLoc();
10509   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10510 
10511   // Handle immediate and symbolic callees.
10512   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10513     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10514                                    /*isTarget=*/true);
10515   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10516     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10517                                          SDLoc(SymbolicCallee),
10518                                          SymbolicCallee->getValueType(0));
10519 
10520   // Get the real number of arguments participating in the call <numArgs>
10521   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10522   unsigned NumArgs = NArgVal->getAsZExtVal();
10523 
10524   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10525   // Intrinsics include all meta-operands up to but not including CC.
10526   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10527   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10528          "Not enough arguments provided to the patchpoint intrinsic");
10529 
10530   // For AnyRegCC the arguments are lowered later on manually.
10531   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10532   Type *ReturnTy =
10533       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10534 
10535   TargetLowering::CallLoweringInfo CLI(DAG);
10536   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10537                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10538   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10539 
10540   SDNode *CallEnd = Result.second.getNode();
10541   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10542     CallEnd = CallEnd->getOperand(0).getNode();
10543   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10544     CallEnd = CallEnd->getOperand(0).getNode();
10545 
10546   /// Get a call instruction from the call sequence chain.
10547   /// Tail calls are not allowed.
10548   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10549          "Expected a callseq node.");
10550   SDNode *Call = CallEnd->getOperand(0).getNode();
10551   bool HasGlue = Call->getGluedNode();
10552 
10553   // Replace the target specific call node with the patchable intrinsic.
10554   SmallVector<SDValue, 8> Ops;
10555 
10556   // Push the chain.
10557   Ops.push_back(*(Call->op_begin()));
10558 
10559   // Optionally, push the glue (if any).
10560   if (HasGlue)
10561     Ops.push_back(*(Call->op_end() - 1));
10562 
10563   // Push the register mask info.
10564   if (HasGlue)
10565     Ops.push_back(*(Call->op_end() - 2));
10566   else
10567     Ops.push_back(*(Call->op_end() - 1));
10568 
10569   // Add the <id> and <numBytes> constants.
10570   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10571   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10572   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10573   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10574 
10575   // Add the callee.
10576   Ops.push_back(Callee);
10577 
10578   // Adjust <numArgs> to account for any arguments that have been passed on the
10579   // stack instead.
10580   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10581   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10582   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10583   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10584 
10585   // Add the calling convention
10586   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10587 
10588   // Add the arguments we omitted previously. The register allocator should
10589   // place these in any free register.
10590   if (IsAnyRegCC)
10591     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10592       Ops.push_back(getValue(CB.getArgOperand(i)));
10593 
10594   // Push the arguments from the call instruction.
10595   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10596   Ops.append(Call->op_begin() + 2, e);
10597 
10598   // Push live variables for the stack map.
10599   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10600 
10601   SDVTList NodeTys;
10602   if (IsAnyRegCC && HasDef) {
10603     // Create the return types based on the intrinsic definition
10604     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10605     SmallVector<EVT, 3> ValueVTs;
10606     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10607     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10608 
10609     // There is always a chain and a glue type at the end
10610     ValueVTs.push_back(MVT::Other);
10611     ValueVTs.push_back(MVT::Glue);
10612     NodeTys = DAG.getVTList(ValueVTs);
10613   } else
10614     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10615 
10616   // Replace the target specific call node with a PATCHPOINT node.
10617   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10618 
10619   // Update the NodeMap.
10620   if (HasDef) {
10621     if (IsAnyRegCC)
10622       setValue(&CB, SDValue(PPV.getNode(), 0));
10623     else
10624       setValue(&CB, Result.first);
10625   }
10626 
10627   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10628   // call sequence. Furthermore the location of the chain and glue can change
10629   // when the AnyReg calling convention is used and the intrinsic returns a
10630   // value.
10631   if (IsAnyRegCC && HasDef) {
10632     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10633     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10634     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10635   } else
10636     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10637   DAG.DeleteNode(Call);
10638 
10639   // Inform the Frame Information that we have a patchpoint in this function.
10640   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10641 }
10642 
10643 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10644                                             unsigned Intrinsic) {
10645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10646   SDValue Op1 = getValue(I.getArgOperand(0));
10647   SDValue Op2;
10648   if (I.arg_size() > 1)
10649     Op2 = getValue(I.getArgOperand(1));
10650   SDLoc dl = getCurSDLoc();
10651   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10652   SDValue Res;
10653   SDNodeFlags SDFlags;
10654   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10655     SDFlags.copyFMF(*FPMO);
10656 
10657   switch (Intrinsic) {
10658   case Intrinsic::vector_reduce_fadd:
10659     if (SDFlags.hasAllowReassociation())
10660       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10661                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10662                         SDFlags);
10663     else
10664       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10665     break;
10666   case Intrinsic::vector_reduce_fmul:
10667     if (SDFlags.hasAllowReassociation())
10668       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10669                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10670                         SDFlags);
10671     else
10672       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10673     break;
10674   case Intrinsic::vector_reduce_add:
10675     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10676     break;
10677   case Intrinsic::vector_reduce_mul:
10678     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10679     break;
10680   case Intrinsic::vector_reduce_and:
10681     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10682     break;
10683   case Intrinsic::vector_reduce_or:
10684     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10685     break;
10686   case Intrinsic::vector_reduce_xor:
10687     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10688     break;
10689   case Intrinsic::vector_reduce_smax:
10690     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10691     break;
10692   case Intrinsic::vector_reduce_smin:
10693     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10694     break;
10695   case Intrinsic::vector_reduce_umax:
10696     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10697     break;
10698   case Intrinsic::vector_reduce_umin:
10699     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10700     break;
10701   case Intrinsic::vector_reduce_fmax:
10702     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10703     break;
10704   case Intrinsic::vector_reduce_fmin:
10705     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10706     break;
10707   case Intrinsic::vector_reduce_fmaximum:
10708     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10709     break;
10710   case Intrinsic::vector_reduce_fminimum:
10711     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10712     break;
10713   default:
10714     llvm_unreachable("Unhandled vector reduce intrinsic");
10715   }
10716   setValue(&I, Res);
10717 }
10718 
10719 /// Returns an AttributeList representing the attributes applied to the return
10720 /// value of the given call.
10721 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10722   SmallVector<Attribute::AttrKind, 2> Attrs;
10723   if (CLI.RetSExt)
10724     Attrs.push_back(Attribute::SExt);
10725   if (CLI.RetZExt)
10726     Attrs.push_back(Attribute::ZExt);
10727   if (CLI.IsInReg)
10728     Attrs.push_back(Attribute::InReg);
10729 
10730   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10731                             Attrs);
10732 }
10733 
10734 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10735 /// implementation, which just calls LowerCall.
10736 /// FIXME: When all targets are
10737 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10738 std::pair<SDValue, SDValue>
10739 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10740   // Handle the incoming return values from the call.
10741   CLI.Ins.clear();
10742   Type *OrigRetTy = CLI.RetTy;
10743   SmallVector<EVT, 4> RetTys;
10744   SmallVector<TypeSize, 4> Offsets;
10745   auto &DL = CLI.DAG.getDataLayout();
10746   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10747 
10748   if (CLI.IsPostTypeLegalization) {
10749     // If we are lowering a libcall after legalization, split the return type.
10750     SmallVector<EVT, 4> OldRetTys;
10751     SmallVector<TypeSize, 4> OldOffsets;
10752     RetTys.swap(OldRetTys);
10753     Offsets.swap(OldOffsets);
10754 
10755     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10756       EVT RetVT = OldRetTys[i];
10757       uint64_t Offset = OldOffsets[i];
10758       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10759       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10760       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10761       RetTys.append(NumRegs, RegisterVT);
10762       for (unsigned j = 0; j != NumRegs; ++j)
10763         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10764     }
10765   }
10766 
10767   SmallVector<ISD::OutputArg, 4> Outs;
10768   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10769 
10770   bool CanLowerReturn =
10771       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10772                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10773 
10774   SDValue DemoteStackSlot;
10775   int DemoteStackIdx = -100;
10776   if (!CanLowerReturn) {
10777     // FIXME: equivalent assert?
10778     // assert(!CS.hasInAllocaArgument() &&
10779     //        "sret demotion is incompatible with inalloca");
10780     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10781     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10782     MachineFunction &MF = CLI.DAG.getMachineFunction();
10783     DemoteStackIdx =
10784         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10785     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10786                                               DL.getAllocaAddrSpace());
10787 
10788     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10789     ArgListEntry Entry;
10790     Entry.Node = DemoteStackSlot;
10791     Entry.Ty = StackSlotPtrType;
10792     Entry.IsSExt = false;
10793     Entry.IsZExt = false;
10794     Entry.IsInReg = false;
10795     Entry.IsSRet = true;
10796     Entry.IsNest = false;
10797     Entry.IsByVal = false;
10798     Entry.IsByRef = false;
10799     Entry.IsReturned = false;
10800     Entry.IsSwiftSelf = false;
10801     Entry.IsSwiftAsync = false;
10802     Entry.IsSwiftError = false;
10803     Entry.IsCFGuardTarget = false;
10804     Entry.Alignment = Alignment;
10805     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10806     CLI.NumFixedArgs += 1;
10807     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10808     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10809 
10810     // sret demotion isn't compatible with tail-calls, since the sret argument
10811     // points into the callers stack frame.
10812     CLI.IsTailCall = false;
10813   } else {
10814     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10815         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10816     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10817       ISD::ArgFlagsTy Flags;
10818       if (NeedsRegBlock) {
10819         Flags.setInConsecutiveRegs();
10820         if (I == RetTys.size() - 1)
10821           Flags.setInConsecutiveRegsLast();
10822       }
10823       EVT VT = RetTys[I];
10824       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10825                                                      CLI.CallConv, VT);
10826       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10827                                                        CLI.CallConv, VT);
10828       for (unsigned i = 0; i != NumRegs; ++i) {
10829         ISD::InputArg MyFlags;
10830         MyFlags.Flags = Flags;
10831         MyFlags.VT = RegisterVT;
10832         MyFlags.ArgVT = VT;
10833         MyFlags.Used = CLI.IsReturnValueUsed;
10834         if (CLI.RetTy->isPointerTy()) {
10835           MyFlags.Flags.setPointer();
10836           MyFlags.Flags.setPointerAddrSpace(
10837               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10838         }
10839         if (CLI.RetSExt)
10840           MyFlags.Flags.setSExt();
10841         if (CLI.RetZExt)
10842           MyFlags.Flags.setZExt();
10843         if (CLI.IsInReg)
10844           MyFlags.Flags.setInReg();
10845         CLI.Ins.push_back(MyFlags);
10846       }
10847     }
10848   }
10849 
10850   // We push in swifterror return as the last element of CLI.Ins.
10851   ArgListTy &Args = CLI.getArgs();
10852   if (supportSwiftError()) {
10853     for (const ArgListEntry &Arg : Args) {
10854       if (Arg.IsSwiftError) {
10855         ISD::InputArg MyFlags;
10856         MyFlags.VT = getPointerTy(DL);
10857         MyFlags.ArgVT = EVT(getPointerTy(DL));
10858         MyFlags.Flags.setSwiftError();
10859         CLI.Ins.push_back(MyFlags);
10860       }
10861     }
10862   }
10863 
10864   // Handle all of the outgoing arguments.
10865   CLI.Outs.clear();
10866   CLI.OutVals.clear();
10867   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10868     SmallVector<EVT, 4> ValueVTs;
10869     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10870     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10871     Type *FinalType = Args[i].Ty;
10872     if (Args[i].IsByVal)
10873       FinalType = Args[i].IndirectType;
10874     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10875         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10876     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10877          ++Value) {
10878       EVT VT = ValueVTs[Value];
10879       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10880       SDValue Op = SDValue(Args[i].Node.getNode(),
10881                            Args[i].Node.getResNo() + Value);
10882       ISD::ArgFlagsTy Flags;
10883 
10884       // Certain targets (such as MIPS), may have a different ABI alignment
10885       // for a type depending on the context. Give the target a chance to
10886       // specify the alignment it wants.
10887       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10888       Flags.setOrigAlign(OriginalAlignment);
10889 
10890       if (Args[i].Ty->isPointerTy()) {
10891         Flags.setPointer();
10892         Flags.setPointerAddrSpace(
10893             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10894       }
10895       if (Args[i].IsZExt)
10896         Flags.setZExt();
10897       if (Args[i].IsSExt)
10898         Flags.setSExt();
10899       if (Args[i].IsInReg) {
10900         // If we are using vectorcall calling convention, a structure that is
10901         // passed InReg - is surely an HVA
10902         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10903             isa<StructType>(FinalType)) {
10904           // The first value of a structure is marked
10905           if (0 == Value)
10906             Flags.setHvaStart();
10907           Flags.setHva();
10908         }
10909         // Set InReg Flag
10910         Flags.setInReg();
10911       }
10912       if (Args[i].IsSRet)
10913         Flags.setSRet();
10914       if (Args[i].IsSwiftSelf)
10915         Flags.setSwiftSelf();
10916       if (Args[i].IsSwiftAsync)
10917         Flags.setSwiftAsync();
10918       if (Args[i].IsSwiftError)
10919         Flags.setSwiftError();
10920       if (Args[i].IsCFGuardTarget)
10921         Flags.setCFGuardTarget();
10922       if (Args[i].IsByVal)
10923         Flags.setByVal();
10924       if (Args[i].IsByRef)
10925         Flags.setByRef();
10926       if (Args[i].IsPreallocated) {
10927         Flags.setPreallocated();
10928         // Set the byval flag for CCAssignFn callbacks that don't know about
10929         // preallocated.  This way we can know how many bytes we should've
10930         // allocated and how many bytes a callee cleanup function will pop.  If
10931         // we port preallocated to more targets, we'll have to add custom
10932         // preallocated handling in the various CC lowering callbacks.
10933         Flags.setByVal();
10934       }
10935       if (Args[i].IsInAlloca) {
10936         Flags.setInAlloca();
10937         // Set the byval flag for CCAssignFn callbacks that don't know about
10938         // inalloca.  This way we can know how many bytes we should've allocated
10939         // and how many bytes a callee cleanup function will pop.  If we port
10940         // inalloca to more targets, we'll have to add custom inalloca handling
10941         // in the various CC lowering callbacks.
10942         Flags.setByVal();
10943       }
10944       Align MemAlign;
10945       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10946         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10947         Flags.setByValSize(FrameSize);
10948 
10949         // info is not there but there are cases it cannot get right.
10950         if (auto MA = Args[i].Alignment)
10951           MemAlign = *MA;
10952         else
10953           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10954       } else if (auto MA = Args[i].Alignment) {
10955         MemAlign = *MA;
10956       } else {
10957         MemAlign = OriginalAlignment;
10958       }
10959       Flags.setMemAlign(MemAlign);
10960       if (Args[i].IsNest)
10961         Flags.setNest();
10962       if (NeedsRegBlock)
10963         Flags.setInConsecutiveRegs();
10964 
10965       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10966                                                  CLI.CallConv, VT);
10967       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10968                                                         CLI.CallConv, VT);
10969       SmallVector<SDValue, 4> Parts(NumParts);
10970       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10971 
10972       if (Args[i].IsSExt)
10973         ExtendKind = ISD::SIGN_EXTEND;
10974       else if (Args[i].IsZExt)
10975         ExtendKind = ISD::ZERO_EXTEND;
10976 
10977       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10978       // for now.
10979       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10980           CanLowerReturn) {
10981         assert((CLI.RetTy == Args[i].Ty ||
10982                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10983                  CLI.RetTy->getPointerAddressSpace() ==
10984                      Args[i].Ty->getPointerAddressSpace())) &&
10985                RetTys.size() == NumValues && "unexpected use of 'returned'");
10986         // Before passing 'returned' to the target lowering code, ensure that
10987         // either the register MVT and the actual EVT are the same size or that
10988         // the return value and argument are extended in the same way; in these
10989         // cases it's safe to pass the argument register value unchanged as the
10990         // return register value (although it's at the target's option whether
10991         // to do so)
10992         // TODO: allow code generation to take advantage of partially preserved
10993         // registers rather than clobbering the entire register when the
10994         // parameter extension method is not compatible with the return
10995         // extension method
10996         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10997             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10998              CLI.RetZExt == Args[i].IsZExt))
10999           Flags.setReturned();
11000       }
11001 
11002       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11003                      CLI.CallConv, ExtendKind);
11004 
11005       for (unsigned j = 0; j != NumParts; ++j) {
11006         // if it isn't first piece, alignment must be 1
11007         // For scalable vectors the scalable part is currently handled
11008         // by individual targets, so we just use the known minimum size here.
11009         ISD::OutputArg MyFlags(
11010             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11011             i < CLI.NumFixedArgs, i,
11012             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11013         if (NumParts > 1 && j == 0)
11014           MyFlags.Flags.setSplit();
11015         else if (j != 0) {
11016           MyFlags.Flags.setOrigAlign(Align(1));
11017           if (j == NumParts - 1)
11018             MyFlags.Flags.setSplitEnd();
11019         }
11020 
11021         CLI.Outs.push_back(MyFlags);
11022         CLI.OutVals.push_back(Parts[j]);
11023       }
11024 
11025       if (NeedsRegBlock && Value == NumValues - 1)
11026         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11027     }
11028   }
11029 
11030   SmallVector<SDValue, 4> InVals;
11031   CLI.Chain = LowerCall(CLI, InVals);
11032 
11033   // Update CLI.InVals to use outside of this function.
11034   CLI.InVals = InVals;
11035 
11036   // Verify that the target's LowerCall behaved as expected.
11037   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11038          "LowerCall didn't return a valid chain!");
11039   assert((!CLI.IsTailCall || InVals.empty()) &&
11040          "LowerCall emitted a return value for a tail call!");
11041   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11042          "LowerCall didn't emit the correct number of values!");
11043 
11044   // For a tail call, the return value is merely live-out and there aren't
11045   // any nodes in the DAG representing it. Return a special value to
11046   // indicate that a tail call has been emitted and no more Instructions
11047   // should be processed in the current block.
11048   if (CLI.IsTailCall) {
11049     CLI.DAG.setRoot(CLI.Chain);
11050     return std::make_pair(SDValue(), SDValue());
11051   }
11052 
11053 #ifndef NDEBUG
11054   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11055     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11056     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11057            "LowerCall emitted a value with the wrong type!");
11058   }
11059 #endif
11060 
11061   SmallVector<SDValue, 4> ReturnValues;
11062   if (!CanLowerReturn) {
11063     // The instruction result is the result of loading from the
11064     // hidden sret parameter.
11065     SmallVector<EVT, 1> PVTs;
11066     Type *PtrRetTy =
11067         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11068 
11069     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11070     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11071     EVT PtrVT = PVTs[0];
11072 
11073     unsigned NumValues = RetTys.size();
11074     ReturnValues.resize(NumValues);
11075     SmallVector<SDValue, 4> Chains(NumValues);
11076 
11077     // An aggregate return value cannot wrap around the address space, so
11078     // offsets to its parts don't wrap either.
11079     SDNodeFlags Flags;
11080     Flags.setNoUnsignedWrap(true);
11081 
11082     MachineFunction &MF = CLI.DAG.getMachineFunction();
11083     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11084     for (unsigned i = 0; i < NumValues; ++i) {
11085       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11086                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11087                                                         PtrVT), Flags);
11088       SDValue L = CLI.DAG.getLoad(
11089           RetTys[i], CLI.DL, CLI.Chain, Add,
11090           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11091                                             DemoteStackIdx, Offsets[i]),
11092           HiddenSRetAlign);
11093       ReturnValues[i] = L;
11094       Chains[i] = L.getValue(1);
11095     }
11096 
11097     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11098   } else {
11099     // Collect the legal value parts into potentially illegal values
11100     // that correspond to the original function's return values.
11101     std::optional<ISD::NodeType> AssertOp;
11102     if (CLI.RetSExt)
11103       AssertOp = ISD::AssertSext;
11104     else if (CLI.RetZExt)
11105       AssertOp = ISD::AssertZext;
11106     unsigned CurReg = 0;
11107     for (EVT VT : RetTys) {
11108       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11109                                                      CLI.CallConv, VT);
11110       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11111                                                        CLI.CallConv, VT);
11112 
11113       ReturnValues.push_back(getCopyFromParts(
11114           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11115           CLI.Chain, CLI.CallConv, AssertOp));
11116       CurReg += NumRegs;
11117     }
11118 
11119     // For a function returning void, there is no return value. We can't create
11120     // such a node, so we just return a null return value in that case. In
11121     // that case, nothing will actually look at the value.
11122     if (ReturnValues.empty())
11123       return std::make_pair(SDValue(), CLI.Chain);
11124   }
11125 
11126   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11127                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11128   return std::make_pair(Res, CLI.Chain);
11129 }
11130 
11131 /// Places new result values for the node in Results (their number
11132 /// and types must exactly match those of the original return values of
11133 /// the node), or leaves Results empty, which indicates that the node is not
11134 /// to be custom lowered after all.
11135 void TargetLowering::LowerOperationWrapper(SDNode *N,
11136                                            SmallVectorImpl<SDValue> &Results,
11137                                            SelectionDAG &DAG) const {
11138   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11139 
11140   if (!Res.getNode())
11141     return;
11142 
11143   // If the original node has one result, take the return value from
11144   // LowerOperation as is. It might not be result number 0.
11145   if (N->getNumValues() == 1) {
11146     Results.push_back(Res);
11147     return;
11148   }
11149 
11150   // If the original node has multiple results, then the return node should
11151   // have the same number of results.
11152   assert((N->getNumValues() == Res->getNumValues()) &&
11153       "Lowering returned the wrong number of results!");
11154 
11155   // Places new result values base on N result number.
11156   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11157     Results.push_back(Res.getValue(I));
11158 }
11159 
11160 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11161   llvm_unreachable("LowerOperation not implemented for this target!");
11162 }
11163 
11164 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11165                                                      unsigned Reg,
11166                                                      ISD::NodeType ExtendType) {
11167   SDValue Op = getNonRegisterValue(V);
11168   assert((Op.getOpcode() != ISD::CopyFromReg ||
11169           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11170          "Copy from a reg to the same reg!");
11171   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11172 
11173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11174   // If this is an InlineAsm we have to match the registers required, not the
11175   // notional registers required by the type.
11176 
11177   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11178                    std::nullopt); // This is not an ABI copy.
11179   SDValue Chain = DAG.getEntryNode();
11180 
11181   if (ExtendType == ISD::ANY_EXTEND) {
11182     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11183     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11184       ExtendType = PreferredExtendIt->second;
11185   }
11186   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11187   PendingExports.push_back(Chain);
11188 }
11189 
11190 #include "llvm/CodeGen/SelectionDAGISel.h"
11191 
11192 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11193 /// entry block, return true.  This includes arguments used by switches, since
11194 /// the switch may expand into multiple basic blocks.
11195 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11196   // With FastISel active, we may be splitting blocks, so force creation
11197   // of virtual registers for all non-dead arguments.
11198   if (FastISel)
11199     return A->use_empty();
11200 
11201   const BasicBlock &Entry = A->getParent()->front();
11202   for (const User *U : A->users())
11203     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11204       return false;  // Use not in entry block.
11205 
11206   return true;
11207 }
11208 
11209 using ArgCopyElisionMapTy =
11210     DenseMap<const Argument *,
11211              std::pair<const AllocaInst *, const StoreInst *>>;
11212 
11213 /// Scan the entry block of the function in FuncInfo for arguments that look
11214 /// like copies into a local alloca. Record any copied arguments in
11215 /// ArgCopyElisionCandidates.
11216 static void
11217 findArgumentCopyElisionCandidates(const DataLayout &DL,
11218                                   FunctionLoweringInfo *FuncInfo,
11219                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11220   // Record the state of every static alloca used in the entry block. Argument
11221   // allocas are all used in the entry block, so we need approximately as many
11222   // entries as we have arguments.
11223   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11224   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11225   unsigned NumArgs = FuncInfo->Fn->arg_size();
11226   StaticAllocas.reserve(NumArgs * 2);
11227 
11228   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11229     if (!V)
11230       return nullptr;
11231     V = V->stripPointerCasts();
11232     const auto *AI = dyn_cast<AllocaInst>(V);
11233     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11234       return nullptr;
11235     auto Iter = StaticAllocas.insert({AI, Unknown});
11236     return &Iter.first->second;
11237   };
11238 
11239   // Look for stores of arguments to static allocas. Look through bitcasts and
11240   // GEPs to handle type coercions, as long as the alloca is fully initialized
11241   // by the store. Any non-store use of an alloca escapes it and any subsequent
11242   // unanalyzed store might write it.
11243   // FIXME: Handle structs initialized with multiple stores.
11244   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11245     // Look for stores, and handle non-store uses conservatively.
11246     const auto *SI = dyn_cast<StoreInst>(&I);
11247     if (!SI) {
11248       // We will look through cast uses, so ignore them completely.
11249       if (I.isCast())
11250         continue;
11251       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11252       // to allocas.
11253       if (I.isDebugOrPseudoInst())
11254         continue;
11255       // This is an unknown instruction. Assume it escapes or writes to all
11256       // static alloca operands.
11257       for (const Use &U : I.operands()) {
11258         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11259           *Info = StaticAllocaInfo::Clobbered;
11260       }
11261       continue;
11262     }
11263 
11264     // If the stored value is a static alloca, mark it as escaped.
11265     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11266       *Info = StaticAllocaInfo::Clobbered;
11267 
11268     // Check if the destination is a static alloca.
11269     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11270     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11271     if (!Info)
11272       continue;
11273     const AllocaInst *AI = cast<AllocaInst>(Dst);
11274 
11275     // Skip allocas that have been initialized or clobbered.
11276     if (*Info != StaticAllocaInfo::Unknown)
11277       continue;
11278 
11279     // Check if the stored value is an argument, and that this store fully
11280     // initializes the alloca.
11281     // If the argument type has padding bits we can't directly forward a pointer
11282     // as the upper bits may contain garbage.
11283     // Don't elide copies from the same argument twice.
11284     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11285     const auto *Arg = dyn_cast<Argument>(Val);
11286     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11287         Arg->getType()->isEmptyTy() ||
11288         DL.getTypeStoreSize(Arg->getType()) !=
11289             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11290         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11291         ArgCopyElisionCandidates.count(Arg)) {
11292       *Info = StaticAllocaInfo::Clobbered;
11293       continue;
11294     }
11295 
11296     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11297                       << '\n');
11298 
11299     // Mark this alloca and store for argument copy elision.
11300     *Info = StaticAllocaInfo::Elidable;
11301     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11302 
11303     // Stop scanning if we've seen all arguments. This will happen early in -O0
11304     // builds, which is useful, because -O0 builds have large entry blocks and
11305     // many allocas.
11306     if (ArgCopyElisionCandidates.size() == NumArgs)
11307       break;
11308   }
11309 }
11310 
11311 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11312 /// ArgVal is a load from a suitable fixed stack object.
11313 static void tryToElideArgumentCopy(
11314     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11315     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11316     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11317     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11318     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11319   // Check if this is a load from a fixed stack object.
11320   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11321   if (!LNode)
11322     return;
11323   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11324   if (!FINode)
11325     return;
11326 
11327   // Check that the fixed stack object is the right size and alignment.
11328   // Look at the alignment that the user wrote on the alloca instead of looking
11329   // at the stack object.
11330   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11331   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11332   const AllocaInst *AI = ArgCopyIter->second.first;
11333   int FixedIndex = FINode->getIndex();
11334   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11335   int OldIndex = AllocaIndex;
11336   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11337   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11338     LLVM_DEBUG(
11339         dbgs() << "  argument copy elision failed due to bad fixed stack "
11340                   "object size\n");
11341     return;
11342   }
11343   Align RequiredAlignment = AI->getAlign();
11344   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11345     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11346                          "greater than stack argument alignment ("
11347                       << DebugStr(RequiredAlignment) << " vs "
11348                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11349     return;
11350   }
11351 
11352   // Perform the elision. Delete the old stack object and replace its only use
11353   // in the variable info map. Mark the stack object as mutable and aliased.
11354   LLVM_DEBUG({
11355     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11356            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11357            << '\n';
11358   });
11359   MFI.RemoveStackObject(OldIndex);
11360   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11361   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11362   AllocaIndex = FixedIndex;
11363   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11364   for (SDValue ArgVal : ArgVals)
11365     Chains.push_back(ArgVal.getValue(1));
11366 
11367   // Avoid emitting code for the store implementing the copy.
11368   const StoreInst *SI = ArgCopyIter->second.second;
11369   ElidedArgCopyInstrs.insert(SI);
11370 
11371   // Check for uses of the argument again so that we can avoid exporting ArgVal
11372   // if it is't used by anything other than the store.
11373   for (const Value *U : Arg.users()) {
11374     if (U != SI) {
11375       ArgHasUses = true;
11376       break;
11377     }
11378   }
11379 }
11380 
11381 void SelectionDAGISel::LowerArguments(const Function &F) {
11382   SelectionDAG &DAG = SDB->DAG;
11383   SDLoc dl = SDB->getCurSDLoc();
11384   const DataLayout &DL = DAG.getDataLayout();
11385   SmallVector<ISD::InputArg, 16> Ins;
11386 
11387   // In Naked functions we aren't going to save any registers.
11388   if (F.hasFnAttribute(Attribute::Naked))
11389     return;
11390 
11391   if (!FuncInfo->CanLowerReturn) {
11392     // Put in an sret pointer parameter before all the other parameters.
11393     SmallVector<EVT, 1> ValueVTs;
11394     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11395                     PointerType::get(F.getContext(),
11396                                      DAG.getDataLayout().getAllocaAddrSpace()),
11397                     ValueVTs);
11398 
11399     // NOTE: Assuming that a pointer will never break down to more than one VT
11400     // or one register.
11401     ISD::ArgFlagsTy Flags;
11402     Flags.setSRet();
11403     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11404     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11405                          ISD::InputArg::NoArgIndex, 0);
11406     Ins.push_back(RetArg);
11407   }
11408 
11409   // Look for stores of arguments to static allocas. Mark such arguments with a
11410   // flag to ask the target to give us the memory location of that argument if
11411   // available.
11412   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11413   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11414                                     ArgCopyElisionCandidates);
11415 
11416   // Set up the incoming argument description vector.
11417   for (const Argument &Arg : F.args()) {
11418     unsigned ArgNo = Arg.getArgNo();
11419     SmallVector<EVT, 4> ValueVTs;
11420     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11421     bool isArgValueUsed = !Arg.use_empty();
11422     unsigned PartBase = 0;
11423     Type *FinalType = Arg.getType();
11424     if (Arg.hasAttribute(Attribute::ByVal))
11425       FinalType = Arg.getParamByValType();
11426     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11427         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11428     for (unsigned Value = 0, NumValues = ValueVTs.size();
11429          Value != NumValues; ++Value) {
11430       EVT VT = ValueVTs[Value];
11431       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11432       ISD::ArgFlagsTy Flags;
11433 
11434 
11435       if (Arg.getType()->isPointerTy()) {
11436         Flags.setPointer();
11437         Flags.setPointerAddrSpace(
11438             cast<PointerType>(Arg.getType())->getAddressSpace());
11439       }
11440       if (Arg.hasAttribute(Attribute::ZExt))
11441         Flags.setZExt();
11442       if (Arg.hasAttribute(Attribute::SExt))
11443         Flags.setSExt();
11444       if (Arg.hasAttribute(Attribute::InReg)) {
11445         // If we are using vectorcall calling convention, a structure that is
11446         // passed InReg - is surely an HVA
11447         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11448             isa<StructType>(Arg.getType())) {
11449           // The first value of a structure is marked
11450           if (0 == Value)
11451             Flags.setHvaStart();
11452           Flags.setHva();
11453         }
11454         // Set InReg Flag
11455         Flags.setInReg();
11456       }
11457       if (Arg.hasAttribute(Attribute::StructRet))
11458         Flags.setSRet();
11459       if (Arg.hasAttribute(Attribute::SwiftSelf))
11460         Flags.setSwiftSelf();
11461       if (Arg.hasAttribute(Attribute::SwiftAsync))
11462         Flags.setSwiftAsync();
11463       if (Arg.hasAttribute(Attribute::SwiftError))
11464         Flags.setSwiftError();
11465       if (Arg.hasAttribute(Attribute::ByVal))
11466         Flags.setByVal();
11467       if (Arg.hasAttribute(Attribute::ByRef))
11468         Flags.setByRef();
11469       if (Arg.hasAttribute(Attribute::InAlloca)) {
11470         Flags.setInAlloca();
11471         // Set the byval flag for CCAssignFn callbacks that don't know about
11472         // inalloca.  This way we can know how many bytes we should've allocated
11473         // and how many bytes a callee cleanup function will pop.  If we port
11474         // inalloca to more targets, we'll have to add custom inalloca handling
11475         // in the various CC lowering callbacks.
11476         Flags.setByVal();
11477       }
11478       if (Arg.hasAttribute(Attribute::Preallocated)) {
11479         Flags.setPreallocated();
11480         // Set the byval flag for CCAssignFn callbacks that don't know about
11481         // preallocated.  This way we can know how many bytes we should've
11482         // allocated and how many bytes a callee cleanup function will pop.  If
11483         // we port preallocated to more targets, we'll have to add custom
11484         // preallocated handling in the various CC lowering callbacks.
11485         Flags.setByVal();
11486       }
11487 
11488       // Certain targets (such as MIPS), may have a different ABI alignment
11489       // for a type depending on the context. Give the target a chance to
11490       // specify the alignment it wants.
11491       const Align OriginalAlignment(
11492           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11493       Flags.setOrigAlign(OriginalAlignment);
11494 
11495       Align MemAlign;
11496       Type *ArgMemTy = nullptr;
11497       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11498           Flags.isByRef()) {
11499         if (!ArgMemTy)
11500           ArgMemTy = Arg.getPointeeInMemoryValueType();
11501 
11502         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11503 
11504         // For in-memory arguments, size and alignment should be passed from FE.
11505         // BE will guess if this info is not there but there are cases it cannot
11506         // get right.
11507         if (auto ParamAlign = Arg.getParamStackAlign())
11508           MemAlign = *ParamAlign;
11509         else if ((ParamAlign = Arg.getParamAlign()))
11510           MemAlign = *ParamAlign;
11511         else
11512           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11513         if (Flags.isByRef())
11514           Flags.setByRefSize(MemSize);
11515         else
11516           Flags.setByValSize(MemSize);
11517       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11518         MemAlign = *ParamAlign;
11519       } else {
11520         MemAlign = OriginalAlignment;
11521       }
11522       Flags.setMemAlign(MemAlign);
11523 
11524       if (Arg.hasAttribute(Attribute::Nest))
11525         Flags.setNest();
11526       if (NeedsRegBlock)
11527         Flags.setInConsecutiveRegs();
11528       if (ArgCopyElisionCandidates.count(&Arg))
11529         Flags.setCopyElisionCandidate();
11530       if (Arg.hasAttribute(Attribute::Returned))
11531         Flags.setReturned();
11532 
11533       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11534           *CurDAG->getContext(), F.getCallingConv(), VT);
11535       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11536           *CurDAG->getContext(), F.getCallingConv(), VT);
11537       for (unsigned i = 0; i != NumRegs; ++i) {
11538         // For scalable vectors, use the minimum size; individual targets
11539         // are responsible for handling scalable vector arguments and
11540         // return values.
11541         ISD::InputArg MyFlags(
11542             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11543             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11544         if (NumRegs > 1 && i == 0)
11545           MyFlags.Flags.setSplit();
11546         // if it isn't first piece, alignment must be 1
11547         else if (i > 0) {
11548           MyFlags.Flags.setOrigAlign(Align(1));
11549           if (i == NumRegs - 1)
11550             MyFlags.Flags.setSplitEnd();
11551         }
11552         Ins.push_back(MyFlags);
11553       }
11554       if (NeedsRegBlock && Value == NumValues - 1)
11555         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11556       PartBase += VT.getStoreSize().getKnownMinValue();
11557     }
11558   }
11559 
11560   // Call the target to set up the argument values.
11561   SmallVector<SDValue, 8> InVals;
11562   SDValue NewRoot = TLI->LowerFormalArguments(
11563       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11564 
11565   // Verify that the target's LowerFormalArguments behaved as expected.
11566   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11567          "LowerFormalArguments didn't return a valid chain!");
11568   assert(InVals.size() == Ins.size() &&
11569          "LowerFormalArguments didn't emit the correct number of values!");
11570   LLVM_DEBUG({
11571     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11572       assert(InVals[i].getNode() &&
11573              "LowerFormalArguments emitted a null value!");
11574       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11575              "LowerFormalArguments emitted a value with the wrong type!");
11576     }
11577   });
11578 
11579   // Update the DAG with the new chain value resulting from argument lowering.
11580   DAG.setRoot(NewRoot);
11581 
11582   // Set up the argument values.
11583   unsigned i = 0;
11584   if (!FuncInfo->CanLowerReturn) {
11585     // Create a virtual register for the sret pointer, and put in a copy
11586     // from the sret argument into it.
11587     SmallVector<EVT, 1> ValueVTs;
11588     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11589                     PointerType::get(F.getContext(),
11590                                      DAG.getDataLayout().getAllocaAddrSpace()),
11591                     ValueVTs);
11592     MVT VT = ValueVTs[0].getSimpleVT();
11593     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11594     std::optional<ISD::NodeType> AssertOp;
11595     SDValue ArgValue =
11596         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11597                          F.getCallingConv(), AssertOp);
11598 
11599     MachineFunction& MF = SDB->DAG.getMachineFunction();
11600     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11601     Register SRetReg =
11602         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11603     FuncInfo->DemoteRegister = SRetReg;
11604     NewRoot =
11605         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11606     DAG.setRoot(NewRoot);
11607 
11608     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11609     ++i;
11610   }
11611 
11612   SmallVector<SDValue, 4> Chains;
11613   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11614   for (const Argument &Arg : F.args()) {
11615     SmallVector<SDValue, 4> ArgValues;
11616     SmallVector<EVT, 4> ValueVTs;
11617     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11618     unsigned NumValues = ValueVTs.size();
11619     if (NumValues == 0)
11620       continue;
11621 
11622     bool ArgHasUses = !Arg.use_empty();
11623 
11624     // Elide the copying store if the target loaded this argument from a
11625     // suitable fixed stack object.
11626     if (Ins[i].Flags.isCopyElisionCandidate()) {
11627       unsigned NumParts = 0;
11628       for (EVT VT : ValueVTs)
11629         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11630                                                        F.getCallingConv(), VT);
11631 
11632       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11633                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11634                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11635     }
11636 
11637     // If this argument is unused then remember its value. It is used to generate
11638     // debugging information.
11639     bool isSwiftErrorArg =
11640         TLI->supportSwiftError() &&
11641         Arg.hasAttribute(Attribute::SwiftError);
11642     if (!ArgHasUses && !isSwiftErrorArg) {
11643       SDB->setUnusedArgValue(&Arg, InVals[i]);
11644 
11645       // Also remember any frame index for use in FastISel.
11646       if (FrameIndexSDNode *FI =
11647           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11648         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11649     }
11650 
11651     for (unsigned Val = 0; Val != NumValues; ++Val) {
11652       EVT VT = ValueVTs[Val];
11653       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11654                                                       F.getCallingConv(), VT);
11655       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11656           *CurDAG->getContext(), F.getCallingConv(), VT);
11657 
11658       // Even an apparent 'unused' swifterror argument needs to be returned. So
11659       // we do generate a copy for it that can be used on return from the
11660       // function.
11661       if (ArgHasUses || isSwiftErrorArg) {
11662         std::optional<ISD::NodeType> AssertOp;
11663         if (Arg.hasAttribute(Attribute::SExt))
11664           AssertOp = ISD::AssertSext;
11665         else if (Arg.hasAttribute(Attribute::ZExt))
11666           AssertOp = ISD::AssertZext;
11667 
11668         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11669                                              PartVT, VT, nullptr, NewRoot,
11670                                              F.getCallingConv(), AssertOp));
11671       }
11672 
11673       i += NumParts;
11674     }
11675 
11676     // We don't need to do anything else for unused arguments.
11677     if (ArgValues.empty())
11678       continue;
11679 
11680     // Note down frame index.
11681     if (FrameIndexSDNode *FI =
11682         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11683       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11684 
11685     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11686                                      SDB->getCurSDLoc());
11687 
11688     SDB->setValue(&Arg, Res);
11689     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11690       // We want to associate the argument with the frame index, among
11691       // involved operands, that correspond to the lowest address. The
11692       // getCopyFromParts function, called earlier, is swapping the order of
11693       // the operands to BUILD_PAIR depending on endianness. The result of
11694       // that swapping is that the least significant bits of the argument will
11695       // be in the first operand of the BUILD_PAIR node, and the most
11696       // significant bits will be in the second operand.
11697       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11698       if (LoadSDNode *LNode =
11699           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11700         if (FrameIndexSDNode *FI =
11701             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11702           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11703     }
11704 
11705     // Analyses past this point are naive and don't expect an assertion.
11706     if (Res.getOpcode() == ISD::AssertZext)
11707       Res = Res.getOperand(0);
11708 
11709     // Update the SwiftErrorVRegDefMap.
11710     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11711       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11712       if (Register::isVirtualRegister(Reg))
11713         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11714                                    Reg);
11715     }
11716 
11717     // If this argument is live outside of the entry block, insert a copy from
11718     // wherever we got it to the vreg that other BB's will reference it as.
11719     if (Res.getOpcode() == ISD::CopyFromReg) {
11720       // If we can, though, try to skip creating an unnecessary vreg.
11721       // FIXME: This isn't very clean... it would be nice to make this more
11722       // general.
11723       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11724       if (Register::isVirtualRegister(Reg)) {
11725         FuncInfo->ValueMap[&Arg] = Reg;
11726         continue;
11727       }
11728     }
11729     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11730       FuncInfo->InitializeRegForValue(&Arg);
11731       SDB->CopyToExportRegsIfNeeded(&Arg);
11732     }
11733   }
11734 
11735   if (!Chains.empty()) {
11736     Chains.push_back(NewRoot);
11737     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11738   }
11739 
11740   DAG.setRoot(NewRoot);
11741 
11742   assert(i == InVals.size() && "Argument register count mismatch!");
11743 
11744   // If any argument copy elisions occurred and we have debug info, update the
11745   // stale frame indices used in the dbg.declare variable info table.
11746   if (!ArgCopyElisionFrameIndexMap.empty()) {
11747     for (MachineFunction::VariableDbgInfo &VI :
11748          MF->getInStackSlotVariableDbgInfo()) {
11749       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11750       if (I != ArgCopyElisionFrameIndexMap.end())
11751         VI.updateStackSlot(I->second);
11752     }
11753   }
11754 
11755   // Finally, if the target has anything special to do, allow it to do so.
11756   emitFunctionEntryCode();
11757 }
11758 
11759 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11760 /// ensure constants are generated when needed.  Remember the virtual registers
11761 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11762 /// directly add them, because expansion might result in multiple MBB's for one
11763 /// BB.  As such, the start of the BB might correspond to a different MBB than
11764 /// the end.
11765 void
11766 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11768 
11769   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11770 
11771   // Check PHI nodes in successors that expect a value to be available from this
11772   // block.
11773   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11774     if (!isa<PHINode>(SuccBB->begin())) continue;
11775     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11776 
11777     // If this terminator has multiple identical successors (common for
11778     // switches), only handle each succ once.
11779     if (!SuccsHandled.insert(SuccMBB).second)
11780       continue;
11781 
11782     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11783 
11784     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11785     // nodes and Machine PHI nodes, but the incoming operands have not been
11786     // emitted yet.
11787     for (const PHINode &PN : SuccBB->phis()) {
11788       // Ignore dead phi's.
11789       if (PN.use_empty())
11790         continue;
11791 
11792       // Skip empty types
11793       if (PN.getType()->isEmptyTy())
11794         continue;
11795 
11796       unsigned Reg;
11797       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11798 
11799       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11800         unsigned &RegOut = ConstantsOut[C];
11801         if (RegOut == 0) {
11802           RegOut = FuncInfo.CreateRegs(C);
11803           // We need to zero/sign extend ConstantInt phi operands to match
11804           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11805           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11806           if (auto *CI = dyn_cast<ConstantInt>(C))
11807             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11808                                                     : ISD::ZERO_EXTEND;
11809           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11810         }
11811         Reg = RegOut;
11812       } else {
11813         DenseMap<const Value *, Register>::iterator I =
11814           FuncInfo.ValueMap.find(PHIOp);
11815         if (I != FuncInfo.ValueMap.end())
11816           Reg = I->second;
11817         else {
11818           assert(isa<AllocaInst>(PHIOp) &&
11819                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11820                  "Didn't codegen value into a register!??");
11821           Reg = FuncInfo.CreateRegs(PHIOp);
11822           CopyValueToVirtualRegister(PHIOp, Reg);
11823         }
11824       }
11825 
11826       // Remember that this register needs to added to the machine PHI node as
11827       // the input for this MBB.
11828       SmallVector<EVT, 4> ValueVTs;
11829       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11830       for (EVT VT : ValueVTs) {
11831         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11832         for (unsigned i = 0; i != NumRegisters; ++i)
11833           FuncInfo.PHINodesToUpdate.push_back(
11834               std::make_pair(&*MBBI++, Reg + i));
11835         Reg += NumRegisters;
11836       }
11837     }
11838   }
11839 
11840   ConstantsOut.clear();
11841 }
11842 
11843 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11844   MachineFunction::iterator I(MBB);
11845   if (++I == FuncInfo.MF->end())
11846     return nullptr;
11847   return &*I;
11848 }
11849 
11850 /// During lowering new call nodes can be created (such as memset, etc.).
11851 /// Those will become new roots of the current DAG, but complications arise
11852 /// when they are tail calls. In such cases, the call lowering will update
11853 /// the root, but the builder still needs to know that a tail call has been
11854 /// lowered in order to avoid generating an additional return.
11855 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11856   // If the node is null, we do have a tail call.
11857   if (MaybeTC.getNode() != nullptr)
11858     DAG.setRoot(MaybeTC);
11859   else
11860     HasTailCall = true;
11861 }
11862 
11863 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11864                                         MachineBasicBlock *SwitchMBB,
11865                                         MachineBasicBlock *DefaultMBB) {
11866   MachineFunction *CurMF = FuncInfo.MF;
11867   MachineBasicBlock *NextMBB = nullptr;
11868   MachineFunction::iterator BBI(W.MBB);
11869   if (++BBI != FuncInfo.MF->end())
11870     NextMBB = &*BBI;
11871 
11872   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11873 
11874   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11875 
11876   if (Size == 2 && W.MBB == SwitchMBB) {
11877     // If any two of the cases has the same destination, and if one value
11878     // is the same as the other, but has one bit unset that the other has set,
11879     // use bit manipulation to do two compares at once.  For example:
11880     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11881     // TODO: This could be extended to merge any 2 cases in switches with 3
11882     // cases.
11883     // TODO: Handle cases where W.CaseBB != SwitchBB.
11884     CaseCluster &Small = *W.FirstCluster;
11885     CaseCluster &Big = *W.LastCluster;
11886 
11887     if (Small.Low == Small.High && Big.Low == Big.High &&
11888         Small.MBB == Big.MBB) {
11889       const APInt &SmallValue = Small.Low->getValue();
11890       const APInt &BigValue = Big.Low->getValue();
11891 
11892       // Check that there is only one bit different.
11893       APInt CommonBit = BigValue ^ SmallValue;
11894       if (CommonBit.isPowerOf2()) {
11895         SDValue CondLHS = getValue(Cond);
11896         EVT VT = CondLHS.getValueType();
11897         SDLoc DL = getCurSDLoc();
11898 
11899         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11900                                  DAG.getConstant(CommonBit, DL, VT));
11901         SDValue Cond = DAG.getSetCC(
11902             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11903             ISD::SETEQ);
11904 
11905         // Update successor info.
11906         // Both Small and Big will jump to Small.BB, so we sum up the
11907         // probabilities.
11908         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11909         if (BPI)
11910           addSuccessorWithProb(
11911               SwitchMBB, DefaultMBB,
11912               // The default destination is the first successor in IR.
11913               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11914         else
11915           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11916 
11917         // Insert the true branch.
11918         SDValue BrCond =
11919             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11920                         DAG.getBasicBlock(Small.MBB));
11921         // Insert the false branch.
11922         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11923                              DAG.getBasicBlock(DefaultMBB));
11924 
11925         DAG.setRoot(BrCond);
11926         return;
11927       }
11928     }
11929   }
11930 
11931   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11932     // Here, we order cases by probability so the most likely case will be
11933     // checked first. However, two clusters can have the same probability in
11934     // which case their relative ordering is non-deterministic. So we use Low
11935     // as a tie-breaker as clusters are guaranteed to never overlap.
11936     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11937                [](const CaseCluster &a, const CaseCluster &b) {
11938       return a.Prob != b.Prob ?
11939              a.Prob > b.Prob :
11940              a.Low->getValue().slt(b.Low->getValue());
11941     });
11942 
11943     // Rearrange the case blocks so that the last one falls through if possible
11944     // without changing the order of probabilities.
11945     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11946       --I;
11947       if (I->Prob > W.LastCluster->Prob)
11948         break;
11949       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11950         std::swap(*I, *W.LastCluster);
11951         break;
11952       }
11953     }
11954   }
11955 
11956   // Compute total probability.
11957   BranchProbability DefaultProb = W.DefaultProb;
11958   BranchProbability UnhandledProbs = DefaultProb;
11959   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11960     UnhandledProbs += I->Prob;
11961 
11962   MachineBasicBlock *CurMBB = W.MBB;
11963   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11964     bool FallthroughUnreachable = false;
11965     MachineBasicBlock *Fallthrough;
11966     if (I == W.LastCluster) {
11967       // For the last cluster, fall through to the default destination.
11968       Fallthrough = DefaultMBB;
11969       FallthroughUnreachable = isa<UnreachableInst>(
11970           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11971     } else {
11972       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11973       CurMF->insert(BBI, Fallthrough);
11974       // Put Cond in a virtual register to make it available from the new blocks.
11975       ExportFromCurrentBlock(Cond);
11976     }
11977     UnhandledProbs -= I->Prob;
11978 
11979     switch (I->Kind) {
11980       case CC_JumpTable: {
11981         // FIXME: Optimize away range check based on pivot comparisons.
11982         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11983         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11984 
11985         // The jump block hasn't been inserted yet; insert it here.
11986         MachineBasicBlock *JumpMBB = JT->MBB;
11987         CurMF->insert(BBI, JumpMBB);
11988 
11989         auto JumpProb = I->Prob;
11990         auto FallthroughProb = UnhandledProbs;
11991 
11992         // If the default statement is a target of the jump table, we evenly
11993         // distribute the default probability to successors of CurMBB. Also
11994         // update the probability on the edge from JumpMBB to Fallthrough.
11995         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11996                                               SE = JumpMBB->succ_end();
11997              SI != SE; ++SI) {
11998           if (*SI == DefaultMBB) {
11999             JumpProb += DefaultProb / 2;
12000             FallthroughProb -= DefaultProb / 2;
12001             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12002             JumpMBB->normalizeSuccProbs();
12003             break;
12004           }
12005         }
12006 
12007         // If the default clause is unreachable, propagate that knowledge into
12008         // JTH->FallthroughUnreachable which will use it to suppress the range
12009         // check.
12010         //
12011         // However, don't do this if we're doing branch target enforcement,
12012         // because a table branch _without_ a range check can be a tempting JOP
12013         // gadget - out-of-bounds inputs that are impossible in correct
12014         // execution become possible again if an attacker can influence the
12015         // control flow. So if an attacker doesn't already have a BTI bypass
12016         // available, we don't want them to be able to get one out of this
12017         // table branch.
12018         if (FallthroughUnreachable) {
12019           Function &CurFunc = CurMF->getFunction();
12020           bool HasBranchTargetEnforcement = false;
12021           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
12022             HasBranchTargetEnforcement =
12023                 CurFunc.getFnAttribute("branch-target-enforcement")
12024                     .getValueAsBool();
12025           } else {
12026             HasBranchTargetEnforcement =
12027                 CurMF->getMMI().getModule()->getModuleFlag(
12028                     "branch-target-enforcement");
12029           }
12030           if (!HasBranchTargetEnforcement)
12031             JTH->FallthroughUnreachable = true;
12032         }
12033 
12034         if (!JTH->FallthroughUnreachable)
12035           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12036         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12037         CurMBB->normalizeSuccProbs();
12038 
12039         // The jump table header will be inserted in our current block, do the
12040         // range check, and fall through to our fallthrough block.
12041         JTH->HeaderBB = CurMBB;
12042         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12043 
12044         // If we're in the right place, emit the jump table header right now.
12045         if (CurMBB == SwitchMBB) {
12046           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12047           JTH->Emitted = true;
12048         }
12049         break;
12050       }
12051       case CC_BitTests: {
12052         // FIXME: Optimize away range check based on pivot comparisons.
12053         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12054 
12055         // The bit test blocks haven't been inserted yet; insert them here.
12056         for (BitTestCase &BTC : BTB->Cases)
12057           CurMF->insert(BBI, BTC.ThisBB);
12058 
12059         // Fill in fields of the BitTestBlock.
12060         BTB->Parent = CurMBB;
12061         BTB->Default = Fallthrough;
12062 
12063         BTB->DefaultProb = UnhandledProbs;
12064         // If the cases in bit test don't form a contiguous range, we evenly
12065         // distribute the probability on the edge to Fallthrough to two
12066         // successors of CurMBB.
12067         if (!BTB->ContiguousRange) {
12068           BTB->Prob += DefaultProb / 2;
12069           BTB->DefaultProb -= DefaultProb / 2;
12070         }
12071 
12072         if (FallthroughUnreachable)
12073           BTB->FallthroughUnreachable = true;
12074 
12075         // If we're in the right place, emit the bit test header right now.
12076         if (CurMBB == SwitchMBB) {
12077           visitBitTestHeader(*BTB, SwitchMBB);
12078           BTB->Emitted = true;
12079         }
12080         break;
12081       }
12082       case CC_Range: {
12083         const Value *RHS, *LHS, *MHS;
12084         ISD::CondCode CC;
12085         if (I->Low == I->High) {
12086           // Check Cond == I->Low.
12087           CC = ISD::SETEQ;
12088           LHS = Cond;
12089           RHS=I->Low;
12090           MHS = nullptr;
12091         } else {
12092           // Check I->Low <= Cond <= I->High.
12093           CC = ISD::SETLE;
12094           LHS = I->Low;
12095           MHS = Cond;
12096           RHS = I->High;
12097         }
12098 
12099         // If Fallthrough is unreachable, fold away the comparison.
12100         if (FallthroughUnreachable)
12101           CC = ISD::SETTRUE;
12102 
12103         // The false probability is the sum of all unhandled cases.
12104         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12105                      getCurSDLoc(), I->Prob, UnhandledProbs);
12106 
12107         if (CurMBB == SwitchMBB)
12108           visitSwitchCase(CB, SwitchMBB);
12109         else
12110           SL->SwitchCases.push_back(CB);
12111 
12112         break;
12113       }
12114     }
12115     CurMBB = Fallthrough;
12116   }
12117 }
12118 
12119 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12120                                         const SwitchWorkListItem &W,
12121                                         Value *Cond,
12122                                         MachineBasicBlock *SwitchMBB) {
12123   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12124          "Clusters not sorted?");
12125   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12126 
12127   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12128       SL->computeSplitWorkItemInfo(W);
12129 
12130   // Use the first element on the right as pivot since we will make less-than
12131   // comparisons against it.
12132   CaseClusterIt PivotCluster = FirstRight;
12133   assert(PivotCluster > W.FirstCluster);
12134   assert(PivotCluster <= W.LastCluster);
12135 
12136   CaseClusterIt FirstLeft = W.FirstCluster;
12137   CaseClusterIt LastRight = W.LastCluster;
12138 
12139   const ConstantInt *Pivot = PivotCluster->Low;
12140 
12141   // New blocks will be inserted immediately after the current one.
12142   MachineFunction::iterator BBI(W.MBB);
12143   ++BBI;
12144 
12145   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12146   // we can branch to its destination directly if it's squeezed exactly in
12147   // between the known lower bound and Pivot - 1.
12148   MachineBasicBlock *LeftMBB;
12149   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12150       FirstLeft->Low == W.GE &&
12151       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12152     LeftMBB = FirstLeft->MBB;
12153   } else {
12154     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12155     FuncInfo.MF->insert(BBI, LeftMBB);
12156     WorkList.push_back(
12157         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12158     // Put Cond in a virtual register to make it available from the new blocks.
12159     ExportFromCurrentBlock(Cond);
12160   }
12161 
12162   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12163   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12164   // directly if RHS.High equals the current upper bound.
12165   MachineBasicBlock *RightMBB;
12166   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12167       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12168     RightMBB = FirstRight->MBB;
12169   } else {
12170     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12171     FuncInfo.MF->insert(BBI, RightMBB);
12172     WorkList.push_back(
12173         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12174     // Put Cond in a virtual register to make it available from the new blocks.
12175     ExportFromCurrentBlock(Cond);
12176   }
12177 
12178   // Create the CaseBlock record that will be used to lower the branch.
12179   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12180                getCurSDLoc(), LeftProb, RightProb);
12181 
12182   if (W.MBB == SwitchMBB)
12183     visitSwitchCase(CB, SwitchMBB);
12184   else
12185     SL->SwitchCases.push_back(CB);
12186 }
12187 
12188 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12189 // from the swith statement.
12190 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12191                                             BranchProbability PeeledCaseProb) {
12192   if (PeeledCaseProb == BranchProbability::getOne())
12193     return BranchProbability::getZero();
12194   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12195 
12196   uint32_t Numerator = CaseProb.getNumerator();
12197   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12198   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12199 }
12200 
12201 // Try to peel the top probability case if it exceeds the threshold.
12202 // Return current MachineBasicBlock for the switch statement if the peeling
12203 // does not occur.
12204 // If the peeling is performed, return the newly created MachineBasicBlock
12205 // for the peeled switch statement. Also update Clusters to remove the peeled
12206 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12207 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12208     const SwitchInst &SI, CaseClusterVector &Clusters,
12209     BranchProbability &PeeledCaseProb) {
12210   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12211   // Don't perform if there is only one cluster or optimizing for size.
12212   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12213       TM.getOptLevel() == CodeGenOptLevel::None ||
12214       SwitchMBB->getParent()->getFunction().hasMinSize())
12215     return SwitchMBB;
12216 
12217   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12218   unsigned PeeledCaseIndex = 0;
12219   bool SwitchPeeled = false;
12220   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12221     CaseCluster &CC = Clusters[Index];
12222     if (CC.Prob < TopCaseProb)
12223       continue;
12224     TopCaseProb = CC.Prob;
12225     PeeledCaseIndex = Index;
12226     SwitchPeeled = true;
12227   }
12228   if (!SwitchPeeled)
12229     return SwitchMBB;
12230 
12231   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12232                     << TopCaseProb << "\n");
12233 
12234   // Record the MBB for the peeled switch statement.
12235   MachineFunction::iterator BBI(SwitchMBB);
12236   ++BBI;
12237   MachineBasicBlock *PeeledSwitchMBB =
12238       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12239   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12240 
12241   ExportFromCurrentBlock(SI.getCondition());
12242   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12243   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12244                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12245   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12246 
12247   Clusters.erase(PeeledCaseIt);
12248   for (CaseCluster &CC : Clusters) {
12249     LLVM_DEBUG(
12250         dbgs() << "Scale the probablity for one cluster, before scaling: "
12251                << CC.Prob << "\n");
12252     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12253     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12254   }
12255   PeeledCaseProb = TopCaseProb;
12256   return PeeledSwitchMBB;
12257 }
12258 
12259 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12260   // Extract cases from the switch.
12261   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12262   CaseClusterVector Clusters;
12263   Clusters.reserve(SI.getNumCases());
12264   for (auto I : SI.cases()) {
12265     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12266     const ConstantInt *CaseVal = I.getCaseValue();
12267     BranchProbability Prob =
12268         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12269             : BranchProbability(1, SI.getNumCases() + 1);
12270     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12271   }
12272 
12273   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12274 
12275   // Cluster adjacent cases with the same destination. We do this at all
12276   // optimization levels because it's cheap to do and will make codegen faster
12277   // if there are many clusters.
12278   sortAndRangeify(Clusters);
12279 
12280   // The branch probablity of the peeled case.
12281   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12282   MachineBasicBlock *PeeledSwitchMBB =
12283       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12284 
12285   // If there is only the default destination, jump there directly.
12286   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12287   if (Clusters.empty()) {
12288     assert(PeeledSwitchMBB == SwitchMBB);
12289     SwitchMBB->addSuccessor(DefaultMBB);
12290     if (DefaultMBB != NextBlock(SwitchMBB)) {
12291       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12292                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12293     }
12294     return;
12295   }
12296 
12297   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12298                      DAG.getBFI());
12299   SL->findBitTestClusters(Clusters, &SI);
12300 
12301   LLVM_DEBUG({
12302     dbgs() << "Case clusters: ";
12303     for (const CaseCluster &C : Clusters) {
12304       if (C.Kind == CC_JumpTable)
12305         dbgs() << "JT:";
12306       if (C.Kind == CC_BitTests)
12307         dbgs() << "BT:";
12308 
12309       C.Low->getValue().print(dbgs(), true);
12310       if (C.Low != C.High) {
12311         dbgs() << '-';
12312         C.High->getValue().print(dbgs(), true);
12313       }
12314       dbgs() << ' ';
12315     }
12316     dbgs() << '\n';
12317   });
12318 
12319   assert(!Clusters.empty());
12320   SwitchWorkList WorkList;
12321   CaseClusterIt First = Clusters.begin();
12322   CaseClusterIt Last = Clusters.end() - 1;
12323   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12324   // Scale the branchprobability for DefaultMBB if the peel occurs and
12325   // DefaultMBB is not replaced.
12326   if (PeeledCaseProb != BranchProbability::getZero() &&
12327       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12328     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12329   WorkList.push_back(
12330       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12331 
12332   while (!WorkList.empty()) {
12333     SwitchWorkListItem W = WorkList.pop_back_val();
12334     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12335 
12336     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12337         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12338       // For optimized builds, lower large range as a balanced binary tree.
12339       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12340       continue;
12341     }
12342 
12343     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12344   }
12345 }
12346 
12347 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12349   auto DL = getCurSDLoc();
12350   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12351   setValue(&I, DAG.getStepVector(DL, ResultVT));
12352 }
12353 
12354 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12356   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12357 
12358   SDLoc DL = getCurSDLoc();
12359   SDValue V = getValue(I.getOperand(0));
12360   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12361 
12362   if (VT.isScalableVector()) {
12363     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12364     return;
12365   }
12366 
12367   // Use VECTOR_SHUFFLE for the fixed-length vector
12368   // to maintain existing behavior.
12369   SmallVector<int, 8> Mask;
12370   unsigned NumElts = VT.getVectorMinNumElements();
12371   for (unsigned i = 0; i != NumElts; ++i)
12372     Mask.push_back(NumElts - 1 - i);
12373 
12374   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12375 }
12376 
12377 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12378   auto DL = getCurSDLoc();
12379   SDValue InVec = getValue(I.getOperand(0));
12380   EVT OutVT =
12381       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12382 
12383   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12384 
12385   // ISD Node needs the input vectors split into two equal parts
12386   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12387                            DAG.getVectorIdxConstant(0, DL));
12388   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12389                            DAG.getVectorIdxConstant(OutNumElts, DL));
12390 
12391   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12392   // legalisation and combines.
12393   if (OutVT.isFixedLengthVector()) {
12394     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12395                                         createStrideMask(0, 2, OutNumElts));
12396     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12397                                        createStrideMask(1, 2, OutNumElts));
12398     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12399     setValue(&I, Res);
12400     return;
12401   }
12402 
12403   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12404                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12405   setValue(&I, Res);
12406 }
12407 
12408 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12409   auto DL = getCurSDLoc();
12410   EVT InVT = getValue(I.getOperand(0)).getValueType();
12411   SDValue InVec0 = getValue(I.getOperand(0));
12412   SDValue InVec1 = getValue(I.getOperand(1));
12413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12414   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12415 
12416   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12417   // legalisation and combines.
12418   if (OutVT.isFixedLengthVector()) {
12419     unsigned NumElts = InVT.getVectorMinNumElements();
12420     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12421     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12422                                       createInterleaveMask(NumElts, 2)));
12423     return;
12424   }
12425 
12426   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12427                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12428   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12429                     Res.getValue(1));
12430   setValue(&I, Res);
12431 }
12432 
12433 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12434   SmallVector<EVT, 4> ValueVTs;
12435   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12436                   ValueVTs);
12437   unsigned NumValues = ValueVTs.size();
12438   if (NumValues == 0) return;
12439 
12440   SmallVector<SDValue, 4> Values(NumValues);
12441   SDValue Op = getValue(I.getOperand(0));
12442 
12443   for (unsigned i = 0; i != NumValues; ++i)
12444     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12445                             SDValue(Op.getNode(), Op.getResNo() + i));
12446 
12447   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12448                            DAG.getVTList(ValueVTs), Values));
12449 }
12450 
12451 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12453   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12454 
12455   SDLoc DL = getCurSDLoc();
12456   SDValue V1 = getValue(I.getOperand(0));
12457   SDValue V2 = getValue(I.getOperand(1));
12458   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12459 
12460   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12461   if (VT.isScalableVector()) {
12462     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12463                              DAG.getVectorIdxConstant(Imm, DL)));
12464     return;
12465   }
12466 
12467   unsigned NumElts = VT.getVectorNumElements();
12468 
12469   uint64_t Idx = (NumElts + Imm) % NumElts;
12470 
12471   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12472   SmallVector<int, 8> Mask;
12473   for (unsigned i = 0; i < NumElts; ++i)
12474     Mask.push_back(Idx + i);
12475   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12476 }
12477 
12478 // Consider the following MIR after SelectionDAG, which produces output in
12479 // phyregs in the first case or virtregs in the second case.
12480 //
12481 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12482 // %5:gr32 = COPY $ebx
12483 // %6:gr32 = COPY $edx
12484 // %1:gr32 = COPY %6:gr32
12485 // %0:gr32 = COPY %5:gr32
12486 //
12487 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12488 // %1:gr32 = COPY %6:gr32
12489 // %0:gr32 = COPY %5:gr32
12490 //
12491 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12492 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12493 //
12494 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12495 // to a single virtreg (such as %0). The remaining outputs monotonically
12496 // increase in virtreg number from there. If a callbr has no outputs, then it
12497 // should not have a corresponding callbr landingpad; in fact, the callbr
12498 // landingpad would not even be able to refer to such a callbr.
12499 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12500   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12501   // There is definitely at least one copy.
12502   assert(MI->getOpcode() == TargetOpcode::COPY &&
12503          "start of copy chain MUST be COPY");
12504   Reg = MI->getOperand(1).getReg();
12505   MI = MRI.def_begin(Reg)->getParent();
12506   // There may be an optional second copy.
12507   if (MI->getOpcode() == TargetOpcode::COPY) {
12508     assert(Reg.isVirtual() && "expected COPY of virtual register");
12509     Reg = MI->getOperand(1).getReg();
12510     assert(Reg.isPhysical() && "expected COPY of physical register");
12511     MI = MRI.def_begin(Reg)->getParent();
12512   }
12513   // The start of the chain must be an INLINEASM_BR.
12514   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12515          "end of copy chain MUST be INLINEASM_BR");
12516   return Reg;
12517 }
12518 
12519 // We must do this walk rather than the simpler
12520 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12521 // otherwise we will end up with copies of virtregs only valid along direct
12522 // edges.
12523 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12524   SmallVector<EVT, 8> ResultVTs;
12525   SmallVector<SDValue, 8> ResultValues;
12526   const auto *CBR =
12527       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12528 
12529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12530   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12531   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12532 
12533   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12534   SDValue Chain = DAG.getRoot();
12535 
12536   // Re-parse the asm constraints string.
12537   TargetLowering::AsmOperandInfoVector TargetConstraints =
12538       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12539   for (auto &T : TargetConstraints) {
12540     SDISelAsmOperandInfo OpInfo(T);
12541     if (OpInfo.Type != InlineAsm::isOutput)
12542       continue;
12543 
12544     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12545     // individual constraint.
12546     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12547 
12548     switch (OpInfo.ConstraintType) {
12549     case TargetLowering::C_Register:
12550     case TargetLowering::C_RegisterClass: {
12551       // Fill in OpInfo.AssignedRegs.Regs.
12552       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12553 
12554       // getRegistersForValue may produce 1 to many registers based on whether
12555       // the OpInfo.ConstraintVT is legal on the target or not.
12556       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12557         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12558         if (Register::isPhysicalRegister(OriginalDef))
12559           FuncInfo.MBB->addLiveIn(OriginalDef);
12560         // Update the assigned registers to use the original defs.
12561         Reg = OriginalDef;
12562       }
12563 
12564       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12565           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12566       ResultValues.push_back(V);
12567       ResultVTs.push_back(OpInfo.ConstraintVT);
12568       break;
12569     }
12570     case TargetLowering::C_Other: {
12571       SDValue Flag;
12572       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12573                                                   OpInfo, DAG);
12574       ++InitialDef;
12575       ResultValues.push_back(V);
12576       ResultVTs.push_back(OpInfo.ConstraintVT);
12577       break;
12578     }
12579     default:
12580       break;
12581     }
12582   }
12583   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12584                           DAG.getVTList(ResultVTs), ResultValues);
12585   setValue(&I, V);
12586 }
12587