xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 58fd3bea6d759eb17722ad2e0135714a34efd7e0)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <iterator>
108 #include <limits>
109 #include <optional>
110 #include <tuple>
111 
112 using namespace llvm;
113 using namespace PatternMatch;
114 using namespace SwitchCG;
115 
116 #define DEBUG_TYPE "isel"
117 
118 /// LimitFloatPrecision - Generate low-precision inline sequences for
119 /// some float libcalls (6, 8 or 12 bits).
120 static unsigned LimitFloatPrecision;
121 
122 static cl::opt<bool>
123     InsertAssertAlign("insert-assert-align", cl::init(true),
124                       cl::desc("Insert the experimental `assertalign` node."),
125                       cl::ReallyHidden);
126 
127 static cl::opt<unsigned, true>
128     LimitFPPrecision("limit-float-precision",
129                      cl::desc("Generate low-precision inline sequences "
130                               "for some float libcalls"),
131                      cl::location(LimitFloatPrecision), cl::Hidden,
132                      cl::init(0));
133 
134 static cl::opt<unsigned> SwitchPeelThreshold(
135     "switch-peel-threshold", cl::Hidden, cl::init(66),
136     cl::desc("Set the case probability threshold for peeling the case from a "
137              "switch statement. A value greater than 100 will void this "
138              "optimization"));
139 
140 // Limit the width of DAG chains. This is important in general to prevent
141 // DAG-based analysis from blowing up. For example, alias analysis and
142 // load clustering may not complete in reasonable time. It is difficult to
143 // recognize and avoid this situation within each individual analysis, and
144 // future analyses are likely to have the same behavior. Limiting DAG width is
145 // the safe approach and will be especially important with global DAGs.
146 //
147 // MaxParallelChains default is arbitrarily high to avoid affecting
148 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
149 // sequence over this should have been converted to llvm.memcpy by the
150 // frontend. It is easy to induce this behavior with .ll code such as:
151 // %buffer = alloca [4096 x i8]
152 // %data = load [4096 x i8]* %argPtr
153 // store [4096 x i8] %data, [4096 x i8]* %buffer
154 static const unsigned MaxParallelChains = 64;
155 
156 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
157                                       const SDValue *Parts, unsigned NumParts,
158                                       MVT PartVT, EVT ValueVT, const Value *V,
159                                       SDValue InChain,
160                                       std::optional<CallingConv::ID> CC);
161 
162 /// getCopyFromParts - Create a value that contains the specified legal parts
163 /// combined into the value they represent.  If the parts combine to a type
164 /// larger than ValueVT then AssertOp can be used to specify whether the extra
165 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
166 /// (ISD::AssertSext).
167 static SDValue
168 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
169                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
170                  SDValue InChain,
171                  std::optional<CallingConv::ID> CC = std::nullopt,
172                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
173   // Let the target assemble the parts if it wants to
174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
175   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
176                                                    PartVT, ValueVT, CC))
177     return Val;
178 
179   if (ValueVT.isVector())
180     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
181                                   InChain, CC);
182 
183   assert(NumParts > 0 && "No parts to assemble!");
184   SDValue Val = Parts[0];
185 
186   if (NumParts > 1) {
187     // Assemble the value from multiple parts.
188     if (ValueVT.isInteger()) {
189       unsigned PartBits = PartVT.getSizeInBits();
190       unsigned ValueBits = ValueVT.getSizeInBits();
191 
192       // Assemble the power of 2 part.
193       unsigned RoundParts = llvm::bit_floor(NumParts);
194       unsigned RoundBits = PartBits * RoundParts;
195       EVT RoundVT = RoundBits == ValueBits ?
196         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
197       SDValue Lo, Hi;
198 
199       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
200 
201       if (RoundParts > 2) {
202         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
203                               InChain);
204         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
205                               PartVT, HalfVT, V, InChain);
206       } else {
207         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
208         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
209       }
210 
211       if (DAG.getDataLayout().isBigEndian())
212         std::swap(Lo, Hi);
213 
214       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
215 
216       if (RoundParts < NumParts) {
217         // Assemble the trailing non-power-of-2 part.
218         unsigned OddParts = NumParts - RoundParts;
219         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
220         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
221                               OddVT, V, InChain, CC);
222 
223         // Combine the round and odd parts.
224         Lo = Val;
225         if (DAG.getDataLayout().isBigEndian())
226           std::swap(Lo, Hi);
227         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
228         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
229         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
230                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
231                                          TLI.getShiftAmountTy(
232                                              TotalVT, DAG.getDataLayout())));
233         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
234         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
235       }
236     } else if (PartVT.isFloatingPoint()) {
237       // FP split into multiple FP parts (for ppcf128)
238       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
239              "Unexpected split");
240       SDValue Lo, Hi;
241       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
242       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
243       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
244         std::swap(Lo, Hi);
245       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
246     } else {
247       // FP split into integer parts (soft fp)
248       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
249              !PartVT.isVector() && "Unexpected split");
250       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
251       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
252                              InChain, CC);
253     }
254   }
255 
256   // There is now one part, held in Val.  Correct it to match ValueVT.
257   // PartEVT is the type of the register class that holds the value.
258   // ValueVT is the type of the inline asm operation.
259   EVT PartEVT = Val.getValueType();
260 
261   if (PartEVT == ValueVT)
262     return Val;
263 
264   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
265       ValueVT.bitsLT(PartEVT)) {
266     // For an FP value in an integer part, we need to truncate to the right
267     // width first.
268     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
269     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
270   }
271 
272   // Handle types that have the same size.
273   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
274     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
275 
276   // Handle types with different sizes.
277   if (PartEVT.isInteger() && ValueVT.isInteger()) {
278     if (ValueVT.bitsLT(PartEVT)) {
279       // For a truncate, see if we have any information to
280       // indicate whether the truncated bits will always be
281       // zero or sign-extension.
282       if (AssertOp)
283         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
284                           DAG.getValueType(ValueVT));
285       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
286     }
287     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
288   }
289 
290   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
291     // FP_ROUND's are always exact here.
292     if (ValueVT.bitsLT(Val.getValueType())) {
293 
294       SDValue NoChange =
295           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
296 
297       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
298               llvm::Attribute::StrictFP)) {
299         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
300                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
301                            NoChange);
302       }
303 
304       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
305     }
306 
307     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
308   }
309 
310   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
311   // then truncating.
312   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
313       ValueVT.bitsLT(PartEVT)) {
314     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
315     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316   }
317 
318   report_fatal_error("Unknown mismatch in getCopyFromParts!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (CI->isInlineAsm())
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       SDValue InChain,
344                                       std::optional<CallingConv::ID> CallConv) {
345   assert(ValueVT.isVector() && "Not a vector value");
346   assert(NumParts > 0 && "No parts to assemble!");
347   const bool IsABIRegCopy = CallConv.has_value();
348 
349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350   SDValue Val = Parts[0];
351 
352   // Handle a multi-element vector.
353   if (NumParts > 1) {
354     EVT IntermediateVT;
355     MVT RegisterVT;
356     unsigned NumIntermediates;
357     unsigned NumRegs;
358 
359     if (IsABIRegCopy) {
360       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
361           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
362           NumIntermediates, RegisterVT);
363     } else {
364       NumRegs =
365           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
366                                      NumIntermediates, RegisterVT);
367     }
368 
369     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
370     NumParts = NumRegs; // Silence a compiler warning.
371     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
372     assert(RegisterVT.getSizeInBits() ==
373            Parts[0].getSimpleValueType().getSizeInBits() &&
374            "Part type sizes don't match!");
375 
376     // Assemble the parts into intermediate operands.
377     SmallVector<SDValue, 8> Ops(NumIntermediates);
378     if (NumIntermediates == NumParts) {
379       // If the register was not expanded, truncate or copy the value,
380       // as appropriate.
381       for (unsigned i = 0; i != NumParts; ++i)
382         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
383                                   V, InChain, CallConv);
384     } else if (NumParts > 0) {
385       // If the intermediate type was expanded, build the intermediate
386       // operands from the parts.
387       assert(NumParts % NumIntermediates == 0 &&
388              "Must expand into a divisible number of parts!");
389       unsigned Factor = NumParts / NumIntermediates;
390       for (unsigned i = 0; i != NumIntermediates; ++i)
391         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
392                                   IntermediateVT, V, InChain, CallConv);
393     }
394 
395     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
396     // intermediate operands.
397     EVT BuiltVectorTy =
398         IntermediateVT.isVector()
399             ? EVT::getVectorVT(
400                   *DAG.getContext(), IntermediateVT.getScalarType(),
401                   IntermediateVT.getVectorElementCount() * NumParts)
402             : EVT::getVectorVT(*DAG.getContext(),
403                                IntermediateVT.getScalarType(),
404                                NumIntermediates);
405     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
406                                                 : ISD::BUILD_VECTOR,
407                       DL, BuiltVectorTy, Ops);
408   }
409 
410   // There is now one part, held in Val.  Correct it to match ValueVT.
411   EVT PartEVT = Val.getValueType();
412 
413   if (PartEVT == ValueVT)
414     return Val;
415 
416   if (PartEVT.isVector()) {
417     // Vector/Vector bitcast.
418     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
419       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420 
421     // If the parts vector has more elements than the value vector, then we
422     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
423     // Extract the elements we want.
424     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
425       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
426               ValueVT.getVectorElementCount().getKnownMinValue()) &&
427              (PartEVT.getVectorElementCount().isScalable() ==
428               ValueVT.getVectorElementCount().isScalable()) &&
429              "Cannot narrow, it would be a lossy transformation");
430       PartEVT =
431           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
432                            ValueVT.getVectorElementCount());
433       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
434                         DAG.getVectorIdxConstant(0, DL));
435       if (PartEVT == ValueVT)
436         return Val;
437       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
438         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
441       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
442         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443     }
444 
445     // Promoted vector extract
446     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
447   }
448 
449   // Trivial bitcast if the types are the same size and the destination
450   // vector type is legal.
451   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
452       TLI.isTypeLegal(ValueVT))
453     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454 
455   if (ValueVT.getVectorNumElements() != 1) {
456      // Certain ABIs require that vectors are passed as integers. For vectors
457      // are the same size, this is an obvious bitcast.
458      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
459        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
460      } else if (ValueVT.bitsLT(PartEVT)) {
461        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
462        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
463        // Drop the extra bits.
464        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
465        return DAG.getBitcast(ValueVT, Val);
466      }
467 
468      diagnosePossiblyInvalidConstraint(
469          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
470      return DAG.getUNDEF(ValueVT);
471   }
472 
473   // Handle cases such as i8 -> <1 x i1>
474   EVT ValueSVT = ValueVT.getVectorElementType();
475   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
476     unsigned ValueSize = ValueSVT.getSizeInBits();
477     if (ValueSize == PartEVT.getSizeInBits()) {
478       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
479     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
480       // It's possible a scalar floating point type gets softened to integer and
481       // then promoted to a larger integer. If PartEVT is the larger integer
482       // we need to truncate it and then bitcast to the FP type.
483       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
484       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
485       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
486       Val = DAG.getBitcast(ValueSVT, Val);
487     } else {
488       Val = ValueVT.isFloatingPoint()
489                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
490                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
491     }
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  std::optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void
506 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
507                unsigned NumParts, MVT PartVT, const Value *V,
508                std::optional<CallingConv::ID> CallConv = std::nullopt,
509                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   // Let the target split the parts if it wants to
511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
512   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
513                                       CallConv))
514     return;
515   EVT ValueVT = Val.getValueType();
516 
517   // Handle the vector case separately.
518   if (ValueVT.isVector())
519     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
520                                 CallConv);
521 
522   unsigned OrigNumParts = NumParts;
523   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
524          "Copying to an illegal type!");
525 
526   if (NumParts == 0)
527     return;
528 
529   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
530   EVT PartEVT = PartVT;
531   if (PartEVT == ValueVT) {
532     assert(NumParts == 1 && "No-op copy with multiple parts!");
533     Parts[0] = Val;
534     return;
535   }
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
539     // If the parts cover more bits than the value has, promote the value.
540     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
541       assert(NumParts == 1 && "Do not know what to promote to!");
542       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
543     } else {
544       if (ValueVT.isFloatingPoint()) {
545         // FP values need to be bitcast, then extended if they are being put
546         // into a larger container.
547         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
548         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
549       }
550       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
551              ValueVT.isInteger() &&
552              "Unknown mismatch!");
553       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
554       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
555       if (PartVT == MVT::x86mmx)
556         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557     }
558   } else if (PartBits == ValueVT.getSizeInBits()) {
559     // Different types of the same size.
560     assert(NumParts == 1 && PartEVT != ValueVT);
561     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
562   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
563     // If the parts cover less bits than value has, truncate the value.
564     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
565            ValueVT.isInteger() &&
566            "Unknown mismatch!");
567     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
568     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
569     if (PartVT == MVT::x86mmx)
570       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571   }
572 
573   // The value may have changed - recompute ValueVT.
574   ValueVT = Val.getValueType();
575   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
576          "Failed to tile the value with PartVT!");
577 
578   if (NumParts == 1) {
579     if (PartEVT != ValueVT) {
580       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
581                                         "scalar-to-vector conversion failed");
582       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583     }
584 
585     Parts[0] = Val;
586     return;
587   }
588 
589   // Expand the value into multiple parts.
590   if (NumParts & (NumParts - 1)) {
591     // The number of parts is not a power of 2.  Split off and copy the tail.
592     assert(PartVT.isInteger() && ValueVT.isInteger() &&
593            "Do not know what to expand to!");
594     unsigned RoundParts = llvm::bit_floor(NumParts);
595     unsigned RoundBits = RoundParts * PartBits;
596     unsigned OddParts = NumParts - RoundParts;
597     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
598       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
599 
600     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
601                    CallConv);
602 
603     if (DAG.getDataLayout().isBigEndian())
604       // The odd parts were reversed by getCopyToParts - unreverse them.
605       std::reverse(Parts + RoundParts, Parts + NumParts);
606 
607     NumParts = RoundParts;
608     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
609     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
610   }
611 
612   // The number of parts is a power of 2.  Repeatedly bisect the value using
613   // EXTRACT_ELEMENT.
614   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
615                          EVT::getIntegerVT(*DAG.getContext(),
616                                            ValueVT.getSizeInBits()),
617                          Val);
618 
619   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
620     for (unsigned i = 0; i < NumParts; i += StepSize) {
621       unsigned ThisBits = StepSize * PartBits / 2;
622       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
623       SDValue &Part0 = Parts[i];
624       SDValue &Part1 = Parts[i+StepSize/2];
625 
626       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
628       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
629                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
630 
631       if (ThisBits == PartBits && ThisVT != PartVT) {
632         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
633         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
634       }
635     }
636   }
637 
638   if (DAG.getDataLayout().isBigEndian())
639     std::reverse(Parts, Parts + OrigNumParts);
640 }
641 
642 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
643                                      const SDLoc &DL, EVT PartVT) {
644   if (!PartVT.isVector())
645     return SDValue();
646 
647   EVT ValueVT = Val.getValueType();
648   EVT PartEVT = PartVT.getVectorElementType();
649   EVT ValueEVT = ValueVT.getVectorElementType();
650   ElementCount PartNumElts = PartVT.getVectorElementCount();
651   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
652 
653   // We only support widening vectors with equivalent element types and
654   // fixed/scalable properties. If a target needs to widen a fixed-length type
655   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
656   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
657       PartNumElts.isScalable() != ValueNumElts.isScalable())
658     return SDValue();
659 
660   // Have a try for bf16 because some targets share its ABI with fp16.
661   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
662     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
663            "Cannot widen to illegal type");
664     Val = DAG.getNode(ISD::BITCAST, DL,
665                       ValueVT.changeVectorElementType(MVT::f16), Val);
666   } else if (PartEVT != ValueEVT) {
667     return SDValue();
668   }
669 
670   // Widening a scalable vector to another scalable vector is done by inserting
671   // the vector into a larger undef one.
672   if (PartNumElts.isScalable())
673     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
674                        Val, DAG.getVectorIdxConstant(0, DL));
675 
676   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
677   // undef elements.
678   SmallVector<SDValue, 16> Ops;
679   DAG.ExtractVectorElements(Val, Ops);
680   SDValue EltUndef = DAG.getUNDEF(PartEVT);
681   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
682 
683   // FIXME: Use CONCAT for 2x -> 4x.
684   return DAG.getBuildVector(PartVT, DL, Ops);
685 }
686 
687 /// getCopyToPartsVector - Create a series of nodes that contain the specified
688 /// value split into legal parts.
689 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
690                                  SDValue Val, SDValue *Parts, unsigned NumParts,
691                                  MVT PartVT, const Value *V,
692                                  std::optional<CallingConv::ID> CallConv) {
693   EVT ValueVT = Val.getValueType();
694   assert(ValueVT.isVector() && "Not a vector");
695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
696   const bool IsABIRegCopy = CallConv.has_value();
697 
698   if (NumParts == 1) {
699     EVT PartEVT = PartVT;
700     if (PartEVT == ValueVT) {
701       // Nothing to do.
702     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
703       // Bitconvert vector->vector case.
704       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
705     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
706       Val = Widened;
707     } else if (PartVT.isVector() &&
708                PartEVT.getVectorElementType().bitsGE(
709                    ValueVT.getVectorElementType()) &&
710                PartEVT.getVectorElementCount() ==
711                    ValueVT.getVectorElementCount()) {
712 
713       // Promoted vector extract
714       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
715     } else if (PartEVT.isVector() &&
716                PartEVT.getVectorElementType() !=
717                    ValueVT.getVectorElementType() &&
718                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
719                    TargetLowering::TypeWidenVector) {
720       // Combination of widening and promotion.
721       EVT WidenVT =
722           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
723                            PartVT.getVectorElementCount());
724       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
725       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
726     } else {
727       // Don't extract an integer from a float vector. This can happen if the
728       // FP type gets softened to integer and then promoted. The promotion
729       // prevents it from being picked up by the earlier bitcast case.
730       if (ValueVT.getVectorElementCount().isScalar() &&
731           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
732         // If we reach this condition and PartVT is FP, this means that
733         // ValueVT is also FP and both have a different size, otherwise we
734         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
735         // would be invalid since that would mean the smaller FP type has to
736         // be extended to the larger one.
737         if (PartVT.isFloatingPoint()) {
738           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
739           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
740         } else
741           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
742                             DAG.getVectorIdxConstant(0, DL));
743       } else {
744         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
745         assert(PartVT.getFixedSizeInBits() > ValueSize &&
746                "lossy conversion of vector to scalar type");
747         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
748         Val = DAG.getBitcast(IntermediateType, Val);
749         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
750       }
751     }
752 
753     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
754     Parts[0] = Val;
755     return;
756   }
757 
758   // Handle a multi-element vector.
759   EVT IntermediateVT;
760   MVT RegisterVT;
761   unsigned NumIntermediates;
762   unsigned NumRegs;
763   if (IsABIRegCopy) {
764     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
765         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
766         RegisterVT);
767   } else {
768     NumRegs =
769         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
770                                    NumIntermediates, RegisterVT);
771   }
772 
773   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
774   NumParts = NumRegs; // Silence a compiler warning.
775   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
776 
777   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
778          "Mixing scalable and fixed vectors when copying in parts");
779 
780   std::optional<ElementCount> DestEltCnt;
781 
782   if (IntermediateVT.isVector())
783     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
784   else
785     DestEltCnt = ElementCount::getFixed(NumIntermediates);
786 
787   EVT BuiltVectorTy = EVT::getVectorVT(
788       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
789 
790   if (ValueVT == BuiltVectorTy) {
791     // Nothing to do.
792   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
793     // Bitconvert vector->vector case.
794     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
795   } else {
796     if (BuiltVectorTy.getVectorElementType().bitsGT(
797             ValueVT.getVectorElementType())) {
798       // Integer promotion.
799       ValueVT = EVT::getVectorVT(*DAG.getContext(),
800                                  BuiltVectorTy.getVectorElementType(),
801                                  ValueVT.getVectorElementCount());
802       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
803     }
804 
805     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
806       Val = Widened;
807     }
808   }
809 
810   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
811 
812   // Split the vector into intermediate operands.
813   SmallVector<SDValue, 8> Ops(NumIntermediates);
814   for (unsigned i = 0; i != NumIntermediates; ++i) {
815     if (IntermediateVT.isVector()) {
816       // This does something sensible for scalable vectors - see the
817       // definition of EXTRACT_SUBVECTOR for further details.
818       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
819       Ops[i] =
820           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
821                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
822     } else {
823       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
824                            DAG.getVectorIdxConstant(i, DL));
825     }
826   }
827 
828   // Split the intermediate operands into legal parts.
829   if (NumParts == NumIntermediates) {
830     // If the register was not expanded, promote or copy the value,
831     // as appropriate.
832     for (unsigned i = 0; i != NumParts; ++i)
833       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
834   } else if (NumParts > 0) {
835     // If the intermediate type was expanded, split each the value into
836     // legal parts.
837     assert(NumIntermediates != 0 && "division by zero");
838     assert(NumParts % NumIntermediates == 0 &&
839            "Must expand into a divisible number of parts!");
840     unsigned Factor = NumParts / NumIntermediates;
841     for (unsigned i = 0; i != NumIntermediates; ++i)
842       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
843                      CallConv);
844   }
845 }
846 
847 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
848                            EVT valuevt, std::optional<CallingConv::ID> CC)
849     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
850       RegCount(1, regs.size()), CallConv(CC) {}
851 
852 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
853                            const DataLayout &DL, unsigned Reg, Type *Ty,
854                            std::optional<CallingConv::ID> CC) {
855   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
856 
857   CallConv = CC;
858 
859   for (EVT ValueVT : ValueVTs) {
860     unsigned NumRegs =
861         isABIMangled()
862             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
863             : TLI.getNumRegisters(Context, ValueVT);
864     MVT RegisterVT =
865         isABIMangled()
866             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
867             : TLI.getRegisterType(Context, ValueVT);
868     for (unsigned i = 0; i != NumRegs; ++i)
869       Regs.push_back(Reg + i);
870     RegVTs.push_back(RegisterVT);
871     RegCount.push_back(NumRegs);
872     Reg += NumRegs;
873   }
874 }
875 
876 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
877                                       FunctionLoweringInfo &FuncInfo,
878                                       const SDLoc &dl, SDValue &Chain,
879                                       SDValue *Glue, const Value *V) const {
880   // A Value with type {} or [0 x %t] needs no registers.
881   if (ValueVTs.empty())
882     return SDValue();
883 
884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
885 
886   // Assemble the legal parts into the final values.
887   SmallVector<SDValue, 4> Values(ValueVTs.size());
888   SmallVector<SDValue, 8> Parts;
889   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
890     // Copy the legal parts from the registers.
891     EVT ValueVT = ValueVTs[Value];
892     unsigned NumRegs = RegCount[Value];
893     MVT RegisterVT = isABIMangled()
894                          ? TLI.getRegisterTypeForCallingConv(
895                                *DAG.getContext(), *CallConv, RegVTs[Value])
896                          : RegVTs[Value];
897 
898     Parts.resize(NumRegs);
899     for (unsigned i = 0; i != NumRegs; ++i) {
900       SDValue P;
901       if (!Glue) {
902         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
903       } else {
904         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
905         *Glue = P.getValue(2);
906       }
907 
908       Chain = P.getValue(1);
909       Parts[i] = P;
910 
911       // If the source register was virtual and if we know something about it,
912       // add an assert node.
913       if (!Register::isVirtualRegister(Regs[Part + i]) ||
914           !RegisterVT.isInteger())
915         continue;
916 
917       const FunctionLoweringInfo::LiveOutInfo *LOI =
918         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
919       if (!LOI)
920         continue;
921 
922       unsigned RegSize = RegisterVT.getScalarSizeInBits();
923       unsigned NumSignBits = LOI->NumSignBits;
924       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
925 
926       if (NumZeroBits == RegSize) {
927         // The current value is a zero.
928         // Explicitly express that as it would be easier for
929         // optimizations to kick in.
930         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
931         continue;
932       }
933 
934       // FIXME: We capture more information than the dag can represent.  For
935       // now, just use the tightest assertzext/assertsext possible.
936       bool isSExt;
937       EVT FromVT(MVT::Other);
938       if (NumZeroBits) {
939         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
940         isSExt = false;
941       } else if (NumSignBits > 1) {
942         FromVT =
943             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
944         isSExt = true;
945       } else {
946         continue;
947       }
948       // Add an assertion node.
949       assert(FromVT != MVT::Other);
950       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
951                              RegisterVT, P, DAG.getValueType(FromVT));
952     }
953 
954     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
955                                      RegisterVT, ValueVT, V, Chain, CallConv);
956     Part += NumRegs;
957     Parts.clear();
958   }
959 
960   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
961 }
962 
963 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
964                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
965                                  const Value *V,
966                                  ISD::NodeType PreferredExtendType) const {
967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
968   ISD::NodeType ExtendKind = PreferredExtendType;
969 
970   // Get the list of the values's legal parts.
971   unsigned NumRegs = Regs.size();
972   SmallVector<SDValue, 8> Parts(NumRegs);
973   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
974     unsigned NumParts = RegCount[Value];
975 
976     MVT RegisterVT = isABIMangled()
977                          ? TLI.getRegisterTypeForCallingConv(
978                                *DAG.getContext(), *CallConv, RegVTs[Value])
979                          : RegVTs[Value];
980 
981     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
982       ExtendKind = ISD::ZERO_EXTEND;
983 
984     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
985                    NumParts, RegisterVT, V, CallConv, ExtendKind);
986     Part += NumParts;
987   }
988 
989   // Copy the parts into the registers.
990   SmallVector<SDValue, 8> Chains(NumRegs);
991   for (unsigned i = 0; i != NumRegs; ++i) {
992     SDValue Part;
993     if (!Glue) {
994       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
995     } else {
996       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
997       *Glue = Part.getValue(1);
998     }
999 
1000     Chains[i] = Part.getValue(0);
1001   }
1002 
1003   if (NumRegs == 1 || Glue)
1004     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1005     // flagged to it. That is the CopyToReg nodes and the user are considered
1006     // a single scheduling unit. If we create a TokenFactor and return it as
1007     // chain, then the TokenFactor is both a predecessor (operand) of the
1008     // user as well as a successor (the TF operands are flagged to the user).
1009     // c1, f1 = CopyToReg
1010     // c2, f2 = CopyToReg
1011     // c3     = TokenFactor c1, c2
1012     // ...
1013     //        = op c3, ..., f2
1014     Chain = Chains[NumRegs-1];
1015   else
1016     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1017 }
1018 
1019 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1020                                         unsigned MatchingIdx, const SDLoc &dl,
1021                                         SelectionDAG &DAG,
1022                                         std::vector<SDValue> &Ops) const {
1023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1024 
1025   InlineAsm::Flag Flag(Code, Regs.size());
1026   if (HasMatching)
1027     Flag.setMatchingOp(MatchingIdx);
1028   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1029     // Put the register class of the virtual registers in the flag word.  That
1030     // way, later passes can recompute register class constraints for inline
1031     // assembly as well as normal instructions.
1032     // Don't do this for tied operands that can use the regclass information
1033     // from the def.
1034     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1035     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1036     Flag.setRegClass(RC->getID());
1037   }
1038 
1039   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1040   Ops.push_back(Res);
1041 
1042   if (Code == InlineAsm::Kind::Clobber) {
1043     // Clobbers should always have a 1:1 mapping with registers, and may
1044     // reference registers that have illegal (e.g. vector) types. Hence, we
1045     // shouldn't try to apply any sort of splitting logic to them.
1046     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1047            "No 1:1 mapping from clobbers to regs?");
1048     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1049     (void)SP;
1050     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1051       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1052       assert(
1053           (Regs[I] != SP ||
1054            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1055           "If we clobbered the stack pointer, MFI should know about it.");
1056     }
1057     return;
1058   }
1059 
1060   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1061     MVT RegisterVT = RegVTs[Value];
1062     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1063                                            RegisterVT);
1064     for (unsigned i = 0; i != NumRegs; ++i) {
1065       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1066       unsigned TheReg = Regs[Reg++];
1067       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1068     }
1069   }
1070 }
1071 
1072 SmallVector<std::pair<unsigned, TypeSize>, 4>
1073 RegsForValue::getRegsAndSizes() const {
1074   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1075   unsigned I = 0;
1076   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1077     unsigned RegCount = std::get<0>(CountAndVT);
1078     MVT RegisterVT = std::get<1>(CountAndVT);
1079     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1080     for (unsigned E = I + RegCount; I != E; ++I)
1081       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1082   }
1083   return OutVec;
1084 }
1085 
1086 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1087                                AssumptionCache *ac,
1088                                const TargetLibraryInfo *li) {
1089   AA = aa;
1090   AC = ac;
1091   GFI = gfi;
1092   LibInfo = li;
1093   Context = DAG.getContext();
1094   LPadToCallSiteMap.clear();
1095   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1096   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1097       *DAG.getMachineFunction().getFunction().getParent());
1098 }
1099 
1100 void SelectionDAGBuilder::clear() {
1101   NodeMap.clear();
1102   UnusedArgNodeMap.clear();
1103   PendingLoads.clear();
1104   PendingExports.clear();
1105   PendingConstrainedFP.clear();
1106   PendingConstrainedFPStrict.clear();
1107   CurInst = nullptr;
1108   HasTailCall = false;
1109   SDNodeOrder = LowestSDNodeOrder;
1110   StatepointLowering.clear();
1111 }
1112 
1113 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1114   DanglingDebugInfoMap.clear();
1115 }
1116 
1117 // Update DAG root to include dependencies on Pending chains.
1118 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1119   SDValue Root = DAG.getRoot();
1120 
1121   if (Pending.empty())
1122     return Root;
1123 
1124   // Add current root to PendingChains, unless we already indirectly
1125   // depend on it.
1126   if (Root.getOpcode() != ISD::EntryToken) {
1127     unsigned i = 0, e = Pending.size();
1128     for (; i != e; ++i) {
1129       assert(Pending[i].getNode()->getNumOperands() > 1);
1130       if (Pending[i].getNode()->getOperand(0) == Root)
1131         break;  // Don't add the root if we already indirectly depend on it.
1132     }
1133 
1134     if (i == e)
1135       Pending.push_back(Root);
1136   }
1137 
1138   if (Pending.size() == 1)
1139     Root = Pending[0];
1140   else
1141     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1142 
1143   DAG.setRoot(Root);
1144   Pending.clear();
1145   return Root;
1146 }
1147 
1148 SDValue SelectionDAGBuilder::getMemoryRoot() {
1149   return updateRoot(PendingLoads);
1150 }
1151 
1152 SDValue SelectionDAGBuilder::getRoot() {
1153   // Chain up all pending constrained intrinsics together with all
1154   // pending loads, by simply appending them to PendingLoads and
1155   // then calling getMemoryRoot().
1156   PendingLoads.reserve(PendingLoads.size() +
1157                        PendingConstrainedFP.size() +
1158                        PendingConstrainedFPStrict.size());
1159   PendingLoads.append(PendingConstrainedFP.begin(),
1160                       PendingConstrainedFP.end());
1161   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1162                       PendingConstrainedFPStrict.end());
1163   PendingConstrainedFP.clear();
1164   PendingConstrainedFPStrict.clear();
1165   return getMemoryRoot();
1166 }
1167 
1168 SDValue SelectionDAGBuilder::getControlRoot() {
1169   // We need to emit pending fpexcept.strict constrained intrinsics,
1170   // so append them to the PendingExports list.
1171   PendingExports.append(PendingConstrainedFPStrict.begin(),
1172                         PendingConstrainedFPStrict.end());
1173   PendingConstrainedFPStrict.clear();
1174   return updateRoot(PendingExports);
1175 }
1176 
1177 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1178                                              DILocalVariable *Variable,
1179                                              DIExpression *Expression,
1180                                              DebugLoc DL) {
1181   assert(Variable && "Missing variable");
1182 
1183   // Check if address has undef value.
1184   if (!Address || isa<UndefValue>(Address) ||
1185       (Address->use_empty() && !isa<Argument>(Address))) {
1186     LLVM_DEBUG(
1187         dbgs()
1188         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1189     return;
1190   }
1191 
1192   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1193 
1194   SDValue &N = NodeMap[Address];
1195   if (!N.getNode() && isa<Argument>(Address))
1196     // Check unused arguments map.
1197     N = UnusedArgNodeMap[Address];
1198   SDDbgValue *SDV;
1199   if (N.getNode()) {
1200     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1201       Address = BCI->getOperand(0);
1202     // Parameters are handled specially.
1203     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1204     if (IsParameter && FINode) {
1205       // Byval parameter. We have a frame index at this point.
1206       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1207                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1208     } else if (isa<Argument>(Address)) {
1209       // Address is an argument, so try to emit its dbg value using
1210       // virtual register info from the FuncInfo.ValueMap.
1211       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1212                                FuncArgumentDbgValueKind::Declare, N);
1213       return;
1214     } else {
1215       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1216                             true, DL, SDNodeOrder);
1217     }
1218     DAG.AddDbgValue(SDV, IsParameter);
1219   } else {
1220     // If Address is an argument then try to emit its dbg value using
1221     // virtual register info from the FuncInfo.ValueMap.
1222     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1223                                   FuncArgumentDbgValueKind::Declare, N)) {
1224       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1225                         << " (could not emit func-arg dbg_value)\n");
1226     }
1227   }
1228   return;
1229 }
1230 
1231 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1232   // Add SDDbgValue nodes for any var locs here. Do so before updating
1233   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1234   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1235     // Add SDDbgValue nodes for any var locs here. Do so before updating
1236     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1237     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1238          It != End; ++It) {
1239       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1240       dropDanglingDebugInfo(Var, It->Expr);
1241       if (It->Values.isKillLocation(It->Expr)) {
1242         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1243         continue;
1244       }
1245       SmallVector<Value *> Values(It->Values.location_ops());
1246       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1247                             It->Values.hasArgList())) {
1248         SmallVector<Value *, 4> Vals;
1249         for (Value *V : It->Values.location_ops())
1250           Vals.push_back(V);
1251         addDanglingDebugInfo(Vals,
1252                              FnVarLocs->getDILocalVariable(It->VariableID),
1253                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1254       }
1255     }
1256   }
1257 
1258   // We must skip DbgVariableRecords if they've already been processed above as
1259   // we have just emitted the debug values resulting from assignment tracking
1260   // analysis, making any existing DbgVariableRecords redundant (and probably
1261   // less correct). We still need to process DbgLabelRecords. This does sink
1262   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1263   // be important as it does so deterministcally and ordering between
1264   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1265   // printing).
1266   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1267   // Is there is any debug-info attached to this instruction, in the form of
1268   // DbgRecord non-instruction debug-info records.
1269   for (DbgRecord &DR : I.getDbgRecordRange()) {
1270     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1271       assert(DLR->getLabel() && "Missing label");
1272       SDDbgLabel *SDV =
1273           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1274       DAG.AddDbgLabel(SDV);
1275       continue;
1276     }
1277 
1278     if (SkipDbgVariableRecords)
1279       continue;
1280     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1281     DILocalVariable *Variable = DVR.getVariable();
1282     DIExpression *Expression = DVR.getExpression();
1283     dropDanglingDebugInfo(Variable, Expression);
1284 
1285     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1286       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1287         continue;
1288       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1289                         << "\n");
1290       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1291                          DVR.getDebugLoc());
1292       continue;
1293     }
1294 
1295     // A DbgVariableRecord with no locations is a kill location.
1296     SmallVector<Value *, 4> Values(DVR.location_ops());
1297     if (Values.empty()) {
1298       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1299                            SDNodeOrder);
1300       continue;
1301     }
1302 
1303     // A DbgVariableRecord with an undef or absent location is also a kill
1304     // location.
1305     if (llvm::any_of(Values,
1306                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1307       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1308                            SDNodeOrder);
1309       continue;
1310     }
1311 
1312     bool IsVariadic = DVR.hasArgList();
1313     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1314                           SDNodeOrder, IsVariadic)) {
1315       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1316                            DVR.getDebugLoc(), SDNodeOrder);
1317     }
1318   }
1319 }
1320 
1321 void SelectionDAGBuilder::visit(const Instruction &I) {
1322   visitDbgInfo(I);
1323 
1324   // Set up outgoing PHI node register values before emitting the terminator.
1325   if (I.isTerminator()) {
1326     HandlePHINodesInSuccessorBlocks(I.getParent());
1327   }
1328 
1329   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1330   if (!isa<DbgInfoIntrinsic>(I))
1331     ++SDNodeOrder;
1332 
1333   CurInst = &I;
1334 
1335   // Set inserted listener only if required.
1336   bool NodeInserted = false;
1337   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1338   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1339   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1340   if (PCSectionsMD || MMRA) {
1341     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1342         DAG, [&](SDNode *) { NodeInserted = true; });
1343   }
1344 
1345   visit(I.getOpcode(), I);
1346 
1347   if (!I.isTerminator() && !HasTailCall &&
1348       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1349     CopyToExportRegsIfNeeded(&I);
1350 
1351   // Handle metadata.
1352   if (PCSectionsMD || MMRA) {
1353     auto It = NodeMap.find(&I);
1354     if (It != NodeMap.end()) {
1355       if (PCSectionsMD)
1356         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1357       if (MMRA)
1358         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1359     } else if (NodeInserted) {
1360       // This should not happen; if it does, don't let it go unnoticed so we can
1361       // fix it. Relevant visit*() function is probably missing a setValue().
1362       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1363              << I.getModule()->getName() << "]\n";
1364       LLVM_DEBUG(I.dump());
1365       assert(false);
1366     }
1367   }
1368 
1369   CurInst = nullptr;
1370 }
1371 
1372 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1373   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1374 }
1375 
1376 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1377   // Note: this doesn't use InstVisitor, because it has to work with
1378   // ConstantExpr's in addition to instructions.
1379   switch (Opcode) {
1380   default: llvm_unreachable("Unknown instruction type encountered!");
1381     // Build the switch statement using the Instruction.def file.
1382 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1383     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1384 #include "llvm/IR/Instruction.def"
1385   }
1386 }
1387 
1388 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1389                                             DILocalVariable *Variable,
1390                                             DebugLoc DL, unsigned Order,
1391                                             SmallVectorImpl<Value *> &Values,
1392                                             DIExpression *Expression) {
1393   // For variadic dbg_values we will now insert an undef.
1394   // FIXME: We can potentially recover these!
1395   SmallVector<SDDbgOperand, 2> Locs;
1396   for (const Value *V : Values) {
1397     auto *Undef = UndefValue::get(V->getType());
1398     Locs.push_back(SDDbgOperand::fromConst(Undef));
1399   }
1400   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1401                                         /*IsIndirect=*/false, DL, Order,
1402                                         /*IsVariadic=*/true);
1403   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1404   return true;
1405 }
1406 
1407 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1408                                                DILocalVariable *Var,
1409                                                DIExpression *Expr,
1410                                                bool IsVariadic, DebugLoc DL,
1411                                                unsigned Order) {
1412   if (IsVariadic) {
1413     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1414     return;
1415   }
1416   // TODO: Dangling debug info will eventually either be resolved or produce
1417   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1418   // between the original dbg.value location and its resolved DBG_VALUE,
1419   // which we should ideally fill with an extra Undef DBG_VALUE.
1420   assert(Values.size() == 1);
1421   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1422 }
1423 
1424 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1425                                                 const DIExpression *Expr) {
1426   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1427     DIVariable *DanglingVariable = DDI.getVariable();
1428     DIExpression *DanglingExpr = DDI.getExpression();
1429     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1430       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1431                         << printDDI(nullptr, DDI) << "\n");
1432       return true;
1433     }
1434     return false;
1435   };
1436 
1437   for (auto &DDIMI : DanglingDebugInfoMap) {
1438     DanglingDebugInfoVector &DDIV = DDIMI.second;
1439 
1440     // If debug info is to be dropped, run it through final checks to see
1441     // whether it can be salvaged.
1442     for (auto &DDI : DDIV)
1443       if (isMatchingDbgValue(DDI))
1444         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1445 
1446     erase_if(DDIV, isMatchingDbgValue);
1447   }
1448 }
1449 
1450 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1451 // generate the debug data structures now that we've seen its definition.
1452 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1453                                                    SDValue Val) {
1454   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1455   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1456     return;
1457 
1458   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1459   for (auto &DDI : DDIV) {
1460     DebugLoc DL = DDI.getDebugLoc();
1461     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1462     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1463     DILocalVariable *Variable = DDI.getVariable();
1464     DIExpression *Expr = DDI.getExpression();
1465     assert(Variable->isValidLocationForIntrinsic(DL) &&
1466            "Expected inlined-at fields to agree");
1467     SDDbgValue *SDV;
1468     if (Val.getNode()) {
1469       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1470       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1471       // we couldn't resolve it directly when examining the DbgValue intrinsic
1472       // in the first place we should not be more successful here). Unless we
1473       // have some test case that prove this to be correct we should avoid
1474       // calling EmitFuncArgumentDbgValue here.
1475       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1476                                     FuncArgumentDbgValueKind::Value, Val)) {
1477         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1478                           << printDDI(V, DDI) << "\n");
1479         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1480         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1481         // inserted after the definition of Val when emitting the instructions
1482         // after ISel. An alternative could be to teach
1483         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1484         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1485                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1486                    << ValSDNodeOrder << "\n");
1487         SDV = getDbgValue(Val, Variable, Expr, DL,
1488                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1489         DAG.AddDbgValue(SDV, false);
1490       } else
1491         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1492                           << printDDI(V, DDI)
1493                           << " in EmitFuncArgumentDbgValue\n");
1494     } else {
1495       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1496                         << "\n");
1497       auto Undef = UndefValue::get(V->getType());
1498       auto SDV =
1499           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1500       DAG.AddDbgValue(SDV, false);
1501     }
1502   }
1503   DDIV.clear();
1504 }
1505 
1506 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1507                                                     DanglingDebugInfo &DDI) {
1508   // TODO: For the variadic implementation, instead of only checking the fail
1509   // state of `handleDebugValue`, we need know specifically which values were
1510   // invalid, so that we attempt to salvage only those values when processing
1511   // a DIArgList.
1512   const Value *OrigV = V;
1513   DILocalVariable *Var = DDI.getVariable();
1514   DIExpression *Expr = DDI.getExpression();
1515   DebugLoc DL = DDI.getDebugLoc();
1516   unsigned SDOrder = DDI.getSDNodeOrder();
1517 
1518   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1519   // that DW_OP_stack_value is desired.
1520   bool StackValue = true;
1521 
1522   // Can this Value can be encoded without any further work?
1523   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1524     return;
1525 
1526   // Attempt to salvage back through as many instructions as possible. Bail if
1527   // a non-instruction is seen, such as a constant expression or global
1528   // variable. FIXME: Further work could recover those too.
1529   while (isa<Instruction>(V)) {
1530     const Instruction &VAsInst = *cast<const Instruction>(V);
1531     // Temporary "0", awaiting real implementation.
1532     SmallVector<uint64_t, 16> Ops;
1533     SmallVector<Value *, 4> AdditionalValues;
1534     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1535                              Expr->getNumLocationOperands(), Ops,
1536                              AdditionalValues);
1537     // If we cannot salvage any further, and haven't yet found a suitable debug
1538     // expression, bail out.
1539     if (!V)
1540       break;
1541 
1542     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1543     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1544     // here for variadic dbg_values, remove that condition.
1545     if (!AdditionalValues.empty())
1546       break;
1547 
1548     // New value and expr now represent this debuginfo.
1549     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1550 
1551     // Some kind of simplification occurred: check whether the operand of the
1552     // salvaged debug expression can be encoded in this DAG.
1553     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1554       LLVM_DEBUG(
1555           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1556                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1557       return;
1558     }
1559   }
1560 
1561   // This was the final opportunity to salvage this debug information, and it
1562   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1563   // any earlier variable location.
1564   assert(OrigV && "V shouldn't be null");
1565   auto *Undef = UndefValue::get(OrigV->getType());
1566   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1567   DAG.AddDbgValue(SDV, false);
1568   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1569                     << printDDI(OrigV, DDI) << "\n");
1570 }
1571 
1572 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1573                                                DIExpression *Expr,
1574                                                DebugLoc DbgLoc,
1575                                                unsigned Order) {
1576   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1577   DIExpression *NewExpr =
1578       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1579   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1580                    /*IsVariadic*/ false);
1581 }
1582 
1583 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1584                                            DILocalVariable *Var,
1585                                            DIExpression *Expr, DebugLoc DbgLoc,
1586                                            unsigned Order, bool IsVariadic) {
1587   if (Values.empty())
1588     return true;
1589 
1590   // Filter EntryValue locations out early.
1591   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1592     return true;
1593 
1594   SmallVector<SDDbgOperand> LocationOps;
1595   SmallVector<SDNode *> Dependencies;
1596   for (const Value *V : Values) {
1597     // Constant value.
1598     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1599         isa<ConstantPointerNull>(V)) {
1600       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1601       continue;
1602     }
1603 
1604     // Look through IntToPtr constants.
1605     if (auto *CE = dyn_cast<ConstantExpr>(V))
1606       if (CE->getOpcode() == Instruction::IntToPtr) {
1607         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1608         continue;
1609       }
1610 
1611     // If the Value is a frame index, we can create a FrameIndex debug value
1612     // without relying on the DAG at all.
1613     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1614       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1615       if (SI != FuncInfo.StaticAllocaMap.end()) {
1616         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1617         continue;
1618       }
1619     }
1620 
1621     // Do not use getValue() in here; we don't want to generate code at
1622     // this point if it hasn't been done yet.
1623     SDValue N = NodeMap[V];
1624     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1625       N = UnusedArgNodeMap[V];
1626     if (N.getNode()) {
1627       // Only emit func arg dbg value for non-variadic dbg.values for now.
1628       if (!IsVariadic &&
1629           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1630                                    FuncArgumentDbgValueKind::Value, N))
1631         return true;
1632       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1633         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1634         // describe stack slot locations.
1635         //
1636         // Consider "int x = 0; int *px = &x;". There are two kinds of
1637         // interesting debug values here after optimization:
1638         //
1639         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1640         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1641         //
1642         // Both describe the direct values of their associated variables.
1643         Dependencies.push_back(N.getNode());
1644         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1645         continue;
1646       }
1647       LocationOps.emplace_back(
1648           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1649       continue;
1650     }
1651 
1652     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1653     // Special rules apply for the first dbg.values of parameter variables in a
1654     // function. Identify them by the fact they reference Argument Values, that
1655     // they're parameters, and they are parameters of the current function. We
1656     // need to let them dangle until they get an SDNode.
1657     bool IsParamOfFunc =
1658         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1659     if (IsParamOfFunc)
1660       return false;
1661 
1662     // The value is not used in this block yet (or it would have an SDNode).
1663     // We still want the value to appear for the user if possible -- if it has
1664     // an associated VReg, we can refer to that instead.
1665     auto VMI = FuncInfo.ValueMap.find(V);
1666     if (VMI != FuncInfo.ValueMap.end()) {
1667       unsigned Reg = VMI->second;
1668       // If this is a PHI node, it may be split up into several MI PHI nodes
1669       // (in FunctionLoweringInfo::set).
1670       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1671                        V->getType(), std::nullopt);
1672       if (RFV.occupiesMultipleRegs()) {
1673         // FIXME: We could potentially support variadic dbg_values here.
1674         if (IsVariadic)
1675           return false;
1676         unsigned Offset = 0;
1677         unsigned BitsToDescribe = 0;
1678         if (auto VarSize = Var->getSizeInBits())
1679           BitsToDescribe = *VarSize;
1680         if (auto Fragment = Expr->getFragmentInfo())
1681           BitsToDescribe = Fragment->SizeInBits;
1682         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1683           // Bail out if all bits are described already.
1684           if (Offset >= BitsToDescribe)
1685             break;
1686           // TODO: handle scalable vectors.
1687           unsigned RegisterSize = RegAndSize.second;
1688           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1689                                       ? BitsToDescribe - Offset
1690                                       : RegisterSize;
1691           auto FragmentExpr = DIExpression::createFragmentExpression(
1692               Expr, Offset, FragmentSize);
1693           if (!FragmentExpr)
1694             continue;
1695           SDDbgValue *SDV = DAG.getVRegDbgValue(
1696               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1697           DAG.AddDbgValue(SDV, false);
1698           Offset += RegisterSize;
1699         }
1700         return true;
1701       }
1702       // We can use simple vreg locations for variadic dbg_values as well.
1703       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1704       continue;
1705     }
1706     // We failed to create a SDDbgOperand for V.
1707     return false;
1708   }
1709 
1710   // We have created a SDDbgOperand for each Value in Values.
1711   assert(!LocationOps.empty());
1712   SDDbgValue *SDV =
1713       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1714                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1715   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1716   return true;
1717 }
1718 
1719 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1720   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1721   for (auto &Pair : DanglingDebugInfoMap)
1722     for (auto &DDI : Pair.second)
1723       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1724   clearDanglingDebugInfo();
1725 }
1726 
1727 /// getCopyFromRegs - If there was virtual register allocated for the value V
1728 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1729 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1730   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1731   SDValue Result;
1732 
1733   if (It != FuncInfo.ValueMap.end()) {
1734     Register InReg = It->second;
1735 
1736     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1737                      DAG.getDataLayout(), InReg, Ty,
1738                      std::nullopt); // This is not an ABI copy.
1739     SDValue Chain = DAG.getEntryNode();
1740     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1741                                  V);
1742     resolveDanglingDebugInfo(V, Result);
1743   }
1744 
1745   return Result;
1746 }
1747 
1748 /// getValue - Return an SDValue for the given Value.
1749 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1750   // If we already have an SDValue for this value, use it. It's important
1751   // to do this first, so that we don't create a CopyFromReg if we already
1752   // have a regular SDValue.
1753   SDValue &N = NodeMap[V];
1754   if (N.getNode()) return N;
1755 
1756   // If there's a virtual register allocated and initialized for this
1757   // value, use it.
1758   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1759     return copyFromReg;
1760 
1761   // Otherwise create a new SDValue and remember it.
1762   SDValue Val = getValueImpl(V);
1763   NodeMap[V] = Val;
1764   resolveDanglingDebugInfo(V, Val);
1765   return Val;
1766 }
1767 
1768 /// getNonRegisterValue - Return an SDValue for the given Value, but
1769 /// don't look in FuncInfo.ValueMap for a virtual register.
1770 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1771   // If we already have an SDValue for this value, use it.
1772   SDValue &N = NodeMap[V];
1773   if (N.getNode()) {
1774     if (isIntOrFPConstant(N)) {
1775       // Remove the debug location from the node as the node is about to be used
1776       // in a location which may differ from the original debug location.  This
1777       // is relevant to Constant and ConstantFP nodes because they can appear
1778       // as constant expressions inside PHI nodes.
1779       N->setDebugLoc(DebugLoc());
1780     }
1781     return N;
1782   }
1783 
1784   // Otherwise create a new SDValue and remember it.
1785   SDValue Val = getValueImpl(V);
1786   NodeMap[V] = Val;
1787   resolveDanglingDebugInfo(V, Val);
1788   return Val;
1789 }
1790 
1791 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1792 /// Create an SDValue for the given value.
1793 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1795 
1796   if (const Constant *C = dyn_cast<Constant>(V)) {
1797     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1798 
1799     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1800       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1801 
1802     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1803       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1804 
1805     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1806       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1807                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1808                          getValue(CPA->getAddrDiscriminator()),
1809                          getValue(CPA->getDiscriminator()));
1810     }
1811 
1812     if (isa<ConstantPointerNull>(C)) {
1813       unsigned AS = V->getType()->getPointerAddressSpace();
1814       return DAG.getConstant(0, getCurSDLoc(),
1815                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1816     }
1817 
1818     if (match(C, m_VScale()))
1819       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1820 
1821     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1822       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1823 
1824     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1825       return DAG.getUNDEF(VT);
1826 
1827     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1828       visit(CE->getOpcode(), *CE);
1829       SDValue N1 = NodeMap[V];
1830       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1831       return N1;
1832     }
1833 
1834     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1835       SmallVector<SDValue, 4> Constants;
1836       for (const Use &U : C->operands()) {
1837         SDNode *Val = getValue(U).getNode();
1838         // If the operand is an empty aggregate, there are no values.
1839         if (!Val) continue;
1840         // Add each leaf value from the operand to the Constants list
1841         // to form a flattened list of all the values.
1842         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1843           Constants.push_back(SDValue(Val, i));
1844       }
1845 
1846       return DAG.getMergeValues(Constants, getCurSDLoc());
1847     }
1848 
1849     if (const ConstantDataSequential *CDS =
1850           dyn_cast<ConstantDataSequential>(C)) {
1851       SmallVector<SDValue, 4> Ops;
1852       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1853         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1854         // Add each leaf value from the operand to the Constants list
1855         // to form a flattened list of all the values.
1856         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1857           Ops.push_back(SDValue(Val, i));
1858       }
1859 
1860       if (isa<ArrayType>(CDS->getType()))
1861         return DAG.getMergeValues(Ops, getCurSDLoc());
1862       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1863     }
1864 
1865     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1866       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1867              "Unknown struct or array constant!");
1868 
1869       SmallVector<EVT, 4> ValueVTs;
1870       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1871       unsigned NumElts = ValueVTs.size();
1872       if (NumElts == 0)
1873         return SDValue(); // empty struct
1874       SmallVector<SDValue, 4> Constants(NumElts);
1875       for (unsigned i = 0; i != NumElts; ++i) {
1876         EVT EltVT = ValueVTs[i];
1877         if (isa<UndefValue>(C))
1878           Constants[i] = DAG.getUNDEF(EltVT);
1879         else if (EltVT.isFloatingPoint())
1880           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1881         else
1882           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1883       }
1884 
1885       return DAG.getMergeValues(Constants, getCurSDLoc());
1886     }
1887 
1888     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1889       return DAG.getBlockAddress(BA, VT);
1890 
1891     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1892       return getValue(Equiv->getGlobalValue());
1893 
1894     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1895       return getValue(NC->getGlobalValue());
1896 
1897     if (VT == MVT::aarch64svcount) {
1898       assert(C->isNullValue() && "Can only zero this target type!");
1899       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1900                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1901     }
1902 
1903     VectorType *VecTy = cast<VectorType>(V->getType());
1904 
1905     // Now that we know the number and type of the elements, get that number of
1906     // elements into the Ops array based on what kind of constant it is.
1907     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1908       SmallVector<SDValue, 16> Ops;
1909       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1910       for (unsigned i = 0; i != NumElements; ++i)
1911         Ops.push_back(getValue(CV->getOperand(i)));
1912 
1913       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1914     }
1915 
1916     if (isa<ConstantAggregateZero>(C)) {
1917       EVT EltVT =
1918           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1919 
1920       SDValue Op;
1921       if (EltVT.isFloatingPoint())
1922         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1923       else
1924         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1925 
1926       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1927     }
1928 
1929     llvm_unreachable("Unknown vector constant");
1930   }
1931 
1932   // If this is a static alloca, generate it as the frameindex instead of
1933   // computation.
1934   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1935     DenseMap<const AllocaInst*, int>::iterator SI =
1936       FuncInfo.StaticAllocaMap.find(AI);
1937     if (SI != FuncInfo.StaticAllocaMap.end())
1938       return DAG.getFrameIndex(
1939           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1940   }
1941 
1942   // If this is an instruction which fast-isel has deferred, select it now.
1943   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1944     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1945 
1946     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1947                      Inst->getType(), std::nullopt);
1948     SDValue Chain = DAG.getEntryNode();
1949     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1950   }
1951 
1952   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1953     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1954 
1955   if (const auto *BB = dyn_cast<BasicBlock>(V))
1956     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1957 
1958   llvm_unreachable("Can't get register for value!");
1959 }
1960 
1961 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1962   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1963   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1964   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1965   bool IsSEH = isAsynchronousEHPersonality(Pers);
1966   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1967   if (!IsSEH)
1968     CatchPadMBB->setIsEHScopeEntry();
1969   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1970   if (IsMSVCCXX || IsCoreCLR)
1971     CatchPadMBB->setIsEHFuncletEntry();
1972 }
1973 
1974 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1975   // Update machine-CFG edge.
1976   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1977   FuncInfo.MBB->addSuccessor(TargetMBB);
1978   TargetMBB->setIsEHCatchretTarget(true);
1979   DAG.getMachineFunction().setHasEHCatchret(true);
1980 
1981   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1982   bool IsSEH = isAsynchronousEHPersonality(Pers);
1983   if (IsSEH) {
1984     // If this is not a fall-through branch or optimizations are switched off,
1985     // emit the branch.
1986     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1987         TM.getOptLevel() == CodeGenOptLevel::None)
1988       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1989                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1990     return;
1991   }
1992 
1993   // Figure out the funclet membership for the catchret's successor.
1994   // This will be used by the FuncletLayout pass to determine how to order the
1995   // BB's.
1996   // A 'catchret' returns to the outer scope's color.
1997   Value *ParentPad = I.getCatchSwitchParentPad();
1998   const BasicBlock *SuccessorColor;
1999   if (isa<ConstantTokenNone>(ParentPad))
2000     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2001   else
2002     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2003   assert(SuccessorColor && "No parent funclet for catchret!");
2004   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
2005   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2006 
2007   // Create the terminator node.
2008   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2009                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2010                             DAG.getBasicBlock(SuccessorColorMBB));
2011   DAG.setRoot(Ret);
2012 }
2013 
2014 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2015   // Don't emit any special code for the cleanuppad instruction. It just marks
2016   // the start of an EH scope/funclet.
2017   FuncInfo.MBB->setIsEHScopeEntry();
2018   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2019   if (Pers != EHPersonality::Wasm_CXX) {
2020     FuncInfo.MBB->setIsEHFuncletEntry();
2021     FuncInfo.MBB->setIsCleanupFuncletEntry();
2022   }
2023 }
2024 
2025 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2026 // not match, it is OK to add only the first unwind destination catchpad to the
2027 // successors, because there will be at least one invoke instruction within the
2028 // catch scope that points to the next unwind destination, if one exists, so
2029 // CFGSort cannot mess up with BB sorting order.
2030 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2031 // call within them, and catchpads only consisting of 'catch (...)' have a
2032 // '__cxa_end_catch' call within them, both of which generate invokes in case
2033 // the next unwind destination exists, i.e., the next unwind destination is not
2034 // the caller.)
2035 //
2036 // Having at most one EH pad successor is also simpler and helps later
2037 // transformations.
2038 //
2039 // For example,
2040 // current:
2041 //   invoke void @foo to ... unwind label %catch.dispatch
2042 // catch.dispatch:
2043 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2044 // catch.start:
2045 //   ...
2046 //   ... in this BB or some other child BB dominated by this BB there will be an
2047 //   invoke that points to 'next' BB as an unwind destination
2048 //
2049 // next: ; We don't need to add this to 'current' BB's successor
2050 //   ...
2051 static void findWasmUnwindDestinations(
2052     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2053     BranchProbability Prob,
2054     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2055         &UnwindDests) {
2056   while (EHPadBB) {
2057     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2058     if (isa<CleanupPadInst>(Pad)) {
2059       // Stop on cleanup pads.
2060       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2061       UnwindDests.back().first->setIsEHScopeEntry();
2062       break;
2063     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2064       // Add the catchpad handlers to the possible destinations. We don't
2065       // continue to the unwind destination of the catchswitch for wasm.
2066       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2067         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2068         UnwindDests.back().first->setIsEHScopeEntry();
2069       }
2070       break;
2071     } else {
2072       continue;
2073     }
2074   }
2075 }
2076 
2077 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2078 /// many places it could ultimately go. In the IR, we have a single unwind
2079 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2080 /// This function skips over imaginary basic blocks that hold catchswitch
2081 /// instructions, and finds all the "real" machine
2082 /// basic block destinations. As those destinations may not be successors of
2083 /// EHPadBB, here we also calculate the edge probability to those destinations.
2084 /// The passed-in Prob is the edge probability to EHPadBB.
2085 static void findUnwindDestinations(
2086     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2087     BranchProbability Prob,
2088     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2089         &UnwindDests) {
2090   EHPersonality Personality =
2091     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2092   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2093   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2094   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2095   bool IsSEH = isAsynchronousEHPersonality(Personality);
2096 
2097   if (IsWasmCXX) {
2098     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2099     assert(UnwindDests.size() <= 1 &&
2100            "There should be at most one unwind destination for wasm");
2101     return;
2102   }
2103 
2104   while (EHPadBB) {
2105     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2106     BasicBlock *NewEHPadBB = nullptr;
2107     if (isa<LandingPadInst>(Pad)) {
2108       // Stop on landingpads. They are not funclets.
2109       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2110       break;
2111     } else if (isa<CleanupPadInst>(Pad)) {
2112       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2113       // personalities.
2114       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2115       UnwindDests.back().first->setIsEHScopeEntry();
2116       UnwindDests.back().first->setIsEHFuncletEntry();
2117       break;
2118     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2119       // Add the catchpad handlers to the possible destinations.
2120       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2121         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2122         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2123         if (IsMSVCCXX || IsCoreCLR)
2124           UnwindDests.back().first->setIsEHFuncletEntry();
2125         if (!IsSEH)
2126           UnwindDests.back().first->setIsEHScopeEntry();
2127       }
2128       NewEHPadBB = CatchSwitch->getUnwindDest();
2129     } else {
2130       continue;
2131     }
2132 
2133     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2134     if (BPI && NewEHPadBB)
2135       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2136     EHPadBB = NewEHPadBB;
2137   }
2138 }
2139 
2140 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2141   // Update successor info.
2142   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2143   auto UnwindDest = I.getUnwindDest();
2144   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2145   BranchProbability UnwindDestProb =
2146       (BPI && UnwindDest)
2147           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2148           : BranchProbability::getZero();
2149   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2150   for (auto &UnwindDest : UnwindDests) {
2151     UnwindDest.first->setIsEHPad();
2152     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2153   }
2154   FuncInfo.MBB->normalizeSuccProbs();
2155 
2156   // Create the terminator node.
2157   SDValue Ret =
2158       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2159   DAG.setRoot(Ret);
2160 }
2161 
2162 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2163   report_fatal_error("visitCatchSwitch not yet implemented!");
2164 }
2165 
2166 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2168   auto &DL = DAG.getDataLayout();
2169   SDValue Chain = getControlRoot();
2170   SmallVector<ISD::OutputArg, 8> Outs;
2171   SmallVector<SDValue, 8> OutVals;
2172 
2173   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2174   // lower
2175   //
2176   //   %val = call <ty> @llvm.experimental.deoptimize()
2177   //   ret <ty> %val
2178   //
2179   // differently.
2180   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2181     LowerDeoptimizingReturn();
2182     return;
2183   }
2184 
2185   if (!FuncInfo.CanLowerReturn) {
2186     unsigned DemoteReg = FuncInfo.DemoteRegister;
2187     const Function *F = I.getParent()->getParent();
2188 
2189     // Emit a store of the return value through the virtual register.
2190     // Leave Outs empty so that LowerReturn won't try to load return
2191     // registers the usual way.
2192     SmallVector<EVT, 1> PtrValueVTs;
2193     ComputeValueVTs(TLI, DL,
2194                     PointerType::get(F->getContext(),
2195                                      DAG.getDataLayout().getAllocaAddrSpace()),
2196                     PtrValueVTs);
2197 
2198     SDValue RetPtr =
2199         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2200     SDValue RetOp = getValue(I.getOperand(0));
2201 
2202     SmallVector<EVT, 4> ValueVTs, MemVTs;
2203     SmallVector<uint64_t, 4> Offsets;
2204     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2205                     &Offsets, 0);
2206     unsigned NumValues = ValueVTs.size();
2207 
2208     SmallVector<SDValue, 4> Chains(NumValues);
2209     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2210     for (unsigned i = 0; i != NumValues; ++i) {
2211       // An aggregate return value cannot wrap around the address space, so
2212       // offsets to its parts don't wrap either.
2213       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2214                                            TypeSize::getFixed(Offsets[i]));
2215 
2216       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2217       if (MemVTs[i] != ValueVTs[i])
2218         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2219       Chains[i] = DAG.getStore(
2220           Chain, getCurSDLoc(), Val,
2221           // FIXME: better loc info would be nice.
2222           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2223           commonAlignment(BaseAlign, Offsets[i]));
2224     }
2225 
2226     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2227                         MVT::Other, Chains);
2228   } else if (I.getNumOperands() != 0) {
2229     SmallVector<EVT, 4> ValueVTs;
2230     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2231     unsigned NumValues = ValueVTs.size();
2232     if (NumValues) {
2233       SDValue RetOp = getValue(I.getOperand(0));
2234 
2235       const Function *F = I.getParent()->getParent();
2236 
2237       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2238           I.getOperand(0)->getType(), F->getCallingConv(),
2239           /*IsVarArg*/ false, DL);
2240 
2241       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2242       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2243         ExtendKind = ISD::SIGN_EXTEND;
2244       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2245         ExtendKind = ISD::ZERO_EXTEND;
2246 
2247       LLVMContext &Context = F->getContext();
2248       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2249 
2250       for (unsigned j = 0; j != NumValues; ++j) {
2251         EVT VT = ValueVTs[j];
2252 
2253         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2254           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2255 
2256         CallingConv::ID CC = F->getCallingConv();
2257 
2258         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2259         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2260         SmallVector<SDValue, 4> Parts(NumParts);
2261         getCopyToParts(DAG, getCurSDLoc(),
2262                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2263                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2264 
2265         // 'inreg' on function refers to return value
2266         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2267         if (RetInReg)
2268           Flags.setInReg();
2269 
2270         if (I.getOperand(0)->getType()->isPointerTy()) {
2271           Flags.setPointer();
2272           Flags.setPointerAddrSpace(
2273               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2274         }
2275 
2276         if (NeedsRegBlock) {
2277           Flags.setInConsecutiveRegs();
2278           if (j == NumValues - 1)
2279             Flags.setInConsecutiveRegsLast();
2280         }
2281 
2282         // Propagate extension type if any
2283         if (ExtendKind == ISD::SIGN_EXTEND)
2284           Flags.setSExt();
2285         else if (ExtendKind == ISD::ZERO_EXTEND)
2286           Flags.setZExt();
2287 
2288         for (unsigned i = 0; i < NumParts; ++i) {
2289           Outs.push_back(ISD::OutputArg(Flags,
2290                                         Parts[i].getValueType().getSimpleVT(),
2291                                         VT, /*isfixed=*/true, 0, 0));
2292           OutVals.push_back(Parts[i]);
2293         }
2294       }
2295     }
2296   }
2297 
2298   // Push in swifterror virtual register as the last element of Outs. This makes
2299   // sure swifterror virtual register will be returned in the swifterror
2300   // physical register.
2301   const Function *F = I.getParent()->getParent();
2302   if (TLI.supportSwiftError() &&
2303       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2304     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2305     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2306     Flags.setSwiftError();
2307     Outs.push_back(ISD::OutputArg(
2308         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2309         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2310     // Create SDNode for the swifterror virtual register.
2311     OutVals.push_back(
2312         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2313                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2314                         EVT(TLI.getPointerTy(DL))));
2315   }
2316 
2317   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2318   CallingConv::ID CallConv =
2319     DAG.getMachineFunction().getFunction().getCallingConv();
2320   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2321       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2322 
2323   // Verify that the target's LowerReturn behaved as expected.
2324   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2325          "LowerReturn didn't return a valid chain!");
2326 
2327   // Update the DAG with the new chain value resulting from return lowering.
2328   DAG.setRoot(Chain);
2329 }
2330 
2331 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2332 /// created for it, emit nodes to copy the value into the virtual
2333 /// registers.
2334 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2335   // Skip empty types
2336   if (V->getType()->isEmptyTy())
2337     return;
2338 
2339   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2340   if (VMI != FuncInfo.ValueMap.end()) {
2341     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2342            "Unused value assigned virtual registers!");
2343     CopyValueToVirtualRegister(V, VMI->second);
2344   }
2345 }
2346 
2347 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2348 /// the current basic block, add it to ValueMap now so that we'll get a
2349 /// CopyTo/FromReg.
2350 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2351   // No need to export constants.
2352   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2353 
2354   // Already exported?
2355   if (FuncInfo.isExportedInst(V)) return;
2356 
2357   Register Reg = FuncInfo.InitializeRegForValue(V);
2358   CopyValueToVirtualRegister(V, Reg);
2359 }
2360 
2361 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2362                                                      const BasicBlock *FromBB) {
2363   // The operands of the setcc have to be in this block.  We don't know
2364   // how to export them from some other block.
2365   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2366     // Can export from current BB.
2367     if (VI->getParent() == FromBB)
2368       return true;
2369 
2370     // Is already exported, noop.
2371     return FuncInfo.isExportedInst(V);
2372   }
2373 
2374   // If this is an argument, we can export it if the BB is the entry block or
2375   // if it is already exported.
2376   if (isa<Argument>(V)) {
2377     if (FromBB->isEntryBlock())
2378       return true;
2379 
2380     // Otherwise, can only export this if it is already exported.
2381     return FuncInfo.isExportedInst(V);
2382   }
2383 
2384   // Otherwise, constants can always be exported.
2385   return true;
2386 }
2387 
2388 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2389 BranchProbability
2390 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2391                                         const MachineBasicBlock *Dst) const {
2392   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2393   const BasicBlock *SrcBB = Src->getBasicBlock();
2394   const BasicBlock *DstBB = Dst->getBasicBlock();
2395   if (!BPI) {
2396     // If BPI is not available, set the default probability as 1 / N, where N is
2397     // the number of successors.
2398     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2399     return BranchProbability(1, SuccSize);
2400   }
2401   return BPI->getEdgeProbability(SrcBB, DstBB);
2402 }
2403 
2404 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2405                                                MachineBasicBlock *Dst,
2406                                                BranchProbability Prob) {
2407   if (!FuncInfo.BPI)
2408     Src->addSuccessorWithoutProb(Dst);
2409   else {
2410     if (Prob.isUnknown())
2411       Prob = getEdgeProbability(Src, Dst);
2412     Src->addSuccessor(Dst, Prob);
2413   }
2414 }
2415 
2416 static bool InBlock(const Value *V, const BasicBlock *BB) {
2417   if (const Instruction *I = dyn_cast<Instruction>(V))
2418     return I->getParent() == BB;
2419   return true;
2420 }
2421 
2422 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2423 /// This function emits a branch and is used at the leaves of an OR or an
2424 /// AND operator tree.
2425 void
2426 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2427                                                   MachineBasicBlock *TBB,
2428                                                   MachineBasicBlock *FBB,
2429                                                   MachineBasicBlock *CurBB,
2430                                                   MachineBasicBlock *SwitchBB,
2431                                                   BranchProbability TProb,
2432                                                   BranchProbability FProb,
2433                                                   bool InvertCond) {
2434   const BasicBlock *BB = CurBB->getBasicBlock();
2435 
2436   // If the leaf of the tree is a comparison, merge the condition into
2437   // the caseblock.
2438   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2439     // The operands of the cmp have to be in this block.  We don't know
2440     // how to export them from some other block.  If this is the first block
2441     // of the sequence, no exporting is needed.
2442     if (CurBB == SwitchBB ||
2443         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2444          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2445       ISD::CondCode Condition;
2446       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2447         ICmpInst::Predicate Pred =
2448             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2449         Condition = getICmpCondCode(Pred);
2450       } else {
2451         const FCmpInst *FC = cast<FCmpInst>(Cond);
2452         FCmpInst::Predicate Pred =
2453             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2454         Condition = getFCmpCondCode(Pred);
2455         if (TM.Options.NoNaNsFPMath)
2456           Condition = getFCmpCodeWithoutNaN(Condition);
2457       }
2458 
2459       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2460                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2461       SL->SwitchCases.push_back(CB);
2462       return;
2463     }
2464   }
2465 
2466   // Create a CaseBlock record representing this branch.
2467   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2468   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2469                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2470   SL->SwitchCases.push_back(CB);
2471 }
2472 
2473 // Collect dependencies on V recursively. This is used for the cost analysis in
2474 // `shouldKeepJumpConditionsTogether`.
2475 static bool collectInstructionDeps(
2476     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2477     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2478     unsigned Depth = 0) {
2479   // Return false if we have an incomplete count.
2480   if (Depth >= SelectionDAG::MaxRecursionDepth)
2481     return false;
2482 
2483   auto *I = dyn_cast<Instruction>(V);
2484   if (I == nullptr)
2485     return true;
2486 
2487   if (Necessary != nullptr) {
2488     // This instruction is necessary for the other side of the condition so
2489     // don't count it.
2490     if (Necessary->contains(I))
2491       return true;
2492   }
2493 
2494   // Already added this dep.
2495   if (!Deps->try_emplace(I, false).second)
2496     return true;
2497 
2498   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2499     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2500                                 Depth + 1))
2501       return false;
2502   return true;
2503 }
2504 
2505 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2506     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2507     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2508     TargetLoweringBase::CondMergingParams Params) const {
2509   if (I.getNumSuccessors() != 2)
2510     return false;
2511 
2512   if (!I.isConditional())
2513     return false;
2514 
2515   if (Params.BaseCost < 0)
2516     return false;
2517 
2518   // Baseline cost.
2519   InstructionCost CostThresh = Params.BaseCost;
2520 
2521   BranchProbabilityInfo *BPI = nullptr;
2522   if (Params.LikelyBias || Params.UnlikelyBias)
2523     BPI = FuncInfo.BPI;
2524   if (BPI != nullptr) {
2525     // See if we are either likely to get an early out or compute both lhs/rhs
2526     // of the condition.
2527     BasicBlock *IfFalse = I.getSuccessor(0);
2528     BasicBlock *IfTrue = I.getSuccessor(1);
2529 
2530     std::optional<bool> Likely;
2531     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2532       Likely = true;
2533     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2534       Likely = false;
2535 
2536     if (Likely) {
2537       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2538         // Its likely we will have to compute both lhs and rhs of condition
2539         CostThresh += Params.LikelyBias;
2540       else {
2541         if (Params.UnlikelyBias < 0)
2542           return false;
2543         // Its likely we will get an early out.
2544         CostThresh -= Params.UnlikelyBias;
2545       }
2546     }
2547   }
2548 
2549   if (CostThresh <= 0)
2550     return false;
2551 
2552   // Collect "all" instructions that lhs condition is dependent on.
2553   // Use map for stable iteration (to avoid non-determanism of iteration of
2554   // SmallPtrSet). The `bool` value is just a dummy.
2555   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2556   collectInstructionDeps(&LhsDeps, Lhs);
2557   // Collect "all" instructions that rhs condition is dependent on AND are
2558   // dependencies of lhs. This gives us an estimate on which instructions we
2559   // stand to save by splitting the condition.
2560   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2561     return false;
2562   // Add the compare instruction itself unless its a dependency on the LHS.
2563   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2564     if (!LhsDeps.contains(RhsI))
2565       RhsDeps.try_emplace(RhsI, false);
2566 
2567   const auto &TLI = DAG.getTargetLoweringInfo();
2568   const auto &TTI =
2569       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2570 
2571   InstructionCost CostOfIncluding = 0;
2572   // See if this instruction will need to computed independently of whether RHS
2573   // is.
2574   Value *BrCond = I.getCondition();
2575   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2576     for (const auto *U : Ins->users()) {
2577       // If user is independent of RHS calculation we don't need to count it.
2578       if (auto *UIns = dyn_cast<Instruction>(U))
2579         if (UIns != BrCond && !RhsDeps.contains(UIns))
2580           return false;
2581     }
2582     return true;
2583   };
2584 
2585   // Prune instructions from RHS Deps that are dependencies of unrelated
2586   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2587   // arbitrary and just meant to cap the how much time we spend in the pruning
2588   // loop. Its highly unlikely to come into affect.
2589   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2590   // Stop after a certain point. No incorrectness from including too many
2591   // instructions.
2592   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2593     const Instruction *ToDrop = nullptr;
2594     for (const auto &InsPair : RhsDeps) {
2595       if (!ShouldCountInsn(InsPair.first)) {
2596         ToDrop = InsPair.first;
2597         break;
2598       }
2599     }
2600     if (ToDrop == nullptr)
2601       break;
2602     RhsDeps.erase(ToDrop);
2603   }
2604 
2605   for (const auto &InsPair : RhsDeps) {
2606     // Finally accumulate latency that we can only attribute to computing the
2607     // RHS condition. Use latency because we are essentially trying to calculate
2608     // the cost of the dependency chain.
2609     // Possible TODO: We could try to estimate ILP and make this more precise.
2610     CostOfIncluding +=
2611         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2612 
2613     if (CostOfIncluding > CostThresh)
2614       return false;
2615   }
2616   return true;
2617 }
2618 
2619 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2620                                                MachineBasicBlock *TBB,
2621                                                MachineBasicBlock *FBB,
2622                                                MachineBasicBlock *CurBB,
2623                                                MachineBasicBlock *SwitchBB,
2624                                                Instruction::BinaryOps Opc,
2625                                                BranchProbability TProb,
2626                                                BranchProbability FProb,
2627                                                bool InvertCond) {
2628   // Skip over not part of the tree and remember to invert op and operands at
2629   // next level.
2630   Value *NotCond;
2631   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2632       InBlock(NotCond, CurBB->getBasicBlock())) {
2633     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2634                          !InvertCond);
2635     return;
2636   }
2637 
2638   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2639   const Value *BOpOp0, *BOpOp1;
2640   // Compute the effective opcode for Cond, taking into account whether it needs
2641   // to be inverted, e.g.
2642   //   and (not (or A, B)), C
2643   // gets lowered as
2644   //   and (and (not A, not B), C)
2645   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2646   if (BOp) {
2647     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2648                ? Instruction::And
2649                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2650                       ? Instruction::Or
2651                       : (Instruction::BinaryOps)0);
2652     if (InvertCond) {
2653       if (BOpc == Instruction::And)
2654         BOpc = Instruction::Or;
2655       else if (BOpc == Instruction::Or)
2656         BOpc = Instruction::And;
2657     }
2658   }
2659 
2660   // If this node is not part of the or/and tree, emit it as a branch.
2661   // Note that all nodes in the tree should have same opcode.
2662   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2663   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2664       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2665       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2666     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2667                                  TProb, FProb, InvertCond);
2668     return;
2669   }
2670 
2671   //  Create TmpBB after CurBB.
2672   MachineFunction::iterator BBI(CurBB);
2673   MachineFunction &MF = DAG.getMachineFunction();
2674   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2675   CurBB->getParent()->insert(++BBI, TmpBB);
2676 
2677   if (Opc == Instruction::Or) {
2678     // Codegen X | Y as:
2679     // BB1:
2680     //   jmp_if_X TBB
2681     //   jmp TmpBB
2682     // TmpBB:
2683     //   jmp_if_Y TBB
2684     //   jmp FBB
2685     //
2686 
2687     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2688     // The requirement is that
2689     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2690     //     = TrueProb for original BB.
2691     // Assuming the original probabilities are A and B, one choice is to set
2692     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2693     // A/(1+B) and 2B/(1+B). This choice assumes that
2694     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2695     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2696     // TmpBB, but the math is more complicated.
2697 
2698     auto NewTrueProb = TProb / 2;
2699     auto NewFalseProb = TProb / 2 + FProb;
2700     // Emit the LHS condition.
2701     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2702                          NewFalseProb, InvertCond);
2703 
2704     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2705     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2706     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2707     // Emit the RHS condition into TmpBB.
2708     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2709                          Probs[1], InvertCond);
2710   } else {
2711     assert(Opc == Instruction::And && "Unknown merge op!");
2712     // Codegen X & Y as:
2713     // BB1:
2714     //   jmp_if_X TmpBB
2715     //   jmp FBB
2716     // TmpBB:
2717     //   jmp_if_Y TBB
2718     //   jmp FBB
2719     //
2720     //  This requires creation of TmpBB after CurBB.
2721 
2722     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2723     // The requirement is that
2724     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2725     //     = FalseProb for original BB.
2726     // Assuming the original probabilities are A and B, one choice is to set
2727     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2728     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2729     // TrueProb for BB1 * FalseProb for TmpBB.
2730 
2731     auto NewTrueProb = TProb + FProb / 2;
2732     auto NewFalseProb = FProb / 2;
2733     // Emit the LHS condition.
2734     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2735                          NewFalseProb, InvertCond);
2736 
2737     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2738     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2739     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2740     // Emit the RHS condition into TmpBB.
2741     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2742                          Probs[1], InvertCond);
2743   }
2744 }
2745 
2746 /// If the set of cases should be emitted as a series of branches, return true.
2747 /// If we should emit this as a bunch of and/or'd together conditions, return
2748 /// false.
2749 bool
2750 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2751   if (Cases.size() != 2) return true;
2752 
2753   // If this is two comparisons of the same values or'd or and'd together, they
2754   // will get folded into a single comparison, so don't emit two blocks.
2755   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2756        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2757       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2758        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2759     return false;
2760   }
2761 
2762   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2763   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2764   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2765       Cases[0].CC == Cases[1].CC &&
2766       isa<Constant>(Cases[0].CmpRHS) &&
2767       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2768     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2769       return false;
2770     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2771       return false;
2772   }
2773 
2774   return true;
2775 }
2776 
2777 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2778   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2779 
2780   // Update machine-CFG edges.
2781   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2782 
2783   if (I.isUnconditional()) {
2784     // Update machine-CFG edges.
2785     BrMBB->addSuccessor(Succ0MBB);
2786 
2787     // If this is not a fall-through branch or optimizations are switched off,
2788     // emit the branch.
2789     if (Succ0MBB != NextBlock(BrMBB) ||
2790         TM.getOptLevel() == CodeGenOptLevel::None) {
2791       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2792                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2793       setValue(&I, Br);
2794       DAG.setRoot(Br);
2795     }
2796 
2797     return;
2798   }
2799 
2800   // If this condition is one of the special cases we handle, do special stuff
2801   // now.
2802   const Value *CondVal = I.getCondition();
2803   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2804 
2805   // If this is a series of conditions that are or'd or and'd together, emit
2806   // this as a sequence of branches instead of setcc's with and/or operations.
2807   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2808   // unpredictable branches, and vector extracts because those jumps are likely
2809   // expensive for any target), this should improve performance.
2810   // For example, instead of something like:
2811   //     cmp A, B
2812   //     C = seteq
2813   //     cmp D, E
2814   //     F = setle
2815   //     or C, F
2816   //     jnz foo
2817   // Emit:
2818   //     cmp A, B
2819   //     je foo
2820   //     cmp D, E
2821   //     jle foo
2822   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2823   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2824       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2825     Value *Vec;
2826     const Value *BOp0, *BOp1;
2827     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2828     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2829       Opcode = Instruction::And;
2830     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2831       Opcode = Instruction::Or;
2832 
2833     if (Opcode &&
2834         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2835           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2836         !shouldKeepJumpConditionsTogether(
2837             FuncInfo, I, Opcode, BOp0, BOp1,
2838             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2839                 Opcode, BOp0, BOp1))) {
2840       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2841                            getEdgeProbability(BrMBB, Succ0MBB),
2842                            getEdgeProbability(BrMBB, Succ1MBB),
2843                            /*InvertCond=*/false);
2844       // If the compares in later blocks need to use values not currently
2845       // exported from this block, export them now.  This block should always
2846       // be the first entry.
2847       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2848 
2849       // Allow some cases to be rejected.
2850       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2851         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2852           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2854         }
2855 
2856         // Emit the branch for this block.
2857         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2858         SL->SwitchCases.erase(SL->SwitchCases.begin());
2859         return;
2860       }
2861 
2862       // Okay, we decided not to do this, remove any inserted MBB's and clear
2863       // SwitchCases.
2864       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2865         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2866 
2867       SL->SwitchCases.clear();
2868     }
2869   }
2870 
2871   // Create a CaseBlock record representing this branch.
2872   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2873                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2874 
2875   // Use visitSwitchCase to actually insert the fast branch sequence for this
2876   // cond branch.
2877   visitSwitchCase(CB, BrMBB);
2878 }
2879 
2880 /// visitSwitchCase - Emits the necessary code to represent a single node in
2881 /// the binary search tree resulting from lowering a switch instruction.
2882 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2883                                           MachineBasicBlock *SwitchBB) {
2884   SDValue Cond;
2885   SDValue CondLHS = getValue(CB.CmpLHS);
2886   SDLoc dl = CB.DL;
2887 
2888   if (CB.CC == ISD::SETTRUE) {
2889     // Branch or fall through to TrueBB.
2890     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2891     SwitchBB->normalizeSuccProbs();
2892     if (CB.TrueBB != NextBlock(SwitchBB)) {
2893       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2894                               DAG.getBasicBlock(CB.TrueBB)));
2895     }
2896     return;
2897   }
2898 
2899   auto &TLI = DAG.getTargetLoweringInfo();
2900   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2901 
2902   // Build the setcc now.
2903   if (!CB.CmpMHS) {
2904     // Fold "(X == true)" to X and "(X == false)" to !X to
2905     // handle common cases produced by branch lowering.
2906     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2907         CB.CC == ISD::SETEQ)
2908       Cond = CondLHS;
2909     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2910              CB.CC == ISD::SETEQ) {
2911       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2912       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2913     } else {
2914       SDValue CondRHS = getValue(CB.CmpRHS);
2915 
2916       // If a pointer's DAG type is larger than its memory type then the DAG
2917       // values are zero-extended. This breaks signed comparisons so truncate
2918       // back to the underlying type before doing the compare.
2919       if (CondLHS.getValueType() != MemVT) {
2920         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2921         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2922       }
2923       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2924     }
2925   } else {
2926     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2927 
2928     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2929     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2930 
2931     SDValue CmpOp = getValue(CB.CmpMHS);
2932     EVT VT = CmpOp.getValueType();
2933 
2934     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2935       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2936                           ISD::SETLE);
2937     } else {
2938       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2939                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2940       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2941                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2942     }
2943   }
2944 
2945   // Update successor info
2946   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2947   // TrueBB and FalseBB are always different unless the incoming IR is
2948   // degenerate. This only happens when running llc on weird IR.
2949   if (CB.TrueBB != CB.FalseBB)
2950     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2951   SwitchBB->normalizeSuccProbs();
2952 
2953   // If the lhs block is the next block, invert the condition so that we can
2954   // fall through to the lhs instead of the rhs block.
2955   if (CB.TrueBB == NextBlock(SwitchBB)) {
2956     std::swap(CB.TrueBB, CB.FalseBB);
2957     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2958     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2959   }
2960 
2961   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2962                                MVT::Other, getControlRoot(), Cond,
2963                                DAG.getBasicBlock(CB.TrueBB));
2964 
2965   setValue(CurInst, BrCond);
2966 
2967   // Insert the false branch. Do this even if it's a fall through branch,
2968   // this makes it easier to do DAG optimizations which require inverting
2969   // the branch condition.
2970   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2971                        DAG.getBasicBlock(CB.FalseBB));
2972 
2973   DAG.setRoot(BrCond);
2974 }
2975 
2976 /// visitJumpTable - Emit JumpTable node in the current MBB
2977 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2978   // Emit the code for the jump table
2979   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2980   assert(JT.Reg != -1U && "Should lower JT Header first!");
2981   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2982   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2983   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2984   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2985                                     Index.getValue(1), Table, Index);
2986   DAG.setRoot(BrJumpTable);
2987 }
2988 
2989 /// visitJumpTableHeader - This function emits necessary code to produce index
2990 /// in the JumpTable from switch case.
2991 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2992                                                JumpTableHeader &JTH,
2993                                                MachineBasicBlock *SwitchBB) {
2994   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2995   const SDLoc &dl = *JT.SL;
2996 
2997   // Subtract the lowest switch case value from the value being switched on.
2998   SDValue SwitchOp = getValue(JTH.SValue);
2999   EVT VT = SwitchOp.getValueType();
3000   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3001                             DAG.getConstant(JTH.First, dl, VT));
3002 
3003   // The SDNode we just created, which holds the value being switched on minus
3004   // the smallest case value, needs to be copied to a virtual register so it
3005   // can be used as an index into the jump table in a subsequent basic block.
3006   // This value may be smaller or larger than the target's pointer type, and
3007   // therefore require extension or truncating.
3008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3009   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
3010 
3011   unsigned JumpTableReg =
3012       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
3013   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
3014                                     JumpTableReg, SwitchOp);
3015   JT.Reg = JumpTableReg;
3016 
3017   if (!JTH.FallthroughUnreachable) {
3018     // Emit the range check for the jump table, and branch to the default block
3019     // for the switch statement if the value being switched on exceeds the
3020     // largest case in the switch.
3021     SDValue CMP = DAG.getSetCC(
3022         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3023                                    Sub.getValueType()),
3024         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3025 
3026     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3027                                  MVT::Other, CopyTo, CMP,
3028                                  DAG.getBasicBlock(JT.Default));
3029 
3030     // Avoid emitting unnecessary branches to the next block.
3031     if (JT.MBB != NextBlock(SwitchBB))
3032       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3033                            DAG.getBasicBlock(JT.MBB));
3034 
3035     DAG.setRoot(BrCond);
3036   } else {
3037     // Avoid emitting unnecessary branches to the next block.
3038     if (JT.MBB != NextBlock(SwitchBB))
3039       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3040                               DAG.getBasicBlock(JT.MBB)));
3041     else
3042       DAG.setRoot(CopyTo);
3043   }
3044 }
3045 
3046 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3047 /// variable if there exists one.
3048 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3049                                  SDValue &Chain) {
3050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3051   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3052   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3053   MachineFunction &MF = DAG.getMachineFunction();
3054   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3055   MachineSDNode *Node =
3056       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3057   if (Global) {
3058     MachinePointerInfo MPInfo(Global);
3059     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3060                  MachineMemOperand::MODereferenceable;
3061     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3062         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3063         DAG.getEVTAlign(PtrTy));
3064     DAG.setNodeMemRefs(Node, {MemRef});
3065   }
3066   if (PtrTy != PtrMemTy)
3067     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3068   return SDValue(Node, 0);
3069 }
3070 
3071 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3072 /// tail spliced into a stack protector check success bb.
3073 ///
3074 /// For a high level explanation of how this fits into the stack protector
3075 /// generation see the comment on the declaration of class
3076 /// StackProtectorDescriptor.
3077 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3078                                                   MachineBasicBlock *ParentBB) {
3079 
3080   // First create the loads to the guard/stack slot for the comparison.
3081   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3082   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3083   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3084 
3085   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3086   int FI = MFI.getStackProtectorIndex();
3087 
3088   SDValue Guard;
3089   SDLoc dl = getCurSDLoc();
3090   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3091   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3092   Align Align =
3093       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3094 
3095   // Generate code to load the content of the guard slot.
3096   SDValue GuardVal = DAG.getLoad(
3097       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3098       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3099       MachineMemOperand::MOVolatile);
3100 
3101   if (TLI.useStackGuardXorFP())
3102     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3103 
3104   // Retrieve guard check function, nullptr if instrumentation is inlined.
3105   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3106     // The target provides a guard check function to validate the guard value.
3107     // Generate a call to that function with the content of the guard slot as
3108     // argument.
3109     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3110     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3111 
3112     TargetLowering::ArgListTy Args;
3113     TargetLowering::ArgListEntry Entry;
3114     Entry.Node = GuardVal;
3115     Entry.Ty = FnTy->getParamType(0);
3116     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3117       Entry.IsInReg = true;
3118     Args.push_back(Entry);
3119 
3120     TargetLowering::CallLoweringInfo CLI(DAG);
3121     CLI.setDebugLoc(getCurSDLoc())
3122         .setChain(DAG.getEntryNode())
3123         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3124                    getValue(GuardCheckFn), std::move(Args));
3125 
3126     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3127     DAG.setRoot(Result.second);
3128     return;
3129   }
3130 
3131   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3132   // Otherwise, emit a volatile load to retrieve the stack guard value.
3133   SDValue Chain = DAG.getEntryNode();
3134   if (TLI.useLoadStackGuardNode()) {
3135     Guard = getLoadStackGuard(DAG, dl, Chain);
3136   } else {
3137     const Value *IRGuard = TLI.getSDagStackGuard(M);
3138     SDValue GuardPtr = getValue(IRGuard);
3139 
3140     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3141                         MachinePointerInfo(IRGuard, 0), Align,
3142                         MachineMemOperand::MOVolatile);
3143   }
3144 
3145   // Perform the comparison via a getsetcc.
3146   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3147                                                         *DAG.getContext(),
3148                                                         Guard.getValueType()),
3149                              Guard, GuardVal, ISD::SETNE);
3150 
3151   // If the guard/stackslot do not equal, branch to failure MBB.
3152   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3153                                MVT::Other, GuardVal.getOperand(0),
3154                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3155   // Otherwise branch to success MBB.
3156   SDValue Br = DAG.getNode(ISD::BR, dl,
3157                            MVT::Other, BrCond,
3158                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3159 
3160   DAG.setRoot(Br);
3161 }
3162 
3163 /// Codegen the failure basic block for a stack protector check.
3164 ///
3165 /// A failure stack protector machine basic block consists simply of a call to
3166 /// __stack_chk_fail().
3167 ///
3168 /// For a high level explanation of how this fits into the stack protector
3169 /// generation see the comment on the declaration of class
3170 /// StackProtectorDescriptor.
3171 void
3172 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3174   TargetLowering::MakeLibCallOptions CallOptions;
3175   CallOptions.setDiscardResult(true);
3176   SDValue Chain =
3177       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3178                       std::nullopt, CallOptions, getCurSDLoc())
3179           .second;
3180   // On PS4/PS5, the "return address" must still be within the calling
3181   // function, even if it's at the very end, so emit an explicit TRAP here.
3182   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3183   if (TM.getTargetTriple().isPS())
3184     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3185   // WebAssembly needs an unreachable instruction after a non-returning call,
3186   // because the function return type can be different from __stack_chk_fail's
3187   // return type (void).
3188   if (TM.getTargetTriple().isWasm())
3189     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3190 
3191   DAG.setRoot(Chain);
3192 }
3193 
3194 /// visitBitTestHeader - This function emits necessary code to produce value
3195 /// suitable for "bit tests"
3196 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3197                                              MachineBasicBlock *SwitchBB) {
3198   SDLoc dl = getCurSDLoc();
3199 
3200   // Subtract the minimum value.
3201   SDValue SwitchOp = getValue(B.SValue);
3202   EVT VT = SwitchOp.getValueType();
3203   SDValue RangeSub =
3204       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3205 
3206   // Determine the type of the test operands.
3207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3208   bool UsePtrType = false;
3209   if (!TLI.isTypeLegal(VT)) {
3210     UsePtrType = true;
3211   } else {
3212     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3213       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3214         // Switch table case range are encoded into series of masks.
3215         // Just use pointer type, it's guaranteed to fit.
3216         UsePtrType = true;
3217         break;
3218       }
3219   }
3220   SDValue Sub = RangeSub;
3221   if (UsePtrType) {
3222     VT = TLI.getPointerTy(DAG.getDataLayout());
3223     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3224   }
3225 
3226   B.RegVT = VT.getSimpleVT();
3227   B.Reg = FuncInfo.CreateReg(B.RegVT);
3228   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3229 
3230   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3231 
3232   if (!B.FallthroughUnreachable)
3233     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3234   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3235   SwitchBB->normalizeSuccProbs();
3236 
3237   SDValue Root = CopyTo;
3238   if (!B.FallthroughUnreachable) {
3239     // Conditional branch to the default block.
3240     SDValue RangeCmp = DAG.getSetCC(dl,
3241         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3242                                RangeSub.getValueType()),
3243         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3244         ISD::SETUGT);
3245 
3246     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3247                        DAG.getBasicBlock(B.Default));
3248   }
3249 
3250   // Avoid emitting unnecessary branches to the next block.
3251   if (MBB != NextBlock(SwitchBB))
3252     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3253 
3254   DAG.setRoot(Root);
3255 }
3256 
3257 /// visitBitTestCase - this function produces one "bit test"
3258 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3259                                            MachineBasicBlock* NextMBB,
3260                                            BranchProbability BranchProbToNext,
3261                                            unsigned Reg,
3262                                            BitTestCase &B,
3263                                            MachineBasicBlock *SwitchBB) {
3264   SDLoc dl = getCurSDLoc();
3265   MVT VT = BB.RegVT;
3266   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3267   SDValue Cmp;
3268   unsigned PopCount = llvm::popcount(B.Mask);
3269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3270   if (PopCount == 1) {
3271     // Testing for a single bit; just compare the shift count with what it
3272     // would need to be to shift a 1 bit in that position.
3273     Cmp = DAG.getSetCC(
3274         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3275         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3276         ISD::SETEQ);
3277   } else if (PopCount == BB.Range) {
3278     // There is only one zero bit in the range, test for it directly.
3279     Cmp = DAG.getSetCC(
3280         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3281         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3282   } else {
3283     // Make desired shift
3284     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3285                                     DAG.getConstant(1, dl, VT), ShiftOp);
3286 
3287     // Emit bit tests and jumps
3288     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3289                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3290     Cmp = DAG.getSetCC(
3291         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3292         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3293   }
3294 
3295   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3296   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3297   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3298   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3299   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3300   // one as they are relative probabilities (and thus work more like weights),
3301   // and hence we need to normalize them to let the sum of them become one.
3302   SwitchBB->normalizeSuccProbs();
3303 
3304   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3305                               MVT::Other, getControlRoot(),
3306                               Cmp, DAG.getBasicBlock(B.TargetBB));
3307 
3308   // Avoid emitting unnecessary branches to the next block.
3309   if (NextMBB != NextBlock(SwitchBB))
3310     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3311                         DAG.getBasicBlock(NextMBB));
3312 
3313   DAG.setRoot(BrAnd);
3314 }
3315 
3316 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3317   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3318 
3319   // Retrieve successors. Look through artificial IR level blocks like
3320   // catchswitch for successors.
3321   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3322   const BasicBlock *EHPadBB = I.getSuccessor(1);
3323   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3324 
3325   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3326   // have to do anything here to lower funclet bundles.
3327   assert(!I.hasOperandBundlesOtherThan(
3328              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3329               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3330               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3331               LLVMContext::OB_clang_arc_attachedcall}) &&
3332          "Cannot lower invokes with arbitrary operand bundles yet!");
3333 
3334   const Value *Callee(I.getCalledOperand());
3335   const Function *Fn = dyn_cast<Function>(Callee);
3336   if (isa<InlineAsm>(Callee))
3337     visitInlineAsm(I, EHPadBB);
3338   else if (Fn && Fn->isIntrinsic()) {
3339     switch (Fn->getIntrinsicID()) {
3340     default:
3341       llvm_unreachable("Cannot invoke this intrinsic");
3342     case Intrinsic::donothing:
3343       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3344     case Intrinsic::seh_try_begin:
3345     case Intrinsic::seh_scope_begin:
3346     case Intrinsic::seh_try_end:
3347     case Intrinsic::seh_scope_end:
3348       if (EHPadMBB)
3349           // a block referenced by EH table
3350           // so dtor-funclet not removed by opts
3351           EHPadMBB->setMachineBlockAddressTaken();
3352       break;
3353     case Intrinsic::experimental_patchpoint_void:
3354     case Intrinsic::experimental_patchpoint:
3355       visitPatchpoint(I, EHPadBB);
3356       break;
3357     case Intrinsic::experimental_gc_statepoint:
3358       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3359       break;
3360     case Intrinsic::wasm_rethrow: {
3361       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3362       // special because it can be invoked, so we manually lower it to a DAG
3363       // node here.
3364       SmallVector<SDValue, 8> Ops;
3365       Ops.push_back(getControlRoot()); // inchain for the terminator node
3366       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3367       Ops.push_back(
3368           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3369                                 TLI.getPointerTy(DAG.getDataLayout())));
3370       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3371       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3372       break;
3373     }
3374     }
3375   } else if (I.hasDeoptState()) {
3376     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3377     // Eventually we will support lowering the @llvm.experimental.deoptimize
3378     // intrinsic, and right now there are no plans to support other intrinsics
3379     // with deopt state.
3380     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3381   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3382     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3383   } else {
3384     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3385   }
3386 
3387   // If the value of the invoke is used outside of its defining block, make it
3388   // available as a virtual register.
3389   // We already took care of the exported value for the statepoint instruction
3390   // during call to the LowerStatepoint.
3391   if (!isa<GCStatepointInst>(I)) {
3392     CopyToExportRegsIfNeeded(&I);
3393   }
3394 
3395   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3396   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3397   BranchProbability EHPadBBProb =
3398       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3399           : BranchProbability::getZero();
3400   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3401 
3402   // Update successor info.
3403   addSuccessorWithProb(InvokeMBB, Return);
3404   for (auto &UnwindDest : UnwindDests) {
3405     UnwindDest.first->setIsEHPad();
3406     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3407   }
3408   InvokeMBB->normalizeSuccProbs();
3409 
3410   // Drop into normal successor.
3411   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3412                           DAG.getBasicBlock(Return)));
3413 }
3414 
3415 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3416   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3417 
3418   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3419   // have to do anything here to lower funclet bundles.
3420   assert(!I.hasOperandBundlesOtherThan(
3421              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3422          "Cannot lower callbrs with arbitrary operand bundles yet!");
3423 
3424   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3425   visitInlineAsm(I);
3426   CopyToExportRegsIfNeeded(&I);
3427 
3428   // Retrieve successors.
3429   SmallPtrSet<BasicBlock *, 8> Dests;
3430   Dests.insert(I.getDefaultDest());
3431   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3432 
3433   // Update successor info.
3434   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3435   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3436     BasicBlock *Dest = I.getIndirectDest(i);
3437     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3438     Target->setIsInlineAsmBrIndirectTarget();
3439     Target->setMachineBlockAddressTaken();
3440     Target->setLabelMustBeEmitted();
3441     // Don't add duplicate machine successors.
3442     if (Dests.insert(Dest).second)
3443       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3444   }
3445   CallBrMBB->normalizeSuccProbs();
3446 
3447   // Drop into default successor.
3448   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3449                           MVT::Other, getControlRoot(),
3450                           DAG.getBasicBlock(Return)));
3451 }
3452 
3453 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3454   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3455 }
3456 
3457 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3458   assert(FuncInfo.MBB->isEHPad() &&
3459          "Call to landingpad not in landing pad!");
3460 
3461   // If there aren't registers to copy the values into (e.g., during SjLj
3462   // exceptions), then don't bother to create these DAG nodes.
3463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3464   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3465   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3466       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3467     return;
3468 
3469   // If landingpad's return type is token type, we don't create DAG nodes
3470   // for its exception pointer and selector value. The extraction of exception
3471   // pointer or selector value from token type landingpads is not currently
3472   // supported.
3473   if (LP.getType()->isTokenTy())
3474     return;
3475 
3476   SmallVector<EVT, 2> ValueVTs;
3477   SDLoc dl = getCurSDLoc();
3478   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3479   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3480 
3481   // Get the two live-in registers as SDValues. The physregs have already been
3482   // copied into virtual registers.
3483   SDValue Ops[2];
3484   if (FuncInfo.ExceptionPointerVirtReg) {
3485     Ops[0] = DAG.getZExtOrTrunc(
3486         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3487                            FuncInfo.ExceptionPointerVirtReg,
3488                            TLI.getPointerTy(DAG.getDataLayout())),
3489         dl, ValueVTs[0]);
3490   } else {
3491     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3492   }
3493   Ops[1] = DAG.getZExtOrTrunc(
3494       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3495                          FuncInfo.ExceptionSelectorVirtReg,
3496                          TLI.getPointerTy(DAG.getDataLayout())),
3497       dl, ValueVTs[1]);
3498 
3499   // Merge into one.
3500   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3501                             DAG.getVTList(ValueVTs), Ops);
3502   setValue(&LP, Res);
3503 }
3504 
3505 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3506                                            MachineBasicBlock *Last) {
3507   // Update JTCases.
3508   for (JumpTableBlock &JTB : SL->JTCases)
3509     if (JTB.first.HeaderBB == First)
3510       JTB.first.HeaderBB = Last;
3511 
3512   // Update BitTestCases.
3513   for (BitTestBlock &BTB : SL->BitTestCases)
3514     if (BTB.Parent == First)
3515       BTB.Parent = Last;
3516 }
3517 
3518 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3519   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3520 
3521   // Update machine-CFG edges with unique successors.
3522   SmallSet<BasicBlock*, 32> Done;
3523   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3524     BasicBlock *BB = I.getSuccessor(i);
3525     bool Inserted = Done.insert(BB).second;
3526     if (!Inserted)
3527         continue;
3528 
3529     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3530     addSuccessorWithProb(IndirectBrMBB, Succ);
3531   }
3532   IndirectBrMBB->normalizeSuccProbs();
3533 
3534   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3535                           MVT::Other, getControlRoot(),
3536                           getValue(I.getAddress())));
3537 }
3538 
3539 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3540   if (!DAG.getTarget().Options.TrapUnreachable)
3541     return;
3542 
3543   // We may be able to ignore unreachable behind a noreturn call.
3544   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3545       Call && Call->doesNotReturn()) {
3546     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3547       return;
3548     // Do not emit an additional trap instruction.
3549     if (Call->isNonContinuableTrap())
3550       return;
3551   }
3552 
3553   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3554 }
3555 
3556 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3557   SDNodeFlags Flags;
3558   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3559     Flags.copyFMF(*FPOp);
3560 
3561   SDValue Op = getValue(I.getOperand(0));
3562   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3563                                     Op, Flags);
3564   setValue(&I, UnNodeValue);
3565 }
3566 
3567 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3568   SDNodeFlags Flags;
3569   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3570     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3571     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3572   }
3573   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3574     Flags.setExact(ExactOp->isExact());
3575   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3576     Flags.setDisjoint(DisjointOp->isDisjoint());
3577   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3578     Flags.copyFMF(*FPOp);
3579 
3580   SDValue Op1 = getValue(I.getOperand(0));
3581   SDValue Op2 = getValue(I.getOperand(1));
3582   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3583                                      Op1, Op2, Flags);
3584   setValue(&I, BinNodeValue);
3585 }
3586 
3587 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3588   SDValue Op1 = getValue(I.getOperand(0));
3589   SDValue Op2 = getValue(I.getOperand(1));
3590 
3591   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3592       Op1.getValueType(), DAG.getDataLayout());
3593 
3594   // Coerce the shift amount to the right type if we can. This exposes the
3595   // truncate or zext to optimization early.
3596   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3597     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3598            "Unexpected shift type");
3599     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3600   }
3601 
3602   bool nuw = false;
3603   bool nsw = false;
3604   bool exact = false;
3605 
3606   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3607 
3608     if (const OverflowingBinaryOperator *OFBinOp =
3609             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3610       nuw = OFBinOp->hasNoUnsignedWrap();
3611       nsw = OFBinOp->hasNoSignedWrap();
3612     }
3613     if (const PossiblyExactOperator *ExactOp =
3614             dyn_cast<const PossiblyExactOperator>(&I))
3615       exact = ExactOp->isExact();
3616   }
3617   SDNodeFlags Flags;
3618   Flags.setExact(exact);
3619   Flags.setNoSignedWrap(nsw);
3620   Flags.setNoUnsignedWrap(nuw);
3621   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3622                             Flags);
3623   setValue(&I, Res);
3624 }
3625 
3626 void SelectionDAGBuilder::visitSDiv(const User &I) {
3627   SDValue Op1 = getValue(I.getOperand(0));
3628   SDValue Op2 = getValue(I.getOperand(1));
3629 
3630   SDNodeFlags Flags;
3631   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3632                  cast<PossiblyExactOperator>(&I)->isExact());
3633   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3634                            Op2, Flags));
3635 }
3636 
3637 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3638   ICmpInst::Predicate predicate = I.getPredicate();
3639   SDValue Op1 = getValue(I.getOperand(0));
3640   SDValue Op2 = getValue(I.getOperand(1));
3641   ISD::CondCode Opcode = getICmpCondCode(predicate);
3642 
3643   auto &TLI = DAG.getTargetLoweringInfo();
3644   EVT MemVT =
3645       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3646 
3647   // If a pointer's DAG type is larger than its memory type then the DAG values
3648   // are zero-extended. This breaks signed comparisons so truncate back to the
3649   // underlying type before doing the compare.
3650   if (Op1.getValueType() != MemVT) {
3651     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3652     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3653   }
3654 
3655   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3656                                                         I.getType());
3657   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3658 }
3659 
3660 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3661   FCmpInst::Predicate predicate = I.getPredicate();
3662   SDValue Op1 = getValue(I.getOperand(0));
3663   SDValue Op2 = getValue(I.getOperand(1));
3664 
3665   ISD::CondCode Condition = getFCmpCondCode(predicate);
3666   auto *FPMO = cast<FPMathOperator>(&I);
3667   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3668     Condition = getFCmpCodeWithoutNaN(Condition);
3669 
3670   SDNodeFlags Flags;
3671   Flags.copyFMF(*FPMO);
3672   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3673 
3674   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3675                                                         I.getType());
3676   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3677 }
3678 
3679 // Check if the condition of the select has one use or two users that are both
3680 // selects with the same condition.
3681 static bool hasOnlySelectUsers(const Value *Cond) {
3682   return llvm::all_of(Cond->users(), [](const Value *V) {
3683     return isa<SelectInst>(V);
3684   });
3685 }
3686 
3687 void SelectionDAGBuilder::visitSelect(const User &I) {
3688   SmallVector<EVT, 4> ValueVTs;
3689   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3690                   ValueVTs);
3691   unsigned NumValues = ValueVTs.size();
3692   if (NumValues == 0) return;
3693 
3694   SmallVector<SDValue, 4> Values(NumValues);
3695   SDValue Cond     = getValue(I.getOperand(0));
3696   SDValue LHSVal   = getValue(I.getOperand(1));
3697   SDValue RHSVal   = getValue(I.getOperand(2));
3698   SmallVector<SDValue, 1> BaseOps(1, Cond);
3699   ISD::NodeType OpCode =
3700       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3701 
3702   bool IsUnaryAbs = false;
3703   bool Negate = false;
3704 
3705   SDNodeFlags Flags;
3706   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3707     Flags.copyFMF(*FPOp);
3708 
3709   Flags.setUnpredictable(
3710       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3711 
3712   // Min/max matching is only viable if all output VTs are the same.
3713   if (all_equal(ValueVTs)) {
3714     EVT VT = ValueVTs[0];
3715     LLVMContext &Ctx = *DAG.getContext();
3716     auto &TLI = DAG.getTargetLoweringInfo();
3717 
3718     // We care about the legality of the operation after it has been type
3719     // legalized.
3720     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3721       VT = TLI.getTypeToTransformTo(Ctx, VT);
3722 
3723     // If the vselect is legal, assume we want to leave this as a vector setcc +
3724     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3725     // min/max is legal on the scalar type.
3726     bool UseScalarMinMax = VT.isVector() &&
3727       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3728 
3729     // ValueTracking's select pattern matching does not account for -0.0,
3730     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3731     // -0.0 is less than +0.0.
3732     Value *LHS, *RHS;
3733     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3734     ISD::NodeType Opc = ISD::DELETED_NODE;
3735     switch (SPR.Flavor) {
3736     case SPF_UMAX:    Opc = ISD::UMAX; break;
3737     case SPF_UMIN:    Opc = ISD::UMIN; break;
3738     case SPF_SMAX:    Opc = ISD::SMAX; break;
3739     case SPF_SMIN:    Opc = ISD::SMIN; break;
3740     case SPF_FMINNUM:
3741       switch (SPR.NaNBehavior) {
3742       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3743       case SPNB_RETURNS_NAN: break;
3744       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3745       case SPNB_RETURNS_ANY:
3746         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3747             (UseScalarMinMax &&
3748              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3749           Opc = ISD::FMINNUM;
3750         break;
3751       }
3752       break;
3753     case SPF_FMAXNUM:
3754       switch (SPR.NaNBehavior) {
3755       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3756       case SPNB_RETURNS_NAN: break;
3757       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3758       case SPNB_RETURNS_ANY:
3759         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3760             (UseScalarMinMax &&
3761              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3762           Opc = ISD::FMAXNUM;
3763         break;
3764       }
3765       break;
3766     case SPF_NABS:
3767       Negate = true;
3768       [[fallthrough]];
3769     case SPF_ABS:
3770       IsUnaryAbs = true;
3771       Opc = ISD::ABS;
3772       break;
3773     default: break;
3774     }
3775 
3776     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3777         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3778          (UseScalarMinMax &&
3779           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3780         // If the underlying comparison instruction is used by any other
3781         // instruction, the consumed instructions won't be destroyed, so it is
3782         // not profitable to convert to a min/max.
3783         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3784       OpCode = Opc;
3785       LHSVal = getValue(LHS);
3786       RHSVal = getValue(RHS);
3787       BaseOps.clear();
3788     }
3789 
3790     if (IsUnaryAbs) {
3791       OpCode = Opc;
3792       LHSVal = getValue(LHS);
3793       BaseOps.clear();
3794     }
3795   }
3796 
3797   if (IsUnaryAbs) {
3798     for (unsigned i = 0; i != NumValues; ++i) {
3799       SDLoc dl = getCurSDLoc();
3800       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3801       Values[i] =
3802           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3803       if (Negate)
3804         Values[i] = DAG.getNegative(Values[i], dl, VT);
3805     }
3806   } else {
3807     for (unsigned i = 0; i != NumValues; ++i) {
3808       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3809       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3810       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3811       Values[i] = DAG.getNode(
3812           OpCode, getCurSDLoc(),
3813           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3814     }
3815   }
3816 
3817   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3818                            DAG.getVTList(ValueVTs), Values));
3819 }
3820 
3821 void SelectionDAGBuilder::visitTrunc(const User &I) {
3822   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3823   SDValue N = getValue(I.getOperand(0));
3824   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3825                                                         I.getType());
3826   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3827 }
3828 
3829 void SelectionDAGBuilder::visitZExt(const User &I) {
3830   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3831   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3832   SDValue N = getValue(I.getOperand(0));
3833   auto &TLI = DAG.getTargetLoweringInfo();
3834   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3835 
3836   SDNodeFlags Flags;
3837   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3838     Flags.setNonNeg(PNI->hasNonNeg());
3839 
3840   // Eagerly use nonneg information to canonicalize towards sign_extend if
3841   // that is the target's preference.
3842   // TODO: Let the target do this later.
3843   if (Flags.hasNonNeg() &&
3844       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3845     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3846     return;
3847   }
3848 
3849   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3850 }
3851 
3852 void SelectionDAGBuilder::visitSExt(const User &I) {
3853   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3854   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3855   SDValue N = getValue(I.getOperand(0));
3856   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3857                                                         I.getType());
3858   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3859 }
3860 
3861 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3862   // FPTrunc is never a no-op cast, no need to check
3863   SDValue N = getValue(I.getOperand(0));
3864   SDLoc dl = getCurSDLoc();
3865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3866   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3867   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3868                            DAG.getTargetConstant(
3869                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3870 }
3871 
3872 void SelectionDAGBuilder::visitFPExt(const User &I) {
3873   // FPExt is never a no-op cast, no need to check
3874   SDValue N = getValue(I.getOperand(0));
3875   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3876                                                         I.getType());
3877   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3878 }
3879 
3880 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3881   // FPToUI is never a no-op cast, no need to check
3882   SDValue N = getValue(I.getOperand(0));
3883   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3884                                                         I.getType());
3885   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3886 }
3887 
3888 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3889   // FPToSI is never a no-op cast, no need to check
3890   SDValue N = getValue(I.getOperand(0));
3891   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3892                                                         I.getType());
3893   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3894 }
3895 
3896 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3897   // UIToFP is never a no-op cast, no need to check
3898   SDValue N = getValue(I.getOperand(0));
3899   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3900                                                         I.getType());
3901   SDNodeFlags Flags;
3902   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3903     Flags.setNonNeg(PNI->hasNonNeg());
3904 
3905   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3906 }
3907 
3908 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3909   // SIToFP is never a no-op cast, no need to check
3910   SDValue N = getValue(I.getOperand(0));
3911   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3912                                                         I.getType());
3913   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3914 }
3915 
3916 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3917   // What to do depends on the size of the integer and the size of the pointer.
3918   // We can either truncate, zero extend, or no-op, accordingly.
3919   SDValue N = getValue(I.getOperand(0));
3920   auto &TLI = DAG.getTargetLoweringInfo();
3921   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3922                                                         I.getType());
3923   EVT PtrMemVT =
3924       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3925   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3926   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3927   setValue(&I, N);
3928 }
3929 
3930 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3931   // What to do depends on the size of the integer and the size of the pointer.
3932   // We can either truncate, zero extend, or no-op, accordingly.
3933   SDValue N = getValue(I.getOperand(0));
3934   auto &TLI = DAG.getTargetLoweringInfo();
3935   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3936   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3937   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3938   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3939   setValue(&I, N);
3940 }
3941 
3942 void SelectionDAGBuilder::visitBitCast(const User &I) {
3943   SDValue N = getValue(I.getOperand(0));
3944   SDLoc dl = getCurSDLoc();
3945   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3946                                                         I.getType());
3947 
3948   // BitCast assures us that source and destination are the same size so this is
3949   // either a BITCAST or a no-op.
3950   if (DestVT != N.getValueType())
3951     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3952                              DestVT, N)); // convert types.
3953   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3954   // might fold any kind of constant expression to an integer constant and that
3955   // is not what we are looking for. Only recognize a bitcast of a genuine
3956   // constant integer as an opaque constant.
3957   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3958     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3959                                  /*isOpaque*/true));
3960   else
3961     setValue(&I, N);            // noop cast.
3962 }
3963 
3964 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3966   const Value *SV = I.getOperand(0);
3967   SDValue N = getValue(SV);
3968   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3969 
3970   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3971   unsigned DestAS = I.getType()->getPointerAddressSpace();
3972 
3973   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3974     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3975 
3976   setValue(&I, N);
3977 }
3978 
3979 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3981   SDValue InVec = getValue(I.getOperand(0));
3982   SDValue InVal = getValue(I.getOperand(1));
3983   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3984                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3985   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3986                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3987                            InVec, InVal, InIdx));
3988 }
3989 
3990 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3992   SDValue InVec = getValue(I.getOperand(0));
3993   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3994                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3995   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3996                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3997                            InVec, InIdx));
3998 }
3999 
4000 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4001   SDValue Src1 = getValue(I.getOperand(0));
4002   SDValue Src2 = getValue(I.getOperand(1));
4003   ArrayRef<int> Mask;
4004   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4005     Mask = SVI->getShuffleMask();
4006   else
4007     Mask = cast<ConstantExpr>(I).getShuffleMask();
4008   SDLoc DL = getCurSDLoc();
4009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4010   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4011   EVT SrcVT = Src1.getValueType();
4012 
4013   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4014       VT.isScalableVector()) {
4015     // Canonical splat form of first element of first input vector.
4016     SDValue FirstElt =
4017         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4018                     DAG.getVectorIdxConstant(0, DL));
4019     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4020     return;
4021   }
4022 
4023   // For now, we only handle splats for scalable vectors.
4024   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4025   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4026   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4027 
4028   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4029   unsigned MaskNumElts = Mask.size();
4030 
4031   if (SrcNumElts == MaskNumElts) {
4032     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4033     return;
4034   }
4035 
4036   // Normalize the shuffle vector since mask and vector length don't match.
4037   if (SrcNumElts < MaskNumElts) {
4038     // Mask is longer than the source vectors. We can use concatenate vector to
4039     // make the mask and vectors lengths match.
4040 
4041     if (MaskNumElts % SrcNumElts == 0) {
4042       // Mask length is a multiple of the source vector length.
4043       // Check if the shuffle is some kind of concatenation of the input
4044       // vectors.
4045       unsigned NumConcat = MaskNumElts / SrcNumElts;
4046       bool IsConcat = true;
4047       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4048       for (unsigned i = 0; i != MaskNumElts; ++i) {
4049         int Idx = Mask[i];
4050         if (Idx < 0)
4051           continue;
4052         // Ensure the indices in each SrcVT sized piece are sequential and that
4053         // the same source is used for the whole piece.
4054         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4055             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4056              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4057           IsConcat = false;
4058           break;
4059         }
4060         // Remember which source this index came from.
4061         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4062       }
4063 
4064       // The shuffle is concatenating multiple vectors together. Just emit
4065       // a CONCAT_VECTORS operation.
4066       if (IsConcat) {
4067         SmallVector<SDValue, 8> ConcatOps;
4068         for (auto Src : ConcatSrcs) {
4069           if (Src < 0)
4070             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4071           else if (Src == 0)
4072             ConcatOps.push_back(Src1);
4073           else
4074             ConcatOps.push_back(Src2);
4075         }
4076         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4077         return;
4078       }
4079     }
4080 
4081     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4082     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4083     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4084                                     PaddedMaskNumElts);
4085 
4086     // Pad both vectors with undefs to make them the same length as the mask.
4087     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4088 
4089     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4090     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4091     MOps1[0] = Src1;
4092     MOps2[0] = Src2;
4093 
4094     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4095     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4096 
4097     // Readjust mask for new input vector length.
4098     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4099     for (unsigned i = 0; i != MaskNumElts; ++i) {
4100       int Idx = Mask[i];
4101       if (Idx >= (int)SrcNumElts)
4102         Idx -= SrcNumElts - PaddedMaskNumElts;
4103       MappedOps[i] = Idx;
4104     }
4105 
4106     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4107 
4108     // If the concatenated vector was padded, extract a subvector with the
4109     // correct number of elements.
4110     if (MaskNumElts != PaddedMaskNumElts)
4111       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4112                            DAG.getVectorIdxConstant(0, DL));
4113 
4114     setValue(&I, Result);
4115     return;
4116   }
4117 
4118   if (SrcNumElts > MaskNumElts) {
4119     // Analyze the access pattern of the vector to see if we can extract
4120     // two subvectors and do the shuffle.
4121     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4122     bool CanExtract = true;
4123     for (int Idx : Mask) {
4124       unsigned Input = 0;
4125       if (Idx < 0)
4126         continue;
4127 
4128       if (Idx >= (int)SrcNumElts) {
4129         Input = 1;
4130         Idx -= SrcNumElts;
4131       }
4132 
4133       // If all the indices come from the same MaskNumElts sized portion of
4134       // the sources we can use extract. Also make sure the extract wouldn't
4135       // extract past the end of the source.
4136       int NewStartIdx = alignDown(Idx, MaskNumElts);
4137       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4138           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4139         CanExtract = false;
4140       // Make sure we always update StartIdx as we use it to track if all
4141       // elements are undef.
4142       StartIdx[Input] = NewStartIdx;
4143     }
4144 
4145     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4146       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4147       return;
4148     }
4149     if (CanExtract) {
4150       // Extract appropriate subvector and generate a vector shuffle
4151       for (unsigned Input = 0; Input < 2; ++Input) {
4152         SDValue &Src = Input == 0 ? Src1 : Src2;
4153         if (StartIdx[Input] < 0)
4154           Src = DAG.getUNDEF(VT);
4155         else {
4156           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4157                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4158         }
4159       }
4160 
4161       // Calculate new mask.
4162       SmallVector<int, 8> MappedOps(Mask);
4163       for (int &Idx : MappedOps) {
4164         if (Idx >= (int)SrcNumElts)
4165           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4166         else if (Idx >= 0)
4167           Idx -= StartIdx[0];
4168       }
4169 
4170       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4171       return;
4172     }
4173   }
4174 
4175   // We can't use either concat vectors or extract subvectors so fall back to
4176   // replacing the shuffle with extract and build vector.
4177   // to insert and build vector.
4178   EVT EltVT = VT.getVectorElementType();
4179   SmallVector<SDValue,8> Ops;
4180   for (int Idx : Mask) {
4181     SDValue Res;
4182 
4183     if (Idx < 0) {
4184       Res = DAG.getUNDEF(EltVT);
4185     } else {
4186       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4187       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4188 
4189       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4190                         DAG.getVectorIdxConstant(Idx, DL));
4191     }
4192 
4193     Ops.push_back(Res);
4194   }
4195 
4196   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4197 }
4198 
4199 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4200   ArrayRef<unsigned> Indices = I.getIndices();
4201   const Value *Op0 = I.getOperand(0);
4202   const Value *Op1 = I.getOperand(1);
4203   Type *AggTy = I.getType();
4204   Type *ValTy = Op1->getType();
4205   bool IntoUndef = isa<UndefValue>(Op0);
4206   bool FromUndef = isa<UndefValue>(Op1);
4207 
4208   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4209 
4210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4211   SmallVector<EVT, 4> AggValueVTs;
4212   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4213   SmallVector<EVT, 4> ValValueVTs;
4214   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4215 
4216   unsigned NumAggValues = AggValueVTs.size();
4217   unsigned NumValValues = ValValueVTs.size();
4218   SmallVector<SDValue, 4> Values(NumAggValues);
4219 
4220   // Ignore an insertvalue that produces an empty object
4221   if (!NumAggValues) {
4222     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4223     return;
4224   }
4225 
4226   SDValue Agg = getValue(Op0);
4227   unsigned i = 0;
4228   // Copy the beginning value(s) from the original aggregate.
4229   for (; i != LinearIndex; ++i)
4230     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4231                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4232   // Copy values from the inserted value(s).
4233   if (NumValValues) {
4234     SDValue Val = getValue(Op1);
4235     for (; i != LinearIndex + NumValValues; ++i)
4236       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4237                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4238   }
4239   // Copy remaining value(s) from the original aggregate.
4240   for (; i != NumAggValues; ++i)
4241     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4242                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4243 
4244   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4245                            DAG.getVTList(AggValueVTs), Values));
4246 }
4247 
4248 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4249   ArrayRef<unsigned> Indices = I.getIndices();
4250   const Value *Op0 = I.getOperand(0);
4251   Type *AggTy = Op0->getType();
4252   Type *ValTy = I.getType();
4253   bool OutOfUndef = isa<UndefValue>(Op0);
4254 
4255   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4256 
4257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4258   SmallVector<EVT, 4> ValValueVTs;
4259   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4260 
4261   unsigned NumValValues = ValValueVTs.size();
4262 
4263   // Ignore a extractvalue that produces an empty object
4264   if (!NumValValues) {
4265     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4266     return;
4267   }
4268 
4269   SmallVector<SDValue, 4> Values(NumValValues);
4270 
4271   SDValue Agg = getValue(Op0);
4272   // Copy out the selected value(s).
4273   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4274     Values[i - LinearIndex] =
4275       OutOfUndef ?
4276         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4277         SDValue(Agg.getNode(), Agg.getResNo() + i);
4278 
4279   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4280                            DAG.getVTList(ValValueVTs), Values));
4281 }
4282 
4283 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4284   Value *Op0 = I.getOperand(0);
4285   // Note that the pointer operand may be a vector of pointers. Take the scalar
4286   // element which holds a pointer.
4287   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4288   SDValue N = getValue(Op0);
4289   SDLoc dl = getCurSDLoc();
4290   auto &TLI = DAG.getTargetLoweringInfo();
4291 
4292   // Normalize Vector GEP - all scalar operands should be converted to the
4293   // splat vector.
4294   bool IsVectorGEP = I.getType()->isVectorTy();
4295   ElementCount VectorElementCount =
4296       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4297                   : ElementCount::getFixed(0);
4298 
4299   if (IsVectorGEP && !N.getValueType().isVector()) {
4300     LLVMContext &Context = *DAG.getContext();
4301     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4302     N = DAG.getSplat(VT, dl, N);
4303   }
4304 
4305   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4306        GTI != E; ++GTI) {
4307     const Value *Idx = GTI.getOperand();
4308     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4309       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4310       if (Field) {
4311         // N = N + Offset
4312         uint64_t Offset =
4313             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4314 
4315         // In an inbounds GEP with an offset that is nonnegative even when
4316         // interpreted as signed, assume there is no unsigned overflow.
4317         SDNodeFlags Flags;
4318         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4319           Flags.setNoUnsignedWrap(true);
4320 
4321         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4322                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4323       }
4324     } else {
4325       // IdxSize is the width of the arithmetic according to IR semantics.
4326       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4327       // (and fix up the result later).
4328       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4329       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4330       TypeSize ElementSize =
4331           GTI.getSequentialElementStride(DAG.getDataLayout());
4332       // We intentionally mask away the high bits here; ElementSize may not
4333       // fit in IdxTy.
4334       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4335       bool ElementScalable = ElementSize.isScalable();
4336 
4337       // If this is a scalar constant or a splat vector of constants,
4338       // handle it quickly.
4339       const auto *C = dyn_cast<Constant>(Idx);
4340       if (C && isa<VectorType>(C->getType()))
4341         C = C->getSplatValue();
4342 
4343       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4344       if (CI && CI->isZero())
4345         continue;
4346       if (CI && !ElementScalable) {
4347         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4348         LLVMContext &Context = *DAG.getContext();
4349         SDValue OffsVal;
4350         if (IsVectorGEP)
4351           OffsVal = DAG.getConstant(
4352               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4353         else
4354           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4355 
4356         // In an inbounds GEP with an offset that is nonnegative even when
4357         // interpreted as signed, assume there is no unsigned overflow.
4358         SDNodeFlags Flags;
4359         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4360           Flags.setNoUnsignedWrap(true);
4361 
4362         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4363 
4364         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4365         continue;
4366       }
4367 
4368       // N = N + Idx * ElementMul;
4369       SDValue IdxN = getValue(Idx);
4370 
4371       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4372         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4373                                   VectorElementCount);
4374         IdxN = DAG.getSplat(VT, dl, IdxN);
4375       }
4376 
4377       // If the index is smaller or larger than intptr_t, truncate or extend
4378       // it.
4379       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4380 
4381       if (ElementScalable) {
4382         EVT VScaleTy = N.getValueType().getScalarType();
4383         SDValue VScale = DAG.getNode(
4384             ISD::VSCALE, dl, VScaleTy,
4385             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4386         if (IsVectorGEP)
4387           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4388         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4389       } else {
4390         // If this is a multiply by a power of two, turn it into a shl
4391         // immediately.  This is a very common case.
4392         if (ElementMul != 1) {
4393           if (ElementMul.isPowerOf2()) {
4394             unsigned Amt = ElementMul.logBase2();
4395             IdxN = DAG.getNode(ISD::SHL, dl,
4396                                N.getValueType(), IdxN,
4397                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4398           } else {
4399             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4400                                             IdxN.getValueType());
4401             IdxN = DAG.getNode(ISD::MUL, dl,
4402                                N.getValueType(), IdxN, Scale);
4403           }
4404         }
4405       }
4406 
4407       N = DAG.getNode(ISD::ADD, dl,
4408                       N.getValueType(), N, IdxN);
4409     }
4410   }
4411 
4412   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4413   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4414   if (IsVectorGEP) {
4415     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4416     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4417   }
4418 
4419   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4420     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4421 
4422   setValue(&I, N);
4423 }
4424 
4425 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4426   // If this is a fixed sized alloca in the entry block of the function,
4427   // allocate it statically on the stack.
4428   if (FuncInfo.StaticAllocaMap.count(&I))
4429     return;   // getValue will auto-populate this.
4430 
4431   SDLoc dl = getCurSDLoc();
4432   Type *Ty = I.getAllocatedType();
4433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4434   auto &DL = DAG.getDataLayout();
4435   TypeSize TySize = DL.getTypeAllocSize(Ty);
4436   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4437 
4438   SDValue AllocSize = getValue(I.getArraySize());
4439 
4440   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4441   if (AllocSize.getValueType() != IntPtr)
4442     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4443 
4444   if (TySize.isScalable())
4445     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4446                             DAG.getVScale(dl, IntPtr,
4447                                           APInt(IntPtr.getScalarSizeInBits(),
4448                                                 TySize.getKnownMinValue())));
4449   else {
4450     SDValue TySizeValue =
4451         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4452     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4453                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4454   }
4455 
4456   // Handle alignment.  If the requested alignment is less than or equal to
4457   // the stack alignment, ignore it.  If the size is greater than or equal to
4458   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4459   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4460   if (*Alignment <= StackAlign)
4461     Alignment = std::nullopt;
4462 
4463   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4464   // Round the size of the allocation up to the stack alignment size
4465   // by add SA-1 to the size. This doesn't overflow because we're computing
4466   // an address inside an alloca.
4467   SDNodeFlags Flags;
4468   Flags.setNoUnsignedWrap(true);
4469   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4470                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4471 
4472   // Mask out the low bits for alignment purposes.
4473   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4474                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4475 
4476   SDValue Ops[] = {
4477       getRoot(), AllocSize,
4478       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4479   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4480   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4481   setValue(&I, DSA);
4482   DAG.setRoot(DSA.getValue(1));
4483 
4484   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4485 }
4486 
4487 static const MDNode *getRangeMetadata(const Instruction &I) {
4488   // If !noundef is not present, then !range violation results in a poison
4489   // value rather than immediate undefined behavior. In theory, transferring
4490   // these annotations to SDAG is fine, but in practice there are key SDAG
4491   // transforms that are known not to be poison-safe, such as folding logical
4492   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4493   // also present.
4494   if (!I.hasMetadata(LLVMContext::MD_noundef))
4495     return nullptr;
4496   return I.getMetadata(LLVMContext::MD_range);
4497 }
4498 
4499 static std::optional<ConstantRange> getRange(const Instruction &I) {
4500   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4501     // see comment in getRangeMetadata about this check
4502     if (CB->hasRetAttr(Attribute::NoUndef))
4503       return CB->getRange();
4504   }
4505   if (const MDNode *Range = getRangeMetadata(I))
4506     return getConstantRangeFromMetadata(*Range);
4507   return std::nullopt;
4508 }
4509 
4510 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4511   if (I.isAtomic())
4512     return visitAtomicLoad(I);
4513 
4514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4515   const Value *SV = I.getOperand(0);
4516   if (TLI.supportSwiftError()) {
4517     // Swifterror values can come from either a function parameter with
4518     // swifterror attribute or an alloca with swifterror attribute.
4519     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4520       if (Arg->hasSwiftErrorAttr())
4521         return visitLoadFromSwiftError(I);
4522     }
4523 
4524     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4525       if (Alloca->isSwiftError())
4526         return visitLoadFromSwiftError(I);
4527     }
4528   }
4529 
4530   SDValue Ptr = getValue(SV);
4531 
4532   Type *Ty = I.getType();
4533   SmallVector<EVT, 4> ValueVTs, MemVTs;
4534   SmallVector<TypeSize, 4> Offsets;
4535   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4536   unsigned NumValues = ValueVTs.size();
4537   if (NumValues == 0)
4538     return;
4539 
4540   Align Alignment = I.getAlign();
4541   AAMDNodes AAInfo = I.getAAMetadata();
4542   const MDNode *Ranges = getRangeMetadata(I);
4543   bool isVolatile = I.isVolatile();
4544   MachineMemOperand::Flags MMOFlags =
4545       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4546 
4547   SDValue Root;
4548   bool ConstantMemory = false;
4549   if (isVolatile)
4550     // Serialize volatile loads with other side effects.
4551     Root = getRoot();
4552   else if (NumValues > MaxParallelChains)
4553     Root = getMemoryRoot();
4554   else if (AA &&
4555            AA->pointsToConstantMemory(MemoryLocation(
4556                SV,
4557                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4558                AAInfo))) {
4559     // Do not serialize (non-volatile) loads of constant memory with anything.
4560     Root = DAG.getEntryNode();
4561     ConstantMemory = true;
4562     MMOFlags |= MachineMemOperand::MOInvariant;
4563   } else {
4564     // Do not serialize non-volatile loads against each other.
4565     Root = DAG.getRoot();
4566   }
4567 
4568   SDLoc dl = getCurSDLoc();
4569 
4570   if (isVolatile)
4571     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4572 
4573   SmallVector<SDValue, 4> Values(NumValues);
4574   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4575 
4576   unsigned ChainI = 0;
4577   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4578     // Serializing loads here may result in excessive register pressure, and
4579     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4580     // could recover a bit by hoisting nodes upward in the chain by recognizing
4581     // they are side-effect free or do not alias. The optimizer should really
4582     // avoid this case by converting large object/array copies to llvm.memcpy
4583     // (MaxParallelChains should always remain as failsafe).
4584     if (ChainI == MaxParallelChains) {
4585       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4586       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4587                                   ArrayRef(Chains.data(), ChainI));
4588       Root = Chain;
4589       ChainI = 0;
4590     }
4591 
4592     // TODO: MachinePointerInfo only supports a fixed length offset.
4593     MachinePointerInfo PtrInfo =
4594         !Offsets[i].isScalable() || Offsets[i].isZero()
4595             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4596             : MachinePointerInfo();
4597 
4598     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4599     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4600                             MMOFlags, AAInfo, Ranges);
4601     Chains[ChainI] = L.getValue(1);
4602 
4603     if (MemVTs[i] != ValueVTs[i])
4604       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4605 
4606     Values[i] = L;
4607   }
4608 
4609   if (!ConstantMemory) {
4610     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4611                                 ArrayRef(Chains.data(), ChainI));
4612     if (isVolatile)
4613       DAG.setRoot(Chain);
4614     else
4615       PendingLoads.push_back(Chain);
4616   }
4617 
4618   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4619                            DAG.getVTList(ValueVTs), Values));
4620 }
4621 
4622 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4623   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4624          "call visitStoreToSwiftError when backend supports swifterror");
4625 
4626   SmallVector<EVT, 4> ValueVTs;
4627   SmallVector<uint64_t, 4> Offsets;
4628   const Value *SrcV = I.getOperand(0);
4629   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4630                   SrcV->getType(), ValueVTs, &Offsets, 0);
4631   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4632          "expect a single EVT for swifterror");
4633 
4634   SDValue Src = getValue(SrcV);
4635   // Create a virtual register, then update the virtual register.
4636   Register VReg =
4637       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4638   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4639   // Chain can be getRoot or getControlRoot.
4640   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4641                                       SDValue(Src.getNode(), Src.getResNo()));
4642   DAG.setRoot(CopyNode);
4643 }
4644 
4645 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4646   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4647          "call visitLoadFromSwiftError when backend supports swifterror");
4648 
4649   assert(!I.isVolatile() &&
4650          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4651          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4652          "Support volatile, non temporal, invariant for load_from_swift_error");
4653 
4654   const Value *SV = I.getOperand(0);
4655   Type *Ty = I.getType();
4656   assert(
4657       (!AA ||
4658        !AA->pointsToConstantMemory(MemoryLocation(
4659            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4660            I.getAAMetadata()))) &&
4661       "load_from_swift_error should not be constant memory");
4662 
4663   SmallVector<EVT, 4> ValueVTs;
4664   SmallVector<uint64_t, 4> Offsets;
4665   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4666                   ValueVTs, &Offsets, 0);
4667   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4668          "expect a single EVT for swifterror");
4669 
4670   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4671   SDValue L = DAG.getCopyFromReg(
4672       getRoot(), getCurSDLoc(),
4673       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4674 
4675   setValue(&I, L);
4676 }
4677 
4678 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4679   if (I.isAtomic())
4680     return visitAtomicStore(I);
4681 
4682   const Value *SrcV = I.getOperand(0);
4683   const Value *PtrV = I.getOperand(1);
4684 
4685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4686   if (TLI.supportSwiftError()) {
4687     // Swifterror values can come from either a function parameter with
4688     // swifterror attribute or an alloca with swifterror attribute.
4689     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4690       if (Arg->hasSwiftErrorAttr())
4691         return visitStoreToSwiftError(I);
4692     }
4693 
4694     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4695       if (Alloca->isSwiftError())
4696         return visitStoreToSwiftError(I);
4697     }
4698   }
4699 
4700   SmallVector<EVT, 4> ValueVTs, MemVTs;
4701   SmallVector<TypeSize, 4> Offsets;
4702   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4703                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4704   unsigned NumValues = ValueVTs.size();
4705   if (NumValues == 0)
4706     return;
4707 
4708   // Get the lowered operands. Note that we do this after
4709   // checking if NumResults is zero, because with zero results
4710   // the operands won't have values in the map.
4711   SDValue Src = getValue(SrcV);
4712   SDValue Ptr = getValue(PtrV);
4713 
4714   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4715   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4716   SDLoc dl = getCurSDLoc();
4717   Align Alignment = I.getAlign();
4718   AAMDNodes AAInfo = I.getAAMetadata();
4719 
4720   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4721 
4722   unsigned ChainI = 0;
4723   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4724     // See visitLoad comments.
4725     if (ChainI == MaxParallelChains) {
4726       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4727                                   ArrayRef(Chains.data(), ChainI));
4728       Root = Chain;
4729       ChainI = 0;
4730     }
4731 
4732     // TODO: MachinePointerInfo only supports a fixed length offset.
4733     MachinePointerInfo PtrInfo =
4734         !Offsets[i].isScalable() || Offsets[i].isZero()
4735             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4736             : MachinePointerInfo();
4737 
4738     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4739     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4740     if (MemVTs[i] != ValueVTs[i])
4741       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4742     SDValue St =
4743         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4744     Chains[ChainI] = St;
4745   }
4746 
4747   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4748                                   ArrayRef(Chains.data(), ChainI));
4749   setValue(&I, StoreNode);
4750   DAG.setRoot(StoreNode);
4751 }
4752 
4753 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4754                                            bool IsCompressing) {
4755   SDLoc sdl = getCurSDLoc();
4756 
4757   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4758                                Align &Alignment) {
4759     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4760     Src0 = I.getArgOperand(0);
4761     Ptr = I.getArgOperand(1);
4762     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4763     Mask = I.getArgOperand(3);
4764   };
4765   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4766                                     Align &Alignment) {
4767     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4768     Src0 = I.getArgOperand(0);
4769     Ptr = I.getArgOperand(1);
4770     Mask = I.getArgOperand(2);
4771     Alignment = I.getParamAlign(1).valueOrOne();
4772   };
4773 
4774   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4775   Align Alignment;
4776   if (IsCompressing)
4777     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4778   else
4779     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4780 
4781   SDValue Ptr = getValue(PtrOperand);
4782   SDValue Src0 = getValue(Src0Operand);
4783   SDValue Mask = getValue(MaskOperand);
4784   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4785 
4786   EVT VT = Src0.getValueType();
4787 
4788   auto MMOFlags = MachineMemOperand::MOStore;
4789   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4790     MMOFlags |= MachineMemOperand::MONonTemporal;
4791 
4792   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4793       MachinePointerInfo(PtrOperand), MMOFlags,
4794       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4795 
4796   const auto &TLI = DAG.getTargetLoweringInfo();
4797   const auto &TTI =
4798       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4799   SDValue StoreNode =
4800       !IsCompressing && TTI.hasConditionalLoadStoreForType(
4801                             I.getArgOperand(0)->getType()->getScalarType())
4802           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4803                                  Mask)
4804           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4805                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4806                                IsCompressing);
4807   DAG.setRoot(StoreNode);
4808   setValue(&I, StoreNode);
4809 }
4810 
4811 // Get a uniform base for the Gather/Scatter intrinsic.
4812 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4813 // We try to represent it as a base pointer + vector of indices.
4814 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4815 // The first operand of the GEP may be a single pointer or a vector of pointers
4816 // Example:
4817 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4818 //  or
4819 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4820 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4821 //
4822 // When the first GEP operand is a single pointer - it is the uniform base we
4823 // are looking for. If first operand of the GEP is a splat vector - we
4824 // extract the splat value and use it as a uniform base.
4825 // In all other cases the function returns 'false'.
4826 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4827                            ISD::MemIndexType &IndexType, SDValue &Scale,
4828                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4829                            uint64_t ElemSize) {
4830   SelectionDAG& DAG = SDB->DAG;
4831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4832   const DataLayout &DL = DAG.getDataLayout();
4833 
4834   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4835 
4836   // Handle splat constant pointer.
4837   if (auto *C = dyn_cast<Constant>(Ptr)) {
4838     C = C->getSplatValue();
4839     if (!C)
4840       return false;
4841 
4842     Base = SDB->getValue(C);
4843 
4844     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4845     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4846     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4847     IndexType = ISD::SIGNED_SCALED;
4848     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4849     return true;
4850   }
4851 
4852   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4853   if (!GEP || GEP->getParent() != CurBB)
4854     return false;
4855 
4856   if (GEP->getNumOperands() != 2)
4857     return false;
4858 
4859   const Value *BasePtr = GEP->getPointerOperand();
4860   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4861 
4862   // Make sure the base is scalar and the index is a vector.
4863   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4864     return false;
4865 
4866   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4867   if (ScaleVal.isScalable())
4868     return false;
4869 
4870   // Target may not support the required addressing mode.
4871   if (ScaleVal != 1 &&
4872       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4873     return false;
4874 
4875   Base = SDB->getValue(BasePtr);
4876   Index = SDB->getValue(IndexVal);
4877   IndexType = ISD::SIGNED_SCALED;
4878 
4879   Scale =
4880       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4881   return true;
4882 }
4883 
4884 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4885   SDLoc sdl = getCurSDLoc();
4886 
4887   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4888   const Value *Ptr = I.getArgOperand(1);
4889   SDValue Src0 = getValue(I.getArgOperand(0));
4890   SDValue Mask = getValue(I.getArgOperand(3));
4891   EVT VT = Src0.getValueType();
4892   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4893                         ->getMaybeAlignValue()
4894                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4896 
4897   SDValue Base;
4898   SDValue Index;
4899   ISD::MemIndexType IndexType;
4900   SDValue Scale;
4901   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4902                                     I.getParent(), VT.getScalarStoreSize());
4903 
4904   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4905   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4906       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4907       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4908   if (!UniformBase) {
4909     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4910     Index = getValue(Ptr);
4911     IndexType = ISD::SIGNED_SCALED;
4912     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4913   }
4914 
4915   EVT IdxVT = Index.getValueType();
4916   EVT EltTy = IdxVT.getVectorElementType();
4917   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4918     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4919     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4920   }
4921 
4922   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4923   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4924                                          Ops, MMO, IndexType, false);
4925   DAG.setRoot(Scatter);
4926   setValue(&I, Scatter);
4927 }
4928 
4929 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4930   SDLoc sdl = getCurSDLoc();
4931 
4932   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4933                               Align &Alignment) {
4934     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4935     Ptr = I.getArgOperand(0);
4936     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4937     Mask = I.getArgOperand(2);
4938     Src0 = I.getArgOperand(3);
4939   };
4940   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4941                                  Align &Alignment) {
4942     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4943     Ptr = I.getArgOperand(0);
4944     Alignment = I.getParamAlign(0).valueOrOne();
4945     Mask = I.getArgOperand(1);
4946     Src0 = I.getArgOperand(2);
4947   };
4948 
4949   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4950   Align Alignment;
4951   if (IsExpanding)
4952     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4953   else
4954     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4955 
4956   SDValue Ptr = getValue(PtrOperand);
4957   SDValue Src0 = getValue(Src0Operand);
4958   SDValue Mask = getValue(MaskOperand);
4959   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4960 
4961   EVT VT = Src0.getValueType();
4962   AAMDNodes AAInfo = I.getAAMetadata();
4963   const MDNode *Ranges = getRangeMetadata(I);
4964 
4965   // Do not serialize masked loads of constant memory with anything.
4966   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4967   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4968 
4969   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4970 
4971   auto MMOFlags = MachineMemOperand::MOLoad;
4972   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4973     MMOFlags |= MachineMemOperand::MONonTemporal;
4974 
4975   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4976       MachinePointerInfo(PtrOperand), MMOFlags,
4977       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4978 
4979   const auto &TLI = DAG.getTargetLoweringInfo();
4980   const auto &TTI =
4981       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4982   // The Load/Res may point to different values and both of them are output
4983   // variables.
4984   SDValue Load;
4985   SDValue Res;
4986   if (!IsExpanding && TTI.hasConditionalLoadStoreForType(
4987                           Src0Operand->getType()->getScalarType()))
4988     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4989   else
4990     Res = Load =
4991         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4992                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4993   if (AddToChain)
4994     PendingLoads.push_back(Load.getValue(1));
4995   setValue(&I, Res);
4996 }
4997 
4998 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4999   SDLoc sdl = getCurSDLoc();
5000 
5001   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5002   const Value *Ptr = I.getArgOperand(0);
5003   SDValue Src0 = getValue(I.getArgOperand(3));
5004   SDValue Mask = getValue(I.getArgOperand(2));
5005 
5006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5007   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5008   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5009                         ->getMaybeAlignValue()
5010                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5011 
5012   const MDNode *Ranges = getRangeMetadata(I);
5013 
5014   SDValue Root = DAG.getRoot();
5015   SDValue Base;
5016   SDValue Index;
5017   ISD::MemIndexType IndexType;
5018   SDValue Scale;
5019   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5020                                     I.getParent(), VT.getScalarStoreSize());
5021   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5022   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5023       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5024       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5025       Ranges);
5026 
5027   if (!UniformBase) {
5028     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5029     Index = getValue(Ptr);
5030     IndexType = ISD::SIGNED_SCALED;
5031     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5032   }
5033 
5034   EVT IdxVT = Index.getValueType();
5035   EVT EltTy = IdxVT.getVectorElementType();
5036   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5037     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5038     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5039   }
5040 
5041   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5042   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5043                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5044 
5045   PendingLoads.push_back(Gather.getValue(1));
5046   setValue(&I, Gather);
5047 }
5048 
5049 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5050   SDLoc dl = getCurSDLoc();
5051   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5052   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5053   SyncScope::ID SSID = I.getSyncScopeID();
5054 
5055   SDValue InChain = getRoot();
5056 
5057   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5058   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5059 
5060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5061   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5062 
5063   MachineFunction &MF = DAG.getMachineFunction();
5064   MachineMemOperand *MMO = MF.getMachineMemOperand(
5065       MachinePointerInfo(I.getPointerOperand()), Flags,
5066       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5067       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5068 
5069   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5070                                    dl, MemVT, VTs, InChain,
5071                                    getValue(I.getPointerOperand()),
5072                                    getValue(I.getCompareOperand()),
5073                                    getValue(I.getNewValOperand()), MMO);
5074 
5075   SDValue OutChain = L.getValue(2);
5076 
5077   setValue(&I, L);
5078   DAG.setRoot(OutChain);
5079 }
5080 
5081 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5082   SDLoc dl = getCurSDLoc();
5083   ISD::NodeType NT;
5084   switch (I.getOperation()) {
5085   default: llvm_unreachable("Unknown atomicrmw operation");
5086   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5087   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5088   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5089   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5090   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5091   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5092   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5093   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5094   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5095   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5096   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5097   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5098   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5099   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5100   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5101   case AtomicRMWInst::UIncWrap:
5102     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5103     break;
5104   case AtomicRMWInst::UDecWrap:
5105     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5106     break;
5107   }
5108   AtomicOrdering Ordering = I.getOrdering();
5109   SyncScope::ID SSID = I.getSyncScopeID();
5110 
5111   SDValue InChain = getRoot();
5112 
5113   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5115   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5116 
5117   MachineFunction &MF = DAG.getMachineFunction();
5118   MachineMemOperand *MMO = MF.getMachineMemOperand(
5119       MachinePointerInfo(I.getPointerOperand()), Flags,
5120       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5121       AAMDNodes(), nullptr, SSID, Ordering);
5122 
5123   SDValue L =
5124     DAG.getAtomic(NT, dl, MemVT, InChain,
5125                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5126                   MMO);
5127 
5128   SDValue OutChain = L.getValue(1);
5129 
5130   setValue(&I, L);
5131   DAG.setRoot(OutChain);
5132 }
5133 
5134 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5135   SDLoc dl = getCurSDLoc();
5136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5137   SDValue Ops[3];
5138   Ops[0] = getRoot();
5139   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5140                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5141   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5142                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5143   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5144   setValue(&I, N);
5145   DAG.setRoot(N);
5146 }
5147 
5148 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5149   SDLoc dl = getCurSDLoc();
5150   AtomicOrdering Order = I.getOrdering();
5151   SyncScope::ID SSID = I.getSyncScopeID();
5152 
5153   SDValue InChain = getRoot();
5154 
5155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5156   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5157   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5158 
5159   if (!TLI.supportsUnalignedAtomics() &&
5160       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5161     report_fatal_error("Cannot generate unaligned atomic load");
5162 
5163   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5164 
5165   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5166       MachinePointerInfo(I.getPointerOperand()), Flags,
5167       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5168       nullptr, SSID, Order);
5169 
5170   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5171 
5172   SDValue Ptr = getValue(I.getPointerOperand());
5173   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5174                             Ptr, MMO);
5175 
5176   SDValue OutChain = L.getValue(1);
5177   if (MemVT != VT)
5178     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5179 
5180   setValue(&I, L);
5181   DAG.setRoot(OutChain);
5182 }
5183 
5184 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5185   SDLoc dl = getCurSDLoc();
5186 
5187   AtomicOrdering Ordering = I.getOrdering();
5188   SyncScope::ID SSID = I.getSyncScopeID();
5189 
5190   SDValue InChain = getRoot();
5191 
5192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5193   EVT MemVT =
5194       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5195 
5196   if (!TLI.supportsUnalignedAtomics() &&
5197       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5198     report_fatal_error("Cannot generate unaligned atomic store");
5199 
5200   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5201 
5202   MachineFunction &MF = DAG.getMachineFunction();
5203   MachineMemOperand *MMO = MF.getMachineMemOperand(
5204       MachinePointerInfo(I.getPointerOperand()), Flags,
5205       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5206       nullptr, SSID, Ordering);
5207 
5208   SDValue Val = getValue(I.getValueOperand());
5209   if (Val.getValueType() != MemVT)
5210     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5211   SDValue Ptr = getValue(I.getPointerOperand());
5212 
5213   SDValue OutChain =
5214       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5215 
5216   setValue(&I, OutChain);
5217   DAG.setRoot(OutChain);
5218 }
5219 
5220 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5221 /// node.
5222 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5223                                                unsigned Intrinsic) {
5224   // Ignore the callsite's attributes. A specific call site may be marked with
5225   // readnone, but the lowering code will expect the chain based on the
5226   // definition.
5227   const Function *F = I.getCalledFunction();
5228   bool HasChain = !F->doesNotAccessMemory();
5229   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5230 
5231   // Build the operand list.
5232   SmallVector<SDValue, 8> Ops;
5233   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5234     if (OnlyLoad) {
5235       // We don't need to serialize loads against other loads.
5236       Ops.push_back(DAG.getRoot());
5237     } else {
5238       Ops.push_back(getRoot());
5239     }
5240   }
5241 
5242   // Info is set by getTgtMemIntrinsic
5243   TargetLowering::IntrinsicInfo Info;
5244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5245   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5246                                                DAG.getMachineFunction(),
5247                                                Intrinsic);
5248 
5249   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5250   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5251       Info.opc == ISD::INTRINSIC_W_CHAIN)
5252     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5253                                         TLI.getPointerTy(DAG.getDataLayout())));
5254 
5255   // Add all operands of the call to the operand list.
5256   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5257     const Value *Arg = I.getArgOperand(i);
5258     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5259       Ops.push_back(getValue(Arg));
5260       continue;
5261     }
5262 
5263     // Use TargetConstant instead of a regular constant for immarg.
5264     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5265     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5266       assert(CI->getBitWidth() <= 64 &&
5267              "large intrinsic immediates not handled");
5268       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5269     } else {
5270       Ops.push_back(
5271           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5272     }
5273   }
5274 
5275   SmallVector<EVT, 4> ValueVTs;
5276   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5277 
5278   if (HasChain)
5279     ValueVTs.push_back(MVT::Other);
5280 
5281   SDVTList VTs = DAG.getVTList(ValueVTs);
5282 
5283   // Propagate fast-math-flags from IR to node(s).
5284   SDNodeFlags Flags;
5285   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5286     Flags.copyFMF(*FPMO);
5287   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5288 
5289   // Create the node.
5290   SDValue Result;
5291 
5292   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5293     auto *Token = Bundle->Inputs[0].get();
5294     SDValue ConvControlToken = getValue(Token);
5295     assert(Ops.back().getValueType() != MVT::Glue &&
5296            "Did not expected another glue node here.");
5297     ConvControlToken =
5298         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5299     Ops.push_back(ConvControlToken);
5300   }
5301 
5302   // In some cases, custom collection of operands from CallInst I may be needed.
5303   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5304   if (IsTgtIntrinsic) {
5305     // This is target intrinsic that touches memory
5306     //
5307     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5308     //       didn't yield anything useful.
5309     MachinePointerInfo MPI;
5310     if (Info.ptrVal)
5311       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5312     else if (Info.fallbackAddressSpace)
5313       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5314     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5315                                      Info.memVT, MPI, Info.align, Info.flags,
5316                                      Info.size, I.getAAMetadata());
5317   } else if (!HasChain) {
5318     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5319   } else if (!I.getType()->isVoidTy()) {
5320     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5321   } else {
5322     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5323   }
5324 
5325   if (HasChain) {
5326     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5327     if (OnlyLoad)
5328       PendingLoads.push_back(Chain);
5329     else
5330       DAG.setRoot(Chain);
5331   }
5332 
5333   if (!I.getType()->isVoidTy()) {
5334     if (!isa<VectorType>(I.getType()))
5335       Result = lowerRangeToAssertZExt(DAG, I, Result);
5336 
5337     MaybeAlign Alignment = I.getRetAlign();
5338 
5339     // Insert `assertalign` node if there's an alignment.
5340     if (InsertAssertAlign && Alignment) {
5341       Result =
5342           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5343     }
5344   }
5345 
5346   setValue(&I, Result);
5347 }
5348 
5349 /// GetSignificand - Get the significand and build it into a floating-point
5350 /// number with exponent of 1:
5351 ///
5352 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5353 ///
5354 /// where Op is the hexadecimal representation of floating point value.
5355 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5356   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5357                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5358   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5359                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5360   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5361 }
5362 
5363 /// GetExponent - Get the exponent:
5364 ///
5365 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5366 ///
5367 /// where Op is the hexadecimal representation of floating point value.
5368 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5369                            const TargetLowering &TLI, const SDLoc &dl) {
5370   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5371                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5372   SDValue t1 = DAG.getNode(
5373       ISD::SRL, dl, MVT::i32, t0,
5374       DAG.getConstant(23, dl,
5375                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5376   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5377                            DAG.getConstant(127, dl, MVT::i32));
5378   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5379 }
5380 
5381 /// getF32Constant - Get 32-bit floating point constant.
5382 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5383                               const SDLoc &dl) {
5384   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5385                            MVT::f32);
5386 }
5387 
5388 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5389                                        SelectionDAG &DAG) {
5390   // TODO: What fast-math-flags should be set on the floating-point nodes?
5391 
5392   //   IntegerPartOfX = ((int32_t)(t0);
5393   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5394 
5395   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5396   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5397   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5398 
5399   //   IntegerPartOfX <<= 23;
5400   IntegerPartOfX =
5401       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5402                   DAG.getConstant(23, dl,
5403                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5404                                       MVT::i32, DAG.getDataLayout())));
5405 
5406   SDValue TwoToFractionalPartOfX;
5407   if (LimitFloatPrecision <= 6) {
5408     // For floating-point precision of 6:
5409     //
5410     //   TwoToFractionalPartOfX =
5411     //     0.997535578f +
5412     //       (0.735607626f + 0.252464424f * x) * x;
5413     //
5414     // error 0.0144103317, which is 6 bits
5415     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5416                              getF32Constant(DAG, 0x3e814304, dl));
5417     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5418                              getF32Constant(DAG, 0x3f3c50c8, dl));
5419     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5420     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5421                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5422   } else if (LimitFloatPrecision <= 12) {
5423     // For floating-point precision of 12:
5424     //
5425     //   TwoToFractionalPartOfX =
5426     //     0.999892986f +
5427     //       (0.696457318f +
5428     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5429     //
5430     // error 0.000107046256, which is 13 to 14 bits
5431     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5432                              getF32Constant(DAG, 0x3da235e3, dl));
5433     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5434                              getF32Constant(DAG, 0x3e65b8f3, dl));
5435     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5436     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5437                              getF32Constant(DAG, 0x3f324b07, dl));
5438     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5439     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5440                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5441   } else { // LimitFloatPrecision <= 18
5442     // For floating-point precision of 18:
5443     //
5444     //   TwoToFractionalPartOfX =
5445     //     0.999999982f +
5446     //       (0.693148872f +
5447     //         (0.240227044f +
5448     //           (0.554906021e-1f +
5449     //             (0.961591928e-2f +
5450     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5451     // error 2.47208000*10^(-7), which is better than 18 bits
5452     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5453                              getF32Constant(DAG, 0x3924b03e, dl));
5454     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5455                              getF32Constant(DAG, 0x3ab24b87, dl));
5456     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5457     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5458                              getF32Constant(DAG, 0x3c1d8c17, dl));
5459     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5460     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5461                              getF32Constant(DAG, 0x3d634a1d, dl));
5462     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5463     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5464                              getF32Constant(DAG, 0x3e75fe14, dl));
5465     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5466     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5467                               getF32Constant(DAG, 0x3f317234, dl));
5468     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5469     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5470                                          getF32Constant(DAG, 0x3f800000, dl));
5471   }
5472 
5473   // Add the exponent into the result in integer domain.
5474   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5475   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5476                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5477 }
5478 
5479 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5480 /// limited-precision mode.
5481 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5482                          const TargetLowering &TLI, SDNodeFlags Flags) {
5483   if (Op.getValueType() == MVT::f32 &&
5484       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5485 
5486     // Put the exponent in the right bit position for later addition to the
5487     // final result:
5488     //
5489     // t0 = Op * log2(e)
5490 
5491     // TODO: What fast-math-flags should be set here?
5492     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5493                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5494     return getLimitedPrecisionExp2(t0, dl, DAG);
5495   }
5496 
5497   // No special expansion.
5498   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5499 }
5500 
5501 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5502 /// limited-precision mode.
5503 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5504                          const TargetLowering &TLI, SDNodeFlags Flags) {
5505   // TODO: What fast-math-flags should be set on the floating-point nodes?
5506 
5507   if (Op.getValueType() == MVT::f32 &&
5508       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5509     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5510 
5511     // Scale the exponent by log(2).
5512     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5513     SDValue LogOfExponent =
5514         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5515                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5516 
5517     // Get the significand and build it into a floating-point number with
5518     // exponent of 1.
5519     SDValue X = GetSignificand(DAG, Op1, dl);
5520 
5521     SDValue LogOfMantissa;
5522     if (LimitFloatPrecision <= 6) {
5523       // For floating-point precision of 6:
5524       //
5525       //   LogofMantissa =
5526       //     -1.1609546f +
5527       //       (1.4034025f - 0.23903021f * x) * x;
5528       //
5529       // error 0.0034276066, which is better than 8 bits
5530       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5531                                getF32Constant(DAG, 0xbe74c456, dl));
5532       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5533                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5534       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5535       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5536                                   getF32Constant(DAG, 0x3f949a29, dl));
5537     } else if (LimitFloatPrecision <= 12) {
5538       // For floating-point precision of 12:
5539       //
5540       //   LogOfMantissa =
5541       //     -1.7417939f +
5542       //       (2.8212026f +
5543       //         (-1.4699568f +
5544       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5545       //
5546       // error 0.000061011436, which is 14 bits
5547       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5548                                getF32Constant(DAG, 0xbd67b6d6, dl));
5549       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5550                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5551       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5552       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5553                                getF32Constant(DAG, 0x3fbc278b, dl));
5554       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5555       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5556                                getF32Constant(DAG, 0x40348e95, dl));
5557       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5558       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5559                                   getF32Constant(DAG, 0x3fdef31a, dl));
5560     } else { // LimitFloatPrecision <= 18
5561       // For floating-point precision of 18:
5562       //
5563       //   LogOfMantissa =
5564       //     -2.1072184f +
5565       //       (4.2372794f +
5566       //         (-3.7029485f +
5567       //           (2.2781945f +
5568       //             (-0.87823314f +
5569       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5570       //
5571       // error 0.0000023660568, which is better than 18 bits
5572       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5573                                getF32Constant(DAG, 0xbc91e5ac, dl));
5574       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5575                                getF32Constant(DAG, 0x3e4350aa, dl));
5576       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5577       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5578                                getF32Constant(DAG, 0x3f60d3e3, dl));
5579       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5580       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5581                                getF32Constant(DAG, 0x4011cdf0, dl));
5582       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5583       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5584                                getF32Constant(DAG, 0x406cfd1c, dl));
5585       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5586       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5587                                getF32Constant(DAG, 0x408797cb, dl));
5588       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5589       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5590                                   getF32Constant(DAG, 0x4006dcab, dl));
5591     }
5592 
5593     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5594   }
5595 
5596   // No special expansion.
5597   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5598 }
5599 
5600 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5601 /// limited-precision mode.
5602 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5603                           const TargetLowering &TLI, SDNodeFlags Flags) {
5604   // TODO: What fast-math-flags should be set on the floating-point nodes?
5605 
5606   if (Op.getValueType() == MVT::f32 &&
5607       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5608     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5609 
5610     // Get the exponent.
5611     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5612 
5613     // Get the significand and build it into a floating-point number with
5614     // exponent of 1.
5615     SDValue X = GetSignificand(DAG, Op1, dl);
5616 
5617     // Different possible minimax approximations of significand in
5618     // floating-point for various degrees of accuracy over [1,2].
5619     SDValue Log2ofMantissa;
5620     if (LimitFloatPrecision <= 6) {
5621       // For floating-point precision of 6:
5622       //
5623       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5624       //
5625       // error 0.0049451742, which is more than 7 bits
5626       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5627                                getF32Constant(DAG, 0xbeb08fe0, dl));
5628       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5629                                getF32Constant(DAG, 0x40019463, dl));
5630       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5631       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5632                                    getF32Constant(DAG, 0x3fd6633d, dl));
5633     } else if (LimitFloatPrecision <= 12) {
5634       // For floating-point precision of 12:
5635       //
5636       //   Log2ofMantissa =
5637       //     -2.51285454f +
5638       //       (4.07009056f +
5639       //         (-2.12067489f +
5640       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5641       //
5642       // error 0.0000876136000, which is better than 13 bits
5643       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5644                                getF32Constant(DAG, 0xbda7262e, dl));
5645       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5646                                getF32Constant(DAG, 0x3f25280b, dl));
5647       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5648       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5649                                getF32Constant(DAG, 0x4007b923, dl));
5650       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5651       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5652                                getF32Constant(DAG, 0x40823e2f, dl));
5653       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5654       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5655                                    getF32Constant(DAG, 0x4020d29c, dl));
5656     } else { // LimitFloatPrecision <= 18
5657       // For floating-point precision of 18:
5658       //
5659       //   Log2ofMantissa =
5660       //     -3.0400495f +
5661       //       (6.1129976f +
5662       //         (-5.3420409f +
5663       //           (3.2865683f +
5664       //             (-1.2669343f +
5665       //               (0.27515199f -
5666       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5667       //
5668       // error 0.0000018516, which is better than 18 bits
5669       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5670                                getF32Constant(DAG, 0xbcd2769e, dl));
5671       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5672                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5673       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5674       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5675                                getF32Constant(DAG, 0x3fa22ae7, dl));
5676       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5677       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5678                                getF32Constant(DAG, 0x40525723, dl));
5679       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5680       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5681                                getF32Constant(DAG, 0x40aaf200, dl));
5682       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5683       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5684                                getF32Constant(DAG, 0x40c39dad, dl));
5685       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5686       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5687                                    getF32Constant(DAG, 0x4042902c, dl));
5688     }
5689 
5690     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5691   }
5692 
5693   // No special expansion.
5694   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5695 }
5696 
5697 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5698 /// limited-precision mode.
5699 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5700                            const TargetLowering &TLI, SDNodeFlags Flags) {
5701   // TODO: What fast-math-flags should be set on the floating-point nodes?
5702 
5703   if (Op.getValueType() == MVT::f32 &&
5704       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5705     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5706 
5707     // Scale the exponent by log10(2) [0.30102999f].
5708     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5709     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5710                                         getF32Constant(DAG, 0x3e9a209a, dl));
5711 
5712     // Get the significand and build it into a floating-point number with
5713     // exponent of 1.
5714     SDValue X = GetSignificand(DAG, Op1, dl);
5715 
5716     SDValue Log10ofMantissa;
5717     if (LimitFloatPrecision <= 6) {
5718       // For floating-point precision of 6:
5719       //
5720       //   Log10ofMantissa =
5721       //     -0.50419619f +
5722       //       (0.60948995f - 0.10380950f * x) * x;
5723       //
5724       // error 0.0014886165, which is 6 bits
5725       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5726                                getF32Constant(DAG, 0xbdd49a13, dl));
5727       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5728                                getF32Constant(DAG, 0x3f1c0789, dl));
5729       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5730       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5731                                     getF32Constant(DAG, 0x3f011300, dl));
5732     } else if (LimitFloatPrecision <= 12) {
5733       // For floating-point precision of 12:
5734       //
5735       //   Log10ofMantissa =
5736       //     -0.64831180f +
5737       //       (0.91751397f +
5738       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5739       //
5740       // error 0.00019228036, which is better than 12 bits
5741       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5742                                getF32Constant(DAG, 0x3d431f31, dl));
5743       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5744                                getF32Constant(DAG, 0x3ea21fb2, dl));
5745       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5746       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5747                                getF32Constant(DAG, 0x3f6ae232, dl));
5748       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5749       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5750                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5751     } else { // LimitFloatPrecision <= 18
5752       // For floating-point precision of 18:
5753       //
5754       //   Log10ofMantissa =
5755       //     -0.84299375f +
5756       //       (1.5327582f +
5757       //         (-1.0688956f +
5758       //           (0.49102474f +
5759       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5760       //
5761       // error 0.0000037995730, which is better than 18 bits
5762       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5763                                getF32Constant(DAG, 0x3c5d51ce, dl));
5764       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5765                                getF32Constant(DAG, 0x3e00685a, dl));
5766       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5767       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5768                                getF32Constant(DAG, 0x3efb6798, dl));
5769       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5770       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5771                                getF32Constant(DAG, 0x3f88d192, dl));
5772       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5773       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5774                                getF32Constant(DAG, 0x3fc4316c, dl));
5775       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5776       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5777                                     getF32Constant(DAG, 0x3f57ce70, dl));
5778     }
5779 
5780     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5781   }
5782 
5783   // No special expansion.
5784   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5785 }
5786 
5787 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5788 /// limited-precision mode.
5789 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5790                           const TargetLowering &TLI, SDNodeFlags Flags) {
5791   if (Op.getValueType() == MVT::f32 &&
5792       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5793     return getLimitedPrecisionExp2(Op, dl, DAG);
5794 
5795   // No special expansion.
5796   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5797 }
5798 
5799 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5800 /// limited-precision mode with x == 10.0f.
5801 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5802                          SelectionDAG &DAG, const TargetLowering &TLI,
5803                          SDNodeFlags Flags) {
5804   bool IsExp10 = false;
5805   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5806       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5807     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5808       APFloat Ten(10.0f);
5809       IsExp10 = LHSC->isExactlyValue(Ten);
5810     }
5811   }
5812 
5813   // TODO: What fast-math-flags should be set on the FMUL node?
5814   if (IsExp10) {
5815     // Put the exponent in the right bit position for later addition to the
5816     // final result:
5817     //
5818     //   #define LOG2OF10 3.3219281f
5819     //   t0 = Op * LOG2OF10;
5820     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5821                              getF32Constant(DAG, 0x40549a78, dl));
5822     return getLimitedPrecisionExp2(t0, dl, DAG);
5823   }
5824 
5825   // No special expansion.
5826   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5827 }
5828 
5829 /// ExpandPowI - Expand a llvm.powi intrinsic.
5830 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5831                           SelectionDAG &DAG) {
5832   // If RHS is a constant, we can expand this out to a multiplication tree if
5833   // it's beneficial on the target, otherwise we end up lowering to a call to
5834   // __powidf2 (for example).
5835   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5836     unsigned Val = RHSC->getSExtValue();
5837 
5838     // powi(x, 0) -> 1.0
5839     if (Val == 0)
5840       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5841 
5842     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5843             Val, DAG.shouldOptForSize())) {
5844       // Get the exponent as a positive value.
5845       if ((int)Val < 0)
5846         Val = -Val;
5847       // We use the simple binary decomposition method to generate the multiply
5848       // sequence.  There are more optimal ways to do this (for example,
5849       // powi(x,15) generates one more multiply than it should), but this has
5850       // the benefit of being both really simple and much better than a libcall.
5851       SDValue Res; // Logically starts equal to 1.0
5852       SDValue CurSquare = LHS;
5853       // TODO: Intrinsics should have fast-math-flags that propagate to these
5854       // nodes.
5855       while (Val) {
5856         if (Val & 1) {
5857           if (Res.getNode())
5858             Res =
5859                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5860           else
5861             Res = CurSquare; // 1.0*CurSquare.
5862         }
5863 
5864         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5865                                 CurSquare, CurSquare);
5866         Val >>= 1;
5867       }
5868 
5869       // If the original was negative, invert the result, producing 1/(x*x*x).
5870       if (RHSC->getSExtValue() < 0)
5871         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5872                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5873       return Res;
5874     }
5875   }
5876 
5877   // Otherwise, expand to a libcall.
5878   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5879 }
5880 
5881 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5882                             SDValue LHS, SDValue RHS, SDValue Scale,
5883                             SelectionDAG &DAG, const TargetLowering &TLI) {
5884   EVT VT = LHS.getValueType();
5885   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5886   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5887   LLVMContext &Ctx = *DAG.getContext();
5888 
5889   // If the type is legal but the operation isn't, this node might survive all
5890   // the way to operation legalization. If we end up there and we do not have
5891   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5892   // node.
5893 
5894   // Coax the legalizer into expanding the node during type legalization instead
5895   // by bumping the size by one bit. This will force it to Promote, enabling the
5896   // early expansion and avoiding the need to expand later.
5897 
5898   // We don't have to do this if Scale is 0; that can always be expanded, unless
5899   // it's a saturating signed operation. Those can experience true integer
5900   // division overflow, a case which we must avoid.
5901 
5902   // FIXME: We wouldn't have to do this (or any of the early
5903   // expansion/promotion) if it was possible to expand a libcall of an
5904   // illegal type during operation legalization. But it's not, so things
5905   // get a bit hacky.
5906   unsigned ScaleInt = Scale->getAsZExtVal();
5907   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5908       (TLI.isTypeLegal(VT) ||
5909        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5910     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5911         Opcode, VT, ScaleInt);
5912     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5913       EVT PromVT;
5914       if (VT.isScalarInteger())
5915         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5916       else if (VT.isVector()) {
5917         PromVT = VT.getVectorElementType();
5918         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5919         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5920       } else
5921         llvm_unreachable("Wrong VT for DIVFIX?");
5922       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5923       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5924       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5925       // For saturating operations, we need to shift up the LHS to get the
5926       // proper saturation width, and then shift down again afterwards.
5927       if (Saturating)
5928         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5929                           DAG.getConstant(1, DL, ShiftTy));
5930       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5931       if (Saturating)
5932         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5933                           DAG.getConstant(1, DL, ShiftTy));
5934       return DAG.getZExtOrTrunc(Res, DL, VT);
5935     }
5936   }
5937 
5938   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5939 }
5940 
5941 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5942 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5943 static void
5944 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5945                      const SDValue &N) {
5946   switch (N.getOpcode()) {
5947   case ISD::CopyFromReg: {
5948     SDValue Op = N.getOperand(1);
5949     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5950                       Op.getValueType().getSizeInBits());
5951     return;
5952   }
5953   case ISD::BITCAST:
5954   case ISD::AssertZext:
5955   case ISD::AssertSext:
5956   case ISD::TRUNCATE:
5957     getUnderlyingArgRegs(Regs, N.getOperand(0));
5958     return;
5959   case ISD::BUILD_PAIR:
5960   case ISD::BUILD_VECTOR:
5961   case ISD::CONCAT_VECTORS:
5962     for (SDValue Op : N->op_values())
5963       getUnderlyingArgRegs(Regs, Op);
5964     return;
5965   default:
5966     return;
5967   }
5968 }
5969 
5970 /// If the DbgValueInst is a dbg_value of a function argument, create the
5971 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5972 /// instruction selection, they will be inserted to the entry BB.
5973 /// We don't currently support this for variadic dbg_values, as they shouldn't
5974 /// appear for function arguments or in the prologue.
5975 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5976     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5977     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5978   const Argument *Arg = dyn_cast<Argument>(V);
5979   if (!Arg)
5980     return false;
5981 
5982   MachineFunction &MF = DAG.getMachineFunction();
5983   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5984 
5985   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5986   // we've been asked to pursue.
5987   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5988                               bool Indirect) {
5989     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5990       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5991       // pointing at the VReg, which will be patched up later.
5992       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5993       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5994           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5995           /* isKill */ false, /* isDead */ false,
5996           /* isUndef */ false, /* isEarlyClobber */ false,
5997           /* SubReg */ 0, /* isDebug */ true)});
5998 
5999       auto *NewDIExpr = FragExpr;
6000       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6001       // the DIExpression.
6002       if (Indirect)
6003         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6004       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6005       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6006       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6007     } else {
6008       // Create a completely standard DBG_VALUE.
6009       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6010       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6011     }
6012   };
6013 
6014   if (Kind == FuncArgumentDbgValueKind::Value) {
6015     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6016     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6017     // the entry block.
6018     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6019     if (!IsInEntryBlock)
6020       return false;
6021 
6022     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6023     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6024     // variable that also is a param.
6025     //
6026     // Although, if we are at the top of the entry block already, we can still
6027     // emit using ArgDbgValue. This might catch some situations when the
6028     // dbg.value refers to an argument that isn't used in the entry block, so
6029     // any CopyToReg node would be optimized out and the only way to express
6030     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6031     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6032     // we should only emit as ArgDbgValue if the Variable is an argument to the
6033     // current function, and the dbg.value intrinsic is found in the entry
6034     // block.
6035     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6036         !DL->getInlinedAt();
6037     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6038     if (!IsInPrologue && !VariableIsFunctionInputArg)
6039       return false;
6040 
6041     // Here we assume that a function argument on IR level only can be used to
6042     // describe one input parameter on source level. If we for example have
6043     // source code like this
6044     //
6045     //    struct A { long x, y; };
6046     //    void foo(struct A a, long b) {
6047     //      ...
6048     //      b = a.x;
6049     //      ...
6050     //    }
6051     //
6052     // and IR like this
6053     //
6054     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6055     //  entry:
6056     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6057     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6058     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6059     //    ...
6060     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6061     //    ...
6062     //
6063     // then the last dbg.value is describing a parameter "b" using a value that
6064     // is an argument. But since we already has used %a1 to describe a parameter
6065     // we should not handle that last dbg.value here (that would result in an
6066     // incorrect hoisting of the DBG_VALUE to the function entry).
6067     // Notice that we allow one dbg.value per IR level argument, to accommodate
6068     // for the situation with fragments above.
6069     // If there is no node for the value being handled, we return true to skip
6070     // the normal generation of debug info, as it would kill existing debug
6071     // info for the parameter in case of duplicates.
6072     if (VariableIsFunctionInputArg) {
6073       unsigned ArgNo = Arg->getArgNo();
6074       if (ArgNo >= FuncInfo.DescribedArgs.size())
6075         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6076       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6077         return !NodeMap[V].getNode();
6078       FuncInfo.DescribedArgs.set(ArgNo);
6079     }
6080   }
6081 
6082   bool IsIndirect = false;
6083   std::optional<MachineOperand> Op;
6084   // Some arguments' frame index is recorded during argument lowering.
6085   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6086   if (FI != std::numeric_limits<int>::max())
6087     Op = MachineOperand::CreateFI(FI);
6088 
6089   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6090   if (!Op && N.getNode()) {
6091     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6092     Register Reg;
6093     if (ArgRegsAndSizes.size() == 1)
6094       Reg = ArgRegsAndSizes.front().first;
6095 
6096     if (Reg && Reg.isVirtual()) {
6097       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6098       Register PR = RegInfo.getLiveInPhysReg(Reg);
6099       if (PR)
6100         Reg = PR;
6101     }
6102     if (Reg) {
6103       Op = MachineOperand::CreateReg(Reg, false);
6104       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6105     }
6106   }
6107 
6108   if (!Op && N.getNode()) {
6109     // Check if frame index is available.
6110     SDValue LCandidate = peekThroughBitcasts(N);
6111     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6112       if (FrameIndexSDNode *FINode =
6113           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6114         Op = MachineOperand::CreateFI(FINode->getIndex());
6115   }
6116 
6117   if (!Op) {
6118     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6119     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6120                                          SplitRegs) {
6121       unsigned Offset = 0;
6122       for (const auto &RegAndSize : SplitRegs) {
6123         // If the expression is already a fragment, the current register
6124         // offset+size might extend beyond the fragment. In this case, only
6125         // the register bits that are inside the fragment are relevant.
6126         int RegFragmentSizeInBits = RegAndSize.second;
6127         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6128           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6129           // The register is entirely outside the expression fragment,
6130           // so is irrelevant for debug info.
6131           if (Offset >= ExprFragmentSizeInBits)
6132             break;
6133           // The register is partially outside the expression fragment, only
6134           // the low bits within the fragment are relevant for debug info.
6135           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6136             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6137           }
6138         }
6139 
6140         auto FragmentExpr = DIExpression::createFragmentExpression(
6141             Expr, Offset, RegFragmentSizeInBits);
6142         Offset += RegAndSize.second;
6143         // If a valid fragment expression cannot be created, the variable's
6144         // correct value cannot be determined and so it is set as Undef.
6145         if (!FragmentExpr) {
6146           SDDbgValue *SDV = DAG.getConstantDbgValue(
6147               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6148           DAG.AddDbgValue(SDV, false);
6149           continue;
6150         }
6151         MachineInstr *NewMI =
6152             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6153                              Kind != FuncArgumentDbgValueKind::Value);
6154         FuncInfo.ArgDbgValues.push_back(NewMI);
6155       }
6156     };
6157 
6158     // Check if ValueMap has reg number.
6159     DenseMap<const Value *, Register>::const_iterator
6160       VMI = FuncInfo.ValueMap.find(V);
6161     if (VMI != FuncInfo.ValueMap.end()) {
6162       const auto &TLI = DAG.getTargetLoweringInfo();
6163       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6164                        V->getType(), std::nullopt);
6165       if (RFV.occupiesMultipleRegs()) {
6166         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6167         return true;
6168       }
6169 
6170       Op = MachineOperand::CreateReg(VMI->second, false);
6171       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6172     } else if (ArgRegsAndSizes.size() > 1) {
6173       // This was split due to the calling convention, and no virtual register
6174       // mapping exists for the value.
6175       splitMultiRegDbgValue(ArgRegsAndSizes);
6176       return true;
6177     }
6178   }
6179 
6180   if (!Op)
6181     return false;
6182 
6183   assert(Variable->isValidLocationForIntrinsic(DL) &&
6184          "Expected inlined-at fields to agree");
6185   MachineInstr *NewMI = nullptr;
6186 
6187   if (Op->isReg())
6188     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6189   else
6190     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6191                     Variable, Expr);
6192 
6193   // Otherwise, use ArgDbgValues.
6194   FuncInfo.ArgDbgValues.push_back(NewMI);
6195   return true;
6196 }
6197 
6198 /// Return the appropriate SDDbgValue based on N.
6199 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6200                                              DILocalVariable *Variable,
6201                                              DIExpression *Expr,
6202                                              const DebugLoc &dl,
6203                                              unsigned DbgSDNodeOrder) {
6204   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6205     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6206     // stack slot locations.
6207     //
6208     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6209     // debug values here after optimization:
6210     //
6211     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6212     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6213     //
6214     // Both describe the direct values of their associated variables.
6215     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6216                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6217   }
6218   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6219                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6220 }
6221 
6222 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6223   switch (Intrinsic) {
6224   case Intrinsic::smul_fix:
6225     return ISD::SMULFIX;
6226   case Intrinsic::umul_fix:
6227     return ISD::UMULFIX;
6228   case Intrinsic::smul_fix_sat:
6229     return ISD::SMULFIXSAT;
6230   case Intrinsic::umul_fix_sat:
6231     return ISD::UMULFIXSAT;
6232   case Intrinsic::sdiv_fix:
6233     return ISD::SDIVFIX;
6234   case Intrinsic::udiv_fix:
6235     return ISD::UDIVFIX;
6236   case Intrinsic::sdiv_fix_sat:
6237     return ISD::SDIVFIXSAT;
6238   case Intrinsic::udiv_fix_sat:
6239     return ISD::UDIVFIXSAT;
6240   default:
6241     llvm_unreachable("Unhandled fixed point intrinsic");
6242   }
6243 }
6244 
6245 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6246                                            const char *FunctionName) {
6247   assert(FunctionName && "FunctionName must not be nullptr");
6248   SDValue Callee = DAG.getExternalSymbol(
6249       FunctionName,
6250       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6251   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6252 }
6253 
6254 /// Given a @llvm.call.preallocated.setup, return the corresponding
6255 /// preallocated call.
6256 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6257   assert(cast<CallBase>(PreallocatedSetup)
6258                  ->getCalledFunction()
6259                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6260          "expected call_preallocated_setup Value");
6261   for (const auto *U : PreallocatedSetup->users()) {
6262     auto *UseCall = cast<CallBase>(U);
6263     const Function *Fn = UseCall->getCalledFunction();
6264     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6265       return UseCall;
6266     }
6267   }
6268   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6269 }
6270 
6271 /// If DI is a debug value with an EntryValue expression, lower it using the
6272 /// corresponding physical register of the associated Argument value
6273 /// (guaranteed to exist by the verifier).
6274 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6275     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6276     DIExpression *Expr, DebugLoc DbgLoc) {
6277   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6278     return false;
6279 
6280   // These properties are guaranteed by the verifier.
6281   const Argument *Arg = cast<Argument>(Values[0]);
6282   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6283 
6284   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6285   if (ArgIt == FuncInfo.ValueMap.end()) {
6286     LLVM_DEBUG(
6287         dbgs() << "Dropping dbg.value: expression is entry_value but "
6288                   "couldn't find an associated register for the Argument\n");
6289     return true;
6290   }
6291   Register ArgVReg = ArgIt->getSecond();
6292 
6293   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6294     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6295       SDDbgValue *SDV = DAG.getVRegDbgValue(
6296           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6297       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6298       return true;
6299     }
6300   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6301                        "couldn't find a physical register\n");
6302   return true;
6303 }
6304 
6305 /// Lower the call to the specified intrinsic function.
6306 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6307                                                   unsigned Intrinsic) {
6308   SDLoc sdl = getCurSDLoc();
6309   switch (Intrinsic) {
6310   case Intrinsic::experimental_convergence_anchor:
6311     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6312     break;
6313   case Intrinsic::experimental_convergence_entry:
6314     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6315     break;
6316   case Intrinsic::experimental_convergence_loop: {
6317     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6318     auto *Token = Bundle->Inputs[0].get();
6319     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6320                              getValue(Token)));
6321     break;
6322   }
6323   }
6324 }
6325 
6326 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6327                                                unsigned IntrinsicID) {
6328   // For now, we're only lowering an 'add' histogram.
6329   // We can add others later, e.g. saturating adds, min/max.
6330   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6331          "Tried to lower unsupported histogram type");
6332   SDLoc sdl = getCurSDLoc();
6333   Value *Ptr = I.getOperand(0);
6334   SDValue Inc = getValue(I.getOperand(1));
6335   SDValue Mask = getValue(I.getOperand(2));
6336 
6337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6338   DataLayout TargetDL = DAG.getDataLayout();
6339   EVT VT = Inc.getValueType();
6340   Align Alignment = DAG.getEVTAlign(VT);
6341 
6342   const MDNode *Ranges = getRangeMetadata(I);
6343 
6344   SDValue Root = DAG.getRoot();
6345   SDValue Base;
6346   SDValue Index;
6347   ISD::MemIndexType IndexType;
6348   SDValue Scale;
6349   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6350                                     I.getParent(), VT.getScalarStoreSize());
6351 
6352   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6353 
6354   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6355       MachinePointerInfo(AS),
6356       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6357       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6358 
6359   if (!UniformBase) {
6360     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6361     Index = getValue(Ptr);
6362     IndexType = ISD::SIGNED_SCALED;
6363     Scale =
6364         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6365   }
6366 
6367   EVT IdxVT = Index.getValueType();
6368   EVT EltTy = IdxVT.getVectorElementType();
6369   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6370     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6371     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6372   }
6373 
6374   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6375 
6376   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6377   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6378                                              Ops, MMO, IndexType);
6379 
6380   setValue(&I, Histogram);
6381   DAG.setRoot(Histogram);
6382 }
6383 
6384 /// Lower the call to the specified intrinsic function.
6385 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6386                                              unsigned Intrinsic) {
6387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6388   SDLoc sdl = getCurSDLoc();
6389   DebugLoc dl = getCurDebugLoc();
6390   SDValue Res;
6391 
6392   SDNodeFlags Flags;
6393   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6394     Flags.copyFMF(*FPOp);
6395 
6396   switch (Intrinsic) {
6397   default:
6398     // By default, turn this into a target intrinsic node.
6399     visitTargetIntrinsic(I, Intrinsic);
6400     return;
6401   case Intrinsic::vscale: {
6402     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6403     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6404     return;
6405   }
6406   case Intrinsic::vastart:  visitVAStart(I); return;
6407   case Intrinsic::vaend:    visitVAEnd(I); return;
6408   case Intrinsic::vacopy:   visitVACopy(I); return;
6409   case Intrinsic::returnaddress:
6410     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6411                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6412                              getValue(I.getArgOperand(0))));
6413     return;
6414   case Intrinsic::addressofreturnaddress:
6415     setValue(&I,
6416              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6417                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6418     return;
6419   case Intrinsic::sponentry:
6420     setValue(&I,
6421              DAG.getNode(ISD::SPONENTRY, sdl,
6422                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6423     return;
6424   case Intrinsic::frameaddress:
6425     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6426                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6427                              getValue(I.getArgOperand(0))));
6428     return;
6429   case Intrinsic::read_volatile_register:
6430   case Intrinsic::read_register: {
6431     Value *Reg = I.getArgOperand(0);
6432     SDValue Chain = getRoot();
6433     SDValue RegName =
6434         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6435     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6436     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6437       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6438     setValue(&I, Res);
6439     DAG.setRoot(Res.getValue(1));
6440     return;
6441   }
6442   case Intrinsic::write_register: {
6443     Value *Reg = I.getArgOperand(0);
6444     Value *RegValue = I.getArgOperand(1);
6445     SDValue Chain = getRoot();
6446     SDValue RegName =
6447         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6448     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6449                             RegName, getValue(RegValue)));
6450     return;
6451   }
6452   case Intrinsic::memcpy: {
6453     const auto &MCI = cast<MemCpyInst>(I);
6454     SDValue Op1 = getValue(I.getArgOperand(0));
6455     SDValue Op2 = getValue(I.getArgOperand(1));
6456     SDValue Op3 = getValue(I.getArgOperand(2));
6457     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6458     Align DstAlign = MCI.getDestAlign().valueOrOne();
6459     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6460     Align Alignment = std::min(DstAlign, SrcAlign);
6461     bool isVol = MCI.isVolatile();
6462     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6463     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6464     // node.
6465     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6466     SDValue MC = DAG.getMemcpy(
6467         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6468         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6469         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6470     updateDAGForMaybeTailCall(MC);
6471     return;
6472   }
6473   case Intrinsic::memcpy_inline: {
6474     const auto &MCI = cast<MemCpyInlineInst>(I);
6475     SDValue Dst = getValue(I.getArgOperand(0));
6476     SDValue Src = getValue(I.getArgOperand(1));
6477     SDValue Size = getValue(I.getArgOperand(2));
6478     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6479     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6480     Align DstAlign = MCI.getDestAlign().valueOrOne();
6481     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6482     Align Alignment = std::min(DstAlign, SrcAlign);
6483     bool isVol = MCI.isVolatile();
6484     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6485     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6486     // node.
6487     SDValue MC = DAG.getMemcpy(
6488         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6489         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6490         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6491     updateDAGForMaybeTailCall(MC);
6492     return;
6493   }
6494   case Intrinsic::memset: {
6495     const auto &MSI = cast<MemSetInst>(I);
6496     SDValue Op1 = getValue(I.getArgOperand(0));
6497     SDValue Op2 = getValue(I.getArgOperand(1));
6498     SDValue Op3 = getValue(I.getArgOperand(2));
6499     // @llvm.memset defines 0 and 1 to both mean no alignment.
6500     Align Alignment = MSI.getDestAlign().valueOrOne();
6501     bool isVol = MSI.isVolatile();
6502     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6503     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6504     SDValue MS = DAG.getMemset(
6505         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6506         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6507     updateDAGForMaybeTailCall(MS);
6508     return;
6509   }
6510   case Intrinsic::memset_inline: {
6511     const auto &MSII = cast<MemSetInlineInst>(I);
6512     SDValue Dst = getValue(I.getArgOperand(0));
6513     SDValue Value = getValue(I.getArgOperand(1));
6514     SDValue Size = getValue(I.getArgOperand(2));
6515     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6516     // @llvm.memset defines 0 and 1 to both mean no alignment.
6517     Align DstAlign = MSII.getDestAlign().valueOrOne();
6518     bool isVol = MSII.isVolatile();
6519     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6520     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6521     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6522                                /* AlwaysInline */ true, isTC,
6523                                MachinePointerInfo(I.getArgOperand(0)),
6524                                I.getAAMetadata());
6525     updateDAGForMaybeTailCall(MC);
6526     return;
6527   }
6528   case Intrinsic::memmove: {
6529     const auto &MMI = cast<MemMoveInst>(I);
6530     SDValue Op1 = getValue(I.getArgOperand(0));
6531     SDValue Op2 = getValue(I.getArgOperand(1));
6532     SDValue Op3 = getValue(I.getArgOperand(2));
6533     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6534     Align DstAlign = MMI.getDestAlign().valueOrOne();
6535     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6536     Align Alignment = std::min(DstAlign, SrcAlign);
6537     bool isVol = MMI.isVolatile();
6538     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6539     // FIXME: Support passing different dest/src alignments to the memmove DAG
6540     // node.
6541     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6542     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6543                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6544                                 MachinePointerInfo(I.getArgOperand(1)),
6545                                 I.getAAMetadata(), AA);
6546     updateDAGForMaybeTailCall(MM);
6547     return;
6548   }
6549   case Intrinsic::memcpy_element_unordered_atomic: {
6550     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6551     SDValue Dst = getValue(MI.getRawDest());
6552     SDValue Src = getValue(MI.getRawSource());
6553     SDValue Length = getValue(MI.getLength());
6554 
6555     Type *LengthTy = MI.getLength()->getType();
6556     unsigned ElemSz = MI.getElementSizeInBytes();
6557     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6558     SDValue MC =
6559         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6560                             isTC, MachinePointerInfo(MI.getRawDest()),
6561                             MachinePointerInfo(MI.getRawSource()));
6562     updateDAGForMaybeTailCall(MC);
6563     return;
6564   }
6565   case Intrinsic::memmove_element_unordered_atomic: {
6566     auto &MI = cast<AtomicMemMoveInst>(I);
6567     SDValue Dst = getValue(MI.getRawDest());
6568     SDValue Src = getValue(MI.getRawSource());
6569     SDValue Length = getValue(MI.getLength());
6570 
6571     Type *LengthTy = MI.getLength()->getType();
6572     unsigned ElemSz = MI.getElementSizeInBytes();
6573     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6574     SDValue MC =
6575         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6576                              isTC, MachinePointerInfo(MI.getRawDest()),
6577                              MachinePointerInfo(MI.getRawSource()));
6578     updateDAGForMaybeTailCall(MC);
6579     return;
6580   }
6581   case Intrinsic::memset_element_unordered_atomic: {
6582     auto &MI = cast<AtomicMemSetInst>(I);
6583     SDValue Dst = getValue(MI.getRawDest());
6584     SDValue Val = getValue(MI.getValue());
6585     SDValue Length = getValue(MI.getLength());
6586 
6587     Type *LengthTy = MI.getLength()->getType();
6588     unsigned ElemSz = MI.getElementSizeInBytes();
6589     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6590     SDValue MC =
6591         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6592                             isTC, MachinePointerInfo(MI.getRawDest()));
6593     updateDAGForMaybeTailCall(MC);
6594     return;
6595   }
6596   case Intrinsic::call_preallocated_setup: {
6597     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6598     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6599     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6600                               getRoot(), SrcValue);
6601     setValue(&I, Res);
6602     DAG.setRoot(Res);
6603     return;
6604   }
6605   case Intrinsic::call_preallocated_arg: {
6606     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6607     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6608     SDValue Ops[3];
6609     Ops[0] = getRoot();
6610     Ops[1] = SrcValue;
6611     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6612                                    MVT::i32); // arg index
6613     SDValue Res = DAG.getNode(
6614         ISD::PREALLOCATED_ARG, sdl,
6615         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6616     setValue(&I, Res);
6617     DAG.setRoot(Res.getValue(1));
6618     return;
6619   }
6620   case Intrinsic::dbg_declare: {
6621     const auto &DI = cast<DbgDeclareInst>(I);
6622     // Debug intrinsics are handled separately in assignment tracking mode.
6623     // Some intrinsics are handled right after Argument lowering.
6624     if (AssignmentTrackingEnabled ||
6625         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6626       return;
6627     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6628     DILocalVariable *Variable = DI.getVariable();
6629     DIExpression *Expression = DI.getExpression();
6630     dropDanglingDebugInfo(Variable, Expression);
6631     // Assume dbg.declare can not currently use DIArgList, i.e.
6632     // it is non-variadic.
6633     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6634     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6635                        DI.getDebugLoc());
6636     return;
6637   }
6638   case Intrinsic::dbg_label: {
6639     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6640     DILabel *Label = DI.getLabel();
6641     assert(Label && "Missing label");
6642 
6643     SDDbgLabel *SDV;
6644     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6645     DAG.AddDbgLabel(SDV);
6646     return;
6647   }
6648   case Intrinsic::dbg_assign: {
6649     // Debug intrinsics are handled separately in assignment tracking mode.
6650     if (AssignmentTrackingEnabled)
6651       return;
6652     // If assignment tracking hasn't been enabled then fall through and treat
6653     // the dbg.assign as a dbg.value.
6654     [[fallthrough]];
6655   }
6656   case Intrinsic::dbg_value: {
6657     // Debug intrinsics are handled separately in assignment tracking mode.
6658     if (AssignmentTrackingEnabled)
6659       return;
6660     const DbgValueInst &DI = cast<DbgValueInst>(I);
6661     assert(DI.getVariable() && "Missing variable");
6662 
6663     DILocalVariable *Variable = DI.getVariable();
6664     DIExpression *Expression = DI.getExpression();
6665     dropDanglingDebugInfo(Variable, Expression);
6666 
6667     if (DI.isKillLocation()) {
6668       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6669       return;
6670     }
6671 
6672     SmallVector<Value *, 4> Values(DI.getValues());
6673     if (Values.empty())
6674       return;
6675 
6676     bool IsVariadic = DI.hasArgList();
6677     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6678                           SDNodeOrder, IsVariadic))
6679       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6680                            DI.getDebugLoc(), SDNodeOrder);
6681     return;
6682   }
6683 
6684   case Intrinsic::eh_typeid_for: {
6685     // Find the type id for the given typeinfo.
6686     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6687     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6688     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6689     setValue(&I, Res);
6690     return;
6691   }
6692 
6693   case Intrinsic::eh_return_i32:
6694   case Intrinsic::eh_return_i64:
6695     DAG.getMachineFunction().setCallsEHReturn(true);
6696     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6697                             MVT::Other,
6698                             getControlRoot(),
6699                             getValue(I.getArgOperand(0)),
6700                             getValue(I.getArgOperand(1))));
6701     return;
6702   case Intrinsic::eh_unwind_init:
6703     DAG.getMachineFunction().setCallsUnwindInit(true);
6704     return;
6705   case Intrinsic::eh_dwarf_cfa:
6706     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6707                              TLI.getPointerTy(DAG.getDataLayout()),
6708                              getValue(I.getArgOperand(0))));
6709     return;
6710   case Intrinsic::eh_sjlj_callsite: {
6711     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6712     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6713     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6714 
6715     MMI.setCurrentCallSite(CI->getZExtValue());
6716     return;
6717   }
6718   case Intrinsic::eh_sjlj_functioncontext: {
6719     // Get and store the index of the function context.
6720     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6721     AllocaInst *FnCtx =
6722       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6723     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6724     MFI.setFunctionContextIndex(FI);
6725     return;
6726   }
6727   case Intrinsic::eh_sjlj_setjmp: {
6728     SDValue Ops[2];
6729     Ops[0] = getRoot();
6730     Ops[1] = getValue(I.getArgOperand(0));
6731     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6732                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6733     setValue(&I, Op.getValue(0));
6734     DAG.setRoot(Op.getValue(1));
6735     return;
6736   }
6737   case Intrinsic::eh_sjlj_longjmp:
6738     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6739                             getRoot(), getValue(I.getArgOperand(0))));
6740     return;
6741   case Intrinsic::eh_sjlj_setup_dispatch:
6742     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6743                             getRoot()));
6744     return;
6745   case Intrinsic::masked_gather:
6746     visitMaskedGather(I);
6747     return;
6748   case Intrinsic::masked_load:
6749     visitMaskedLoad(I);
6750     return;
6751   case Intrinsic::masked_scatter:
6752     visitMaskedScatter(I);
6753     return;
6754   case Intrinsic::masked_store:
6755     visitMaskedStore(I);
6756     return;
6757   case Intrinsic::masked_expandload:
6758     visitMaskedLoad(I, true /* IsExpanding */);
6759     return;
6760   case Intrinsic::masked_compressstore:
6761     visitMaskedStore(I, true /* IsCompressing */);
6762     return;
6763   case Intrinsic::powi:
6764     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6765                             getValue(I.getArgOperand(1)), DAG));
6766     return;
6767   case Intrinsic::log:
6768     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6769     return;
6770   case Intrinsic::log2:
6771     setValue(&I,
6772              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6773     return;
6774   case Intrinsic::log10:
6775     setValue(&I,
6776              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6777     return;
6778   case Intrinsic::exp:
6779     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6780     return;
6781   case Intrinsic::exp2:
6782     setValue(&I,
6783              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6784     return;
6785   case Intrinsic::pow:
6786     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6787                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6788     return;
6789   case Intrinsic::sqrt:
6790   case Intrinsic::fabs:
6791   case Intrinsic::sin:
6792   case Intrinsic::cos:
6793   case Intrinsic::tan:
6794   case Intrinsic::exp10:
6795   case Intrinsic::floor:
6796   case Intrinsic::ceil:
6797   case Intrinsic::trunc:
6798   case Intrinsic::rint:
6799   case Intrinsic::nearbyint:
6800   case Intrinsic::round:
6801   case Intrinsic::roundeven:
6802   case Intrinsic::canonicalize: {
6803     unsigned Opcode;
6804     // clang-format off
6805     switch (Intrinsic) {
6806     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6807     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6808     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6809     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6810     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6811     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6812     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6813     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6814     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6815     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6816     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6817     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6818     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6819     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6820     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6821     }
6822     // clang-format on
6823 
6824     setValue(&I, DAG.getNode(Opcode, sdl,
6825                              getValue(I.getArgOperand(0)).getValueType(),
6826                              getValue(I.getArgOperand(0)), Flags));
6827     return;
6828   }
6829   case Intrinsic::lround:
6830   case Intrinsic::llround:
6831   case Intrinsic::lrint:
6832   case Intrinsic::llrint: {
6833     unsigned Opcode;
6834     // clang-format off
6835     switch (Intrinsic) {
6836     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6837     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6838     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6839     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6840     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6841     }
6842     // clang-format on
6843 
6844     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6845     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6846                              getValue(I.getArgOperand(0))));
6847     return;
6848   }
6849   case Intrinsic::minnum:
6850     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6851                              getValue(I.getArgOperand(0)).getValueType(),
6852                              getValue(I.getArgOperand(0)),
6853                              getValue(I.getArgOperand(1)), Flags));
6854     return;
6855   case Intrinsic::maxnum:
6856     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6857                              getValue(I.getArgOperand(0)).getValueType(),
6858                              getValue(I.getArgOperand(0)),
6859                              getValue(I.getArgOperand(1)), Flags));
6860     return;
6861   case Intrinsic::minimum:
6862     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6863                              getValue(I.getArgOperand(0)).getValueType(),
6864                              getValue(I.getArgOperand(0)),
6865                              getValue(I.getArgOperand(1)), Flags));
6866     return;
6867   case Intrinsic::maximum:
6868     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6869                              getValue(I.getArgOperand(0)).getValueType(),
6870                              getValue(I.getArgOperand(0)),
6871                              getValue(I.getArgOperand(1)), Flags));
6872     return;
6873   case Intrinsic::copysign:
6874     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6875                              getValue(I.getArgOperand(0)).getValueType(),
6876                              getValue(I.getArgOperand(0)),
6877                              getValue(I.getArgOperand(1)), Flags));
6878     return;
6879   case Intrinsic::ldexp:
6880     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6881                              getValue(I.getArgOperand(0)).getValueType(),
6882                              getValue(I.getArgOperand(0)),
6883                              getValue(I.getArgOperand(1)), Flags));
6884     return;
6885   case Intrinsic::frexp: {
6886     SmallVector<EVT, 2> ValueVTs;
6887     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6888     SDVTList VTs = DAG.getVTList(ValueVTs);
6889     setValue(&I,
6890              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6891     return;
6892   }
6893   case Intrinsic::arithmetic_fence: {
6894     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6895                              getValue(I.getArgOperand(0)).getValueType(),
6896                              getValue(I.getArgOperand(0)), Flags));
6897     return;
6898   }
6899   case Intrinsic::fma:
6900     setValue(&I, DAG.getNode(
6901                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6902                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6903                      getValue(I.getArgOperand(2)), Flags));
6904     return;
6905 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6906   case Intrinsic::INTRINSIC:
6907 #include "llvm/IR/ConstrainedOps.def"
6908     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6909     return;
6910 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6911 #include "llvm/IR/VPIntrinsics.def"
6912     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6913     return;
6914   case Intrinsic::fptrunc_round: {
6915     // Get the last argument, the metadata and convert it to an integer in the
6916     // call
6917     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6918     std::optional<RoundingMode> RoundMode =
6919         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6920 
6921     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6922 
6923     // Propagate fast-math-flags from IR to node(s).
6924     SDNodeFlags Flags;
6925     Flags.copyFMF(*cast<FPMathOperator>(&I));
6926     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6927 
6928     SDValue Result;
6929     Result = DAG.getNode(
6930         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6931         DAG.getTargetConstant((int)*RoundMode, sdl,
6932                               TLI.getPointerTy(DAG.getDataLayout())));
6933     setValue(&I, Result);
6934 
6935     return;
6936   }
6937   case Intrinsic::fmuladd: {
6938     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6939     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6940         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6941       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6942                                getValue(I.getArgOperand(0)).getValueType(),
6943                                getValue(I.getArgOperand(0)),
6944                                getValue(I.getArgOperand(1)),
6945                                getValue(I.getArgOperand(2)), Flags));
6946     } else {
6947       // TODO: Intrinsic calls should have fast-math-flags.
6948       SDValue Mul = DAG.getNode(
6949           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6950           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6951       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6952                                 getValue(I.getArgOperand(0)).getValueType(),
6953                                 Mul, getValue(I.getArgOperand(2)), Flags);
6954       setValue(&I, Add);
6955     }
6956     return;
6957   }
6958   case Intrinsic::convert_to_fp16:
6959     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6960                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6961                                          getValue(I.getArgOperand(0)),
6962                                          DAG.getTargetConstant(0, sdl,
6963                                                                MVT::i32))));
6964     return;
6965   case Intrinsic::convert_from_fp16:
6966     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6967                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6968                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6969                                          getValue(I.getArgOperand(0)))));
6970     return;
6971   case Intrinsic::fptosi_sat: {
6972     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6973     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6974                              getValue(I.getArgOperand(0)),
6975                              DAG.getValueType(VT.getScalarType())));
6976     return;
6977   }
6978   case Intrinsic::fptoui_sat: {
6979     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6980     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6981                              getValue(I.getArgOperand(0)),
6982                              DAG.getValueType(VT.getScalarType())));
6983     return;
6984   }
6985   case Intrinsic::set_rounding:
6986     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6987                       {getRoot(), getValue(I.getArgOperand(0))});
6988     setValue(&I, Res);
6989     DAG.setRoot(Res.getValue(0));
6990     return;
6991   case Intrinsic::is_fpclass: {
6992     const DataLayout DLayout = DAG.getDataLayout();
6993     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6994     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6995     FPClassTest Test = static_cast<FPClassTest>(
6996         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6997     MachineFunction &MF = DAG.getMachineFunction();
6998     const Function &F = MF.getFunction();
6999     SDValue Op = getValue(I.getArgOperand(0));
7000     SDNodeFlags Flags;
7001     Flags.setNoFPExcept(
7002         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7003     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7004     // expansion can use illegal types. Making expansion early allows
7005     // legalizing these types prior to selection.
7006     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
7007       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7008       setValue(&I, Result);
7009       return;
7010     }
7011 
7012     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7013     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7014     setValue(&I, V);
7015     return;
7016   }
7017   case Intrinsic::get_fpenv: {
7018     const DataLayout DLayout = DAG.getDataLayout();
7019     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7020     Align TempAlign = DAG.getEVTAlign(EnvVT);
7021     SDValue Chain = getRoot();
7022     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7023     // and temporary storage in stack.
7024     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7025       Res = DAG.getNode(
7026           ISD::GET_FPENV, sdl,
7027           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7028                         MVT::Other),
7029           Chain);
7030     } else {
7031       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7032       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7033       auto MPI =
7034           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7035       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7036           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7037           TempAlign);
7038       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7039       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7040     }
7041     setValue(&I, Res);
7042     DAG.setRoot(Res.getValue(1));
7043     return;
7044   }
7045   case Intrinsic::set_fpenv: {
7046     const DataLayout DLayout = DAG.getDataLayout();
7047     SDValue Env = getValue(I.getArgOperand(0));
7048     EVT EnvVT = Env.getValueType();
7049     Align TempAlign = DAG.getEVTAlign(EnvVT);
7050     SDValue Chain = getRoot();
7051     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7052     // environment from memory.
7053     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7054       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7055     } else {
7056       // Allocate space in stack, copy environment bits into it and use this
7057       // memory in SET_FPENV_MEM.
7058       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7059       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7060       auto MPI =
7061           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7062       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7063                            MachineMemOperand::MOStore);
7064       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7065           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7066           TempAlign);
7067       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7068     }
7069     DAG.setRoot(Chain);
7070     return;
7071   }
7072   case Intrinsic::reset_fpenv:
7073     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7074     return;
7075   case Intrinsic::get_fpmode:
7076     Res = DAG.getNode(
7077         ISD::GET_FPMODE, sdl,
7078         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7079                       MVT::Other),
7080         DAG.getRoot());
7081     setValue(&I, Res);
7082     DAG.setRoot(Res.getValue(1));
7083     return;
7084   case Intrinsic::set_fpmode:
7085     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7086                       getValue(I.getArgOperand(0)));
7087     DAG.setRoot(Res);
7088     return;
7089   case Intrinsic::reset_fpmode: {
7090     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7091     DAG.setRoot(Res);
7092     return;
7093   }
7094   case Intrinsic::pcmarker: {
7095     SDValue Tmp = getValue(I.getArgOperand(0));
7096     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7097     return;
7098   }
7099   case Intrinsic::readcyclecounter: {
7100     SDValue Op = getRoot();
7101     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7102                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7103     setValue(&I, Res);
7104     DAG.setRoot(Res.getValue(1));
7105     return;
7106   }
7107   case Intrinsic::readsteadycounter: {
7108     SDValue Op = getRoot();
7109     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7110                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7111     setValue(&I, Res);
7112     DAG.setRoot(Res.getValue(1));
7113     return;
7114   }
7115   case Intrinsic::bitreverse:
7116     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7117                              getValue(I.getArgOperand(0)).getValueType(),
7118                              getValue(I.getArgOperand(0))));
7119     return;
7120   case Intrinsic::bswap:
7121     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7122                              getValue(I.getArgOperand(0)).getValueType(),
7123                              getValue(I.getArgOperand(0))));
7124     return;
7125   case Intrinsic::cttz: {
7126     SDValue Arg = getValue(I.getArgOperand(0));
7127     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7128     EVT Ty = Arg.getValueType();
7129     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7130                              sdl, Ty, Arg));
7131     return;
7132   }
7133   case Intrinsic::ctlz: {
7134     SDValue Arg = getValue(I.getArgOperand(0));
7135     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7136     EVT Ty = Arg.getValueType();
7137     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7138                              sdl, Ty, Arg));
7139     return;
7140   }
7141   case Intrinsic::ctpop: {
7142     SDValue Arg = getValue(I.getArgOperand(0));
7143     EVT Ty = Arg.getValueType();
7144     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7145     return;
7146   }
7147   case Intrinsic::fshl:
7148   case Intrinsic::fshr: {
7149     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7150     SDValue X = getValue(I.getArgOperand(0));
7151     SDValue Y = getValue(I.getArgOperand(1));
7152     SDValue Z = getValue(I.getArgOperand(2));
7153     EVT VT = X.getValueType();
7154 
7155     if (X == Y) {
7156       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7157       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7158     } else {
7159       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7160       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7161     }
7162     return;
7163   }
7164   case Intrinsic::sadd_sat: {
7165     SDValue Op1 = getValue(I.getArgOperand(0));
7166     SDValue Op2 = getValue(I.getArgOperand(1));
7167     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7168     return;
7169   }
7170   case Intrinsic::uadd_sat: {
7171     SDValue Op1 = getValue(I.getArgOperand(0));
7172     SDValue Op2 = getValue(I.getArgOperand(1));
7173     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7174     return;
7175   }
7176   case Intrinsic::ssub_sat: {
7177     SDValue Op1 = getValue(I.getArgOperand(0));
7178     SDValue Op2 = getValue(I.getArgOperand(1));
7179     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7180     return;
7181   }
7182   case Intrinsic::usub_sat: {
7183     SDValue Op1 = getValue(I.getArgOperand(0));
7184     SDValue Op2 = getValue(I.getArgOperand(1));
7185     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7186     return;
7187   }
7188   case Intrinsic::sshl_sat: {
7189     SDValue Op1 = getValue(I.getArgOperand(0));
7190     SDValue Op2 = getValue(I.getArgOperand(1));
7191     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7192     return;
7193   }
7194   case Intrinsic::ushl_sat: {
7195     SDValue Op1 = getValue(I.getArgOperand(0));
7196     SDValue Op2 = getValue(I.getArgOperand(1));
7197     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7198     return;
7199   }
7200   case Intrinsic::smul_fix:
7201   case Intrinsic::umul_fix:
7202   case Intrinsic::smul_fix_sat:
7203   case Intrinsic::umul_fix_sat: {
7204     SDValue Op1 = getValue(I.getArgOperand(0));
7205     SDValue Op2 = getValue(I.getArgOperand(1));
7206     SDValue Op3 = getValue(I.getArgOperand(2));
7207     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7208                              Op1.getValueType(), Op1, Op2, Op3));
7209     return;
7210   }
7211   case Intrinsic::sdiv_fix:
7212   case Intrinsic::udiv_fix:
7213   case Intrinsic::sdiv_fix_sat:
7214   case Intrinsic::udiv_fix_sat: {
7215     SDValue Op1 = getValue(I.getArgOperand(0));
7216     SDValue Op2 = getValue(I.getArgOperand(1));
7217     SDValue Op3 = getValue(I.getArgOperand(2));
7218     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7219                               Op1, Op2, Op3, DAG, TLI));
7220     return;
7221   }
7222   case Intrinsic::smax: {
7223     SDValue Op1 = getValue(I.getArgOperand(0));
7224     SDValue Op2 = getValue(I.getArgOperand(1));
7225     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7226     return;
7227   }
7228   case Intrinsic::smin: {
7229     SDValue Op1 = getValue(I.getArgOperand(0));
7230     SDValue Op2 = getValue(I.getArgOperand(1));
7231     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7232     return;
7233   }
7234   case Intrinsic::umax: {
7235     SDValue Op1 = getValue(I.getArgOperand(0));
7236     SDValue Op2 = getValue(I.getArgOperand(1));
7237     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7238     return;
7239   }
7240   case Intrinsic::umin: {
7241     SDValue Op1 = getValue(I.getArgOperand(0));
7242     SDValue Op2 = getValue(I.getArgOperand(1));
7243     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7244     return;
7245   }
7246   case Intrinsic::abs: {
7247     // TODO: Preserve "int min is poison" arg in SDAG?
7248     SDValue Op1 = getValue(I.getArgOperand(0));
7249     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7250     return;
7251   }
7252   case Intrinsic::scmp: {
7253     SDValue Op1 = getValue(I.getArgOperand(0));
7254     SDValue Op2 = getValue(I.getArgOperand(1));
7255     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7256     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7257     break;
7258   }
7259   case Intrinsic::ucmp: {
7260     SDValue Op1 = getValue(I.getArgOperand(0));
7261     SDValue Op2 = getValue(I.getArgOperand(1));
7262     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7263     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7264     break;
7265   }
7266   case Intrinsic::stacksave: {
7267     SDValue Op = getRoot();
7268     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7269     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7270     setValue(&I, Res);
7271     DAG.setRoot(Res.getValue(1));
7272     return;
7273   }
7274   case Intrinsic::stackrestore:
7275     Res = getValue(I.getArgOperand(0));
7276     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7277     return;
7278   case Intrinsic::get_dynamic_area_offset: {
7279     SDValue Op = getRoot();
7280     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7281     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7282     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7283     // target.
7284     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7285       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7286                          " intrinsic!");
7287     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7288                       Op);
7289     DAG.setRoot(Op);
7290     setValue(&I, Res);
7291     return;
7292   }
7293   case Intrinsic::stackguard: {
7294     MachineFunction &MF = DAG.getMachineFunction();
7295     const Module &M = *MF.getFunction().getParent();
7296     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7297     SDValue Chain = getRoot();
7298     if (TLI.useLoadStackGuardNode()) {
7299       Res = getLoadStackGuard(DAG, sdl, Chain);
7300       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7301     } else {
7302       const Value *Global = TLI.getSDagStackGuard(M);
7303       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7304       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7305                         MachinePointerInfo(Global, 0), Align,
7306                         MachineMemOperand::MOVolatile);
7307     }
7308     if (TLI.useStackGuardXorFP())
7309       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7310     DAG.setRoot(Chain);
7311     setValue(&I, Res);
7312     return;
7313   }
7314   case Intrinsic::stackprotector: {
7315     // Emit code into the DAG to store the stack guard onto the stack.
7316     MachineFunction &MF = DAG.getMachineFunction();
7317     MachineFrameInfo &MFI = MF.getFrameInfo();
7318     SDValue Src, Chain = getRoot();
7319 
7320     if (TLI.useLoadStackGuardNode())
7321       Src = getLoadStackGuard(DAG, sdl, Chain);
7322     else
7323       Src = getValue(I.getArgOperand(0));   // The guard's value.
7324 
7325     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7326 
7327     int FI = FuncInfo.StaticAllocaMap[Slot];
7328     MFI.setStackProtectorIndex(FI);
7329     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7330 
7331     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7332 
7333     // Store the stack protector onto the stack.
7334     Res = DAG.getStore(
7335         Chain, sdl, Src, FIN,
7336         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7337         MaybeAlign(), MachineMemOperand::MOVolatile);
7338     setValue(&I, Res);
7339     DAG.setRoot(Res);
7340     return;
7341   }
7342   case Intrinsic::objectsize:
7343     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7344 
7345   case Intrinsic::is_constant:
7346     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7347 
7348   case Intrinsic::annotation:
7349   case Intrinsic::ptr_annotation:
7350   case Intrinsic::launder_invariant_group:
7351   case Intrinsic::strip_invariant_group:
7352     // Drop the intrinsic, but forward the value
7353     setValue(&I, getValue(I.getOperand(0)));
7354     return;
7355 
7356   case Intrinsic::assume:
7357   case Intrinsic::experimental_noalias_scope_decl:
7358   case Intrinsic::var_annotation:
7359   case Intrinsic::sideeffect:
7360     // Discard annotate attributes, noalias scope declarations, assumptions, and
7361     // artificial side-effects.
7362     return;
7363 
7364   case Intrinsic::codeview_annotation: {
7365     // Emit a label associated with this metadata.
7366     MachineFunction &MF = DAG.getMachineFunction();
7367     MCSymbol *Label =
7368         MF.getMMI().getContext().createTempSymbol("annotation", true);
7369     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7370     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7371     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7372     DAG.setRoot(Res);
7373     return;
7374   }
7375 
7376   case Intrinsic::init_trampoline: {
7377     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7378 
7379     SDValue Ops[6];
7380     Ops[0] = getRoot();
7381     Ops[1] = getValue(I.getArgOperand(0));
7382     Ops[2] = getValue(I.getArgOperand(1));
7383     Ops[3] = getValue(I.getArgOperand(2));
7384     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7385     Ops[5] = DAG.getSrcValue(F);
7386 
7387     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7388 
7389     DAG.setRoot(Res);
7390     return;
7391   }
7392   case Intrinsic::adjust_trampoline:
7393     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7394                              TLI.getPointerTy(DAG.getDataLayout()),
7395                              getValue(I.getArgOperand(0))));
7396     return;
7397   case Intrinsic::gcroot: {
7398     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7399            "only valid in functions with gc specified, enforced by Verifier");
7400     assert(GFI && "implied by previous");
7401     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7402     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7403 
7404     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7405     GFI->addStackRoot(FI->getIndex(), TypeMap);
7406     return;
7407   }
7408   case Intrinsic::gcread:
7409   case Intrinsic::gcwrite:
7410     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7411   case Intrinsic::get_rounding:
7412     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7413     setValue(&I, Res);
7414     DAG.setRoot(Res.getValue(1));
7415     return;
7416 
7417   case Intrinsic::expect:
7418     // Just replace __builtin_expect(exp, c) with EXP.
7419     setValue(&I, getValue(I.getArgOperand(0)));
7420     return;
7421 
7422   case Intrinsic::ubsantrap:
7423   case Intrinsic::debugtrap:
7424   case Intrinsic::trap: {
7425     StringRef TrapFuncName =
7426         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7427     if (TrapFuncName.empty()) {
7428       switch (Intrinsic) {
7429       case Intrinsic::trap:
7430         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7431         break;
7432       case Intrinsic::debugtrap:
7433         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7434         break;
7435       case Intrinsic::ubsantrap:
7436         DAG.setRoot(DAG.getNode(
7437             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7438             DAG.getTargetConstant(
7439                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7440                 MVT::i32)));
7441         break;
7442       default: llvm_unreachable("unknown trap intrinsic");
7443       }
7444       return;
7445     }
7446     TargetLowering::ArgListTy Args;
7447     if (Intrinsic == Intrinsic::ubsantrap) {
7448       Args.push_back(TargetLoweringBase::ArgListEntry());
7449       Args[0].Val = I.getArgOperand(0);
7450       Args[0].Node = getValue(Args[0].Val);
7451       Args[0].Ty = Args[0].Val->getType();
7452     }
7453 
7454     TargetLowering::CallLoweringInfo CLI(DAG);
7455     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7456         CallingConv::C, I.getType(),
7457         DAG.getExternalSymbol(TrapFuncName.data(),
7458                               TLI.getPointerTy(DAG.getDataLayout())),
7459         std::move(Args));
7460 
7461     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7462     DAG.setRoot(Result.second);
7463     return;
7464   }
7465 
7466   case Intrinsic::allow_runtime_check:
7467   case Intrinsic::allow_ubsan_check:
7468     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7469     return;
7470 
7471   case Intrinsic::uadd_with_overflow:
7472   case Intrinsic::sadd_with_overflow:
7473   case Intrinsic::usub_with_overflow:
7474   case Intrinsic::ssub_with_overflow:
7475   case Intrinsic::umul_with_overflow:
7476   case Intrinsic::smul_with_overflow: {
7477     ISD::NodeType Op;
7478     switch (Intrinsic) {
7479     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7480     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7481     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7482     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7483     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7484     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7485     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7486     }
7487     SDValue Op1 = getValue(I.getArgOperand(0));
7488     SDValue Op2 = getValue(I.getArgOperand(1));
7489 
7490     EVT ResultVT = Op1.getValueType();
7491     EVT OverflowVT = MVT::i1;
7492     if (ResultVT.isVector())
7493       OverflowVT = EVT::getVectorVT(
7494           *Context, OverflowVT, ResultVT.getVectorElementCount());
7495 
7496     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7497     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7498     return;
7499   }
7500   case Intrinsic::prefetch: {
7501     SDValue Ops[5];
7502     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7503     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7504     Ops[0] = DAG.getRoot();
7505     Ops[1] = getValue(I.getArgOperand(0));
7506     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7507                                    MVT::i32);
7508     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7509                                    MVT::i32);
7510     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7511                                    MVT::i32);
7512     SDValue Result = DAG.getMemIntrinsicNode(
7513         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7514         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7515         /* align */ std::nullopt, Flags);
7516 
7517     // Chain the prefetch in parallel with any pending loads, to stay out of
7518     // the way of later optimizations.
7519     PendingLoads.push_back(Result);
7520     Result = getRoot();
7521     DAG.setRoot(Result);
7522     return;
7523   }
7524   case Intrinsic::lifetime_start:
7525   case Intrinsic::lifetime_end: {
7526     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7527     // Stack coloring is not enabled in O0, discard region information.
7528     if (TM.getOptLevel() == CodeGenOptLevel::None)
7529       return;
7530 
7531     const int64_t ObjectSize =
7532         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7533     Value *const ObjectPtr = I.getArgOperand(1);
7534     SmallVector<const Value *, 4> Allocas;
7535     getUnderlyingObjects(ObjectPtr, Allocas);
7536 
7537     for (const Value *Alloca : Allocas) {
7538       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7539 
7540       // Could not find an Alloca.
7541       if (!LifetimeObject)
7542         continue;
7543 
7544       // First check that the Alloca is static, otherwise it won't have a
7545       // valid frame index.
7546       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7547       if (SI == FuncInfo.StaticAllocaMap.end())
7548         return;
7549 
7550       const int FrameIndex = SI->second;
7551       int64_t Offset;
7552       if (GetPointerBaseWithConstantOffset(
7553               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7554         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7555       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7556                                 Offset);
7557       DAG.setRoot(Res);
7558     }
7559     return;
7560   }
7561   case Intrinsic::pseudoprobe: {
7562     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7563     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7564     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7565     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7566     DAG.setRoot(Res);
7567     return;
7568   }
7569   case Intrinsic::invariant_start:
7570     // Discard region information.
7571     setValue(&I,
7572              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7573     return;
7574   case Intrinsic::invariant_end:
7575     // Discard region information.
7576     return;
7577   case Intrinsic::clear_cache: {
7578     SDValue InputChain = DAG.getRoot();
7579     SDValue StartVal = getValue(I.getArgOperand(0));
7580     SDValue EndVal = getValue(I.getArgOperand(1));
7581     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7582                       {InputChain, StartVal, EndVal});
7583     setValue(&I, Res);
7584     DAG.setRoot(Res);
7585     return;
7586   }
7587   case Intrinsic::donothing:
7588   case Intrinsic::seh_try_begin:
7589   case Intrinsic::seh_scope_begin:
7590   case Intrinsic::seh_try_end:
7591   case Intrinsic::seh_scope_end:
7592     // ignore
7593     return;
7594   case Intrinsic::experimental_stackmap:
7595     visitStackmap(I);
7596     return;
7597   case Intrinsic::experimental_patchpoint_void:
7598   case Intrinsic::experimental_patchpoint:
7599     visitPatchpoint(I);
7600     return;
7601   case Intrinsic::experimental_gc_statepoint:
7602     LowerStatepoint(cast<GCStatepointInst>(I));
7603     return;
7604   case Intrinsic::experimental_gc_result:
7605     visitGCResult(cast<GCResultInst>(I));
7606     return;
7607   case Intrinsic::experimental_gc_relocate:
7608     visitGCRelocate(cast<GCRelocateInst>(I));
7609     return;
7610   case Intrinsic::instrprof_cover:
7611     llvm_unreachable("instrprof failed to lower a cover");
7612   case Intrinsic::instrprof_increment:
7613     llvm_unreachable("instrprof failed to lower an increment");
7614   case Intrinsic::instrprof_timestamp:
7615     llvm_unreachable("instrprof failed to lower a timestamp");
7616   case Intrinsic::instrprof_value_profile:
7617     llvm_unreachable("instrprof failed to lower a value profiling call");
7618   case Intrinsic::instrprof_mcdc_parameters:
7619     llvm_unreachable("instrprof failed to lower mcdc parameters");
7620   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7621     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7622   case Intrinsic::localescape: {
7623     MachineFunction &MF = DAG.getMachineFunction();
7624     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7625 
7626     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7627     // is the same on all targets.
7628     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7629       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7630       if (isa<ConstantPointerNull>(Arg))
7631         continue; // Skip null pointers. They represent a hole in index space.
7632       AllocaInst *Slot = cast<AllocaInst>(Arg);
7633       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7634              "can only escape static allocas");
7635       int FI = FuncInfo.StaticAllocaMap[Slot];
7636       MCSymbol *FrameAllocSym =
7637           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7638               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7639       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7640               TII->get(TargetOpcode::LOCAL_ESCAPE))
7641           .addSym(FrameAllocSym)
7642           .addFrameIndex(FI);
7643     }
7644 
7645     return;
7646   }
7647 
7648   case Intrinsic::localrecover: {
7649     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7650     MachineFunction &MF = DAG.getMachineFunction();
7651 
7652     // Get the symbol that defines the frame offset.
7653     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7654     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7655     unsigned IdxVal =
7656         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7657     MCSymbol *FrameAllocSym =
7658         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7659             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7660 
7661     Value *FP = I.getArgOperand(1);
7662     SDValue FPVal = getValue(FP);
7663     EVT PtrVT = FPVal.getValueType();
7664 
7665     // Create a MCSymbol for the label to avoid any target lowering
7666     // that would make this PC relative.
7667     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7668     SDValue OffsetVal =
7669         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7670 
7671     // Add the offset to the FP.
7672     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7673     setValue(&I, Add);
7674 
7675     return;
7676   }
7677 
7678   case Intrinsic::eh_exceptionpointer:
7679   case Intrinsic::eh_exceptioncode: {
7680     // Get the exception pointer vreg, copy from it, and resize it to fit.
7681     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7682     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7683     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7684     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7685     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7686     if (Intrinsic == Intrinsic::eh_exceptioncode)
7687       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7688     setValue(&I, N);
7689     return;
7690   }
7691   case Intrinsic::xray_customevent: {
7692     // Here we want to make sure that the intrinsic behaves as if it has a
7693     // specific calling convention.
7694     const auto &Triple = DAG.getTarget().getTargetTriple();
7695     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7696       return;
7697 
7698     SmallVector<SDValue, 8> Ops;
7699 
7700     // We want to say that we always want the arguments in registers.
7701     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7702     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7703     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7704     SDValue Chain = getRoot();
7705     Ops.push_back(LogEntryVal);
7706     Ops.push_back(StrSizeVal);
7707     Ops.push_back(Chain);
7708 
7709     // We need to enforce the calling convention for the callsite, so that
7710     // argument ordering is enforced correctly, and that register allocation can
7711     // see that some registers may be assumed clobbered and have to preserve
7712     // them across calls to the intrinsic.
7713     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7714                                            sdl, NodeTys, Ops);
7715     SDValue patchableNode = SDValue(MN, 0);
7716     DAG.setRoot(patchableNode);
7717     setValue(&I, patchableNode);
7718     return;
7719   }
7720   case Intrinsic::xray_typedevent: {
7721     // Here we want to make sure that the intrinsic behaves as if it has a
7722     // specific calling convention.
7723     const auto &Triple = DAG.getTarget().getTargetTriple();
7724     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7725       return;
7726 
7727     SmallVector<SDValue, 8> Ops;
7728 
7729     // We want to say that we always want the arguments in registers.
7730     // It's unclear to me how manipulating the selection DAG here forces callers
7731     // to provide arguments in registers instead of on the stack.
7732     SDValue LogTypeId = getValue(I.getArgOperand(0));
7733     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7734     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7735     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7736     SDValue Chain = getRoot();
7737     Ops.push_back(LogTypeId);
7738     Ops.push_back(LogEntryVal);
7739     Ops.push_back(StrSizeVal);
7740     Ops.push_back(Chain);
7741 
7742     // We need to enforce the calling convention for the callsite, so that
7743     // argument ordering is enforced correctly, and that register allocation can
7744     // see that some registers may be assumed clobbered and have to preserve
7745     // them across calls to the intrinsic.
7746     MachineSDNode *MN = DAG.getMachineNode(
7747         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7748     SDValue patchableNode = SDValue(MN, 0);
7749     DAG.setRoot(patchableNode);
7750     setValue(&I, patchableNode);
7751     return;
7752   }
7753   case Intrinsic::experimental_deoptimize:
7754     LowerDeoptimizeCall(&I);
7755     return;
7756   case Intrinsic::experimental_stepvector:
7757     visitStepVector(I);
7758     return;
7759   case Intrinsic::vector_reduce_fadd:
7760   case Intrinsic::vector_reduce_fmul:
7761   case Intrinsic::vector_reduce_add:
7762   case Intrinsic::vector_reduce_mul:
7763   case Intrinsic::vector_reduce_and:
7764   case Intrinsic::vector_reduce_or:
7765   case Intrinsic::vector_reduce_xor:
7766   case Intrinsic::vector_reduce_smax:
7767   case Intrinsic::vector_reduce_smin:
7768   case Intrinsic::vector_reduce_umax:
7769   case Intrinsic::vector_reduce_umin:
7770   case Intrinsic::vector_reduce_fmax:
7771   case Intrinsic::vector_reduce_fmin:
7772   case Intrinsic::vector_reduce_fmaximum:
7773   case Intrinsic::vector_reduce_fminimum:
7774     visitVectorReduce(I, Intrinsic);
7775     return;
7776 
7777   case Intrinsic::icall_branch_funnel: {
7778     SmallVector<SDValue, 16> Ops;
7779     Ops.push_back(getValue(I.getArgOperand(0)));
7780 
7781     int64_t Offset;
7782     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7783         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7784     if (!Base)
7785       report_fatal_error(
7786           "llvm.icall.branch.funnel operand must be a GlobalValue");
7787     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7788 
7789     struct BranchFunnelTarget {
7790       int64_t Offset;
7791       SDValue Target;
7792     };
7793     SmallVector<BranchFunnelTarget, 8> Targets;
7794 
7795     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7796       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7797           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7798       if (ElemBase != Base)
7799         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7800                            "to the same GlobalValue");
7801 
7802       SDValue Val = getValue(I.getArgOperand(Op + 1));
7803       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7804       if (!GA)
7805         report_fatal_error(
7806             "llvm.icall.branch.funnel operand must be a GlobalValue");
7807       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7808                                      GA->getGlobal(), sdl, Val.getValueType(),
7809                                      GA->getOffset())});
7810     }
7811     llvm::sort(Targets,
7812                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7813                  return T1.Offset < T2.Offset;
7814                });
7815 
7816     for (auto &T : Targets) {
7817       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7818       Ops.push_back(T.Target);
7819     }
7820 
7821     Ops.push_back(DAG.getRoot()); // Chain
7822     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7823                                  MVT::Other, Ops),
7824               0);
7825     DAG.setRoot(N);
7826     setValue(&I, N);
7827     HasTailCall = true;
7828     return;
7829   }
7830 
7831   case Intrinsic::wasm_landingpad_index:
7832     // Information this intrinsic contained has been transferred to
7833     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7834     // delete it now.
7835     return;
7836 
7837   case Intrinsic::aarch64_settag:
7838   case Intrinsic::aarch64_settag_zero: {
7839     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7840     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7841     SDValue Val = TSI.EmitTargetCodeForSetTag(
7842         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7843         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7844         ZeroMemory);
7845     DAG.setRoot(Val);
7846     setValue(&I, Val);
7847     return;
7848   }
7849   case Intrinsic::amdgcn_cs_chain: {
7850     assert(I.arg_size() == 5 && "Additional args not supported yet");
7851     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7852            "Non-zero flags not supported yet");
7853 
7854     // At this point we don't care if it's amdgpu_cs_chain or
7855     // amdgpu_cs_chain_preserve.
7856     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7857 
7858     Type *RetTy = I.getType();
7859     assert(RetTy->isVoidTy() && "Should not return");
7860 
7861     SDValue Callee = getValue(I.getOperand(0));
7862 
7863     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7864     // We'll also tack the value of the EXEC mask at the end.
7865     TargetLowering::ArgListTy Args;
7866     Args.reserve(3);
7867 
7868     for (unsigned Idx : {2, 3, 1}) {
7869       TargetLowering::ArgListEntry Arg;
7870       Arg.Node = getValue(I.getOperand(Idx));
7871       Arg.Ty = I.getOperand(Idx)->getType();
7872       Arg.setAttributes(&I, Idx);
7873       Args.push_back(Arg);
7874     }
7875 
7876     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7877     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7878     Args[2].IsInReg = true; // EXEC should be inreg
7879 
7880     TargetLowering::CallLoweringInfo CLI(DAG);
7881     CLI.setDebugLoc(getCurSDLoc())
7882         .setChain(getRoot())
7883         .setCallee(CC, RetTy, Callee, std::move(Args))
7884         .setNoReturn(true)
7885         .setTailCall(true)
7886         .setConvergent(I.isConvergent());
7887     CLI.CB = &I;
7888     std::pair<SDValue, SDValue> Result =
7889         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7890     (void)Result;
7891     assert(!Result.first.getNode() && !Result.second.getNode() &&
7892            "Should've lowered as tail call");
7893 
7894     HasTailCall = true;
7895     return;
7896   }
7897   case Intrinsic::ptrmask: {
7898     SDValue Ptr = getValue(I.getOperand(0));
7899     SDValue Mask = getValue(I.getOperand(1));
7900 
7901     // On arm64_32, pointers are 32 bits when stored in memory, but
7902     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7903     // match the index type, but the pointer is 64 bits, so the the mask must be
7904     // zero-extended up to 64 bits to match the pointer.
7905     EVT PtrVT =
7906         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7907     EVT MemVT =
7908         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7909     assert(PtrVT == Ptr.getValueType());
7910     assert(MemVT == Mask.getValueType());
7911     if (MemVT != PtrVT)
7912       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7913 
7914     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7915     return;
7916   }
7917   case Intrinsic::threadlocal_address: {
7918     setValue(&I, getValue(I.getOperand(0)));
7919     return;
7920   }
7921   case Intrinsic::get_active_lane_mask: {
7922     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7923     SDValue Index = getValue(I.getOperand(0));
7924     EVT ElementVT = Index.getValueType();
7925 
7926     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7927       visitTargetIntrinsic(I, Intrinsic);
7928       return;
7929     }
7930 
7931     SDValue TripCount = getValue(I.getOperand(1));
7932     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7933                                  CCVT.getVectorElementCount());
7934 
7935     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7936     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7937     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7938     SDValue VectorInduction = DAG.getNode(
7939         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7940     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7941                                  VectorTripCount, ISD::CondCode::SETULT);
7942     setValue(&I, SetCC);
7943     return;
7944   }
7945   case Intrinsic::experimental_get_vector_length: {
7946     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7947            "Expected positive VF");
7948     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7949     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7950 
7951     SDValue Count = getValue(I.getOperand(0));
7952     EVT CountVT = Count.getValueType();
7953 
7954     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7955       visitTargetIntrinsic(I, Intrinsic);
7956       return;
7957     }
7958 
7959     // Expand to a umin between the trip count and the maximum elements the type
7960     // can hold.
7961     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7962 
7963     // Extend the trip count to at least the result VT.
7964     if (CountVT.bitsLT(VT)) {
7965       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7966       CountVT = VT;
7967     }
7968 
7969     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7970                                          ElementCount::get(VF, IsScalable));
7971 
7972     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7973     // Clip to the result type if needed.
7974     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7975 
7976     setValue(&I, Trunc);
7977     return;
7978   }
7979   case Intrinsic::experimental_cttz_elts: {
7980     auto DL = getCurSDLoc();
7981     SDValue Op = getValue(I.getOperand(0));
7982     EVT OpVT = Op.getValueType();
7983 
7984     if (!TLI.shouldExpandCttzElements(OpVT)) {
7985       visitTargetIntrinsic(I, Intrinsic);
7986       return;
7987     }
7988 
7989     if (OpVT.getScalarType() != MVT::i1) {
7990       // Compare the input vector elements to zero & use to count trailing zeros
7991       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7992       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7993                               OpVT.getVectorElementCount());
7994       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7995     }
7996 
7997     // If the zero-is-poison flag is set, we can assume the upper limit
7998     // of the result is VF-1.
7999     bool ZeroIsPoison =
8000         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8001     ConstantRange VScaleRange(1, true); // Dummy value.
8002     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8003       VScaleRange = getVScaleRange(I.getCaller(), 64);
8004     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8005         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8006 
8007     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8008 
8009     // Create the new vector type & get the vector length
8010     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8011                                  OpVT.getVectorElementCount());
8012 
8013     SDValue VL =
8014         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8015 
8016     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8017     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8018     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8019     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8020     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8021     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8022     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8023 
8024     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8025     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8026 
8027     setValue(&I, Ret);
8028     return;
8029   }
8030   case Intrinsic::vector_insert: {
8031     SDValue Vec = getValue(I.getOperand(0));
8032     SDValue SubVec = getValue(I.getOperand(1));
8033     SDValue Index = getValue(I.getOperand(2));
8034 
8035     // The intrinsic's index type is i64, but the SDNode requires an index type
8036     // suitable for the target. Convert the index as required.
8037     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8038     if (Index.getValueType() != VectorIdxTy)
8039       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8040 
8041     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8042     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8043                              Index));
8044     return;
8045   }
8046   case Intrinsic::vector_extract: {
8047     SDValue Vec = getValue(I.getOperand(0));
8048     SDValue Index = getValue(I.getOperand(1));
8049     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8050 
8051     // The intrinsic's index type is i64, but the SDNode requires an index type
8052     // suitable for the target. Convert the index as required.
8053     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8054     if (Index.getValueType() != VectorIdxTy)
8055       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8056 
8057     setValue(&I,
8058              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8059     return;
8060   }
8061   case Intrinsic::vector_reverse:
8062     visitVectorReverse(I);
8063     return;
8064   case Intrinsic::vector_splice:
8065     visitVectorSplice(I);
8066     return;
8067   case Intrinsic::callbr_landingpad:
8068     visitCallBrLandingPad(I);
8069     return;
8070   case Intrinsic::vector_interleave2:
8071     visitVectorInterleave(I);
8072     return;
8073   case Intrinsic::vector_deinterleave2:
8074     visitVectorDeinterleave(I);
8075     return;
8076   case Intrinsic::experimental_convergence_anchor:
8077   case Intrinsic::experimental_convergence_entry:
8078   case Intrinsic::experimental_convergence_loop:
8079     visitConvergenceControl(I, Intrinsic);
8080     return;
8081   case Intrinsic::experimental_vector_histogram_add: {
8082     visitVectorHistogram(I, Intrinsic);
8083     return;
8084   }
8085   }
8086 }
8087 
8088 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8089     const ConstrainedFPIntrinsic &FPI) {
8090   SDLoc sdl = getCurSDLoc();
8091 
8092   // We do not need to serialize constrained FP intrinsics against
8093   // each other or against (nonvolatile) loads, so they can be
8094   // chained like loads.
8095   SDValue Chain = DAG.getRoot();
8096   SmallVector<SDValue, 4> Opers;
8097   Opers.push_back(Chain);
8098   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8099     Opers.push_back(getValue(FPI.getArgOperand(I)));
8100 
8101   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8102     assert(Result.getNode()->getNumValues() == 2);
8103 
8104     // Push node to the appropriate list so that future instructions can be
8105     // chained up correctly.
8106     SDValue OutChain = Result.getValue(1);
8107     switch (EB) {
8108     case fp::ExceptionBehavior::ebIgnore:
8109       // The only reason why ebIgnore nodes still need to be chained is that
8110       // they might depend on the current rounding mode, and therefore must
8111       // not be moved across instruction that may change that mode.
8112       [[fallthrough]];
8113     case fp::ExceptionBehavior::ebMayTrap:
8114       // These must not be moved across calls or instructions that may change
8115       // floating-point exception masks.
8116       PendingConstrainedFP.push_back(OutChain);
8117       break;
8118     case fp::ExceptionBehavior::ebStrict:
8119       // These must not be moved across calls or instructions that may change
8120       // floating-point exception masks or read floating-point exception flags.
8121       // In addition, they cannot be optimized out even if unused.
8122       PendingConstrainedFPStrict.push_back(OutChain);
8123       break;
8124     }
8125   };
8126 
8127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8128   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8129   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8130   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8131 
8132   SDNodeFlags Flags;
8133   if (EB == fp::ExceptionBehavior::ebIgnore)
8134     Flags.setNoFPExcept(true);
8135 
8136   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8137     Flags.copyFMF(*FPOp);
8138 
8139   unsigned Opcode;
8140   switch (FPI.getIntrinsicID()) {
8141   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8142 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8143   case Intrinsic::INTRINSIC:                                                   \
8144     Opcode = ISD::STRICT_##DAGN;                                               \
8145     break;
8146 #include "llvm/IR/ConstrainedOps.def"
8147   case Intrinsic::experimental_constrained_fmuladd: {
8148     Opcode = ISD::STRICT_FMA;
8149     // Break fmuladd into fmul and fadd.
8150     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8151         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8152       Opers.pop_back();
8153       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8154       pushOutChain(Mul, EB);
8155       Opcode = ISD::STRICT_FADD;
8156       Opers.clear();
8157       Opers.push_back(Mul.getValue(1));
8158       Opers.push_back(Mul.getValue(0));
8159       Opers.push_back(getValue(FPI.getArgOperand(2)));
8160     }
8161     break;
8162   }
8163   }
8164 
8165   // A few strict DAG nodes carry additional operands that are not
8166   // set up by the default code above.
8167   switch (Opcode) {
8168   default: break;
8169   case ISD::STRICT_FP_ROUND:
8170     Opers.push_back(
8171         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8172     break;
8173   case ISD::STRICT_FSETCC:
8174   case ISD::STRICT_FSETCCS: {
8175     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8176     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8177     if (TM.Options.NoNaNsFPMath)
8178       Condition = getFCmpCodeWithoutNaN(Condition);
8179     Opers.push_back(DAG.getCondCode(Condition));
8180     break;
8181   }
8182   }
8183 
8184   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8185   pushOutChain(Result, EB);
8186 
8187   SDValue FPResult = Result.getValue(0);
8188   setValue(&FPI, FPResult);
8189 }
8190 
8191 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8192   std::optional<unsigned> ResOPC;
8193   switch (VPIntrin.getIntrinsicID()) {
8194   case Intrinsic::vp_ctlz: {
8195     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8196     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8197     break;
8198   }
8199   case Intrinsic::vp_cttz: {
8200     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8201     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8202     break;
8203   }
8204   case Intrinsic::vp_cttz_elts: {
8205     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8206     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8207     break;
8208   }
8209 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8210   case Intrinsic::VPID:                                                        \
8211     ResOPC = ISD::VPSD;                                                        \
8212     break;
8213 #include "llvm/IR/VPIntrinsics.def"
8214   }
8215 
8216   if (!ResOPC)
8217     llvm_unreachable(
8218         "Inconsistency: no SDNode available for this VPIntrinsic!");
8219 
8220   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8221       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8222     if (VPIntrin.getFastMathFlags().allowReassoc())
8223       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8224                                                 : ISD::VP_REDUCE_FMUL;
8225   }
8226 
8227   return *ResOPC;
8228 }
8229 
8230 void SelectionDAGBuilder::visitVPLoad(
8231     const VPIntrinsic &VPIntrin, EVT VT,
8232     const SmallVectorImpl<SDValue> &OpValues) {
8233   SDLoc DL = getCurSDLoc();
8234   Value *PtrOperand = VPIntrin.getArgOperand(0);
8235   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8236   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8237   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8238   SDValue LD;
8239   // Do not serialize variable-length loads of constant memory with
8240   // anything.
8241   if (!Alignment)
8242     Alignment = DAG.getEVTAlign(VT);
8243   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8244   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8245   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8246   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8247       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8248       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8249   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8250                      MMO, false /*IsExpanding */);
8251   if (AddToChain)
8252     PendingLoads.push_back(LD.getValue(1));
8253   setValue(&VPIntrin, LD);
8254 }
8255 
8256 void SelectionDAGBuilder::visitVPGather(
8257     const VPIntrinsic &VPIntrin, EVT VT,
8258     const SmallVectorImpl<SDValue> &OpValues) {
8259   SDLoc DL = getCurSDLoc();
8260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8261   Value *PtrOperand = VPIntrin.getArgOperand(0);
8262   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8263   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8264   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8265   SDValue LD;
8266   if (!Alignment)
8267     Alignment = DAG.getEVTAlign(VT.getScalarType());
8268   unsigned AS =
8269     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8270   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8271       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8272       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8273   SDValue Base, Index, Scale;
8274   ISD::MemIndexType IndexType;
8275   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8276                                     this, VPIntrin.getParent(),
8277                                     VT.getScalarStoreSize());
8278   if (!UniformBase) {
8279     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8280     Index = getValue(PtrOperand);
8281     IndexType = ISD::SIGNED_SCALED;
8282     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8283   }
8284   EVT IdxVT = Index.getValueType();
8285   EVT EltTy = IdxVT.getVectorElementType();
8286   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8287     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8288     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8289   }
8290   LD = DAG.getGatherVP(
8291       DAG.getVTList(VT, MVT::Other), VT, DL,
8292       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8293       IndexType);
8294   PendingLoads.push_back(LD.getValue(1));
8295   setValue(&VPIntrin, LD);
8296 }
8297 
8298 void SelectionDAGBuilder::visitVPStore(
8299     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8300   SDLoc DL = getCurSDLoc();
8301   Value *PtrOperand = VPIntrin.getArgOperand(1);
8302   EVT VT = OpValues[0].getValueType();
8303   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8304   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8305   SDValue ST;
8306   if (!Alignment)
8307     Alignment = DAG.getEVTAlign(VT);
8308   SDValue Ptr = OpValues[1];
8309   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8310   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8311       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8312       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8313   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8314                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8315                       /* IsTruncating */ false, /*IsCompressing*/ false);
8316   DAG.setRoot(ST);
8317   setValue(&VPIntrin, ST);
8318 }
8319 
8320 void SelectionDAGBuilder::visitVPScatter(
8321     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8322   SDLoc DL = getCurSDLoc();
8323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8324   Value *PtrOperand = VPIntrin.getArgOperand(1);
8325   EVT VT = OpValues[0].getValueType();
8326   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8327   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8328   SDValue ST;
8329   if (!Alignment)
8330     Alignment = DAG.getEVTAlign(VT.getScalarType());
8331   unsigned AS =
8332       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8333   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8334       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8335       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8336   SDValue Base, Index, Scale;
8337   ISD::MemIndexType IndexType;
8338   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8339                                     this, VPIntrin.getParent(),
8340                                     VT.getScalarStoreSize());
8341   if (!UniformBase) {
8342     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8343     Index = getValue(PtrOperand);
8344     IndexType = ISD::SIGNED_SCALED;
8345     Scale =
8346       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8347   }
8348   EVT IdxVT = Index.getValueType();
8349   EVT EltTy = IdxVT.getVectorElementType();
8350   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8351     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8352     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8353   }
8354   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8355                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8356                          OpValues[2], OpValues[3]},
8357                         MMO, IndexType);
8358   DAG.setRoot(ST);
8359   setValue(&VPIntrin, ST);
8360 }
8361 
8362 void SelectionDAGBuilder::visitVPStridedLoad(
8363     const VPIntrinsic &VPIntrin, EVT VT,
8364     const SmallVectorImpl<SDValue> &OpValues) {
8365   SDLoc DL = getCurSDLoc();
8366   Value *PtrOperand = VPIntrin.getArgOperand(0);
8367   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8368   if (!Alignment)
8369     Alignment = DAG.getEVTAlign(VT.getScalarType());
8370   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8371   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8372   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8373   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8374   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8375   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8376   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8377       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8378       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8379 
8380   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8381                                     OpValues[2], OpValues[3], MMO,
8382                                     false /*IsExpanding*/);
8383 
8384   if (AddToChain)
8385     PendingLoads.push_back(LD.getValue(1));
8386   setValue(&VPIntrin, LD);
8387 }
8388 
8389 void SelectionDAGBuilder::visitVPStridedStore(
8390     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8391   SDLoc DL = getCurSDLoc();
8392   Value *PtrOperand = VPIntrin.getArgOperand(1);
8393   EVT VT = OpValues[0].getValueType();
8394   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8395   if (!Alignment)
8396     Alignment = DAG.getEVTAlign(VT.getScalarType());
8397   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8398   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8399   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8400       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8401       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8402 
8403   SDValue ST = DAG.getStridedStoreVP(
8404       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8405       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8406       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8407       /*IsCompressing*/ false);
8408 
8409   DAG.setRoot(ST);
8410   setValue(&VPIntrin, ST);
8411 }
8412 
8413 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8415   SDLoc DL = getCurSDLoc();
8416 
8417   ISD::CondCode Condition;
8418   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8419   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8420   if (IsFP) {
8421     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8422     // flags, but calls that don't return floating-point types can't be
8423     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8424     Condition = getFCmpCondCode(CondCode);
8425     if (TM.Options.NoNaNsFPMath)
8426       Condition = getFCmpCodeWithoutNaN(Condition);
8427   } else {
8428     Condition = getICmpCondCode(CondCode);
8429   }
8430 
8431   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8432   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8433   // #2 is the condition code
8434   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8435   SDValue EVL = getValue(VPIntrin.getOperand(4));
8436   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8437   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8438          "Unexpected target EVL type");
8439   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8440 
8441   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8442                                                         VPIntrin.getType());
8443   setValue(&VPIntrin,
8444            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8445 }
8446 
8447 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8448     const VPIntrinsic &VPIntrin) {
8449   SDLoc DL = getCurSDLoc();
8450   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8451 
8452   auto IID = VPIntrin.getIntrinsicID();
8453 
8454   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8455     return visitVPCmp(*CmpI);
8456 
8457   SmallVector<EVT, 4> ValueVTs;
8458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8460   SDVTList VTs = DAG.getVTList(ValueVTs);
8461 
8462   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8463 
8464   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8465   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8466          "Unexpected target EVL type");
8467 
8468   // Request operands.
8469   SmallVector<SDValue, 7> OpValues;
8470   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8471     auto Op = getValue(VPIntrin.getArgOperand(I));
8472     if (I == EVLParamPos)
8473       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8474     OpValues.push_back(Op);
8475   }
8476 
8477   switch (Opcode) {
8478   default: {
8479     SDNodeFlags SDFlags;
8480     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8481       SDFlags.copyFMF(*FPMO);
8482     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8483     setValue(&VPIntrin, Result);
8484     break;
8485   }
8486   case ISD::VP_LOAD:
8487     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8488     break;
8489   case ISD::VP_GATHER:
8490     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8491     break;
8492   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8493     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8494     break;
8495   case ISD::VP_STORE:
8496     visitVPStore(VPIntrin, OpValues);
8497     break;
8498   case ISD::VP_SCATTER:
8499     visitVPScatter(VPIntrin, OpValues);
8500     break;
8501   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8502     visitVPStridedStore(VPIntrin, OpValues);
8503     break;
8504   case ISD::VP_FMULADD: {
8505     assert(OpValues.size() == 5 && "Unexpected number of operands");
8506     SDNodeFlags SDFlags;
8507     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8508       SDFlags.copyFMF(*FPMO);
8509     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8510         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8511       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8512     } else {
8513       SDValue Mul = DAG.getNode(
8514           ISD::VP_FMUL, DL, VTs,
8515           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8516       SDValue Add =
8517           DAG.getNode(ISD::VP_FADD, DL, VTs,
8518                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8519       setValue(&VPIntrin, Add);
8520     }
8521     break;
8522   }
8523   case ISD::VP_IS_FPCLASS: {
8524     const DataLayout DLayout = DAG.getDataLayout();
8525     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8526     auto Constant = OpValues[1]->getAsZExtVal();
8527     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8528     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8529                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8530     setValue(&VPIntrin, V);
8531     return;
8532   }
8533   case ISD::VP_INTTOPTR: {
8534     SDValue N = OpValues[0];
8535     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8536     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8537     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8538                                OpValues[2]);
8539     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8540                              OpValues[2]);
8541     setValue(&VPIntrin, N);
8542     break;
8543   }
8544   case ISD::VP_PTRTOINT: {
8545     SDValue N = OpValues[0];
8546     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8547                                                           VPIntrin.getType());
8548     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8549                                        VPIntrin.getOperand(0)->getType());
8550     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8551                                OpValues[2]);
8552     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8553                              OpValues[2]);
8554     setValue(&VPIntrin, N);
8555     break;
8556   }
8557   case ISD::VP_ABS:
8558   case ISD::VP_CTLZ:
8559   case ISD::VP_CTLZ_ZERO_UNDEF:
8560   case ISD::VP_CTTZ:
8561   case ISD::VP_CTTZ_ZERO_UNDEF:
8562   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8563   case ISD::VP_CTTZ_ELTS: {
8564     SDValue Result =
8565         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8566     setValue(&VPIntrin, Result);
8567     break;
8568   }
8569   }
8570 }
8571 
8572 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8573                                           const BasicBlock *EHPadBB,
8574                                           MCSymbol *&BeginLabel) {
8575   MachineFunction &MF = DAG.getMachineFunction();
8576   MachineModuleInfo &MMI = MF.getMMI();
8577 
8578   // Insert a label before the invoke call to mark the try range.  This can be
8579   // used to detect deletion of the invoke via the MachineModuleInfo.
8580   BeginLabel = MMI.getContext().createTempSymbol();
8581 
8582   // For SjLj, keep track of which landing pads go with which invokes
8583   // so as to maintain the ordering of pads in the LSDA.
8584   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8585   if (CallSiteIndex) {
8586     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8587     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8588 
8589     // Now that the call site is handled, stop tracking it.
8590     MMI.setCurrentCallSite(0);
8591   }
8592 
8593   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8594 }
8595 
8596 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8597                                         const BasicBlock *EHPadBB,
8598                                         MCSymbol *BeginLabel) {
8599   assert(BeginLabel && "BeginLabel should've been set");
8600 
8601   MachineFunction &MF = DAG.getMachineFunction();
8602   MachineModuleInfo &MMI = MF.getMMI();
8603 
8604   // Insert a label at the end of the invoke call to mark the try range.  This
8605   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8606   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8607   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8608 
8609   // Inform MachineModuleInfo of range.
8610   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8611   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8612   // actually use outlined funclets and their LSDA info style.
8613   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8614     assert(II && "II should've been set");
8615     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8616     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8617   } else if (!isScopedEHPersonality(Pers)) {
8618     assert(EHPadBB);
8619     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8620   }
8621 
8622   return Chain;
8623 }
8624 
8625 std::pair<SDValue, SDValue>
8626 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8627                                     const BasicBlock *EHPadBB) {
8628   MCSymbol *BeginLabel = nullptr;
8629 
8630   if (EHPadBB) {
8631     // Both PendingLoads and PendingExports must be flushed here;
8632     // this call might not return.
8633     (void)getRoot();
8634     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8635     CLI.setChain(getRoot());
8636   }
8637 
8638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8639   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8640 
8641   assert((CLI.IsTailCall || Result.second.getNode()) &&
8642          "Non-null chain expected with non-tail call!");
8643   assert((Result.second.getNode() || !Result.first.getNode()) &&
8644          "Null value expected with tail call!");
8645 
8646   if (!Result.second.getNode()) {
8647     // As a special case, a null chain means that a tail call has been emitted
8648     // and the DAG root is already updated.
8649     HasTailCall = true;
8650 
8651     // Since there's no actual continuation from this block, nothing can be
8652     // relying on us setting vregs for them.
8653     PendingExports.clear();
8654   } else {
8655     DAG.setRoot(Result.second);
8656   }
8657 
8658   if (EHPadBB) {
8659     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8660                            BeginLabel));
8661     Result.second = getRoot();
8662   }
8663 
8664   return Result;
8665 }
8666 
8667 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8668                                       bool isTailCall, bool isMustTailCall,
8669                                       const BasicBlock *EHPadBB,
8670                                       const TargetLowering::PtrAuthInfo *PAI) {
8671   auto &DL = DAG.getDataLayout();
8672   FunctionType *FTy = CB.getFunctionType();
8673   Type *RetTy = CB.getType();
8674 
8675   TargetLowering::ArgListTy Args;
8676   Args.reserve(CB.arg_size());
8677 
8678   const Value *SwiftErrorVal = nullptr;
8679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8680 
8681   if (isTailCall) {
8682     // Avoid emitting tail calls in functions with the disable-tail-calls
8683     // attribute.
8684     auto *Caller = CB.getParent()->getParent();
8685     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8686         "true" && !isMustTailCall)
8687       isTailCall = false;
8688 
8689     // We can't tail call inside a function with a swifterror argument. Lowering
8690     // does not support this yet. It would have to move into the swifterror
8691     // register before the call.
8692     if (TLI.supportSwiftError() &&
8693         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8694       isTailCall = false;
8695   }
8696 
8697   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8698     TargetLowering::ArgListEntry Entry;
8699     const Value *V = *I;
8700 
8701     // Skip empty types
8702     if (V->getType()->isEmptyTy())
8703       continue;
8704 
8705     SDValue ArgNode = getValue(V);
8706     Entry.Node = ArgNode; Entry.Ty = V->getType();
8707 
8708     Entry.setAttributes(&CB, I - CB.arg_begin());
8709 
8710     // Use swifterror virtual register as input to the call.
8711     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8712       SwiftErrorVal = V;
8713       // We find the virtual register for the actual swifterror argument.
8714       // Instead of using the Value, we use the virtual register instead.
8715       Entry.Node =
8716           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8717                           EVT(TLI.getPointerTy(DL)));
8718     }
8719 
8720     Args.push_back(Entry);
8721 
8722     // If we have an explicit sret argument that is an Instruction, (i.e., it
8723     // might point to function-local memory), we can't meaningfully tail-call.
8724     if (Entry.IsSRet && isa<Instruction>(V))
8725       isTailCall = false;
8726   }
8727 
8728   // If call site has a cfguardtarget operand bundle, create and add an
8729   // additional ArgListEntry.
8730   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8731     TargetLowering::ArgListEntry Entry;
8732     Value *V = Bundle->Inputs[0];
8733     SDValue ArgNode = getValue(V);
8734     Entry.Node = ArgNode;
8735     Entry.Ty = V->getType();
8736     Entry.IsCFGuardTarget = true;
8737     Args.push_back(Entry);
8738   }
8739 
8740   // Check if target-independent constraints permit a tail call here.
8741   // Target-dependent constraints are checked within TLI->LowerCallTo.
8742   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8743     isTailCall = false;
8744 
8745   // Disable tail calls if there is an swifterror argument. Targets have not
8746   // been updated to support tail calls.
8747   if (TLI.supportSwiftError() && SwiftErrorVal)
8748     isTailCall = false;
8749 
8750   ConstantInt *CFIType = nullptr;
8751   if (CB.isIndirectCall()) {
8752     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8753       if (!TLI.supportKCFIBundles())
8754         report_fatal_error(
8755             "Target doesn't support calls with kcfi operand bundles.");
8756       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8757       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8758     }
8759   }
8760 
8761   SDValue ConvControlToken;
8762   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8763     auto *Token = Bundle->Inputs[0].get();
8764     ConvControlToken = getValue(Token);
8765   }
8766 
8767   TargetLowering::CallLoweringInfo CLI(DAG);
8768   CLI.setDebugLoc(getCurSDLoc())
8769       .setChain(getRoot())
8770       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8771       .setTailCall(isTailCall)
8772       .setConvergent(CB.isConvergent())
8773       .setIsPreallocated(
8774           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8775       .setCFIType(CFIType)
8776       .setConvergenceControlToken(ConvControlToken);
8777 
8778   // Set the pointer authentication info if we have it.
8779   if (PAI) {
8780     if (!TLI.supportPtrAuthBundles())
8781       report_fatal_error(
8782           "This target doesn't support calls with ptrauth operand bundles.");
8783     CLI.setPtrAuth(*PAI);
8784   }
8785 
8786   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8787 
8788   if (Result.first.getNode()) {
8789     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8790     setValue(&CB, Result.first);
8791   }
8792 
8793   // The last element of CLI.InVals has the SDValue for swifterror return.
8794   // Here we copy it to a virtual register and update SwiftErrorMap for
8795   // book-keeping.
8796   if (SwiftErrorVal && TLI.supportSwiftError()) {
8797     // Get the last element of InVals.
8798     SDValue Src = CLI.InVals.back();
8799     Register VReg =
8800         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8801     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8802     DAG.setRoot(CopyNode);
8803   }
8804 }
8805 
8806 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8807                              SelectionDAGBuilder &Builder) {
8808   // Check to see if this load can be trivially constant folded, e.g. if the
8809   // input is from a string literal.
8810   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8811     // Cast pointer to the type we really want to load.
8812     Type *LoadTy =
8813         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8814     if (LoadVT.isVector())
8815       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8816 
8817     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8818                                          PointerType::getUnqual(LoadTy));
8819 
8820     if (const Constant *LoadCst =
8821             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8822                                          LoadTy, Builder.DAG.getDataLayout()))
8823       return Builder.getValue(LoadCst);
8824   }
8825 
8826   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8827   // still constant memory, the input chain can be the entry node.
8828   SDValue Root;
8829   bool ConstantMemory = false;
8830 
8831   // Do not serialize (non-volatile) loads of constant memory with anything.
8832   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8833     Root = Builder.DAG.getEntryNode();
8834     ConstantMemory = true;
8835   } else {
8836     // Do not serialize non-volatile loads against each other.
8837     Root = Builder.DAG.getRoot();
8838   }
8839 
8840   SDValue Ptr = Builder.getValue(PtrVal);
8841   SDValue LoadVal =
8842       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8843                           MachinePointerInfo(PtrVal), Align(1));
8844 
8845   if (!ConstantMemory)
8846     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8847   return LoadVal;
8848 }
8849 
8850 /// Record the value for an instruction that produces an integer result,
8851 /// converting the type where necessary.
8852 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8853                                                   SDValue Value,
8854                                                   bool IsSigned) {
8855   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8856                                                     I.getType(), true);
8857   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8858   setValue(&I, Value);
8859 }
8860 
8861 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8862 /// true and lower it. Otherwise return false, and it will be lowered like a
8863 /// normal call.
8864 /// The caller already checked that \p I calls the appropriate LibFunc with a
8865 /// correct prototype.
8866 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8867   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8868   const Value *Size = I.getArgOperand(2);
8869   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8870   if (CSize && CSize->getZExtValue() == 0) {
8871     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8872                                                           I.getType(), true);
8873     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8874     return true;
8875   }
8876 
8877   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8878   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8879       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8880       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8881   if (Res.first.getNode()) {
8882     processIntegerCallValue(I, Res.first, true);
8883     PendingLoads.push_back(Res.second);
8884     return true;
8885   }
8886 
8887   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8888   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8889   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8890     return false;
8891 
8892   // If the target has a fast compare for the given size, it will return a
8893   // preferred load type for that size. Require that the load VT is legal and
8894   // that the target supports unaligned loads of that type. Otherwise, return
8895   // INVALID.
8896   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8897     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8898     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8899     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8900       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8901       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8902       // TODO: Check alignment of src and dest ptrs.
8903       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8904       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8905       if (!TLI.isTypeLegal(LVT) ||
8906           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8907           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8908         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8909     }
8910 
8911     return LVT;
8912   };
8913 
8914   // This turns into unaligned loads. We only do this if the target natively
8915   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8916   // we'll only produce a small number of byte loads.
8917   MVT LoadVT;
8918   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8919   switch (NumBitsToCompare) {
8920   default:
8921     return false;
8922   case 16:
8923     LoadVT = MVT::i16;
8924     break;
8925   case 32:
8926     LoadVT = MVT::i32;
8927     break;
8928   case 64:
8929   case 128:
8930   case 256:
8931     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8932     break;
8933   }
8934 
8935   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8936     return false;
8937 
8938   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8939   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8940 
8941   // Bitcast to a wide integer type if the loads are vectors.
8942   if (LoadVT.isVector()) {
8943     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8944     LoadL = DAG.getBitcast(CmpVT, LoadL);
8945     LoadR = DAG.getBitcast(CmpVT, LoadR);
8946   }
8947 
8948   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8949   processIntegerCallValue(I, Cmp, false);
8950   return true;
8951 }
8952 
8953 /// See if we can lower a memchr call into an optimized form. If so, return
8954 /// true and lower it. Otherwise return false, and it will be lowered like a
8955 /// normal call.
8956 /// The caller already checked that \p I calls the appropriate LibFunc with a
8957 /// correct prototype.
8958 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8959   const Value *Src = I.getArgOperand(0);
8960   const Value *Char = I.getArgOperand(1);
8961   const Value *Length = I.getArgOperand(2);
8962 
8963   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8964   std::pair<SDValue, SDValue> Res =
8965     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8966                                 getValue(Src), getValue(Char), getValue(Length),
8967                                 MachinePointerInfo(Src));
8968   if (Res.first.getNode()) {
8969     setValue(&I, Res.first);
8970     PendingLoads.push_back(Res.second);
8971     return true;
8972   }
8973 
8974   return false;
8975 }
8976 
8977 /// See if we can lower a mempcpy call into an optimized form. If so, return
8978 /// true and lower it. Otherwise return false, and it will be lowered like a
8979 /// normal call.
8980 /// The caller already checked that \p I calls the appropriate LibFunc with a
8981 /// correct prototype.
8982 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8983   SDValue Dst = getValue(I.getArgOperand(0));
8984   SDValue Src = getValue(I.getArgOperand(1));
8985   SDValue Size = getValue(I.getArgOperand(2));
8986 
8987   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8988   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8989   // DAG::getMemcpy needs Alignment to be defined.
8990   Align Alignment = std::min(DstAlign, SrcAlign);
8991 
8992   SDLoc sdl = getCurSDLoc();
8993 
8994   // In the mempcpy context we need to pass in a false value for isTailCall
8995   // because the return pointer needs to be adjusted by the size of
8996   // the copied memory.
8997   SDValue Root = getMemoryRoot();
8998   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8999                              /*isTailCall=*/false,
9000                              MachinePointerInfo(I.getArgOperand(0)),
9001                              MachinePointerInfo(I.getArgOperand(1)),
9002                              I.getAAMetadata());
9003   assert(MC.getNode() != nullptr &&
9004          "** memcpy should not be lowered as TailCall in mempcpy context **");
9005   DAG.setRoot(MC);
9006 
9007   // Check if Size needs to be truncated or extended.
9008   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9009 
9010   // Adjust return pointer to point just past the last dst byte.
9011   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9012                                     Dst, Size);
9013   setValue(&I, DstPlusSize);
9014   return true;
9015 }
9016 
9017 /// See if we can lower a strcpy call into an optimized form.  If so, return
9018 /// true and lower it, otherwise return false and it will be lowered like a
9019 /// normal call.
9020 /// The caller already checked that \p I calls the appropriate LibFunc with a
9021 /// correct prototype.
9022 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9023   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9024 
9025   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9026   std::pair<SDValue, SDValue> Res =
9027     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9028                                 getValue(Arg0), getValue(Arg1),
9029                                 MachinePointerInfo(Arg0),
9030                                 MachinePointerInfo(Arg1), isStpcpy);
9031   if (Res.first.getNode()) {
9032     setValue(&I, Res.first);
9033     DAG.setRoot(Res.second);
9034     return true;
9035   }
9036 
9037   return false;
9038 }
9039 
9040 /// See if we can lower a strcmp call into an optimized form.  If so, return
9041 /// true and lower it, otherwise return false and it will be lowered like a
9042 /// normal call.
9043 /// The caller already checked that \p I calls the appropriate LibFunc with a
9044 /// correct prototype.
9045 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9046   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9047 
9048   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9049   std::pair<SDValue, SDValue> Res =
9050     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9051                                 getValue(Arg0), getValue(Arg1),
9052                                 MachinePointerInfo(Arg0),
9053                                 MachinePointerInfo(Arg1));
9054   if (Res.first.getNode()) {
9055     processIntegerCallValue(I, Res.first, true);
9056     PendingLoads.push_back(Res.second);
9057     return true;
9058   }
9059 
9060   return false;
9061 }
9062 
9063 /// See if we can lower a strlen call into an optimized form.  If so, return
9064 /// true and lower it, otherwise return false and it will be lowered like a
9065 /// normal call.
9066 /// The caller already checked that \p I calls the appropriate LibFunc with a
9067 /// correct prototype.
9068 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9069   const Value *Arg0 = I.getArgOperand(0);
9070 
9071   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9072   std::pair<SDValue, SDValue> Res =
9073     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9074                                 getValue(Arg0), MachinePointerInfo(Arg0));
9075   if (Res.first.getNode()) {
9076     processIntegerCallValue(I, Res.first, false);
9077     PendingLoads.push_back(Res.second);
9078     return true;
9079   }
9080 
9081   return false;
9082 }
9083 
9084 /// See if we can lower a strnlen call into an optimized form.  If so, return
9085 /// true and lower it, otherwise return false and it will be lowered like a
9086 /// normal call.
9087 /// The caller already checked that \p I calls the appropriate LibFunc with a
9088 /// correct prototype.
9089 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9090   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9091 
9092   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9093   std::pair<SDValue, SDValue> Res =
9094     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9095                                  getValue(Arg0), getValue(Arg1),
9096                                  MachinePointerInfo(Arg0));
9097   if (Res.first.getNode()) {
9098     processIntegerCallValue(I, Res.first, false);
9099     PendingLoads.push_back(Res.second);
9100     return true;
9101   }
9102 
9103   return false;
9104 }
9105 
9106 /// See if we can lower a unary floating-point operation into an SDNode with
9107 /// the specified Opcode.  If so, return true and lower it, otherwise return
9108 /// false and it will be lowered like a normal call.
9109 /// The caller already checked that \p I calls the appropriate LibFunc with a
9110 /// correct prototype.
9111 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9112                                               unsigned Opcode) {
9113   // We already checked this call's prototype; verify it doesn't modify errno.
9114   if (!I.onlyReadsMemory())
9115     return false;
9116 
9117   SDNodeFlags Flags;
9118   Flags.copyFMF(cast<FPMathOperator>(I));
9119 
9120   SDValue Tmp = getValue(I.getArgOperand(0));
9121   setValue(&I,
9122            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9123   return true;
9124 }
9125 
9126 /// See if we can lower a binary floating-point operation into an SDNode with
9127 /// the specified Opcode. If so, return true and lower it. Otherwise return
9128 /// false, and it will be lowered like a normal call.
9129 /// The caller already checked that \p I calls the appropriate LibFunc with a
9130 /// correct prototype.
9131 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9132                                                unsigned Opcode) {
9133   // We already checked this call's prototype; verify it doesn't modify errno.
9134   if (!I.onlyReadsMemory())
9135     return false;
9136 
9137   SDNodeFlags Flags;
9138   Flags.copyFMF(cast<FPMathOperator>(I));
9139 
9140   SDValue Tmp0 = getValue(I.getArgOperand(0));
9141   SDValue Tmp1 = getValue(I.getArgOperand(1));
9142   EVT VT = Tmp0.getValueType();
9143   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9144   return true;
9145 }
9146 
9147 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9148   // Handle inline assembly differently.
9149   if (I.isInlineAsm()) {
9150     visitInlineAsm(I);
9151     return;
9152   }
9153 
9154   diagnoseDontCall(I);
9155 
9156   if (Function *F = I.getCalledFunction()) {
9157     if (F->isDeclaration()) {
9158       // Is this an LLVM intrinsic or a target-specific intrinsic?
9159       unsigned IID = F->getIntrinsicID();
9160       if (!IID)
9161         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9162           IID = II->getIntrinsicID(F);
9163 
9164       if (IID) {
9165         visitIntrinsicCall(I, IID);
9166         return;
9167       }
9168     }
9169 
9170     // Check for well-known libc/libm calls.  If the function is internal, it
9171     // can't be a library call.  Don't do the check if marked as nobuiltin for
9172     // some reason or the call site requires strict floating point semantics.
9173     LibFunc Func;
9174     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9175         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9176         LibInfo->hasOptimizedCodeGen(Func)) {
9177       switch (Func) {
9178       default: break;
9179       case LibFunc_bcmp:
9180         if (visitMemCmpBCmpCall(I))
9181           return;
9182         break;
9183       case LibFunc_copysign:
9184       case LibFunc_copysignf:
9185       case LibFunc_copysignl:
9186         // We already checked this call's prototype; verify it doesn't modify
9187         // errno.
9188         if (I.onlyReadsMemory()) {
9189           SDValue LHS = getValue(I.getArgOperand(0));
9190           SDValue RHS = getValue(I.getArgOperand(1));
9191           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9192                                    LHS.getValueType(), LHS, RHS));
9193           return;
9194         }
9195         break;
9196       case LibFunc_fabs:
9197       case LibFunc_fabsf:
9198       case LibFunc_fabsl:
9199         if (visitUnaryFloatCall(I, ISD::FABS))
9200           return;
9201         break;
9202       case LibFunc_fmin:
9203       case LibFunc_fminf:
9204       case LibFunc_fminl:
9205         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9206           return;
9207         break;
9208       case LibFunc_fmax:
9209       case LibFunc_fmaxf:
9210       case LibFunc_fmaxl:
9211         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9212           return;
9213         break;
9214       case LibFunc_sin:
9215       case LibFunc_sinf:
9216       case LibFunc_sinl:
9217         if (visitUnaryFloatCall(I, ISD::FSIN))
9218           return;
9219         break;
9220       case LibFunc_cos:
9221       case LibFunc_cosf:
9222       case LibFunc_cosl:
9223         if (visitUnaryFloatCall(I, ISD::FCOS))
9224           return;
9225         break;
9226       case LibFunc_tan:
9227       case LibFunc_tanf:
9228       case LibFunc_tanl:
9229         if (visitUnaryFloatCall(I, ISD::FTAN))
9230           return;
9231         break;
9232       case LibFunc_sqrt:
9233       case LibFunc_sqrtf:
9234       case LibFunc_sqrtl:
9235       case LibFunc_sqrt_finite:
9236       case LibFunc_sqrtf_finite:
9237       case LibFunc_sqrtl_finite:
9238         if (visitUnaryFloatCall(I, ISD::FSQRT))
9239           return;
9240         break;
9241       case LibFunc_floor:
9242       case LibFunc_floorf:
9243       case LibFunc_floorl:
9244         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9245           return;
9246         break;
9247       case LibFunc_nearbyint:
9248       case LibFunc_nearbyintf:
9249       case LibFunc_nearbyintl:
9250         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9251           return;
9252         break;
9253       case LibFunc_ceil:
9254       case LibFunc_ceilf:
9255       case LibFunc_ceill:
9256         if (visitUnaryFloatCall(I, ISD::FCEIL))
9257           return;
9258         break;
9259       case LibFunc_rint:
9260       case LibFunc_rintf:
9261       case LibFunc_rintl:
9262         if (visitUnaryFloatCall(I, ISD::FRINT))
9263           return;
9264         break;
9265       case LibFunc_round:
9266       case LibFunc_roundf:
9267       case LibFunc_roundl:
9268         if (visitUnaryFloatCall(I, ISD::FROUND))
9269           return;
9270         break;
9271       case LibFunc_trunc:
9272       case LibFunc_truncf:
9273       case LibFunc_truncl:
9274         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9275           return;
9276         break;
9277       case LibFunc_log2:
9278       case LibFunc_log2f:
9279       case LibFunc_log2l:
9280         if (visitUnaryFloatCall(I, ISD::FLOG2))
9281           return;
9282         break;
9283       case LibFunc_exp2:
9284       case LibFunc_exp2f:
9285       case LibFunc_exp2l:
9286         if (visitUnaryFloatCall(I, ISD::FEXP2))
9287           return;
9288         break;
9289       case LibFunc_exp10:
9290       case LibFunc_exp10f:
9291       case LibFunc_exp10l:
9292         if (visitUnaryFloatCall(I, ISD::FEXP10))
9293           return;
9294         break;
9295       case LibFunc_ldexp:
9296       case LibFunc_ldexpf:
9297       case LibFunc_ldexpl:
9298         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9299           return;
9300         break;
9301       case LibFunc_memcmp:
9302         if (visitMemCmpBCmpCall(I))
9303           return;
9304         break;
9305       case LibFunc_mempcpy:
9306         if (visitMemPCpyCall(I))
9307           return;
9308         break;
9309       case LibFunc_memchr:
9310         if (visitMemChrCall(I))
9311           return;
9312         break;
9313       case LibFunc_strcpy:
9314         if (visitStrCpyCall(I, false))
9315           return;
9316         break;
9317       case LibFunc_stpcpy:
9318         if (visitStrCpyCall(I, true))
9319           return;
9320         break;
9321       case LibFunc_strcmp:
9322         if (visitStrCmpCall(I))
9323           return;
9324         break;
9325       case LibFunc_strlen:
9326         if (visitStrLenCall(I))
9327           return;
9328         break;
9329       case LibFunc_strnlen:
9330         if (visitStrNLenCall(I))
9331           return;
9332         break;
9333       }
9334     }
9335   }
9336 
9337   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9338     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9339     return;
9340   }
9341 
9342   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9343   // have to do anything here to lower funclet bundles.
9344   // CFGuardTarget bundles are lowered in LowerCallTo.
9345   assert(!I.hasOperandBundlesOtherThan(
9346              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9347               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9348               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9349               LLVMContext::OB_convergencectrl}) &&
9350          "Cannot lower calls with arbitrary operand bundles!");
9351 
9352   SDValue Callee = getValue(I.getCalledOperand());
9353 
9354   if (I.hasDeoptState())
9355     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9356   else
9357     // Check if we can potentially perform a tail call. More detailed checking
9358     // is be done within LowerCallTo, after more information about the call is
9359     // known.
9360     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9361 }
9362 
9363 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9364     const CallBase &CB, const BasicBlock *EHPadBB) {
9365   auto PAB = CB.getOperandBundle("ptrauth");
9366   const Value *CalleeV = CB.getCalledOperand();
9367 
9368   // Gather the call ptrauth data from the operand bundle:
9369   //   [ i32 <key>, i64 <discriminator> ]
9370   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9371   const Value *Discriminator = PAB->Inputs[1];
9372 
9373   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9374   assert(Discriminator->getType()->isIntegerTy(64) &&
9375          "Invalid ptrauth discriminator");
9376 
9377   // Functions should never be ptrauth-called directly.
9378   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9379 
9380   // Otherwise, do an authenticated indirect call.
9381   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9382                                      getValue(Discriminator)};
9383 
9384   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9385               EHPadBB, &PAI);
9386 }
9387 
9388 namespace {
9389 
9390 /// AsmOperandInfo - This contains information for each constraint that we are
9391 /// lowering.
9392 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9393 public:
9394   /// CallOperand - If this is the result output operand or a clobber
9395   /// this is null, otherwise it is the incoming operand to the CallInst.
9396   /// This gets modified as the asm is processed.
9397   SDValue CallOperand;
9398 
9399   /// AssignedRegs - If this is a register or register class operand, this
9400   /// contains the set of register corresponding to the operand.
9401   RegsForValue AssignedRegs;
9402 
9403   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9404     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9405   }
9406 
9407   /// Whether or not this operand accesses memory
9408   bool hasMemory(const TargetLowering &TLI) const {
9409     // Indirect operand accesses access memory.
9410     if (isIndirect)
9411       return true;
9412 
9413     for (const auto &Code : Codes)
9414       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9415         return true;
9416 
9417     return false;
9418   }
9419 };
9420 
9421 
9422 } // end anonymous namespace
9423 
9424 /// Make sure that the output operand \p OpInfo and its corresponding input
9425 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9426 /// out).
9427 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9428                                SDISelAsmOperandInfo &MatchingOpInfo,
9429                                SelectionDAG &DAG) {
9430   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9431     return;
9432 
9433   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9434   const auto &TLI = DAG.getTargetLoweringInfo();
9435 
9436   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9437       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9438                                        OpInfo.ConstraintVT);
9439   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9440       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9441                                        MatchingOpInfo.ConstraintVT);
9442   if ((OpInfo.ConstraintVT.isInteger() !=
9443        MatchingOpInfo.ConstraintVT.isInteger()) ||
9444       (MatchRC.second != InputRC.second)) {
9445     // FIXME: error out in a more elegant fashion
9446     report_fatal_error("Unsupported asm: input constraint"
9447                        " with a matching output constraint of"
9448                        " incompatible type!");
9449   }
9450   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9451 }
9452 
9453 /// Get a direct memory input to behave well as an indirect operand.
9454 /// This may introduce stores, hence the need for a \p Chain.
9455 /// \return The (possibly updated) chain.
9456 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9457                                         SDISelAsmOperandInfo &OpInfo,
9458                                         SelectionDAG &DAG) {
9459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9460 
9461   // If we don't have an indirect input, put it in the constpool if we can,
9462   // otherwise spill it to a stack slot.
9463   // TODO: This isn't quite right. We need to handle these according to
9464   // the addressing mode that the constraint wants. Also, this may take
9465   // an additional register for the computation and we don't want that
9466   // either.
9467 
9468   // If the operand is a float, integer, or vector constant, spill to a
9469   // constant pool entry to get its address.
9470   const Value *OpVal = OpInfo.CallOperandVal;
9471   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9472       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9473     OpInfo.CallOperand = DAG.getConstantPool(
9474         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9475     return Chain;
9476   }
9477 
9478   // Otherwise, create a stack slot and emit a store to it before the asm.
9479   Type *Ty = OpVal->getType();
9480   auto &DL = DAG.getDataLayout();
9481   uint64_t TySize = DL.getTypeAllocSize(Ty);
9482   MachineFunction &MF = DAG.getMachineFunction();
9483   int SSFI = MF.getFrameInfo().CreateStackObject(
9484       TySize, DL.getPrefTypeAlign(Ty), false);
9485   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9486   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9487                             MachinePointerInfo::getFixedStack(MF, SSFI),
9488                             TLI.getMemValueType(DL, Ty));
9489   OpInfo.CallOperand = StackSlot;
9490 
9491   return Chain;
9492 }
9493 
9494 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9495 /// specified operand.  We prefer to assign virtual registers, to allow the
9496 /// register allocator to handle the assignment process.  However, if the asm
9497 /// uses features that we can't model on machineinstrs, we have SDISel do the
9498 /// allocation.  This produces generally horrible, but correct, code.
9499 ///
9500 ///   OpInfo describes the operand
9501 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9502 static std::optional<unsigned>
9503 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9504                      SDISelAsmOperandInfo &OpInfo,
9505                      SDISelAsmOperandInfo &RefOpInfo) {
9506   LLVMContext &Context = *DAG.getContext();
9507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9508 
9509   MachineFunction &MF = DAG.getMachineFunction();
9510   SmallVector<unsigned, 4> Regs;
9511   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9512 
9513   // No work to do for memory/address operands.
9514   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9515       OpInfo.ConstraintType == TargetLowering::C_Address)
9516     return std::nullopt;
9517 
9518   // If this is a constraint for a single physreg, or a constraint for a
9519   // register class, find it.
9520   unsigned AssignedReg;
9521   const TargetRegisterClass *RC;
9522   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9523       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9524   // RC is unset only on failure. Return immediately.
9525   if (!RC)
9526     return std::nullopt;
9527 
9528   // Get the actual register value type.  This is important, because the user
9529   // may have asked for (e.g.) the AX register in i32 type.  We need to
9530   // remember that AX is actually i16 to get the right extension.
9531   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9532 
9533   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9534     // If this is an FP operand in an integer register (or visa versa), or more
9535     // generally if the operand value disagrees with the register class we plan
9536     // to stick it in, fix the operand type.
9537     //
9538     // If this is an input value, the bitcast to the new type is done now.
9539     // Bitcast for output value is done at the end of visitInlineAsm().
9540     if ((OpInfo.Type == InlineAsm::isOutput ||
9541          OpInfo.Type == InlineAsm::isInput) &&
9542         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9543       // Try to convert to the first EVT that the reg class contains.  If the
9544       // types are identical size, use a bitcast to convert (e.g. two differing
9545       // vector types).  Note: output bitcast is done at the end of
9546       // visitInlineAsm().
9547       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9548         // Exclude indirect inputs while they are unsupported because the code
9549         // to perform the load is missing and thus OpInfo.CallOperand still
9550         // refers to the input address rather than the pointed-to value.
9551         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9552           OpInfo.CallOperand =
9553               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9554         OpInfo.ConstraintVT = RegVT;
9555         // If the operand is an FP value and we want it in integer registers,
9556         // use the corresponding integer type. This turns an f64 value into
9557         // i64, which can be passed with two i32 values on a 32-bit machine.
9558       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9559         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9560         if (OpInfo.Type == InlineAsm::isInput)
9561           OpInfo.CallOperand =
9562               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9563         OpInfo.ConstraintVT = VT;
9564       }
9565     }
9566   }
9567 
9568   // No need to allocate a matching input constraint since the constraint it's
9569   // matching to has already been allocated.
9570   if (OpInfo.isMatchingInputConstraint())
9571     return std::nullopt;
9572 
9573   EVT ValueVT = OpInfo.ConstraintVT;
9574   if (OpInfo.ConstraintVT == MVT::Other)
9575     ValueVT = RegVT;
9576 
9577   // Initialize NumRegs.
9578   unsigned NumRegs = 1;
9579   if (OpInfo.ConstraintVT != MVT::Other)
9580     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9581 
9582   // If this is a constraint for a specific physical register, like {r17},
9583   // assign it now.
9584 
9585   // If this associated to a specific register, initialize iterator to correct
9586   // place. If virtual, make sure we have enough registers
9587 
9588   // Initialize iterator if necessary
9589   TargetRegisterClass::iterator I = RC->begin();
9590   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9591 
9592   // Do not check for single registers.
9593   if (AssignedReg) {
9594     I = std::find(I, RC->end(), AssignedReg);
9595     if (I == RC->end()) {
9596       // RC does not contain the selected register, which indicates a
9597       // mismatch between the register and the required type/bitwidth.
9598       return {AssignedReg};
9599     }
9600   }
9601 
9602   for (; NumRegs; --NumRegs, ++I) {
9603     assert(I != RC->end() && "Ran out of registers to allocate!");
9604     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9605     Regs.push_back(R);
9606   }
9607 
9608   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9609   return std::nullopt;
9610 }
9611 
9612 static unsigned
9613 findMatchingInlineAsmOperand(unsigned OperandNo,
9614                              const std::vector<SDValue> &AsmNodeOperands) {
9615   // Scan until we find the definition we already emitted of this operand.
9616   unsigned CurOp = InlineAsm::Op_FirstOperand;
9617   for (; OperandNo; --OperandNo) {
9618     // Advance to the next operand.
9619     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9620     const InlineAsm::Flag F(OpFlag);
9621     assert(
9622         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9623         "Skipped past definitions?");
9624     CurOp += F.getNumOperandRegisters() + 1;
9625   }
9626   return CurOp;
9627 }
9628 
9629 namespace {
9630 
9631 class ExtraFlags {
9632   unsigned Flags = 0;
9633 
9634 public:
9635   explicit ExtraFlags(const CallBase &Call) {
9636     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9637     if (IA->hasSideEffects())
9638       Flags |= InlineAsm::Extra_HasSideEffects;
9639     if (IA->isAlignStack())
9640       Flags |= InlineAsm::Extra_IsAlignStack;
9641     if (Call.isConvergent())
9642       Flags |= InlineAsm::Extra_IsConvergent;
9643     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9644   }
9645 
9646   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9647     // Ideally, we would only check against memory constraints.  However, the
9648     // meaning of an Other constraint can be target-specific and we can't easily
9649     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9650     // for Other constraints as well.
9651     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9652         OpInfo.ConstraintType == TargetLowering::C_Other) {
9653       if (OpInfo.Type == InlineAsm::isInput)
9654         Flags |= InlineAsm::Extra_MayLoad;
9655       else if (OpInfo.Type == InlineAsm::isOutput)
9656         Flags |= InlineAsm::Extra_MayStore;
9657       else if (OpInfo.Type == InlineAsm::isClobber)
9658         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9659     }
9660   }
9661 
9662   unsigned get() const { return Flags; }
9663 };
9664 
9665 } // end anonymous namespace
9666 
9667 static bool isFunction(SDValue Op) {
9668   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9669     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9670       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9671 
9672       // In normal "call dllimport func" instruction (non-inlineasm) it force
9673       // indirect access by specifing call opcode. And usually specially print
9674       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9675       // not do in this way now. (In fact, this is similar with "Data Access"
9676       // action). So here we ignore dllimport function.
9677       if (Fn && !Fn->hasDLLImportStorageClass())
9678         return true;
9679     }
9680   }
9681   return false;
9682 }
9683 
9684 /// visitInlineAsm - Handle a call to an InlineAsm object.
9685 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9686                                          const BasicBlock *EHPadBB) {
9687   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9688 
9689   /// ConstraintOperands - Information about all of the constraints.
9690   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9691 
9692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9693   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9694       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9695 
9696   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9697   // AsmDialect, MayLoad, MayStore).
9698   bool HasSideEffect = IA->hasSideEffects();
9699   ExtraFlags ExtraInfo(Call);
9700 
9701   for (auto &T : TargetConstraints) {
9702     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9703     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9704 
9705     if (OpInfo.CallOperandVal)
9706       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9707 
9708     if (!HasSideEffect)
9709       HasSideEffect = OpInfo.hasMemory(TLI);
9710 
9711     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9712     // FIXME: Could we compute this on OpInfo rather than T?
9713 
9714     // Compute the constraint code and ConstraintType to use.
9715     TLI.ComputeConstraintToUse(T, SDValue());
9716 
9717     if (T.ConstraintType == TargetLowering::C_Immediate &&
9718         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9719       // We've delayed emitting a diagnostic like the "n" constraint because
9720       // inlining could cause an integer showing up.
9721       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9722                                           "' expects an integer constant "
9723                                           "expression");
9724 
9725     ExtraInfo.update(T);
9726   }
9727 
9728   // We won't need to flush pending loads if this asm doesn't touch
9729   // memory and is nonvolatile.
9730   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9731 
9732   bool EmitEHLabels = isa<InvokeInst>(Call);
9733   if (EmitEHLabels) {
9734     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9735   }
9736   bool IsCallBr = isa<CallBrInst>(Call);
9737 
9738   if (IsCallBr || EmitEHLabels) {
9739     // If this is a callbr or invoke we need to flush pending exports since
9740     // inlineasm_br and invoke are terminators.
9741     // We need to do this before nodes are glued to the inlineasm_br node.
9742     Chain = getControlRoot();
9743   }
9744 
9745   MCSymbol *BeginLabel = nullptr;
9746   if (EmitEHLabels) {
9747     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9748   }
9749 
9750   int OpNo = -1;
9751   SmallVector<StringRef> AsmStrs;
9752   IA->collectAsmStrs(AsmStrs);
9753 
9754   // Second pass over the constraints: compute which constraint option to use.
9755   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9756     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9757       OpNo++;
9758 
9759     // If this is an output operand with a matching input operand, look up the
9760     // matching input. If their types mismatch, e.g. one is an integer, the
9761     // other is floating point, or their sizes are different, flag it as an
9762     // error.
9763     if (OpInfo.hasMatchingInput()) {
9764       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9765       patchMatchingInput(OpInfo, Input, DAG);
9766     }
9767 
9768     // Compute the constraint code and ConstraintType to use.
9769     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9770 
9771     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9772          OpInfo.Type == InlineAsm::isClobber) ||
9773         OpInfo.ConstraintType == TargetLowering::C_Address)
9774       continue;
9775 
9776     // In Linux PIC model, there are 4 cases about value/label addressing:
9777     //
9778     // 1: Function call or Label jmp inside the module.
9779     // 2: Data access (such as global variable, static variable) inside module.
9780     // 3: Function call or Label jmp outside the module.
9781     // 4: Data access (such as global variable) outside the module.
9782     //
9783     // Due to current llvm inline asm architecture designed to not "recognize"
9784     // the asm code, there are quite troubles for us to treat mem addressing
9785     // differently for same value/adress used in different instuctions.
9786     // For example, in pic model, call a func may in plt way or direclty
9787     // pc-related, but lea/mov a function adress may use got.
9788     //
9789     // Here we try to "recognize" function call for the case 1 and case 3 in
9790     // inline asm. And try to adjust the constraint for them.
9791     //
9792     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9793     // label, so here we don't handle jmp function label now, but we need to
9794     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9795     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9796         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9797         TM.getCodeModel() != CodeModel::Large) {
9798       OpInfo.isIndirect = false;
9799       OpInfo.ConstraintType = TargetLowering::C_Address;
9800     }
9801 
9802     // If this is a memory input, and if the operand is not indirect, do what we
9803     // need to provide an address for the memory input.
9804     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9805         !OpInfo.isIndirect) {
9806       assert((OpInfo.isMultipleAlternative ||
9807               (OpInfo.Type == InlineAsm::isInput)) &&
9808              "Can only indirectify direct input operands!");
9809 
9810       // Memory operands really want the address of the value.
9811       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9812 
9813       // There is no longer a Value* corresponding to this operand.
9814       OpInfo.CallOperandVal = nullptr;
9815 
9816       // It is now an indirect operand.
9817       OpInfo.isIndirect = true;
9818     }
9819 
9820   }
9821 
9822   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9823   std::vector<SDValue> AsmNodeOperands;
9824   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9825   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9826       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9827 
9828   // If we have a !srcloc metadata node associated with it, we want to attach
9829   // this to the ultimately generated inline asm machineinstr.  To do this, we
9830   // pass in the third operand as this (potentially null) inline asm MDNode.
9831   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9832   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9833 
9834   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9835   // bits as operand 3.
9836   AsmNodeOperands.push_back(DAG.getTargetConstant(
9837       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9838 
9839   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9840   // this, assign virtual and physical registers for inputs and otput.
9841   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9842     // Assign Registers.
9843     SDISelAsmOperandInfo &RefOpInfo =
9844         OpInfo.isMatchingInputConstraint()
9845             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9846             : OpInfo;
9847     const auto RegError =
9848         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9849     if (RegError) {
9850       const MachineFunction &MF = DAG.getMachineFunction();
9851       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9852       const char *RegName = TRI.getName(*RegError);
9853       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9854                                    "' allocated for constraint '" +
9855                                    Twine(OpInfo.ConstraintCode) +
9856                                    "' does not match required type");
9857       return;
9858     }
9859 
9860     auto DetectWriteToReservedRegister = [&]() {
9861       const MachineFunction &MF = DAG.getMachineFunction();
9862       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9863       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9864         if (Register::isPhysicalRegister(Reg) &&
9865             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9866           const char *RegName = TRI.getName(Reg);
9867           emitInlineAsmError(Call, "write to reserved register '" +
9868                                        Twine(RegName) + "'");
9869           return true;
9870         }
9871       }
9872       return false;
9873     };
9874     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9875             (OpInfo.Type == InlineAsm::isInput &&
9876              !OpInfo.isMatchingInputConstraint())) &&
9877            "Only address as input operand is allowed.");
9878 
9879     switch (OpInfo.Type) {
9880     case InlineAsm::isOutput:
9881       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9882         const InlineAsm::ConstraintCode ConstraintID =
9883             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9884         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9885                "Failed to convert memory constraint code to constraint id.");
9886 
9887         // Add information to the INLINEASM node to know about this output.
9888         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9889         OpFlags.setMemConstraint(ConstraintID);
9890         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9891                                                         MVT::i32));
9892         AsmNodeOperands.push_back(OpInfo.CallOperand);
9893       } else {
9894         // Otherwise, this outputs to a register (directly for C_Register /
9895         // C_RegisterClass, and a target-defined fashion for
9896         // C_Immediate/C_Other). Find a register that we can use.
9897         if (OpInfo.AssignedRegs.Regs.empty()) {
9898           emitInlineAsmError(
9899               Call, "couldn't allocate output register for constraint '" +
9900                         Twine(OpInfo.ConstraintCode) + "'");
9901           return;
9902         }
9903 
9904         if (DetectWriteToReservedRegister())
9905           return;
9906 
9907         // Add information to the INLINEASM node to know that this register is
9908         // set.
9909         OpInfo.AssignedRegs.AddInlineAsmOperands(
9910             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9911                                   : InlineAsm::Kind::RegDef,
9912             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9913       }
9914       break;
9915 
9916     case InlineAsm::isInput:
9917     case InlineAsm::isLabel: {
9918       SDValue InOperandVal = OpInfo.CallOperand;
9919 
9920       if (OpInfo.isMatchingInputConstraint()) {
9921         // If this is required to match an output register we have already set,
9922         // just use its register.
9923         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9924                                                   AsmNodeOperands);
9925         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9926         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9927           if (OpInfo.isIndirect) {
9928             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9929             emitInlineAsmError(Call, "inline asm not supported yet: "
9930                                      "don't know how to handle tied "
9931                                      "indirect register inputs");
9932             return;
9933           }
9934 
9935           SmallVector<unsigned, 4> Regs;
9936           MachineFunction &MF = DAG.getMachineFunction();
9937           MachineRegisterInfo &MRI = MF.getRegInfo();
9938           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9939           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9940           Register TiedReg = R->getReg();
9941           MVT RegVT = R->getSimpleValueType(0);
9942           const TargetRegisterClass *RC =
9943               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9944               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9945                                       : TRI.getMinimalPhysRegClass(TiedReg);
9946           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9947             Regs.push_back(MRI.createVirtualRegister(RC));
9948 
9949           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9950 
9951           SDLoc dl = getCurSDLoc();
9952           // Use the produced MatchedRegs object to
9953           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9954           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9955                                            OpInfo.getMatchedOperand(), dl, DAG,
9956                                            AsmNodeOperands);
9957           break;
9958         }
9959 
9960         assert(Flag.isMemKind() && "Unknown matching constraint!");
9961         assert(Flag.getNumOperandRegisters() == 1 &&
9962                "Unexpected number of operands");
9963         // Add information to the INLINEASM node to know about this input.
9964         // See InlineAsm.h isUseOperandTiedToDef.
9965         Flag.clearMemConstraint();
9966         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9967         AsmNodeOperands.push_back(DAG.getTargetConstant(
9968             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9969         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9970         break;
9971       }
9972 
9973       // Treat indirect 'X' constraint as memory.
9974       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9975           OpInfo.isIndirect)
9976         OpInfo.ConstraintType = TargetLowering::C_Memory;
9977 
9978       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9979           OpInfo.ConstraintType == TargetLowering::C_Other) {
9980         std::vector<SDValue> Ops;
9981         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9982                                           Ops, DAG);
9983         if (Ops.empty()) {
9984           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9985             if (isa<ConstantSDNode>(InOperandVal)) {
9986               emitInlineAsmError(Call, "value out of range for constraint '" +
9987                                            Twine(OpInfo.ConstraintCode) + "'");
9988               return;
9989             }
9990 
9991           emitInlineAsmError(Call,
9992                              "invalid operand for inline asm constraint '" +
9993                                  Twine(OpInfo.ConstraintCode) + "'");
9994           return;
9995         }
9996 
9997         // Add information to the INLINEASM node to know about this input.
9998         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9999         AsmNodeOperands.push_back(DAG.getTargetConstant(
10000             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10001         llvm::append_range(AsmNodeOperands, Ops);
10002         break;
10003       }
10004 
10005       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10006         assert((OpInfo.isIndirect ||
10007                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10008                "Operand must be indirect to be a mem!");
10009         assert(InOperandVal.getValueType() ==
10010                    TLI.getPointerTy(DAG.getDataLayout()) &&
10011                "Memory operands expect pointer values");
10012 
10013         const InlineAsm::ConstraintCode ConstraintID =
10014             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10015         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10016                "Failed to convert memory constraint code to constraint id.");
10017 
10018         // Add information to the INLINEASM node to know about this input.
10019         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10020         ResOpType.setMemConstraint(ConstraintID);
10021         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10022                                                         getCurSDLoc(),
10023                                                         MVT::i32));
10024         AsmNodeOperands.push_back(InOperandVal);
10025         break;
10026       }
10027 
10028       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10029         const InlineAsm::ConstraintCode ConstraintID =
10030             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10031         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10032                "Failed to convert memory constraint code to constraint id.");
10033 
10034         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10035 
10036         SDValue AsmOp = InOperandVal;
10037         if (isFunction(InOperandVal)) {
10038           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10039           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10040           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10041                                              InOperandVal.getValueType(),
10042                                              GA->getOffset());
10043         }
10044 
10045         // Add information to the INLINEASM node to know about this input.
10046         ResOpType.setMemConstraint(ConstraintID);
10047 
10048         AsmNodeOperands.push_back(
10049             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10050 
10051         AsmNodeOperands.push_back(AsmOp);
10052         break;
10053       }
10054 
10055       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10056           OpInfo.ConstraintType != TargetLowering::C_Register) {
10057         emitInlineAsmError(Call, "unknown asm constraint '" +
10058                                      Twine(OpInfo.ConstraintCode) + "'");
10059         return;
10060       }
10061 
10062       // TODO: Support this.
10063       if (OpInfo.isIndirect) {
10064         emitInlineAsmError(
10065             Call, "Don't know how to handle indirect register inputs yet "
10066                   "for constraint '" +
10067                       Twine(OpInfo.ConstraintCode) + "'");
10068         return;
10069       }
10070 
10071       // Copy the input into the appropriate registers.
10072       if (OpInfo.AssignedRegs.Regs.empty()) {
10073         emitInlineAsmError(Call,
10074                            "couldn't allocate input reg for constraint '" +
10075                                Twine(OpInfo.ConstraintCode) + "'");
10076         return;
10077       }
10078 
10079       if (DetectWriteToReservedRegister())
10080         return;
10081 
10082       SDLoc dl = getCurSDLoc();
10083 
10084       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10085                                         &Call);
10086 
10087       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10088                                                0, dl, DAG, AsmNodeOperands);
10089       break;
10090     }
10091     case InlineAsm::isClobber:
10092       // Add the clobbered value to the operand list, so that the register
10093       // allocator is aware that the physreg got clobbered.
10094       if (!OpInfo.AssignedRegs.Regs.empty())
10095         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10096                                                  false, 0, getCurSDLoc(), DAG,
10097                                                  AsmNodeOperands);
10098       break;
10099     }
10100   }
10101 
10102   // Finish up input operands.  Set the input chain and add the flag last.
10103   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10104   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10105 
10106   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10107   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10108                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10109   Glue = Chain.getValue(1);
10110 
10111   // Do additional work to generate outputs.
10112 
10113   SmallVector<EVT, 1> ResultVTs;
10114   SmallVector<SDValue, 1> ResultValues;
10115   SmallVector<SDValue, 8> OutChains;
10116 
10117   llvm::Type *CallResultType = Call.getType();
10118   ArrayRef<Type *> ResultTypes;
10119   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10120     ResultTypes = StructResult->elements();
10121   else if (!CallResultType->isVoidTy())
10122     ResultTypes = ArrayRef(CallResultType);
10123 
10124   auto CurResultType = ResultTypes.begin();
10125   auto handleRegAssign = [&](SDValue V) {
10126     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10127     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10128     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10129     ++CurResultType;
10130     // If the type of the inline asm call site return value is different but has
10131     // same size as the type of the asm output bitcast it.  One example of this
10132     // is for vectors with different width / number of elements.  This can
10133     // happen for register classes that can contain multiple different value
10134     // types.  The preg or vreg allocated may not have the same VT as was
10135     // expected.
10136     //
10137     // This can also happen for a return value that disagrees with the register
10138     // class it is put in, eg. a double in a general-purpose register on a
10139     // 32-bit machine.
10140     if (ResultVT != V.getValueType() &&
10141         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10142       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10143     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10144              V.getValueType().isInteger()) {
10145       // If a result value was tied to an input value, the computed result
10146       // may have a wider width than the expected result.  Extract the
10147       // relevant portion.
10148       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10149     }
10150     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10151     ResultVTs.push_back(ResultVT);
10152     ResultValues.push_back(V);
10153   };
10154 
10155   // Deal with output operands.
10156   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10157     if (OpInfo.Type == InlineAsm::isOutput) {
10158       SDValue Val;
10159       // Skip trivial output operands.
10160       if (OpInfo.AssignedRegs.Regs.empty())
10161         continue;
10162 
10163       switch (OpInfo.ConstraintType) {
10164       case TargetLowering::C_Register:
10165       case TargetLowering::C_RegisterClass:
10166         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10167                                                   Chain, &Glue, &Call);
10168         break;
10169       case TargetLowering::C_Immediate:
10170       case TargetLowering::C_Other:
10171         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10172                                               OpInfo, DAG);
10173         break;
10174       case TargetLowering::C_Memory:
10175         break; // Already handled.
10176       case TargetLowering::C_Address:
10177         break; // Silence warning.
10178       case TargetLowering::C_Unknown:
10179         assert(false && "Unexpected unknown constraint");
10180       }
10181 
10182       // Indirect output manifest as stores. Record output chains.
10183       if (OpInfo.isIndirect) {
10184         const Value *Ptr = OpInfo.CallOperandVal;
10185         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10186         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10187                                      MachinePointerInfo(Ptr));
10188         OutChains.push_back(Store);
10189       } else {
10190         // generate CopyFromRegs to associated registers.
10191         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10192         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10193           for (const SDValue &V : Val->op_values())
10194             handleRegAssign(V);
10195         } else
10196           handleRegAssign(Val);
10197       }
10198     }
10199   }
10200 
10201   // Set results.
10202   if (!ResultValues.empty()) {
10203     assert(CurResultType == ResultTypes.end() &&
10204            "Mismatch in number of ResultTypes");
10205     assert(ResultValues.size() == ResultTypes.size() &&
10206            "Mismatch in number of output operands in asm result");
10207 
10208     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10209                             DAG.getVTList(ResultVTs), ResultValues);
10210     setValue(&Call, V);
10211   }
10212 
10213   // Collect store chains.
10214   if (!OutChains.empty())
10215     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10216 
10217   if (EmitEHLabels) {
10218     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10219   }
10220 
10221   // Only Update Root if inline assembly has a memory effect.
10222   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10223       EmitEHLabels)
10224     DAG.setRoot(Chain);
10225 }
10226 
10227 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10228                                              const Twine &Message) {
10229   LLVMContext &Ctx = *DAG.getContext();
10230   Ctx.emitError(&Call, Message);
10231 
10232   // Make sure we leave the DAG in a valid state
10233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10234   SmallVector<EVT, 1> ValueVTs;
10235   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10236 
10237   if (ValueVTs.empty())
10238     return;
10239 
10240   SmallVector<SDValue, 1> Ops;
10241   for (const EVT &VT : ValueVTs)
10242     Ops.push_back(DAG.getUNDEF(VT));
10243 
10244   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10245 }
10246 
10247 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10248   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10249                           MVT::Other, getRoot(),
10250                           getValue(I.getArgOperand(0)),
10251                           DAG.getSrcValue(I.getArgOperand(0))));
10252 }
10253 
10254 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10256   const DataLayout &DL = DAG.getDataLayout();
10257   SDValue V = DAG.getVAArg(
10258       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10259       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10260       DL.getABITypeAlign(I.getType()).value());
10261   DAG.setRoot(V.getValue(1));
10262 
10263   if (I.getType()->isPointerTy())
10264     V = DAG.getPtrExtOrTrunc(
10265         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10266   setValue(&I, V);
10267 }
10268 
10269 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10270   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10271                           MVT::Other, getRoot(),
10272                           getValue(I.getArgOperand(0)),
10273                           DAG.getSrcValue(I.getArgOperand(0))));
10274 }
10275 
10276 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10277   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10278                           MVT::Other, getRoot(),
10279                           getValue(I.getArgOperand(0)),
10280                           getValue(I.getArgOperand(1)),
10281                           DAG.getSrcValue(I.getArgOperand(0)),
10282                           DAG.getSrcValue(I.getArgOperand(1))));
10283 }
10284 
10285 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10286                                                     const Instruction &I,
10287                                                     SDValue Op) {
10288   std::optional<ConstantRange> CR = getRange(I);
10289 
10290   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10291     return Op;
10292 
10293   APInt Lo = CR->getUnsignedMin();
10294   if (!Lo.isMinValue())
10295     return Op;
10296 
10297   APInt Hi = CR->getUnsignedMax();
10298   unsigned Bits = std::max(Hi.getActiveBits(),
10299                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10300 
10301   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10302 
10303   SDLoc SL = getCurSDLoc();
10304 
10305   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10306                              DAG.getValueType(SmallVT));
10307   unsigned NumVals = Op.getNode()->getNumValues();
10308   if (NumVals == 1)
10309     return ZExt;
10310 
10311   SmallVector<SDValue, 4> Ops;
10312 
10313   Ops.push_back(ZExt);
10314   for (unsigned I = 1; I != NumVals; ++I)
10315     Ops.push_back(Op.getValue(I));
10316 
10317   return DAG.getMergeValues(Ops, SL);
10318 }
10319 
10320 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10321 /// the call being lowered.
10322 ///
10323 /// This is a helper for lowering intrinsics that follow a target calling
10324 /// convention or require stack pointer adjustment. Only a subset of the
10325 /// intrinsic's operands need to participate in the calling convention.
10326 void SelectionDAGBuilder::populateCallLoweringInfo(
10327     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10328     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10329     AttributeSet RetAttrs, bool IsPatchPoint) {
10330   TargetLowering::ArgListTy Args;
10331   Args.reserve(NumArgs);
10332 
10333   // Populate the argument list.
10334   // Attributes for args start at offset 1, after the return attribute.
10335   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10336        ArgI != ArgE; ++ArgI) {
10337     const Value *V = Call->getOperand(ArgI);
10338 
10339     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10340 
10341     TargetLowering::ArgListEntry Entry;
10342     Entry.Node = getValue(V);
10343     Entry.Ty = V->getType();
10344     Entry.setAttributes(Call, ArgI);
10345     Args.push_back(Entry);
10346   }
10347 
10348   CLI.setDebugLoc(getCurSDLoc())
10349       .setChain(getRoot())
10350       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10351                  RetAttrs)
10352       .setDiscardResult(Call->use_empty())
10353       .setIsPatchPoint(IsPatchPoint)
10354       .setIsPreallocated(
10355           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10356 }
10357 
10358 /// Add a stack map intrinsic call's live variable operands to a stackmap
10359 /// or patchpoint target node's operand list.
10360 ///
10361 /// Constants are converted to TargetConstants purely as an optimization to
10362 /// avoid constant materialization and register allocation.
10363 ///
10364 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10365 /// generate addess computation nodes, and so FinalizeISel can convert the
10366 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10367 /// address materialization and register allocation, but may also be required
10368 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10369 /// alloca in the entry block, then the runtime may assume that the alloca's
10370 /// StackMap location can be read immediately after compilation and that the
10371 /// location is valid at any point during execution (this is similar to the
10372 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10373 /// only available in a register, then the runtime would need to trap when
10374 /// execution reaches the StackMap in order to read the alloca's location.
10375 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10376                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10377                                 SelectionDAGBuilder &Builder) {
10378   SelectionDAG &DAG = Builder.DAG;
10379   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10380     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10381 
10382     // Things on the stack are pointer-typed, meaning that they are already
10383     // legal and can be emitted directly to target nodes.
10384     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10385       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10386     } else {
10387       // Otherwise emit a target independent node to be legalised.
10388       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10389     }
10390   }
10391 }
10392 
10393 /// Lower llvm.experimental.stackmap.
10394 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10395   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10396   //                                  [live variables...])
10397 
10398   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10399 
10400   SDValue Chain, InGlue, Callee;
10401   SmallVector<SDValue, 32> Ops;
10402 
10403   SDLoc DL = getCurSDLoc();
10404   Callee = getValue(CI.getCalledOperand());
10405 
10406   // The stackmap intrinsic only records the live variables (the arguments
10407   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10408   // intrinsic, this won't be lowered to a function call. This means we don't
10409   // have to worry about calling conventions and target specific lowering code.
10410   // Instead we perform the call lowering right here.
10411   //
10412   // chain, flag = CALLSEQ_START(chain, 0, 0)
10413   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10414   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10415   //
10416   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10417   InGlue = Chain.getValue(1);
10418 
10419   // Add the STACKMAP operands, starting with DAG house-keeping.
10420   Ops.push_back(Chain);
10421   Ops.push_back(InGlue);
10422 
10423   // Add the <id>, <numShadowBytes> operands.
10424   //
10425   // These do not require legalisation, and can be emitted directly to target
10426   // constant nodes.
10427   SDValue ID = getValue(CI.getArgOperand(0));
10428   assert(ID.getValueType() == MVT::i64);
10429   SDValue IDConst =
10430       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10431   Ops.push_back(IDConst);
10432 
10433   SDValue Shad = getValue(CI.getArgOperand(1));
10434   assert(Shad.getValueType() == MVT::i32);
10435   SDValue ShadConst =
10436       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10437   Ops.push_back(ShadConst);
10438 
10439   // Add the live variables.
10440   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10441 
10442   // Create the STACKMAP node.
10443   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10444   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10445   InGlue = Chain.getValue(1);
10446 
10447   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10448 
10449   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10450 
10451   // Set the root to the target-lowered call chain.
10452   DAG.setRoot(Chain);
10453 
10454   // Inform the Frame Information that we have a stackmap in this function.
10455   FuncInfo.MF->getFrameInfo().setHasStackMap();
10456 }
10457 
10458 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10459 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10460                                           const BasicBlock *EHPadBB) {
10461   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10462   //                                         i32 <numBytes>,
10463   //                                         i8* <target>,
10464   //                                         i32 <numArgs>,
10465   //                                         [Args...],
10466   //                                         [live variables...])
10467 
10468   CallingConv::ID CC = CB.getCallingConv();
10469   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10470   bool HasDef = !CB.getType()->isVoidTy();
10471   SDLoc dl = getCurSDLoc();
10472   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10473 
10474   // Handle immediate and symbolic callees.
10475   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10476     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10477                                    /*isTarget=*/true);
10478   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10479     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10480                                          SDLoc(SymbolicCallee),
10481                                          SymbolicCallee->getValueType(0));
10482 
10483   // Get the real number of arguments participating in the call <numArgs>
10484   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10485   unsigned NumArgs = NArgVal->getAsZExtVal();
10486 
10487   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10488   // Intrinsics include all meta-operands up to but not including CC.
10489   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10490   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10491          "Not enough arguments provided to the patchpoint intrinsic");
10492 
10493   // For AnyRegCC the arguments are lowered later on manually.
10494   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10495   Type *ReturnTy =
10496       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10497 
10498   TargetLowering::CallLoweringInfo CLI(DAG);
10499   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10500                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10501   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10502 
10503   SDNode *CallEnd = Result.second.getNode();
10504   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10505     CallEnd = CallEnd->getOperand(0).getNode();
10506   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10507     CallEnd = CallEnd->getOperand(0).getNode();
10508 
10509   /// Get a call instruction from the call sequence chain.
10510   /// Tail calls are not allowed.
10511   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10512          "Expected a callseq node.");
10513   SDNode *Call = CallEnd->getOperand(0).getNode();
10514   bool HasGlue = Call->getGluedNode();
10515 
10516   // Replace the target specific call node with the patchable intrinsic.
10517   SmallVector<SDValue, 8> Ops;
10518 
10519   // Push the chain.
10520   Ops.push_back(*(Call->op_begin()));
10521 
10522   // Optionally, push the glue (if any).
10523   if (HasGlue)
10524     Ops.push_back(*(Call->op_end() - 1));
10525 
10526   // Push the register mask info.
10527   if (HasGlue)
10528     Ops.push_back(*(Call->op_end() - 2));
10529   else
10530     Ops.push_back(*(Call->op_end() - 1));
10531 
10532   // Add the <id> and <numBytes> constants.
10533   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10534   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10535   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10536   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10537 
10538   // Add the callee.
10539   Ops.push_back(Callee);
10540 
10541   // Adjust <numArgs> to account for any arguments that have been passed on the
10542   // stack instead.
10543   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10544   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10545   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10546   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10547 
10548   // Add the calling convention
10549   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10550 
10551   // Add the arguments we omitted previously. The register allocator should
10552   // place these in any free register.
10553   if (IsAnyRegCC)
10554     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10555       Ops.push_back(getValue(CB.getArgOperand(i)));
10556 
10557   // Push the arguments from the call instruction.
10558   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10559   Ops.append(Call->op_begin() + 2, e);
10560 
10561   // Push live variables for the stack map.
10562   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10563 
10564   SDVTList NodeTys;
10565   if (IsAnyRegCC && HasDef) {
10566     // Create the return types based on the intrinsic definition
10567     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10568     SmallVector<EVT, 3> ValueVTs;
10569     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10570     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10571 
10572     // There is always a chain and a glue type at the end
10573     ValueVTs.push_back(MVT::Other);
10574     ValueVTs.push_back(MVT::Glue);
10575     NodeTys = DAG.getVTList(ValueVTs);
10576   } else
10577     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10578 
10579   // Replace the target specific call node with a PATCHPOINT node.
10580   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10581 
10582   // Update the NodeMap.
10583   if (HasDef) {
10584     if (IsAnyRegCC)
10585       setValue(&CB, SDValue(PPV.getNode(), 0));
10586     else
10587       setValue(&CB, Result.first);
10588   }
10589 
10590   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10591   // call sequence. Furthermore the location of the chain and glue can change
10592   // when the AnyReg calling convention is used and the intrinsic returns a
10593   // value.
10594   if (IsAnyRegCC && HasDef) {
10595     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10596     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10597     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10598   } else
10599     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10600   DAG.DeleteNode(Call);
10601 
10602   // Inform the Frame Information that we have a patchpoint in this function.
10603   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10604 }
10605 
10606 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10607                                             unsigned Intrinsic) {
10608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10609   SDValue Op1 = getValue(I.getArgOperand(0));
10610   SDValue Op2;
10611   if (I.arg_size() > 1)
10612     Op2 = getValue(I.getArgOperand(1));
10613   SDLoc dl = getCurSDLoc();
10614   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10615   SDValue Res;
10616   SDNodeFlags SDFlags;
10617   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10618     SDFlags.copyFMF(*FPMO);
10619 
10620   switch (Intrinsic) {
10621   case Intrinsic::vector_reduce_fadd:
10622     if (SDFlags.hasAllowReassociation())
10623       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10624                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10625                         SDFlags);
10626     else
10627       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10628     break;
10629   case Intrinsic::vector_reduce_fmul:
10630     if (SDFlags.hasAllowReassociation())
10631       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10632                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10633                         SDFlags);
10634     else
10635       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10636     break;
10637   case Intrinsic::vector_reduce_add:
10638     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10639     break;
10640   case Intrinsic::vector_reduce_mul:
10641     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10642     break;
10643   case Intrinsic::vector_reduce_and:
10644     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10645     break;
10646   case Intrinsic::vector_reduce_or:
10647     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10648     break;
10649   case Intrinsic::vector_reduce_xor:
10650     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10651     break;
10652   case Intrinsic::vector_reduce_smax:
10653     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10654     break;
10655   case Intrinsic::vector_reduce_smin:
10656     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10657     break;
10658   case Intrinsic::vector_reduce_umax:
10659     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10660     break;
10661   case Intrinsic::vector_reduce_umin:
10662     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10663     break;
10664   case Intrinsic::vector_reduce_fmax:
10665     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10666     break;
10667   case Intrinsic::vector_reduce_fmin:
10668     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10669     break;
10670   case Intrinsic::vector_reduce_fmaximum:
10671     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10672     break;
10673   case Intrinsic::vector_reduce_fminimum:
10674     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10675     break;
10676   default:
10677     llvm_unreachable("Unhandled vector reduce intrinsic");
10678   }
10679   setValue(&I, Res);
10680 }
10681 
10682 /// Returns an AttributeList representing the attributes applied to the return
10683 /// value of the given call.
10684 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10685   SmallVector<Attribute::AttrKind, 2> Attrs;
10686   if (CLI.RetSExt)
10687     Attrs.push_back(Attribute::SExt);
10688   if (CLI.RetZExt)
10689     Attrs.push_back(Attribute::ZExt);
10690   if (CLI.IsInReg)
10691     Attrs.push_back(Attribute::InReg);
10692 
10693   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10694                             Attrs);
10695 }
10696 
10697 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10698 /// implementation, which just calls LowerCall.
10699 /// FIXME: When all targets are
10700 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10701 std::pair<SDValue, SDValue>
10702 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10703   // Handle the incoming return values from the call.
10704   CLI.Ins.clear();
10705   Type *OrigRetTy = CLI.RetTy;
10706   SmallVector<EVT, 4> RetTys;
10707   SmallVector<TypeSize, 4> Offsets;
10708   auto &DL = CLI.DAG.getDataLayout();
10709   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10710 
10711   if (CLI.IsPostTypeLegalization) {
10712     // If we are lowering a libcall after legalization, split the return type.
10713     SmallVector<EVT, 4> OldRetTys;
10714     SmallVector<TypeSize, 4> OldOffsets;
10715     RetTys.swap(OldRetTys);
10716     Offsets.swap(OldOffsets);
10717 
10718     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10719       EVT RetVT = OldRetTys[i];
10720       uint64_t Offset = OldOffsets[i];
10721       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10722       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10723       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10724       RetTys.append(NumRegs, RegisterVT);
10725       for (unsigned j = 0; j != NumRegs; ++j)
10726         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10727     }
10728   }
10729 
10730   SmallVector<ISD::OutputArg, 4> Outs;
10731   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10732 
10733   bool CanLowerReturn =
10734       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10735                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10736 
10737   SDValue DemoteStackSlot;
10738   int DemoteStackIdx = -100;
10739   if (!CanLowerReturn) {
10740     // FIXME: equivalent assert?
10741     // assert(!CS.hasInAllocaArgument() &&
10742     //        "sret demotion is incompatible with inalloca");
10743     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10744     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10745     MachineFunction &MF = CLI.DAG.getMachineFunction();
10746     DemoteStackIdx =
10747         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10748     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10749                                               DL.getAllocaAddrSpace());
10750 
10751     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10752     ArgListEntry Entry;
10753     Entry.Node = DemoteStackSlot;
10754     Entry.Ty = StackSlotPtrType;
10755     Entry.IsSExt = false;
10756     Entry.IsZExt = false;
10757     Entry.IsInReg = false;
10758     Entry.IsSRet = true;
10759     Entry.IsNest = false;
10760     Entry.IsByVal = false;
10761     Entry.IsByRef = false;
10762     Entry.IsReturned = false;
10763     Entry.IsSwiftSelf = false;
10764     Entry.IsSwiftAsync = false;
10765     Entry.IsSwiftError = false;
10766     Entry.IsCFGuardTarget = false;
10767     Entry.Alignment = Alignment;
10768     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10769     CLI.NumFixedArgs += 1;
10770     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10771     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10772 
10773     // sret demotion isn't compatible with tail-calls, since the sret argument
10774     // points into the callers stack frame.
10775     CLI.IsTailCall = false;
10776   } else {
10777     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10778         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10779     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10780       ISD::ArgFlagsTy Flags;
10781       if (NeedsRegBlock) {
10782         Flags.setInConsecutiveRegs();
10783         if (I == RetTys.size() - 1)
10784           Flags.setInConsecutiveRegsLast();
10785       }
10786       EVT VT = RetTys[I];
10787       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10788                                                      CLI.CallConv, VT);
10789       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10790                                                        CLI.CallConv, VT);
10791       for (unsigned i = 0; i != NumRegs; ++i) {
10792         ISD::InputArg MyFlags;
10793         MyFlags.Flags = Flags;
10794         MyFlags.VT = RegisterVT;
10795         MyFlags.ArgVT = VT;
10796         MyFlags.Used = CLI.IsReturnValueUsed;
10797         if (CLI.RetTy->isPointerTy()) {
10798           MyFlags.Flags.setPointer();
10799           MyFlags.Flags.setPointerAddrSpace(
10800               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10801         }
10802         if (CLI.RetSExt)
10803           MyFlags.Flags.setSExt();
10804         if (CLI.RetZExt)
10805           MyFlags.Flags.setZExt();
10806         if (CLI.IsInReg)
10807           MyFlags.Flags.setInReg();
10808         CLI.Ins.push_back(MyFlags);
10809       }
10810     }
10811   }
10812 
10813   // We push in swifterror return as the last element of CLI.Ins.
10814   ArgListTy &Args = CLI.getArgs();
10815   if (supportSwiftError()) {
10816     for (const ArgListEntry &Arg : Args) {
10817       if (Arg.IsSwiftError) {
10818         ISD::InputArg MyFlags;
10819         MyFlags.VT = getPointerTy(DL);
10820         MyFlags.ArgVT = EVT(getPointerTy(DL));
10821         MyFlags.Flags.setSwiftError();
10822         CLI.Ins.push_back(MyFlags);
10823       }
10824     }
10825   }
10826 
10827   // Handle all of the outgoing arguments.
10828   CLI.Outs.clear();
10829   CLI.OutVals.clear();
10830   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10831     SmallVector<EVT, 4> ValueVTs;
10832     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10833     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10834     Type *FinalType = Args[i].Ty;
10835     if (Args[i].IsByVal)
10836       FinalType = Args[i].IndirectType;
10837     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10838         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10839     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10840          ++Value) {
10841       EVT VT = ValueVTs[Value];
10842       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10843       SDValue Op = SDValue(Args[i].Node.getNode(),
10844                            Args[i].Node.getResNo() + Value);
10845       ISD::ArgFlagsTy Flags;
10846 
10847       // Certain targets (such as MIPS), may have a different ABI alignment
10848       // for a type depending on the context. Give the target a chance to
10849       // specify the alignment it wants.
10850       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10851       Flags.setOrigAlign(OriginalAlignment);
10852 
10853       if (Args[i].Ty->isPointerTy()) {
10854         Flags.setPointer();
10855         Flags.setPointerAddrSpace(
10856             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10857       }
10858       if (Args[i].IsZExt)
10859         Flags.setZExt();
10860       if (Args[i].IsSExt)
10861         Flags.setSExt();
10862       if (Args[i].IsInReg) {
10863         // If we are using vectorcall calling convention, a structure that is
10864         // passed InReg - is surely an HVA
10865         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10866             isa<StructType>(FinalType)) {
10867           // The first value of a structure is marked
10868           if (0 == Value)
10869             Flags.setHvaStart();
10870           Flags.setHva();
10871         }
10872         // Set InReg Flag
10873         Flags.setInReg();
10874       }
10875       if (Args[i].IsSRet)
10876         Flags.setSRet();
10877       if (Args[i].IsSwiftSelf)
10878         Flags.setSwiftSelf();
10879       if (Args[i].IsSwiftAsync)
10880         Flags.setSwiftAsync();
10881       if (Args[i].IsSwiftError)
10882         Flags.setSwiftError();
10883       if (Args[i].IsCFGuardTarget)
10884         Flags.setCFGuardTarget();
10885       if (Args[i].IsByVal)
10886         Flags.setByVal();
10887       if (Args[i].IsByRef)
10888         Flags.setByRef();
10889       if (Args[i].IsPreallocated) {
10890         Flags.setPreallocated();
10891         // Set the byval flag for CCAssignFn callbacks that don't know about
10892         // preallocated.  This way we can know how many bytes we should've
10893         // allocated and how many bytes a callee cleanup function will pop.  If
10894         // we port preallocated to more targets, we'll have to add custom
10895         // preallocated handling in the various CC lowering callbacks.
10896         Flags.setByVal();
10897       }
10898       if (Args[i].IsInAlloca) {
10899         Flags.setInAlloca();
10900         // Set the byval flag for CCAssignFn callbacks that don't know about
10901         // inalloca.  This way we can know how many bytes we should've allocated
10902         // and how many bytes a callee cleanup function will pop.  If we port
10903         // inalloca to more targets, we'll have to add custom inalloca handling
10904         // in the various CC lowering callbacks.
10905         Flags.setByVal();
10906       }
10907       Align MemAlign;
10908       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10909         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10910         Flags.setByValSize(FrameSize);
10911 
10912         // info is not there but there are cases it cannot get right.
10913         if (auto MA = Args[i].Alignment)
10914           MemAlign = *MA;
10915         else
10916           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10917       } else if (auto MA = Args[i].Alignment) {
10918         MemAlign = *MA;
10919       } else {
10920         MemAlign = OriginalAlignment;
10921       }
10922       Flags.setMemAlign(MemAlign);
10923       if (Args[i].IsNest)
10924         Flags.setNest();
10925       if (NeedsRegBlock)
10926         Flags.setInConsecutiveRegs();
10927 
10928       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10929                                                  CLI.CallConv, VT);
10930       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10931                                                         CLI.CallConv, VT);
10932       SmallVector<SDValue, 4> Parts(NumParts);
10933       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10934 
10935       if (Args[i].IsSExt)
10936         ExtendKind = ISD::SIGN_EXTEND;
10937       else if (Args[i].IsZExt)
10938         ExtendKind = ISD::ZERO_EXTEND;
10939 
10940       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10941       // for now.
10942       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10943           CanLowerReturn) {
10944         assert((CLI.RetTy == Args[i].Ty ||
10945                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10946                  CLI.RetTy->getPointerAddressSpace() ==
10947                      Args[i].Ty->getPointerAddressSpace())) &&
10948                RetTys.size() == NumValues && "unexpected use of 'returned'");
10949         // Before passing 'returned' to the target lowering code, ensure that
10950         // either the register MVT and the actual EVT are the same size or that
10951         // the return value and argument are extended in the same way; in these
10952         // cases it's safe to pass the argument register value unchanged as the
10953         // return register value (although it's at the target's option whether
10954         // to do so)
10955         // TODO: allow code generation to take advantage of partially preserved
10956         // registers rather than clobbering the entire register when the
10957         // parameter extension method is not compatible with the return
10958         // extension method
10959         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10960             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10961              CLI.RetZExt == Args[i].IsZExt))
10962           Flags.setReturned();
10963       }
10964 
10965       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10966                      CLI.CallConv, ExtendKind);
10967 
10968       for (unsigned j = 0; j != NumParts; ++j) {
10969         // if it isn't first piece, alignment must be 1
10970         // For scalable vectors the scalable part is currently handled
10971         // by individual targets, so we just use the known minimum size here.
10972         ISD::OutputArg MyFlags(
10973             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10974             i < CLI.NumFixedArgs, i,
10975             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10976         if (NumParts > 1 && j == 0)
10977           MyFlags.Flags.setSplit();
10978         else if (j != 0) {
10979           MyFlags.Flags.setOrigAlign(Align(1));
10980           if (j == NumParts - 1)
10981             MyFlags.Flags.setSplitEnd();
10982         }
10983 
10984         CLI.Outs.push_back(MyFlags);
10985         CLI.OutVals.push_back(Parts[j]);
10986       }
10987 
10988       if (NeedsRegBlock && Value == NumValues - 1)
10989         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10990     }
10991   }
10992 
10993   SmallVector<SDValue, 4> InVals;
10994   CLI.Chain = LowerCall(CLI, InVals);
10995 
10996   // Update CLI.InVals to use outside of this function.
10997   CLI.InVals = InVals;
10998 
10999   // Verify that the target's LowerCall behaved as expected.
11000   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11001          "LowerCall didn't return a valid chain!");
11002   assert((!CLI.IsTailCall || InVals.empty()) &&
11003          "LowerCall emitted a return value for a tail call!");
11004   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11005          "LowerCall didn't emit the correct number of values!");
11006 
11007   // For a tail call, the return value is merely live-out and there aren't
11008   // any nodes in the DAG representing it. Return a special value to
11009   // indicate that a tail call has been emitted and no more Instructions
11010   // should be processed in the current block.
11011   if (CLI.IsTailCall) {
11012     CLI.DAG.setRoot(CLI.Chain);
11013     return std::make_pair(SDValue(), SDValue());
11014   }
11015 
11016 #ifndef NDEBUG
11017   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11018     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11019     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11020            "LowerCall emitted a value with the wrong type!");
11021   }
11022 #endif
11023 
11024   SmallVector<SDValue, 4> ReturnValues;
11025   if (!CanLowerReturn) {
11026     // The instruction result is the result of loading from the
11027     // hidden sret parameter.
11028     SmallVector<EVT, 1> PVTs;
11029     Type *PtrRetTy =
11030         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11031 
11032     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11033     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11034     EVT PtrVT = PVTs[0];
11035 
11036     unsigned NumValues = RetTys.size();
11037     ReturnValues.resize(NumValues);
11038     SmallVector<SDValue, 4> Chains(NumValues);
11039 
11040     // An aggregate return value cannot wrap around the address space, so
11041     // offsets to its parts don't wrap either.
11042     SDNodeFlags Flags;
11043     Flags.setNoUnsignedWrap(true);
11044 
11045     MachineFunction &MF = CLI.DAG.getMachineFunction();
11046     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11047     for (unsigned i = 0; i < NumValues; ++i) {
11048       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11049                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11050                                                         PtrVT), Flags);
11051       SDValue L = CLI.DAG.getLoad(
11052           RetTys[i], CLI.DL, CLI.Chain, Add,
11053           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11054                                             DemoteStackIdx, Offsets[i]),
11055           HiddenSRetAlign);
11056       ReturnValues[i] = L;
11057       Chains[i] = L.getValue(1);
11058     }
11059 
11060     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11061   } else {
11062     // Collect the legal value parts into potentially illegal values
11063     // that correspond to the original function's return values.
11064     std::optional<ISD::NodeType> AssertOp;
11065     if (CLI.RetSExt)
11066       AssertOp = ISD::AssertSext;
11067     else if (CLI.RetZExt)
11068       AssertOp = ISD::AssertZext;
11069     unsigned CurReg = 0;
11070     for (EVT VT : RetTys) {
11071       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11072                                                      CLI.CallConv, VT);
11073       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11074                                                        CLI.CallConv, VT);
11075 
11076       ReturnValues.push_back(getCopyFromParts(
11077           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11078           CLI.Chain, CLI.CallConv, AssertOp));
11079       CurReg += NumRegs;
11080     }
11081 
11082     // For a function returning void, there is no return value. We can't create
11083     // such a node, so we just return a null return value in that case. In
11084     // that case, nothing will actually look at the value.
11085     if (ReturnValues.empty())
11086       return std::make_pair(SDValue(), CLI.Chain);
11087   }
11088 
11089   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11090                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11091   return std::make_pair(Res, CLI.Chain);
11092 }
11093 
11094 /// Places new result values for the node in Results (their number
11095 /// and types must exactly match those of the original return values of
11096 /// the node), or leaves Results empty, which indicates that the node is not
11097 /// to be custom lowered after all.
11098 void TargetLowering::LowerOperationWrapper(SDNode *N,
11099                                            SmallVectorImpl<SDValue> &Results,
11100                                            SelectionDAG &DAG) const {
11101   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11102 
11103   if (!Res.getNode())
11104     return;
11105 
11106   // If the original node has one result, take the return value from
11107   // LowerOperation as is. It might not be result number 0.
11108   if (N->getNumValues() == 1) {
11109     Results.push_back(Res);
11110     return;
11111   }
11112 
11113   // If the original node has multiple results, then the return node should
11114   // have the same number of results.
11115   assert((N->getNumValues() == Res->getNumValues()) &&
11116       "Lowering returned the wrong number of results!");
11117 
11118   // Places new result values base on N result number.
11119   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11120     Results.push_back(Res.getValue(I));
11121 }
11122 
11123 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11124   llvm_unreachable("LowerOperation not implemented for this target!");
11125 }
11126 
11127 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11128                                                      unsigned Reg,
11129                                                      ISD::NodeType ExtendType) {
11130   SDValue Op = getNonRegisterValue(V);
11131   assert((Op.getOpcode() != ISD::CopyFromReg ||
11132           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11133          "Copy from a reg to the same reg!");
11134   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11135 
11136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11137   // If this is an InlineAsm we have to match the registers required, not the
11138   // notional registers required by the type.
11139 
11140   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11141                    std::nullopt); // This is not an ABI copy.
11142   SDValue Chain = DAG.getEntryNode();
11143 
11144   if (ExtendType == ISD::ANY_EXTEND) {
11145     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11146     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11147       ExtendType = PreferredExtendIt->second;
11148   }
11149   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11150   PendingExports.push_back(Chain);
11151 }
11152 
11153 #include "llvm/CodeGen/SelectionDAGISel.h"
11154 
11155 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11156 /// entry block, return true.  This includes arguments used by switches, since
11157 /// the switch may expand into multiple basic blocks.
11158 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11159   // With FastISel active, we may be splitting blocks, so force creation
11160   // of virtual registers for all non-dead arguments.
11161   if (FastISel)
11162     return A->use_empty();
11163 
11164   const BasicBlock &Entry = A->getParent()->front();
11165   for (const User *U : A->users())
11166     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11167       return false;  // Use not in entry block.
11168 
11169   return true;
11170 }
11171 
11172 using ArgCopyElisionMapTy =
11173     DenseMap<const Argument *,
11174              std::pair<const AllocaInst *, const StoreInst *>>;
11175 
11176 /// Scan the entry block of the function in FuncInfo for arguments that look
11177 /// like copies into a local alloca. Record any copied arguments in
11178 /// ArgCopyElisionCandidates.
11179 static void
11180 findArgumentCopyElisionCandidates(const DataLayout &DL,
11181                                   FunctionLoweringInfo *FuncInfo,
11182                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11183   // Record the state of every static alloca used in the entry block. Argument
11184   // allocas are all used in the entry block, so we need approximately as many
11185   // entries as we have arguments.
11186   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11187   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11188   unsigned NumArgs = FuncInfo->Fn->arg_size();
11189   StaticAllocas.reserve(NumArgs * 2);
11190 
11191   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11192     if (!V)
11193       return nullptr;
11194     V = V->stripPointerCasts();
11195     const auto *AI = dyn_cast<AllocaInst>(V);
11196     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11197       return nullptr;
11198     auto Iter = StaticAllocas.insert({AI, Unknown});
11199     return &Iter.first->second;
11200   };
11201 
11202   // Look for stores of arguments to static allocas. Look through bitcasts and
11203   // GEPs to handle type coercions, as long as the alloca is fully initialized
11204   // by the store. Any non-store use of an alloca escapes it and any subsequent
11205   // unanalyzed store might write it.
11206   // FIXME: Handle structs initialized with multiple stores.
11207   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11208     // Look for stores, and handle non-store uses conservatively.
11209     const auto *SI = dyn_cast<StoreInst>(&I);
11210     if (!SI) {
11211       // We will look through cast uses, so ignore them completely.
11212       if (I.isCast())
11213         continue;
11214       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11215       // to allocas.
11216       if (I.isDebugOrPseudoInst())
11217         continue;
11218       // This is an unknown instruction. Assume it escapes or writes to all
11219       // static alloca operands.
11220       for (const Use &U : I.operands()) {
11221         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11222           *Info = StaticAllocaInfo::Clobbered;
11223       }
11224       continue;
11225     }
11226 
11227     // If the stored value is a static alloca, mark it as escaped.
11228     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11229       *Info = StaticAllocaInfo::Clobbered;
11230 
11231     // Check if the destination is a static alloca.
11232     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11233     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11234     if (!Info)
11235       continue;
11236     const AllocaInst *AI = cast<AllocaInst>(Dst);
11237 
11238     // Skip allocas that have been initialized or clobbered.
11239     if (*Info != StaticAllocaInfo::Unknown)
11240       continue;
11241 
11242     // Check if the stored value is an argument, and that this store fully
11243     // initializes the alloca.
11244     // If the argument type has padding bits we can't directly forward a pointer
11245     // as the upper bits may contain garbage.
11246     // Don't elide copies from the same argument twice.
11247     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11248     const auto *Arg = dyn_cast<Argument>(Val);
11249     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11250         Arg->getType()->isEmptyTy() ||
11251         DL.getTypeStoreSize(Arg->getType()) !=
11252             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11253         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11254         ArgCopyElisionCandidates.count(Arg)) {
11255       *Info = StaticAllocaInfo::Clobbered;
11256       continue;
11257     }
11258 
11259     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11260                       << '\n');
11261 
11262     // Mark this alloca and store for argument copy elision.
11263     *Info = StaticAllocaInfo::Elidable;
11264     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11265 
11266     // Stop scanning if we've seen all arguments. This will happen early in -O0
11267     // builds, which is useful, because -O0 builds have large entry blocks and
11268     // many allocas.
11269     if (ArgCopyElisionCandidates.size() == NumArgs)
11270       break;
11271   }
11272 }
11273 
11274 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11275 /// ArgVal is a load from a suitable fixed stack object.
11276 static void tryToElideArgumentCopy(
11277     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11278     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11279     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11280     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11281     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11282   // Check if this is a load from a fixed stack object.
11283   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11284   if (!LNode)
11285     return;
11286   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11287   if (!FINode)
11288     return;
11289 
11290   // Check that the fixed stack object is the right size and alignment.
11291   // Look at the alignment that the user wrote on the alloca instead of looking
11292   // at the stack object.
11293   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11294   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11295   const AllocaInst *AI = ArgCopyIter->second.first;
11296   int FixedIndex = FINode->getIndex();
11297   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11298   int OldIndex = AllocaIndex;
11299   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11300   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11301     LLVM_DEBUG(
11302         dbgs() << "  argument copy elision failed due to bad fixed stack "
11303                   "object size\n");
11304     return;
11305   }
11306   Align RequiredAlignment = AI->getAlign();
11307   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11308     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11309                          "greater than stack argument alignment ("
11310                       << DebugStr(RequiredAlignment) << " vs "
11311                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11312     return;
11313   }
11314 
11315   // Perform the elision. Delete the old stack object and replace its only use
11316   // in the variable info map. Mark the stack object as mutable and aliased.
11317   LLVM_DEBUG({
11318     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11319            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11320            << '\n';
11321   });
11322   MFI.RemoveStackObject(OldIndex);
11323   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11324   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11325   AllocaIndex = FixedIndex;
11326   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11327   for (SDValue ArgVal : ArgVals)
11328     Chains.push_back(ArgVal.getValue(1));
11329 
11330   // Avoid emitting code for the store implementing the copy.
11331   const StoreInst *SI = ArgCopyIter->second.second;
11332   ElidedArgCopyInstrs.insert(SI);
11333 
11334   // Check for uses of the argument again so that we can avoid exporting ArgVal
11335   // if it is't used by anything other than the store.
11336   for (const Value *U : Arg.users()) {
11337     if (U != SI) {
11338       ArgHasUses = true;
11339       break;
11340     }
11341   }
11342 }
11343 
11344 void SelectionDAGISel::LowerArguments(const Function &F) {
11345   SelectionDAG &DAG = SDB->DAG;
11346   SDLoc dl = SDB->getCurSDLoc();
11347   const DataLayout &DL = DAG.getDataLayout();
11348   SmallVector<ISD::InputArg, 16> Ins;
11349 
11350   // In Naked functions we aren't going to save any registers.
11351   if (F.hasFnAttribute(Attribute::Naked))
11352     return;
11353 
11354   if (!FuncInfo->CanLowerReturn) {
11355     // Put in an sret pointer parameter before all the other parameters.
11356     SmallVector<EVT, 1> ValueVTs;
11357     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11358                     PointerType::get(F.getContext(),
11359                                      DAG.getDataLayout().getAllocaAddrSpace()),
11360                     ValueVTs);
11361 
11362     // NOTE: Assuming that a pointer will never break down to more than one VT
11363     // or one register.
11364     ISD::ArgFlagsTy Flags;
11365     Flags.setSRet();
11366     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11367     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11368                          ISD::InputArg::NoArgIndex, 0);
11369     Ins.push_back(RetArg);
11370   }
11371 
11372   // Look for stores of arguments to static allocas. Mark such arguments with a
11373   // flag to ask the target to give us the memory location of that argument if
11374   // available.
11375   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11376   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11377                                     ArgCopyElisionCandidates);
11378 
11379   // Set up the incoming argument description vector.
11380   for (const Argument &Arg : F.args()) {
11381     unsigned ArgNo = Arg.getArgNo();
11382     SmallVector<EVT, 4> ValueVTs;
11383     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11384     bool isArgValueUsed = !Arg.use_empty();
11385     unsigned PartBase = 0;
11386     Type *FinalType = Arg.getType();
11387     if (Arg.hasAttribute(Attribute::ByVal))
11388       FinalType = Arg.getParamByValType();
11389     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11390         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11391     for (unsigned Value = 0, NumValues = ValueVTs.size();
11392          Value != NumValues; ++Value) {
11393       EVT VT = ValueVTs[Value];
11394       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11395       ISD::ArgFlagsTy Flags;
11396 
11397 
11398       if (Arg.getType()->isPointerTy()) {
11399         Flags.setPointer();
11400         Flags.setPointerAddrSpace(
11401             cast<PointerType>(Arg.getType())->getAddressSpace());
11402       }
11403       if (Arg.hasAttribute(Attribute::ZExt))
11404         Flags.setZExt();
11405       if (Arg.hasAttribute(Attribute::SExt))
11406         Flags.setSExt();
11407       if (Arg.hasAttribute(Attribute::InReg)) {
11408         // If we are using vectorcall calling convention, a structure that is
11409         // passed InReg - is surely an HVA
11410         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11411             isa<StructType>(Arg.getType())) {
11412           // The first value of a structure is marked
11413           if (0 == Value)
11414             Flags.setHvaStart();
11415           Flags.setHva();
11416         }
11417         // Set InReg Flag
11418         Flags.setInReg();
11419       }
11420       if (Arg.hasAttribute(Attribute::StructRet))
11421         Flags.setSRet();
11422       if (Arg.hasAttribute(Attribute::SwiftSelf))
11423         Flags.setSwiftSelf();
11424       if (Arg.hasAttribute(Attribute::SwiftAsync))
11425         Flags.setSwiftAsync();
11426       if (Arg.hasAttribute(Attribute::SwiftError))
11427         Flags.setSwiftError();
11428       if (Arg.hasAttribute(Attribute::ByVal))
11429         Flags.setByVal();
11430       if (Arg.hasAttribute(Attribute::ByRef))
11431         Flags.setByRef();
11432       if (Arg.hasAttribute(Attribute::InAlloca)) {
11433         Flags.setInAlloca();
11434         // Set the byval flag for CCAssignFn callbacks that don't know about
11435         // inalloca.  This way we can know how many bytes we should've allocated
11436         // and how many bytes a callee cleanup function will pop.  If we port
11437         // inalloca to more targets, we'll have to add custom inalloca handling
11438         // in the various CC lowering callbacks.
11439         Flags.setByVal();
11440       }
11441       if (Arg.hasAttribute(Attribute::Preallocated)) {
11442         Flags.setPreallocated();
11443         // Set the byval flag for CCAssignFn callbacks that don't know about
11444         // preallocated.  This way we can know how many bytes we should've
11445         // allocated and how many bytes a callee cleanup function will pop.  If
11446         // we port preallocated to more targets, we'll have to add custom
11447         // preallocated handling in the various CC lowering callbacks.
11448         Flags.setByVal();
11449       }
11450 
11451       // Certain targets (such as MIPS), may have a different ABI alignment
11452       // for a type depending on the context. Give the target a chance to
11453       // specify the alignment it wants.
11454       const Align OriginalAlignment(
11455           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11456       Flags.setOrigAlign(OriginalAlignment);
11457 
11458       Align MemAlign;
11459       Type *ArgMemTy = nullptr;
11460       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11461           Flags.isByRef()) {
11462         if (!ArgMemTy)
11463           ArgMemTy = Arg.getPointeeInMemoryValueType();
11464 
11465         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11466 
11467         // For in-memory arguments, size and alignment should be passed from FE.
11468         // BE will guess if this info is not there but there are cases it cannot
11469         // get right.
11470         if (auto ParamAlign = Arg.getParamStackAlign())
11471           MemAlign = *ParamAlign;
11472         else if ((ParamAlign = Arg.getParamAlign()))
11473           MemAlign = *ParamAlign;
11474         else
11475           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11476         if (Flags.isByRef())
11477           Flags.setByRefSize(MemSize);
11478         else
11479           Flags.setByValSize(MemSize);
11480       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11481         MemAlign = *ParamAlign;
11482       } else {
11483         MemAlign = OriginalAlignment;
11484       }
11485       Flags.setMemAlign(MemAlign);
11486 
11487       if (Arg.hasAttribute(Attribute::Nest))
11488         Flags.setNest();
11489       if (NeedsRegBlock)
11490         Flags.setInConsecutiveRegs();
11491       if (ArgCopyElisionCandidates.count(&Arg))
11492         Flags.setCopyElisionCandidate();
11493       if (Arg.hasAttribute(Attribute::Returned))
11494         Flags.setReturned();
11495 
11496       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11497           *CurDAG->getContext(), F.getCallingConv(), VT);
11498       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11499           *CurDAG->getContext(), F.getCallingConv(), VT);
11500       for (unsigned i = 0; i != NumRegs; ++i) {
11501         // For scalable vectors, use the minimum size; individual targets
11502         // are responsible for handling scalable vector arguments and
11503         // return values.
11504         ISD::InputArg MyFlags(
11505             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11506             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11507         if (NumRegs > 1 && i == 0)
11508           MyFlags.Flags.setSplit();
11509         // if it isn't first piece, alignment must be 1
11510         else if (i > 0) {
11511           MyFlags.Flags.setOrigAlign(Align(1));
11512           if (i == NumRegs - 1)
11513             MyFlags.Flags.setSplitEnd();
11514         }
11515         Ins.push_back(MyFlags);
11516       }
11517       if (NeedsRegBlock && Value == NumValues - 1)
11518         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11519       PartBase += VT.getStoreSize().getKnownMinValue();
11520     }
11521   }
11522 
11523   // Call the target to set up the argument values.
11524   SmallVector<SDValue, 8> InVals;
11525   SDValue NewRoot = TLI->LowerFormalArguments(
11526       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11527 
11528   // Verify that the target's LowerFormalArguments behaved as expected.
11529   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11530          "LowerFormalArguments didn't return a valid chain!");
11531   assert(InVals.size() == Ins.size() &&
11532          "LowerFormalArguments didn't emit the correct number of values!");
11533   LLVM_DEBUG({
11534     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11535       assert(InVals[i].getNode() &&
11536              "LowerFormalArguments emitted a null value!");
11537       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11538              "LowerFormalArguments emitted a value with the wrong type!");
11539     }
11540   });
11541 
11542   // Update the DAG with the new chain value resulting from argument lowering.
11543   DAG.setRoot(NewRoot);
11544 
11545   // Set up the argument values.
11546   unsigned i = 0;
11547   if (!FuncInfo->CanLowerReturn) {
11548     // Create a virtual register for the sret pointer, and put in a copy
11549     // from the sret argument into it.
11550     SmallVector<EVT, 1> ValueVTs;
11551     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11552                     PointerType::get(F.getContext(),
11553                                      DAG.getDataLayout().getAllocaAddrSpace()),
11554                     ValueVTs);
11555     MVT VT = ValueVTs[0].getSimpleVT();
11556     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11557     std::optional<ISD::NodeType> AssertOp;
11558     SDValue ArgValue =
11559         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11560                          F.getCallingConv(), AssertOp);
11561 
11562     MachineFunction& MF = SDB->DAG.getMachineFunction();
11563     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11564     Register SRetReg =
11565         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11566     FuncInfo->DemoteRegister = SRetReg;
11567     NewRoot =
11568         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11569     DAG.setRoot(NewRoot);
11570 
11571     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11572     ++i;
11573   }
11574 
11575   SmallVector<SDValue, 4> Chains;
11576   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11577   for (const Argument &Arg : F.args()) {
11578     SmallVector<SDValue, 4> ArgValues;
11579     SmallVector<EVT, 4> ValueVTs;
11580     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11581     unsigned NumValues = ValueVTs.size();
11582     if (NumValues == 0)
11583       continue;
11584 
11585     bool ArgHasUses = !Arg.use_empty();
11586 
11587     // Elide the copying store if the target loaded this argument from a
11588     // suitable fixed stack object.
11589     if (Ins[i].Flags.isCopyElisionCandidate()) {
11590       unsigned NumParts = 0;
11591       for (EVT VT : ValueVTs)
11592         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11593                                                        F.getCallingConv(), VT);
11594 
11595       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11596                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11597                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11598     }
11599 
11600     // If this argument is unused then remember its value. It is used to generate
11601     // debugging information.
11602     bool isSwiftErrorArg =
11603         TLI->supportSwiftError() &&
11604         Arg.hasAttribute(Attribute::SwiftError);
11605     if (!ArgHasUses && !isSwiftErrorArg) {
11606       SDB->setUnusedArgValue(&Arg, InVals[i]);
11607 
11608       // Also remember any frame index for use in FastISel.
11609       if (FrameIndexSDNode *FI =
11610           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11611         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11612     }
11613 
11614     for (unsigned Val = 0; Val != NumValues; ++Val) {
11615       EVT VT = ValueVTs[Val];
11616       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11617                                                       F.getCallingConv(), VT);
11618       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11619           *CurDAG->getContext(), F.getCallingConv(), VT);
11620 
11621       // Even an apparent 'unused' swifterror argument needs to be returned. So
11622       // we do generate a copy for it that can be used on return from the
11623       // function.
11624       if (ArgHasUses || isSwiftErrorArg) {
11625         std::optional<ISD::NodeType> AssertOp;
11626         if (Arg.hasAttribute(Attribute::SExt))
11627           AssertOp = ISD::AssertSext;
11628         else if (Arg.hasAttribute(Attribute::ZExt))
11629           AssertOp = ISD::AssertZext;
11630 
11631         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11632                                              PartVT, VT, nullptr, NewRoot,
11633                                              F.getCallingConv(), AssertOp));
11634       }
11635 
11636       i += NumParts;
11637     }
11638 
11639     // We don't need to do anything else for unused arguments.
11640     if (ArgValues.empty())
11641       continue;
11642 
11643     // Note down frame index.
11644     if (FrameIndexSDNode *FI =
11645         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11646       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11647 
11648     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11649                                      SDB->getCurSDLoc());
11650 
11651     SDB->setValue(&Arg, Res);
11652     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11653       // We want to associate the argument with the frame index, among
11654       // involved operands, that correspond to the lowest address. The
11655       // getCopyFromParts function, called earlier, is swapping the order of
11656       // the operands to BUILD_PAIR depending on endianness. The result of
11657       // that swapping is that the least significant bits of the argument will
11658       // be in the first operand of the BUILD_PAIR node, and the most
11659       // significant bits will be in the second operand.
11660       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11661       if (LoadSDNode *LNode =
11662           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11663         if (FrameIndexSDNode *FI =
11664             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11665           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11666     }
11667 
11668     // Analyses past this point are naive and don't expect an assertion.
11669     if (Res.getOpcode() == ISD::AssertZext)
11670       Res = Res.getOperand(0);
11671 
11672     // Update the SwiftErrorVRegDefMap.
11673     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11674       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11675       if (Register::isVirtualRegister(Reg))
11676         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11677                                    Reg);
11678     }
11679 
11680     // If this argument is live outside of the entry block, insert a copy from
11681     // wherever we got it to the vreg that other BB's will reference it as.
11682     if (Res.getOpcode() == ISD::CopyFromReg) {
11683       // If we can, though, try to skip creating an unnecessary vreg.
11684       // FIXME: This isn't very clean... it would be nice to make this more
11685       // general.
11686       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11687       if (Register::isVirtualRegister(Reg)) {
11688         FuncInfo->ValueMap[&Arg] = Reg;
11689         continue;
11690       }
11691     }
11692     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11693       FuncInfo->InitializeRegForValue(&Arg);
11694       SDB->CopyToExportRegsIfNeeded(&Arg);
11695     }
11696   }
11697 
11698   if (!Chains.empty()) {
11699     Chains.push_back(NewRoot);
11700     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11701   }
11702 
11703   DAG.setRoot(NewRoot);
11704 
11705   assert(i == InVals.size() && "Argument register count mismatch!");
11706 
11707   // If any argument copy elisions occurred and we have debug info, update the
11708   // stale frame indices used in the dbg.declare variable info table.
11709   if (!ArgCopyElisionFrameIndexMap.empty()) {
11710     for (MachineFunction::VariableDbgInfo &VI :
11711          MF->getInStackSlotVariableDbgInfo()) {
11712       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11713       if (I != ArgCopyElisionFrameIndexMap.end())
11714         VI.updateStackSlot(I->second);
11715     }
11716   }
11717 
11718   // Finally, if the target has anything special to do, allow it to do so.
11719   emitFunctionEntryCode();
11720 }
11721 
11722 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11723 /// ensure constants are generated when needed.  Remember the virtual registers
11724 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11725 /// directly add them, because expansion might result in multiple MBB's for one
11726 /// BB.  As such, the start of the BB might correspond to a different MBB than
11727 /// the end.
11728 void
11729 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11731 
11732   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11733 
11734   // Check PHI nodes in successors that expect a value to be available from this
11735   // block.
11736   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11737     if (!isa<PHINode>(SuccBB->begin())) continue;
11738     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11739 
11740     // If this terminator has multiple identical successors (common for
11741     // switches), only handle each succ once.
11742     if (!SuccsHandled.insert(SuccMBB).second)
11743       continue;
11744 
11745     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11746 
11747     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11748     // nodes and Machine PHI nodes, but the incoming operands have not been
11749     // emitted yet.
11750     for (const PHINode &PN : SuccBB->phis()) {
11751       // Ignore dead phi's.
11752       if (PN.use_empty())
11753         continue;
11754 
11755       // Skip empty types
11756       if (PN.getType()->isEmptyTy())
11757         continue;
11758 
11759       unsigned Reg;
11760       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11761 
11762       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11763         unsigned &RegOut = ConstantsOut[C];
11764         if (RegOut == 0) {
11765           RegOut = FuncInfo.CreateRegs(C);
11766           // We need to zero/sign extend ConstantInt phi operands to match
11767           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11768           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11769           if (auto *CI = dyn_cast<ConstantInt>(C))
11770             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11771                                                     : ISD::ZERO_EXTEND;
11772           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11773         }
11774         Reg = RegOut;
11775       } else {
11776         DenseMap<const Value *, Register>::iterator I =
11777           FuncInfo.ValueMap.find(PHIOp);
11778         if (I != FuncInfo.ValueMap.end())
11779           Reg = I->second;
11780         else {
11781           assert(isa<AllocaInst>(PHIOp) &&
11782                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11783                  "Didn't codegen value into a register!??");
11784           Reg = FuncInfo.CreateRegs(PHIOp);
11785           CopyValueToVirtualRegister(PHIOp, Reg);
11786         }
11787       }
11788 
11789       // Remember that this register needs to added to the machine PHI node as
11790       // the input for this MBB.
11791       SmallVector<EVT, 4> ValueVTs;
11792       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11793       for (EVT VT : ValueVTs) {
11794         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11795         for (unsigned i = 0; i != NumRegisters; ++i)
11796           FuncInfo.PHINodesToUpdate.push_back(
11797               std::make_pair(&*MBBI++, Reg + i));
11798         Reg += NumRegisters;
11799       }
11800     }
11801   }
11802 
11803   ConstantsOut.clear();
11804 }
11805 
11806 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11807   MachineFunction::iterator I(MBB);
11808   if (++I == FuncInfo.MF->end())
11809     return nullptr;
11810   return &*I;
11811 }
11812 
11813 /// During lowering new call nodes can be created (such as memset, etc.).
11814 /// Those will become new roots of the current DAG, but complications arise
11815 /// when they are tail calls. In such cases, the call lowering will update
11816 /// the root, but the builder still needs to know that a tail call has been
11817 /// lowered in order to avoid generating an additional return.
11818 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11819   // If the node is null, we do have a tail call.
11820   if (MaybeTC.getNode() != nullptr)
11821     DAG.setRoot(MaybeTC);
11822   else
11823     HasTailCall = true;
11824 }
11825 
11826 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11827                                         MachineBasicBlock *SwitchMBB,
11828                                         MachineBasicBlock *DefaultMBB) {
11829   MachineFunction *CurMF = FuncInfo.MF;
11830   MachineBasicBlock *NextMBB = nullptr;
11831   MachineFunction::iterator BBI(W.MBB);
11832   if (++BBI != FuncInfo.MF->end())
11833     NextMBB = &*BBI;
11834 
11835   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11836 
11837   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11838 
11839   if (Size == 2 && W.MBB == SwitchMBB) {
11840     // If any two of the cases has the same destination, and if one value
11841     // is the same as the other, but has one bit unset that the other has set,
11842     // use bit manipulation to do two compares at once.  For example:
11843     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11844     // TODO: This could be extended to merge any 2 cases in switches with 3
11845     // cases.
11846     // TODO: Handle cases where W.CaseBB != SwitchBB.
11847     CaseCluster &Small = *W.FirstCluster;
11848     CaseCluster &Big = *W.LastCluster;
11849 
11850     if (Small.Low == Small.High && Big.Low == Big.High &&
11851         Small.MBB == Big.MBB) {
11852       const APInt &SmallValue = Small.Low->getValue();
11853       const APInt &BigValue = Big.Low->getValue();
11854 
11855       // Check that there is only one bit different.
11856       APInt CommonBit = BigValue ^ SmallValue;
11857       if (CommonBit.isPowerOf2()) {
11858         SDValue CondLHS = getValue(Cond);
11859         EVT VT = CondLHS.getValueType();
11860         SDLoc DL = getCurSDLoc();
11861 
11862         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11863                                  DAG.getConstant(CommonBit, DL, VT));
11864         SDValue Cond = DAG.getSetCC(
11865             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11866             ISD::SETEQ);
11867 
11868         // Update successor info.
11869         // Both Small and Big will jump to Small.BB, so we sum up the
11870         // probabilities.
11871         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11872         if (BPI)
11873           addSuccessorWithProb(
11874               SwitchMBB, DefaultMBB,
11875               // The default destination is the first successor in IR.
11876               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11877         else
11878           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11879 
11880         // Insert the true branch.
11881         SDValue BrCond =
11882             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11883                         DAG.getBasicBlock(Small.MBB));
11884         // Insert the false branch.
11885         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11886                              DAG.getBasicBlock(DefaultMBB));
11887 
11888         DAG.setRoot(BrCond);
11889         return;
11890       }
11891     }
11892   }
11893 
11894   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11895     // Here, we order cases by probability so the most likely case will be
11896     // checked first. However, two clusters can have the same probability in
11897     // which case their relative ordering is non-deterministic. So we use Low
11898     // as a tie-breaker as clusters are guaranteed to never overlap.
11899     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11900                [](const CaseCluster &a, const CaseCluster &b) {
11901       return a.Prob != b.Prob ?
11902              a.Prob > b.Prob :
11903              a.Low->getValue().slt(b.Low->getValue());
11904     });
11905 
11906     // Rearrange the case blocks so that the last one falls through if possible
11907     // without changing the order of probabilities.
11908     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11909       --I;
11910       if (I->Prob > W.LastCluster->Prob)
11911         break;
11912       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11913         std::swap(*I, *W.LastCluster);
11914         break;
11915       }
11916     }
11917   }
11918 
11919   // Compute total probability.
11920   BranchProbability DefaultProb = W.DefaultProb;
11921   BranchProbability UnhandledProbs = DefaultProb;
11922   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11923     UnhandledProbs += I->Prob;
11924 
11925   MachineBasicBlock *CurMBB = W.MBB;
11926   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11927     bool FallthroughUnreachable = false;
11928     MachineBasicBlock *Fallthrough;
11929     if (I == W.LastCluster) {
11930       // For the last cluster, fall through to the default destination.
11931       Fallthrough = DefaultMBB;
11932       FallthroughUnreachable = isa<UnreachableInst>(
11933           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11934     } else {
11935       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11936       CurMF->insert(BBI, Fallthrough);
11937       // Put Cond in a virtual register to make it available from the new blocks.
11938       ExportFromCurrentBlock(Cond);
11939     }
11940     UnhandledProbs -= I->Prob;
11941 
11942     switch (I->Kind) {
11943       case CC_JumpTable: {
11944         // FIXME: Optimize away range check based on pivot comparisons.
11945         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11946         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11947 
11948         // The jump block hasn't been inserted yet; insert it here.
11949         MachineBasicBlock *JumpMBB = JT->MBB;
11950         CurMF->insert(BBI, JumpMBB);
11951 
11952         auto JumpProb = I->Prob;
11953         auto FallthroughProb = UnhandledProbs;
11954 
11955         // If the default statement is a target of the jump table, we evenly
11956         // distribute the default probability to successors of CurMBB. Also
11957         // update the probability on the edge from JumpMBB to Fallthrough.
11958         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11959                                               SE = JumpMBB->succ_end();
11960              SI != SE; ++SI) {
11961           if (*SI == DefaultMBB) {
11962             JumpProb += DefaultProb / 2;
11963             FallthroughProb -= DefaultProb / 2;
11964             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11965             JumpMBB->normalizeSuccProbs();
11966             break;
11967           }
11968         }
11969 
11970         // If the default clause is unreachable, propagate that knowledge into
11971         // JTH->FallthroughUnreachable which will use it to suppress the range
11972         // check.
11973         //
11974         // However, don't do this if we're doing branch target enforcement,
11975         // because a table branch _without_ a range check can be a tempting JOP
11976         // gadget - out-of-bounds inputs that are impossible in correct
11977         // execution become possible again if an attacker can influence the
11978         // control flow. So if an attacker doesn't already have a BTI bypass
11979         // available, we don't want them to be able to get one out of this
11980         // table branch.
11981         if (FallthroughUnreachable) {
11982           Function &CurFunc = CurMF->getFunction();
11983           bool HasBranchTargetEnforcement = false;
11984           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11985             HasBranchTargetEnforcement =
11986                 CurFunc.getFnAttribute("branch-target-enforcement")
11987                     .getValueAsBool();
11988           } else {
11989             HasBranchTargetEnforcement =
11990                 CurMF->getMMI().getModule()->getModuleFlag(
11991                     "branch-target-enforcement");
11992           }
11993           if (!HasBranchTargetEnforcement)
11994             JTH->FallthroughUnreachable = true;
11995         }
11996 
11997         if (!JTH->FallthroughUnreachable)
11998           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11999         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12000         CurMBB->normalizeSuccProbs();
12001 
12002         // The jump table header will be inserted in our current block, do the
12003         // range check, and fall through to our fallthrough block.
12004         JTH->HeaderBB = CurMBB;
12005         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12006 
12007         // If we're in the right place, emit the jump table header right now.
12008         if (CurMBB == SwitchMBB) {
12009           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12010           JTH->Emitted = true;
12011         }
12012         break;
12013       }
12014       case CC_BitTests: {
12015         // FIXME: Optimize away range check based on pivot comparisons.
12016         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12017 
12018         // The bit test blocks haven't been inserted yet; insert them here.
12019         for (BitTestCase &BTC : BTB->Cases)
12020           CurMF->insert(BBI, BTC.ThisBB);
12021 
12022         // Fill in fields of the BitTestBlock.
12023         BTB->Parent = CurMBB;
12024         BTB->Default = Fallthrough;
12025 
12026         BTB->DefaultProb = UnhandledProbs;
12027         // If the cases in bit test don't form a contiguous range, we evenly
12028         // distribute the probability on the edge to Fallthrough to two
12029         // successors of CurMBB.
12030         if (!BTB->ContiguousRange) {
12031           BTB->Prob += DefaultProb / 2;
12032           BTB->DefaultProb -= DefaultProb / 2;
12033         }
12034 
12035         if (FallthroughUnreachable)
12036           BTB->FallthroughUnreachable = true;
12037 
12038         // If we're in the right place, emit the bit test header right now.
12039         if (CurMBB == SwitchMBB) {
12040           visitBitTestHeader(*BTB, SwitchMBB);
12041           BTB->Emitted = true;
12042         }
12043         break;
12044       }
12045       case CC_Range: {
12046         const Value *RHS, *LHS, *MHS;
12047         ISD::CondCode CC;
12048         if (I->Low == I->High) {
12049           // Check Cond == I->Low.
12050           CC = ISD::SETEQ;
12051           LHS = Cond;
12052           RHS=I->Low;
12053           MHS = nullptr;
12054         } else {
12055           // Check I->Low <= Cond <= I->High.
12056           CC = ISD::SETLE;
12057           LHS = I->Low;
12058           MHS = Cond;
12059           RHS = I->High;
12060         }
12061 
12062         // If Fallthrough is unreachable, fold away the comparison.
12063         if (FallthroughUnreachable)
12064           CC = ISD::SETTRUE;
12065 
12066         // The false probability is the sum of all unhandled cases.
12067         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12068                      getCurSDLoc(), I->Prob, UnhandledProbs);
12069 
12070         if (CurMBB == SwitchMBB)
12071           visitSwitchCase(CB, SwitchMBB);
12072         else
12073           SL->SwitchCases.push_back(CB);
12074 
12075         break;
12076       }
12077     }
12078     CurMBB = Fallthrough;
12079   }
12080 }
12081 
12082 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12083                                         const SwitchWorkListItem &W,
12084                                         Value *Cond,
12085                                         MachineBasicBlock *SwitchMBB) {
12086   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12087          "Clusters not sorted?");
12088   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12089 
12090   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12091       SL->computeSplitWorkItemInfo(W);
12092 
12093   // Use the first element on the right as pivot since we will make less-than
12094   // comparisons against it.
12095   CaseClusterIt PivotCluster = FirstRight;
12096   assert(PivotCluster > W.FirstCluster);
12097   assert(PivotCluster <= W.LastCluster);
12098 
12099   CaseClusterIt FirstLeft = W.FirstCluster;
12100   CaseClusterIt LastRight = W.LastCluster;
12101 
12102   const ConstantInt *Pivot = PivotCluster->Low;
12103 
12104   // New blocks will be inserted immediately after the current one.
12105   MachineFunction::iterator BBI(W.MBB);
12106   ++BBI;
12107 
12108   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12109   // we can branch to its destination directly if it's squeezed exactly in
12110   // between the known lower bound and Pivot - 1.
12111   MachineBasicBlock *LeftMBB;
12112   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12113       FirstLeft->Low == W.GE &&
12114       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12115     LeftMBB = FirstLeft->MBB;
12116   } else {
12117     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12118     FuncInfo.MF->insert(BBI, LeftMBB);
12119     WorkList.push_back(
12120         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12121     // Put Cond in a virtual register to make it available from the new blocks.
12122     ExportFromCurrentBlock(Cond);
12123   }
12124 
12125   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12126   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12127   // directly if RHS.High equals the current upper bound.
12128   MachineBasicBlock *RightMBB;
12129   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12130       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12131     RightMBB = FirstRight->MBB;
12132   } else {
12133     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12134     FuncInfo.MF->insert(BBI, RightMBB);
12135     WorkList.push_back(
12136         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12137     // Put Cond in a virtual register to make it available from the new blocks.
12138     ExportFromCurrentBlock(Cond);
12139   }
12140 
12141   // Create the CaseBlock record that will be used to lower the branch.
12142   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12143                getCurSDLoc(), LeftProb, RightProb);
12144 
12145   if (W.MBB == SwitchMBB)
12146     visitSwitchCase(CB, SwitchMBB);
12147   else
12148     SL->SwitchCases.push_back(CB);
12149 }
12150 
12151 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12152 // from the swith statement.
12153 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12154                                             BranchProbability PeeledCaseProb) {
12155   if (PeeledCaseProb == BranchProbability::getOne())
12156     return BranchProbability::getZero();
12157   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12158 
12159   uint32_t Numerator = CaseProb.getNumerator();
12160   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12161   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12162 }
12163 
12164 // Try to peel the top probability case if it exceeds the threshold.
12165 // Return current MachineBasicBlock for the switch statement if the peeling
12166 // does not occur.
12167 // If the peeling is performed, return the newly created MachineBasicBlock
12168 // for the peeled switch statement. Also update Clusters to remove the peeled
12169 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12170 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12171     const SwitchInst &SI, CaseClusterVector &Clusters,
12172     BranchProbability &PeeledCaseProb) {
12173   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12174   // Don't perform if there is only one cluster or optimizing for size.
12175   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12176       TM.getOptLevel() == CodeGenOptLevel::None ||
12177       SwitchMBB->getParent()->getFunction().hasMinSize())
12178     return SwitchMBB;
12179 
12180   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12181   unsigned PeeledCaseIndex = 0;
12182   bool SwitchPeeled = false;
12183   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12184     CaseCluster &CC = Clusters[Index];
12185     if (CC.Prob < TopCaseProb)
12186       continue;
12187     TopCaseProb = CC.Prob;
12188     PeeledCaseIndex = Index;
12189     SwitchPeeled = true;
12190   }
12191   if (!SwitchPeeled)
12192     return SwitchMBB;
12193 
12194   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12195                     << TopCaseProb << "\n");
12196 
12197   // Record the MBB for the peeled switch statement.
12198   MachineFunction::iterator BBI(SwitchMBB);
12199   ++BBI;
12200   MachineBasicBlock *PeeledSwitchMBB =
12201       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12202   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12203 
12204   ExportFromCurrentBlock(SI.getCondition());
12205   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12206   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12207                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12208   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12209 
12210   Clusters.erase(PeeledCaseIt);
12211   for (CaseCluster &CC : Clusters) {
12212     LLVM_DEBUG(
12213         dbgs() << "Scale the probablity for one cluster, before scaling: "
12214                << CC.Prob << "\n");
12215     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12216     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12217   }
12218   PeeledCaseProb = TopCaseProb;
12219   return PeeledSwitchMBB;
12220 }
12221 
12222 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12223   // Extract cases from the switch.
12224   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12225   CaseClusterVector Clusters;
12226   Clusters.reserve(SI.getNumCases());
12227   for (auto I : SI.cases()) {
12228     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12229     const ConstantInt *CaseVal = I.getCaseValue();
12230     BranchProbability Prob =
12231         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12232             : BranchProbability(1, SI.getNumCases() + 1);
12233     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12234   }
12235 
12236   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12237 
12238   // Cluster adjacent cases with the same destination. We do this at all
12239   // optimization levels because it's cheap to do and will make codegen faster
12240   // if there are many clusters.
12241   sortAndRangeify(Clusters);
12242 
12243   // The branch probablity of the peeled case.
12244   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12245   MachineBasicBlock *PeeledSwitchMBB =
12246       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12247 
12248   // If there is only the default destination, jump there directly.
12249   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12250   if (Clusters.empty()) {
12251     assert(PeeledSwitchMBB == SwitchMBB);
12252     SwitchMBB->addSuccessor(DefaultMBB);
12253     if (DefaultMBB != NextBlock(SwitchMBB)) {
12254       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12255                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12256     }
12257     return;
12258   }
12259 
12260   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12261                      DAG.getBFI());
12262   SL->findBitTestClusters(Clusters, &SI);
12263 
12264   LLVM_DEBUG({
12265     dbgs() << "Case clusters: ";
12266     for (const CaseCluster &C : Clusters) {
12267       if (C.Kind == CC_JumpTable)
12268         dbgs() << "JT:";
12269       if (C.Kind == CC_BitTests)
12270         dbgs() << "BT:";
12271 
12272       C.Low->getValue().print(dbgs(), true);
12273       if (C.Low != C.High) {
12274         dbgs() << '-';
12275         C.High->getValue().print(dbgs(), true);
12276       }
12277       dbgs() << ' ';
12278     }
12279     dbgs() << '\n';
12280   });
12281 
12282   assert(!Clusters.empty());
12283   SwitchWorkList WorkList;
12284   CaseClusterIt First = Clusters.begin();
12285   CaseClusterIt Last = Clusters.end() - 1;
12286   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12287   // Scale the branchprobability for DefaultMBB if the peel occurs and
12288   // DefaultMBB is not replaced.
12289   if (PeeledCaseProb != BranchProbability::getZero() &&
12290       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12291     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12292   WorkList.push_back(
12293       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12294 
12295   while (!WorkList.empty()) {
12296     SwitchWorkListItem W = WorkList.pop_back_val();
12297     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12298 
12299     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12300         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12301       // For optimized builds, lower large range as a balanced binary tree.
12302       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12303       continue;
12304     }
12305 
12306     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12307   }
12308 }
12309 
12310 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12312   auto DL = getCurSDLoc();
12313   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12314   setValue(&I, DAG.getStepVector(DL, ResultVT));
12315 }
12316 
12317 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12319   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12320 
12321   SDLoc DL = getCurSDLoc();
12322   SDValue V = getValue(I.getOperand(0));
12323   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12324 
12325   if (VT.isScalableVector()) {
12326     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12327     return;
12328   }
12329 
12330   // Use VECTOR_SHUFFLE for the fixed-length vector
12331   // to maintain existing behavior.
12332   SmallVector<int, 8> Mask;
12333   unsigned NumElts = VT.getVectorMinNumElements();
12334   for (unsigned i = 0; i != NumElts; ++i)
12335     Mask.push_back(NumElts - 1 - i);
12336 
12337   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12338 }
12339 
12340 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12341   auto DL = getCurSDLoc();
12342   SDValue InVec = getValue(I.getOperand(0));
12343   EVT OutVT =
12344       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12345 
12346   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12347 
12348   // ISD Node needs the input vectors split into two equal parts
12349   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12350                            DAG.getVectorIdxConstant(0, DL));
12351   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12352                            DAG.getVectorIdxConstant(OutNumElts, DL));
12353 
12354   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12355   // legalisation and combines.
12356   if (OutVT.isFixedLengthVector()) {
12357     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12358                                         createStrideMask(0, 2, OutNumElts));
12359     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12360                                        createStrideMask(1, 2, OutNumElts));
12361     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12362     setValue(&I, Res);
12363     return;
12364   }
12365 
12366   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12367                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12368   setValue(&I, Res);
12369 }
12370 
12371 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12372   auto DL = getCurSDLoc();
12373   EVT InVT = getValue(I.getOperand(0)).getValueType();
12374   SDValue InVec0 = getValue(I.getOperand(0));
12375   SDValue InVec1 = getValue(I.getOperand(1));
12376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12377   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12378 
12379   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12380   // legalisation and combines.
12381   if (OutVT.isFixedLengthVector()) {
12382     unsigned NumElts = InVT.getVectorMinNumElements();
12383     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12384     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12385                                       createInterleaveMask(NumElts, 2)));
12386     return;
12387   }
12388 
12389   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12390                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12391   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12392                     Res.getValue(1));
12393   setValue(&I, Res);
12394 }
12395 
12396 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12397   SmallVector<EVT, 4> ValueVTs;
12398   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12399                   ValueVTs);
12400   unsigned NumValues = ValueVTs.size();
12401   if (NumValues == 0) return;
12402 
12403   SmallVector<SDValue, 4> Values(NumValues);
12404   SDValue Op = getValue(I.getOperand(0));
12405 
12406   for (unsigned i = 0; i != NumValues; ++i)
12407     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12408                             SDValue(Op.getNode(), Op.getResNo() + i));
12409 
12410   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12411                            DAG.getVTList(ValueVTs), Values));
12412 }
12413 
12414 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12416   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12417 
12418   SDLoc DL = getCurSDLoc();
12419   SDValue V1 = getValue(I.getOperand(0));
12420   SDValue V2 = getValue(I.getOperand(1));
12421   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12422 
12423   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12424   if (VT.isScalableVector()) {
12425     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12426                              DAG.getVectorIdxConstant(Imm, DL)));
12427     return;
12428   }
12429 
12430   unsigned NumElts = VT.getVectorNumElements();
12431 
12432   uint64_t Idx = (NumElts + Imm) % NumElts;
12433 
12434   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12435   SmallVector<int, 8> Mask;
12436   for (unsigned i = 0; i < NumElts; ++i)
12437     Mask.push_back(Idx + i);
12438   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12439 }
12440 
12441 // Consider the following MIR after SelectionDAG, which produces output in
12442 // phyregs in the first case or virtregs in the second case.
12443 //
12444 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12445 // %5:gr32 = COPY $ebx
12446 // %6:gr32 = COPY $edx
12447 // %1:gr32 = COPY %6:gr32
12448 // %0:gr32 = COPY %5:gr32
12449 //
12450 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12451 // %1:gr32 = COPY %6:gr32
12452 // %0:gr32 = COPY %5:gr32
12453 //
12454 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12455 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12456 //
12457 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12458 // to a single virtreg (such as %0). The remaining outputs monotonically
12459 // increase in virtreg number from there. If a callbr has no outputs, then it
12460 // should not have a corresponding callbr landingpad; in fact, the callbr
12461 // landingpad would not even be able to refer to such a callbr.
12462 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12463   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12464   // There is definitely at least one copy.
12465   assert(MI->getOpcode() == TargetOpcode::COPY &&
12466          "start of copy chain MUST be COPY");
12467   Reg = MI->getOperand(1).getReg();
12468   MI = MRI.def_begin(Reg)->getParent();
12469   // There may be an optional second copy.
12470   if (MI->getOpcode() == TargetOpcode::COPY) {
12471     assert(Reg.isVirtual() && "expected COPY of virtual register");
12472     Reg = MI->getOperand(1).getReg();
12473     assert(Reg.isPhysical() && "expected COPY of physical register");
12474     MI = MRI.def_begin(Reg)->getParent();
12475   }
12476   // The start of the chain must be an INLINEASM_BR.
12477   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12478          "end of copy chain MUST be INLINEASM_BR");
12479   return Reg;
12480 }
12481 
12482 // We must do this walk rather than the simpler
12483 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12484 // otherwise we will end up with copies of virtregs only valid along direct
12485 // edges.
12486 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12487   SmallVector<EVT, 8> ResultVTs;
12488   SmallVector<SDValue, 8> ResultValues;
12489   const auto *CBR =
12490       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12491 
12492   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12493   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12494   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12495 
12496   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12497   SDValue Chain = DAG.getRoot();
12498 
12499   // Re-parse the asm constraints string.
12500   TargetLowering::AsmOperandInfoVector TargetConstraints =
12501       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12502   for (auto &T : TargetConstraints) {
12503     SDISelAsmOperandInfo OpInfo(T);
12504     if (OpInfo.Type != InlineAsm::isOutput)
12505       continue;
12506 
12507     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12508     // individual constraint.
12509     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12510 
12511     switch (OpInfo.ConstraintType) {
12512     case TargetLowering::C_Register:
12513     case TargetLowering::C_RegisterClass: {
12514       // Fill in OpInfo.AssignedRegs.Regs.
12515       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12516 
12517       // getRegistersForValue may produce 1 to many registers based on whether
12518       // the OpInfo.ConstraintVT is legal on the target or not.
12519       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12520         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12521         if (Register::isPhysicalRegister(OriginalDef))
12522           FuncInfo.MBB->addLiveIn(OriginalDef);
12523         // Update the assigned registers to use the original defs.
12524         Reg = OriginalDef;
12525       }
12526 
12527       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12528           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12529       ResultValues.push_back(V);
12530       ResultVTs.push_back(OpInfo.ConstraintVT);
12531       break;
12532     }
12533     case TargetLowering::C_Other: {
12534       SDValue Flag;
12535       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12536                                                   OpInfo, DAG);
12537       ++InitialDef;
12538       ResultValues.push_back(V);
12539       ResultVTs.push_back(OpInfo.ConstraintVT);
12540       break;
12541     }
12542     default:
12543       break;
12544     }
12545   }
12546   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12547                           DAG.getVTList(ResultVTs), ResultValues);
12548   setValue(&I, V);
12549 }
12550