xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 3d08ade7bd32f0296e0ca3a13640cc95fa89229a)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcallUtil.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <deque>
108 #include <iterator>
109 #include <limits>
110 #include <optional>
111 #include <tuple>
112 
113 using namespace llvm;
114 using namespace PatternMatch;
115 using namespace SwitchCG;
116 
117 #define DEBUG_TYPE "isel"
118 
119 /// LimitFloatPrecision - Generate low-precision inline sequences for
120 /// some float libcalls (6, 8 or 12 bits).
121 static unsigned LimitFloatPrecision;
122 
123 static cl::opt<bool>
124     InsertAssertAlign("insert-assert-align", cl::init(true),
125                       cl::desc("Insert the experimental `assertalign` node."),
126                       cl::ReallyHidden);
127 
128 static cl::opt<unsigned, true>
129     LimitFPPrecision("limit-float-precision",
130                      cl::desc("Generate low-precision inline sequences "
131                               "for some float libcalls"),
132                      cl::location(LimitFloatPrecision), cl::Hidden,
133                      cl::init(0));
134 
135 static cl::opt<unsigned> SwitchPeelThreshold(
136     "switch-peel-threshold", cl::Hidden, cl::init(66),
137     cl::desc("Set the case probability threshold for peeling the case from a "
138              "switch statement. A value greater than 100 will void this "
139              "optimization"));
140 
141 // Limit the width of DAG chains. This is important in general to prevent
142 // DAG-based analysis from blowing up. For example, alias analysis and
143 // load clustering may not complete in reasonable time. It is difficult to
144 // recognize and avoid this situation within each individual analysis, and
145 // future analyses are likely to have the same behavior. Limiting DAG width is
146 // the safe approach and will be especially important with global DAGs.
147 //
148 // MaxParallelChains default is arbitrarily high to avoid affecting
149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150 // sequence over this should have been converted to llvm.memcpy by the
151 // frontend. It is easy to induce this behavior with .ll code such as:
152 // %buffer = alloca [4096 x i8]
153 // %data = load [4096 x i8]* %argPtr
154 // store [4096 x i8] %data, [4096 x i8]* %buffer
155 static const unsigned MaxParallelChains = 64;
156 
157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
158                                       const SDValue *Parts, unsigned NumParts,
159                                       MVT PartVT, EVT ValueVT, const Value *V,
160                                       SDValue InChain,
161                                       std::optional<CallingConv::ID> CC);
162 
163 /// getCopyFromParts - Create a value that contains the specified legal parts
164 /// combined into the value they represent.  If the parts combine to a type
165 /// larger than ValueVT then AssertOp can be used to specify whether the extra
166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167 /// (ISD::AssertSext).
168 static SDValue
169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171                  SDValue InChain,
172                  std::optional<CallingConv::ID> CC = std::nullopt,
173                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174   // Let the target assemble the parts if it wants to
175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
176   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177                                                    PartVT, ValueVT, CC))
178     return Val;
179 
180   if (ValueVT.isVector())
181     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182                                   InChain, CC);
183 
184   assert(NumParts > 0 && "No parts to assemble!");
185   SDValue Val = Parts[0];
186 
187   if (NumParts > 1) {
188     // Assemble the value from multiple parts.
189     if (ValueVT.isInteger()) {
190       unsigned PartBits = PartVT.getSizeInBits();
191       unsigned ValueBits = ValueVT.getSizeInBits();
192 
193       // Assemble the power of 2 part.
194       unsigned RoundParts = llvm::bit_floor(NumParts);
195       unsigned RoundBits = PartBits * RoundParts;
196       EVT RoundVT = RoundBits == ValueBits ?
197         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198       SDValue Lo, Hi;
199 
200       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201 
202       if (RoundParts > 2) {
203         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204                               InChain);
205         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206                               PartVT, HalfVT, V, InChain);
207       } else {
208         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210       }
211 
212       if (DAG.getDataLayout().isBigEndian())
213         std::swap(Lo, Hi);
214 
215       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216 
217       if (RoundParts < NumParts) {
218         // Assemble the trailing non-power-of-2 part.
219         unsigned OddParts = NumParts - RoundParts;
220         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222                               OddVT, V, InChain, CC);
223 
224         // Combine the round and odd parts.
225         Lo = Val;
226         if (DAG.getDataLayout().isBigEndian())
227           std::swap(Lo, Hi);
228         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
231                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
232                                          TLI.getShiftAmountTy(
233                                              TotalVT, DAG.getDataLayout())));
234         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236       }
237     } else if (PartVT.isFloatingPoint()) {
238       // FP split into multiple FP parts (for ppcf128)
239       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240              "Unexpected split");
241       SDValue Lo, Hi;
242       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245         std::swap(Lo, Hi);
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247     } else {
248       // FP split into integer parts (soft fp)
249       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250              !PartVT.isVector() && "Unexpected split");
251       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253                              InChain, CC);
254     }
255   }
256 
257   // There is now one part, held in Val.  Correct it to match ValueVT.
258   // PartEVT is the type of the register class that holds the value.
259   // ValueVT is the type of the inline asm operation.
260   EVT PartEVT = Val.getValueType();
261 
262   if (PartEVT == ValueVT)
263     return Val;
264 
265   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266       ValueVT.bitsLT(PartEVT)) {
267     // For an FP value in an integer part, we need to truncate to the right
268     // width first.
269     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
270     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271   }
272 
273   // Handle types that have the same size.
274   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276 
277   // Handle types with different sizes.
278   if (PartEVT.isInteger() && ValueVT.isInteger()) {
279     if (ValueVT.bitsLT(PartEVT)) {
280       // For a truncate, see if we have any information to
281       // indicate whether the truncated bits will always be
282       // zero or sign-extension.
283       if (AssertOp)
284         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285                           DAG.getValueType(ValueVT));
286       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287     }
288     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289   }
290 
291   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292     // FP_ROUND's are always exact here.
293     if (ValueVT.bitsLT(Val.getValueType())) {
294 
295       SDValue NoChange =
296           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297 
298       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299               llvm::Attribute::StrictFP)) {
300         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302                            NoChange);
303       }
304 
305       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306     }
307 
308     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309   }
310 
311   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312   // then truncating.
313   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314       ValueVT.bitsLT(PartEVT)) {
315     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317   }
318 
319   report_fatal_error("Unknown mismatch in getCopyFromParts!");
320 }
321 
322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
323                                               const Twine &ErrMsg) {
324   const Instruction *I = dyn_cast_or_null<Instruction>(V);
325   if (!V)
326     return Ctx.emitError(ErrMsg);
327 
328   const char *AsmError = ", possible invalid constraint for vector type";
329   if (const CallInst *CI = dyn_cast<CallInst>(I))
330     if (CI->isInlineAsm())
331       return Ctx.emitError(I, ErrMsg + AsmError);
332 
333   return Ctx.emitError(I, ErrMsg);
334 }
335 
336 /// getCopyFromPartsVector - Create a value that contains the specified legal
337 /// parts combined into the value they represent.  If the parts combine to a
338 /// type larger than ValueVT then AssertOp can be used to specify whether the
339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
340 /// ValueVT (ISD::AssertSext).
341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
342                                       const SDValue *Parts, unsigned NumParts,
343                                       MVT PartVT, EVT ValueVT, const Value *V,
344                                       SDValue InChain,
345                                       std::optional<CallingConv::ID> CallConv) {
346   assert(ValueVT.isVector() && "Not a vector value");
347   assert(NumParts > 0 && "No parts to assemble!");
348   const bool IsABIRegCopy = CallConv.has_value();
349 
350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
351   SDValue Val = Parts[0];
352 
353   // Handle a multi-element vector.
354   if (NumParts > 1) {
355     EVT IntermediateVT;
356     MVT RegisterVT;
357     unsigned NumIntermediates;
358     unsigned NumRegs;
359 
360     if (IsABIRegCopy) {
361       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
362           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
363           NumIntermediates, RegisterVT);
364     } else {
365       NumRegs =
366           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
367                                      NumIntermediates, RegisterVT);
368     }
369 
370     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
371     NumParts = NumRegs; // Silence a compiler warning.
372     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
373     assert(RegisterVT.getSizeInBits() ==
374            Parts[0].getSimpleValueType().getSizeInBits() &&
375            "Part type sizes don't match!");
376 
377     // Assemble the parts into intermediate operands.
378     SmallVector<SDValue, 8> Ops(NumIntermediates);
379     if (NumIntermediates == NumParts) {
380       // If the register was not expanded, truncate or copy the value,
381       // as appropriate.
382       for (unsigned i = 0; i != NumParts; ++i)
383         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
384                                   V, InChain, CallConv);
385     } else if (NumParts > 0) {
386       // If the intermediate type was expanded, build the intermediate
387       // operands from the parts.
388       assert(NumParts % NumIntermediates == 0 &&
389              "Must expand into a divisible number of parts!");
390       unsigned Factor = NumParts / NumIntermediates;
391       for (unsigned i = 0; i != NumIntermediates; ++i)
392         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
393                                   IntermediateVT, V, InChain, CallConv);
394     }
395 
396     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
397     // intermediate operands.
398     EVT BuiltVectorTy =
399         IntermediateVT.isVector()
400             ? EVT::getVectorVT(
401                   *DAG.getContext(), IntermediateVT.getScalarType(),
402                   IntermediateVT.getVectorElementCount() * NumParts)
403             : EVT::getVectorVT(*DAG.getContext(),
404                                IntermediateVT.getScalarType(),
405                                NumIntermediates);
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // Vector/Vector bitcast.
419     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
420       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421 
422     // If the parts vector has more elements than the value vector, then we
423     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
424     // Extract the elements we want.
425     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
427               ValueVT.getVectorElementCount().getKnownMinValue()) &&
428              (PartEVT.getVectorElementCount().isScalable() ==
429               ValueVT.getVectorElementCount().isScalable()) &&
430              "Cannot narrow, it would be a lossy transformation");
431       PartEVT =
432           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
433                            ValueVT.getVectorElementCount());
434       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
435                         DAG.getVectorIdxConstant(0, DL));
436       if (PartEVT == ValueVT)
437         return Val;
438       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440 
441       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
442       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444     }
445 
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448   }
449 
450   // Trivial bitcast if the types are the same size and the destination
451   // vector type is legal.
452   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
453       TLI.isTypeLegal(ValueVT))
454     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 
456   if (ValueVT.getVectorNumElements() != 1) {
457      // Certain ABIs require that vectors are passed as integers. For vectors
458      // are the same size, this is an obvious bitcast.
459      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
460        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461      } else if (ValueVT.bitsLT(PartEVT)) {
462        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
463        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
464        // Drop the extra bits.
465        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
466        return DAG.getBitcast(ValueVT, Val);
467      }
468 
469      diagnosePossiblyInvalidConstraint(
470          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
471      return DAG.getUNDEF(ValueVT);
472   }
473 
474   // Handle cases such as i8 -> <1 x i1>
475   EVT ValueSVT = ValueVT.getVectorElementType();
476   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
477     unsigned ValueSize = ValueSVT.getSizeInBits();
478     if (ValueSize == PartEVT.getSizeInBits()) {
479       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
480     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
481       // It's possible a scalar floating point type gets softened to integer and
482       // then promoted to a larger integer. If PartEVT is the larger integer
483       // we need to truncate it and then bitcast to the FP type.
484       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
485       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
486       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
487       Val = DAG.getBitcast(ValueSVT, Val);
488     } else {
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492     }
493   }
494 
495   return DAG.getBuildVector(ValueVT, DL, Val);
496 }
497 
498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V,
501                                  std::optional<CallingConv::ID> CallConv);
502 
503 /// getCopyToParts - Create a series of nodes that contain the specified value
504 /// split into legal parts.  If the parts contain more bits than Val, then, for
505 /// integers, ExtendKind can be used to specify how to generate the extra bits.
506 static void
507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
508                unsigned NumParts, MVT PartVT, const Value *V,
509                std::optional<CallingConv::ID> CallConv = std::nullopt,
510                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
511   // Let the target split the parts if it wants to
512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
513   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
514                                       CallConv))
515     return;
516   EVT ValueVT = Val.getValueType();
517 
518   // Handle the vector case separately.
519   if (ValueVT.isVector())
520     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
521                                 CallConv);
522 
523   unsigned OrigNumParts = NumParts;
524   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
525          "Copying to an illegal type!");
526 
527   if (NumParts == 0)
528     return;
529 
530   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
531   EVT PartEVT = PartVT;
532   if (PartEVT == ValueVT) {
533     assert(NumParts == 1 && "No-op copy with multiple parts!");
534     Parts[0] = Val;
535     return;
536   }
537 
538   unsigned PartBits = PartVT.getSizeInBits();
539   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540     // If the parts cover more bits than the value has, promote the value.
541     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542       assert(NumParts == 1 && "Do not know what to promote to!");
543       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
544     } else {
545       if (ValueVT.isFloatingPoint()) {
546         // FP values need to be bitcast, then extended if they are being put
547         // into a larger container.
548         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
549         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
550       }
551       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552              ValueVT.isInteger() &&
553              "Unknown mismatch!");
554       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
556       if (PartVT == MVT::x86mmx)
557         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559   } else if (PartBits == ValueVT.getSizeInBits()) {
560     // Different types of the same size.
561     assert(NumParts == 1 && PartEVT != ValueVT);
562     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
564     // If the parts cover less bits than value has, truncate the value.
565     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566            ValueVT.isInteger() &&
567            "Unknown mismatch!");
568     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
570     if (PartVT == MVT::x86mmx)
571       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   }
573 
574   // The value may have changed - recompute ValueVT.
575   ValueVT = Val.getValueType();
576   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
577          "Failed to tile the value with PartVT!");
578 
579   if (NumParts == 1) {
580     if (PartEVT != ValueVT) {
581       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
582                                         "scalar-to-vector conversion failed");
583       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584     }
585 
586     Parts[0] = Val;
587     return;
588   }
589 
590   // Expand the value into multiple parts.
591   if (NumParts & (NumParts - 1)) {
592     // The number of parts is not a power of 2.  Split off and copy the tail.
593     assert(PartVT.isInteger() && ValueVT.isInteger() &&
594            "Do not know what to expand to!");
595     unsigned RoundParts = llvm::bit_floor(NumParts);
596     unsigned RoundBits = RoundParts * PartBits;
597     unsigned OddParts = NumParts - RoundParts;
598     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
599       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
600 
601     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
602                    CallConv);
603 
604     if (DAG.getDataLayout().isBigEndian())
605       // The odd parts were reversed by getCopyToParts - unreverse them.
606       std::reverse(Parts + RoundParts, Parts + NumParts);
607 
608     NumParts = RoundParts;
609     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
610     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
611   }
612 
613   // The number of parts is a power of 2.  Repeatedly bisect the value using
614   // EXTRACT_ELEMENT.
615   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616                          EVT::getIntegerVT(*DAG.getContext(),
617                                            ValueVT.getSizeInBits()),
618                          Val);
619 
620   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
621     for (unsigned i = 0; i < NumParts; i += StepSize) {
622       unsigned ThisBits = StepSize * PartBits / 2;
623       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
624       SDValue &Part0 = Parts[i];
625       SDValue &Part1 = Parts[i+StepSize/2];
626 
627       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
629       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
630                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
631 
632       if (ThisBits == PartBits && ThisVT != PartVT) {
633         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
634         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
635       }
636     }
637   }
638 
639   if (DAG.getDataLayout().isBigEndian())
640     std::reverse(Parts, Parts + OrigNumParts);
641 }
642 
643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
644                                      const SDLoc &DL, EVT PartVT) {
645   if (!PartVT.isVector())
646     return SDValue();
647 
648   EVT ValueVT = Val.getValueType();
649   EVT PartEVT = PartVT.getVectorElementType();
650   EVT ValueEVT = ValueVT.getVectorElementType();
651   ElementCount PartNumElts = PartVT.getVectorElementCount();
652   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
653 
654   // We only support widening vectors with equivalent element types and
655   // fixed/scalable properties. If a target needs to widen a fixed-length type
656   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
657   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
658       PartNumElts.isScalable() != ValueNumElts.isScalable())
659     return SDValue();
660 
661   // Have a try for bf16 because some targets share its ABI with fp16.
662   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
664            "Cannot widen to illegal type");
665     Val = DAG.getNode(ISD::BITCAST, DL,
666                       ValueVT.changeVectorElementType(MVT::f16), Val);
667   } else if (PartEVT != ValueEVT) {
668     return SDValue();
669   }
670 
671   // Widening a scalable vector to another scalable vector is done by inserting
672   // the vector into a larger undef one.
673   if (PartNumElts.isScalable())
674     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675                        Val, DAG.getVectorIdxConstant(0, DL));
676 
677   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
678   // undef elements.
679   SmallVector<SDValue, 16> Ops;
680   DAG.ExtractVectorElements(Val, Ops);
681   SDValue EltUndef = DAG.getUNDEF(PartEVT);
682   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683 
684   // FIXME: Use CONCAT for 2x -> 4x.
685   return DAG.getBuildVector(PartVT, DL, Ops);
686 }
687 
688 /// getCopyToPartsVector - Create a series of nodes that contain the specified
689 /// value split into legal parts.
690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691                                  SDValue Val, SDValue *Parts, unsigned NumParts,
692                                  MVT PartVT, const Value *V,
693                                  std::optional<CallingConv::ID> CallConv) {
694   EVT ValueVT = Val.getValueType();
695   assert(ValueVT.isVector() && "Not a vector");
696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697   const bool IsABIRegCopy = CallConv.has_value();
698 
699   if (NumParts == 1) {
700     EVT PartEVT = PartVT;
701     if (PartEVT == ValueVT) {
702       // Nothing to do.
703     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704       // Bitconvert vector->vector case.
705       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707       Val = Widened;
708     } else if (PartVT.isVector() &&
709                PartEVT.getVectorElementType().bitsGE(
710                    ValueVT.getVectorElementType()) &&
711                PartEVT.getVectorElementCount() ==
712                    ValueVT.getVectorElementCount()) {
713 
714       // Promoted vector extract
715       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716     } else if (PartEVT.isVector() &&
717                PartEVT.getVectorElementType() !=
718                    ValueVT.getVectorElementType() &&
719                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720                    TargetLowering::TypeWidenVector) {
721       // Combination of widening and promotion.
722       EVT WidenVT =
723           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
724                            PartVT.getVectorElementCount());
725       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727     } else {
728       // Don't extract an integer from a float vector. This can happen if the
729       // FP type gets softened to integer and then promoted. The promotion
730       // prevents it from being picked up by the earlier bitcast case.
731       if (ValueVT.getVectorElementCount().isScalar() &&
732           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733         // If we reach this condition and PartVT is FP, this means that
734         // ValueVT is also FP and both have a different size, otherwise we
735         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736         // would be invalid since that would mean the smaller FP type has to
737         // be extended to the larger one.
738         if (PartVT.isFloatingPoint()) {
739           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741         } else
742           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743                             DAG.getVectorIdxConstant(0, DL));
744       } else {
745         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746         assert(PartVT.getFixedSizeInBits() > ValueSize &&
747                "lossy conversion of vector to scalar type");
748         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749         Val = DAG.getBitcast(IntermediateType, Val);
750         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751       }
752     }
753 
754     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755     Parts[0] = Val;
756     return;
757   }
758 
759   // Handle a multi-element vector.
760   EVT IntermediateVT;
761   MVT RegisterVT;
762   unsigned NumIntermediates;
763   unsigned NumRegs;
764   if (IsABIRegCopy) {
765     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
766         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767         RegisterVT);
768   } else {
769     NumRegs =
770         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771                                    NumIntermediates, RegisterVT);
772   }
773 
774   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775   NumParts = NumRegs; // Silence a compiler warning.
776   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777 
778   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779          "Mixing scalable and fixed vectors when copying in parts");
780 
781   std::optional<ElementCount> DestEltCnt;
782 
783   if (IntermediateVT.isVector())
784     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785   else
786     DestEltCnt = ElementCount::getFixed(NumIntermediates);
787 
788   EVT BuiltVectorTy = EVT::getVectorVT(
789       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790 
791   if (ValueVT == BuiltVectorTy) {
792     // Nothing to do.
793   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794     // Bitconvert vector->vector case.
795     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796   } else {
797     if (BuiltVectorTy.getVectorElementType().bitsGT(
798             ValueVT.getVectorElementType())) {
799       // Integer promotion.
800       ValueVT = EVT::getVectorVT(*DAG.getContext(),
801                                  BuiltVectorTy.getVectorElementType(),
802                                  ValueVT.getVectorElementCount());
803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804     }
805 
806     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807       Val = Widened;
808     }
809   }
810 
811   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812 
813   // Split the vector into intermediate operands.
814   SmallVector<SDValue, 8> Ops(NumIntermediates);
815   for (unsigned i = 0; i != NumIntermediates; ++i) {
816     if (IntermediateVT.isVector()) {
817       // This does something sensible for scalable vectors - see the
818       // definition of EXTRACT_SUBVECTOR for further details.
819       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820       Ops[i] =
821           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823     } else {
824       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825                            DAG.getVectorIdxConstant(i, DL));
826     }
827   }
828 
829   // Split the intermediate operands into legal parts.
830   if (NumParts == NumIntermediates) {
831     // If the register was not expanded, promote or copy the value,
832     // as appropriate.
833     for (unsigned i = 0; i != NumParts; ++i)
834       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835   } else if (NumParts > 0) {
836     // If the intermediate type was expanded, split each the value into
837     // legal parts.
838     assert(NumIntermediates != 0 && "division by zero");
839     assert(NumParts % NumIntermediates == 0 &&
840            "Must expand into a divisible number of parts!");
841     unsigned Factor = NumParts / NumIntermediates;
842     for (unsigned i = 0; i != NumIntermediates; ++i)
843       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844                      CallConv);
845   }
846 }
847 
848 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
849                            EVT valuevt, std::optional<CallingConv::ID> CC)
850     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
851       RegCount(1, regs.size()), CallConv(CC) {}
852 
853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
854                            const DataLayout &DL, unsigned Reg, Type *Ty,
855                            std::optional<CallingConv::ID> CC) {
856   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
857 
858   CallConv = CC;
859 
860   for (EVT ValueVT : ValueVTs) {
861     unsigned NumRegs =
862         isABIMangled()
863             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
864             : TLI.getNumRegisters(Context, ValueVT);
865     MVT RegisterVT =
866         isABIMangled()
867             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
868             : TLI.getRegisterType(Context, ValueVT);
869     for (unsigned i = 0; i != NumRegs; ++i)
870       Regs.push_back(Reg + i);
871     RegVTs.push_back(RegisterVT);
872     RegCount.push_back(NumRegs);
873     Reg += NumRegs;
874   }
875 }
876 
877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
878                                       FunctionLoweringInfo &FuncInfo,
879                                       const SDLoc &dl, SDValue &Chain,
880                                       SDValue *Glue, const Value *V) const {
881   // A Value with type {} or [0 x %t] needs no registers.
882   if (ValueVTs.empty())
883     return SDValue();
884 
885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
886 
887   // Assemble the legal parts into the final values.
888   SmallVector<SDValue, 4> Values(ValueVTs.size());
889   SmallVector<SDValue, 8> Parts;
890   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
891     // Copy the legal parts from the registers.
892     EVT ValueVT = ValueVTs[Value];
893     unsigned NumRegs = RegCount[Value];
894     MVT RegisterVT = isABIMangled()
895                          ? TLI.getRegisterTypeForCallingConv(
896                                *DAG.getContext(), *CallConv, RegVTs[Value])
897                          : RegVTs[Value];
898 
899     Parts.resize(NumRegs);
900     for (unsigned i = 0; i != NumRegs; ++i) {
901       SDValue P;
902       if (!Glue) {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
904       } else {
905         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
906         *Glue = P.getValue(2);
907       }
908 
909       Chain = P.getValue(1);
910       Parts[i] = P;
911 
912       // If the source register was virtual and if we know something about it,
913       // add an assert node.
914       if (!Register::isVirtualRegister(Regs[Part + i]) ||
915           !RegisterVT.isInteger())
916         continue;
917 
918       const FunctionLoweringInfo::LiveOutInfo *LOI =
919         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
920       if (!LOI)
921         continue;
922 
923       unsigned RegSize = RegisterVT.getScalarSizeInBits();
924       unsigned NumSignBits = LOI->NumSignBits;
925       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
926 
927       if (NumZeroBits == RegSize) {
928         // The current value is a zero.
929         // Explicitly express that as it would be easier for
930         // optimizations to kick in.
931         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
932         continue;
933       }
934 
935       // FIXME: We capture more information than the dag can represent.  For
936       // now, just use the tightest assertzext/assertsext possible.
937       bool isSExt;
938       EVT FromVT(MVT::Other);
939       if (NumZeroBits) {
940         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
941         isSExt = false;
942       } else if (NumSignBits > 1) {
943         FromVT =
944             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
945         isSExt = true;
946       } else {
947         continue;
948       }
949       // Add an assertion node.
950       assert(FromVT != MVT::Other);
951       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
952                              RegisterVT, P, DAG.getValueType(FromVT));
953     }
954 
955     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
956                                      RegisterVT, ValueVT, V, Chain, CallConv);
957     Part += NumRegs;
958     Parts.clear();
959   }
960 
961   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
962 }
963 
964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
965                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
966                                  const Value *V,
967                                  ISD::NodeType PreferredExtendType) const {
968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
969   ISD::NodeType ExtendKind = PreferredExtendType;
970 
971   // Get the list of the values's legal parts.
972   unsigned NumRegs = Regs.size();
973   SmallVector<SDValue, 8> Parts(NumRegs);
974   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumParts = RegCount[Value];
976 
977     MVT RegisterVT = isABIMangled()
978                          ? TLI.getRegisterTypeForCallingConv(
979                                *DAG.getContext(), *CallConv, RegVTs[Value])
980                          : RegVTs[Value];
981 
982     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
983       ExtendKind = ISD::ZERO_EXTEND;
984 
985     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
986                    NumParts, RegisterVT, V, CallConv, ExtendKind);
987     Part += NumParts;
988   }
989 
990   // Copy the parts into the registers.
991   SmallVector<SDValue, 8> Chains(NumRegs);
992   for (unsigned i = 0; i != NumRegs; ++i) {
993     SDValue Part;
994     if (!Glue) {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
996     } else {
997       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
998       *Glue = Part.getValue(1);
999     }
1000 
1001     Chains[i] = Part.getValue(0);
1002   }
1003 
1004   if (NumRegs == 1 || Glue)
1005     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1006     // flagged to it. That is the CopyToReg nodes and the user are considered
1007     // a single scheduling unit. If we create a TokenFactor and return it as
1008     // chain, then the TokenFactor is both a predecessor (operand) of the
1009     // user as well as a successor (the TF operands are flagged to the user).
1010     // c1, f1 = CopyToReg
1011     // c2, f2 = CopyToReg
1012     // c3     = TokenFactor c1, c2
1013     // ...
1014     //        = op c3, ..., f2
1015     Chain = Chains[NumRegs-1];
1016   else
1017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1018 }
1019 
1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1021                                         unsigned MatchingIdx, const SDLoc &dl,
1022                                         SelectionDAG &DAG,
1023                                         std::vector<SDValue> &Ops) const {
1024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1025 
1026   InlineAsm::Flag Flag(Code, Regs.size());
1027   if (HasMatching)
1028     Flag.setMatchingOp(MatchingIdx);
1029   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1030     // Put the register class of the virtual registers in the flag word.  That
1031     // way, later passes can recompute register class constraints for inline
1032     // assembly as well as normal instructions.
1033     // Don't do this for tied operands that can use the regclass information
1034     // from the def.
1035     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1036     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1037     Flag.setRegClass(RC->getID());
1038   }
1039 
1040   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1041   Ops.push_back(Res);
1042 
1043   if (Code == InlineAsm::Kind::Clobber) {
1044     // Clobbers should always have a 1:1 mapping with registers, and may
1045     // reference registers that have illegal (e.g. vector) types. Hence, we
1046     // shouldn't try to apply any sort of splitting logic to them.
1047     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1048            "No 1:1 mapping from clobbers to regs?");
1049     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1050     (void)SP;
1051     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1052       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1053       assert(
1054           (Regs[I] != SP ||
1055            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1056           "If we clobbered the stack pointer, MFI should know about it.");
1057     }
1058     return;
1059   }
1060 
1061   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1062     MVT RegisterVT = RegVTs[Value];
1063     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1064                                            RegisterVT);
1065     for (unsigned i = 0; i != NumRegs; ++i) {
1066       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1067       unsigned TheReg = Regs[Reg++];
1068       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1069     }
1070   }
1071 }
1072 
1073 SmallVector<std::pair<unsigned, TypeSize>, 4>
1074 RegsForValue::getRegsAndSizes() const {
1075   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1076   unsigned I = 0;
1077   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1078     unsigned RegCount = std::get<0>(CountAndVT);
1079     MVT RegisterVT = std::get<1>(CountAndVT);
1080     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1081     for (unsigned E = I + RegCount; I != E; ++I)
1082       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1083   }
1084   return OutVec;
1085 }
1086 
1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1088                                AssumptionCache *ac,
1089                                const TargetLibraryInfo *li) {
1090   AA = aa;
1091   AC = ac;
1092   GFI = gfi;
1093   LibInfo = li;
1094   Context = DAG.getContext();
1095   LPadToCallSiteMap.clear();
1096   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1097   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1098       *DAG.getMachineFunction().getFunction().getParent());
1099 }
1100 
1101 void SelectionDAGBuilder::clear() {
1102   NodeMap.clear();
1103   UnusedArgNodeMap.clear();
1104   PendingLoads.clear();
1105   PendingExports.clear();
1106   PendingConstrainedFP.clear();
1107   PendingConstrainedFPStrict.clear();
1108   CurInst = nullptr;
1109   HasTailCall = false;
1110   SDNodeOrder = LowestSDNodeOrder;
1111   StatepointLowering.clear();
1112 }
1113 
1114 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1115   DanglingDebugInfoMap.clear();
1116 }
1117 
1118 // Update DAG root to include dependencies on Pending chains.
1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1120   SDValue Root = DAG.getRoot();
1121 
1122   if (Pending.empty())
1123     return Root;
1124 
1125   // Add current root to PendingChains, unless we already indirectly
1126   // depend on it.
1127   if (Root.getOpcode() != ISD::EntryToken) {
1128     unsigned i = 0, e = Pending.size();
1129     for (; i != e; ++i) {
1130       assert(Pending[i].getNode()->getNumOperands() > 1);
1131       if (Pending[i].getNode()->getOperand(0) == Root)
1132         break;  // Don't add the root if we already indirectly depend on it.
1133     }
1134 
1135     if (i == e)
1136       Pending.push_back(Root);
1137   }
1138 
1139   if (Pending.size() == 1)
1140     Root = Pending[0];
1141   else
1142     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1143 
1144   DAG.setRoot(Root);
1145   Pending.clear();
1146   return Root;
1147 }
1148 
1149 SDValue SelectionDAGBuilder::getMemoryRoot() {
1150   return updateRoot(PendingLoads);
1151 }
1152 
1153 SDValue SelectionDAGBuilder::getRoot() {
1154   // Chain up all pending constrained intrinsics together with all
1155   // pending loads, by simply appending them to PendingLoads and
1156   // then calling getMemoryRoot().
1157   PendingLoads.reserve(PendingLoads.size() +
1158                        PendingConstrainedFP.size() +
1159                        PendingConstrainedFPStrict.size());
1160   PendingLoads.append(PendingConstrainedFP.begin(),
1161                       PendingConstrainedFP.end());
1162   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1163                       PendingConstrainedFPStrict.end());
1164   PendingConstrainedFP.clear();
1165   PendingConstrainedFPStrict.clear();
1166   return getMemoryRoot();
1167 }
1168 
1169 SDValue SelectionDAGBuilder::getControlRoot() {
1170   // We need to emit pending fpexcept.strict constrained intrinsics,
1171   // so append them to the PendingExports list.
1172   PendingExports.append(PendingConstrainedFPStrict.begin(),
1173                         PendingConstrainedFPStrict.end());
1174   PendingConstrainedFPStrict.clear();
1175   return updateRoot(PendingExports);
1176 }
1177 
1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1179                                              DILocalVariable *Variable,
1180                                              DIExpression *Expression,
1181                                              DebugLoc DL) {
1182   assert(Variable && "Missing variable");
1183 
1184   // Check if address has undef value.
1185   if (!Address || isa<UndefValue>(Address) ||
1186       (Address->use_empty() && !isa<Argument>(Address))) {
1187     LLVM_DEBUG(
1188         dbgs()
1189         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1190     return;
1191   }
1192 
1193   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1194 
1195   SDValue &N = NodeMap[Address];
1196   if (!N.getNode() && isa<Argument>(Address))
1197     // Check unused arguments map.
1198     N = UnusedArgNodeMap[Address];
1199   SDDbgValue *SDV;
1200   if (N.getNode()) {
1201     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1202       Address = BCI->getOperand(0);
1203     // Parameters are handled specially.
1204     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1205     if (IsParameter && FINode) {
1206       // Byval parameter. We have a frame index at this point.
1207       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1208                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1209     } else if (isa<Argument>(Address)) {
1210       // Address is an argument, so try to emit its dbg value using
1211       // virtual register info from the FuncInfo.ValueMap.
1212       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                FuncArgumentDbgValueKind::Declare, N);
1214       return;
1215     } else {
1216       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1217                             true, DL, SDNodeOrder);
1218     }
1219     DAG.AddDbgValue(SDV, IsParameter);
1220   } else {
1221     // If Address is an argument then try to emit its dbg value using
1222     // virtual register info from the FuncInfo.ValueMap.
1223     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1224                                   FuncArgumentDbgValueKind::Declare, N)) {
1225       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1226                         << " (could not emit func-arg dbg_value)\n");
1227     }
1228   }
1229   return;
1230 }
1231 
1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1233   // Add SDDbgValue nodes for any var locs here. Do so before updating
1234   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1236     // Add SDDbgValue nodes for any var locs here. Do so before updating
1237     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1238     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1239          It != End; ++It) {
1240       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1241       dropDanglingDebugInfo(Var, It->Expr);
1242       if (It->Values.isKillLocation(It->Expr)) {
1243         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1244         continue;
1245       }
1246       SmallVector<Value *> Values(It->Values.location_ops());
1247       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1248                             It->Values.hasArgList())) {
1249         SmallVector<Value *, 4> Vals(It->Values.location_ops());
1250         addDanglingDebugInfo(Vals,
1251                              FnVarLocs->getDILocalVariable(It->VariableID),
1252                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1253       }
1254     }
1255   }
1256 
1257   // We must skip DbgVariableRecords if they've already been processed above as
1258   // we have just emitted the debug values resulting from assignment tracking
1259   // analysis, making any existing DbgVariableRecords redundant (and probably
1260   // less correct). We still need to process DbgLabelRecords. This does sink
1261   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1262   // be important as it does so deterministcally and ordering between
1263   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1264   // printing).
1265   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1266   // Is there is any debug-info attached to this instruction, in the form of
1267   // DbgRecord non-instruction debug-info records.
1268   for (DbgRecord &DR : I.getDbgRecordRange()) {
1269     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1270       assert(DLR->getLabel() && "Missing label");
1271       SDDbgLabel *SDV =
1272           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1273       DAG.AddDbgLabel(SDV);
1274       continue;
1275     }
1276 
1277     if (SkipDbgVariableRecords)
1278       continue;
1279     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1280     DILocalVariable *Variable = DVR.getVariable();
1281     DIExpression *Expression = DVR.getExpression();
1282     dropDanglingDebugInfo(Variable, Expression);
1283 
1284     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1285       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1286         continue;
1287       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1288                         << "\n");
1289       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1290                          DVR.getDebugLoc());
1291       continue;
1292     }
1293 
1294     // A DbgVariableRecord with no locations is a kill location.
1295     SmallVector<Value *, 4> Values(DVR.location_ops());
1296     if (Values.empty()) {
1297       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1298                            SDNodeOrder);
1299       continue;
1300     }
1301 
1302     // A DbgVariableRecord with an undef or absent location is also a kill
1303     // location.
1304     if (llvm::any_of(Values,
1305                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1306       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1307                            SDNodeOrder);
1308       continue;
1309     }
1310 
1311     bool IsVariadic = DVR.hasArgList();
1312     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1313                           SDNodeOrder, IsVariadic)) {
1314       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1315                            DVR.getDebugLoc(), SDNodeOrder);
1316     }
1317   }
1318 }
1319 
1320 void SelectionDAGBuilder::visit(const Instruction &I) {
1321   visitDbgInfo(I);
1322 
1323   // Set up outgoing PHI node register values before emitting the terminator.
1324   if (I.isTerminator()) {
1325     HandlePHINodesInSuccessorBlocks(I.getParent());
1326   }
1327 
1328   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1329   if (!isa<DbgInfoIntrinsic>(I))
1330     ++SDNodeOrder;
1331 
1332   CurInst = &I;
1333 
1334   // Set inserted listener only if required.
1335   bool NodeInserted = false;
1336   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1337   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1338   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1339   if (PCSectionsMD || MMRA) {
1340     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1341         DAG, [&](SDNode *) { NodeInserted = true; });
1342   }
1343 
1344   visit(I.getOpcode(), I);
1345 
1346   if (!I.isTerminator() && !HasTailCall &&
1347       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1348     CopyToExportRegsIfNeeded(&I);
1349 
1350   // Handle metadata.
1351   if (PCSectionsMD || MMRA) {
1352     auto It = NodeMap.find(&I);
1353     if (It != NodeMap.end()) {
1354       if (PCSectionsMD)
1355         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1356       if (MMRA)
1357         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1358     } else if (NodeInserted) {
1359       // This should not happen; if it does, don't let it go unnoticed so we can
1360       // fix it. Relevant visit*() function is probably missing a setValue().
1361       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1362              << I.getModule()->getName() << "]\n";
1363       LLVM_DEBUG(I.dump());
1364       assert(false);
1365     }
1366   }
1367 
1368   CurInst = nullptr;
1369 }
1370 
1371 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1372   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1373 }
1374 
1375 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1376   // Note: this doesn't use InstVisitor, because it has to work with
1377   // ConstantExpr's in addition to instructions.
1378   switch (Opcode) {
1379   default: llvm_unreachable("Unknown instruction type encountered!");
1380     // Build the switch statement using the Instruction.def file.
1381 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1382     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1383 #include "llvm/IR/Instruction.def"
1384   }
1385 }
1386 
1387 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1388                                             DILocalVariable *Variable,
1389                                             DebugLoc DL, unsigned Order,
1390                                             SmallVectorImpl<Value *> &Values,
1391                                             DIExpression *Expression) {
1392   // For variadic dbg_values we will now insert an undef.
1393   // FIXME: We can potentially recover these!
1394   SmallVector<SDDbgOperand, 2> Locs;
1395   for (const Value *V : Values) {
1396     auto *Undef = UndefValue::get(V->getType());
1397     Locs.push_back(SDDbgOperand::fromConst(Undef));
1398   }
1399   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1400                                         /*IsIndirect=*/false, DL, Order,
1401                                         /*IsVariadic=*/true);
1402   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1403   return true;
1404 }
1405 
1406 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1407                                                DILocalVariable *Var,
1408                                                DIExpression *Expr,
1409                                                bool IsVariadic, DebugLoc DL,
1410                                                unsigned Order) {
1411   if (IsVariadic) {
1412     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1413     return;
1414   }
1415   // TODO: Dangling debug info will eventually either be resolved or produce
1416   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1417   // between the original dbg.value location and its resolved DBG_VALUE,
1418   // which we should ideally fill with an extra Undef DBG_VALUE.
1419   assert(Values.size() == 1);
1420   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1421 }
1422 
1423 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1424                                                 const DIExpression *Expr) {
1425   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1426     DIVariable *DanglingVariable = DDI.getVariable();
1427     DIExpression *DanglingExpr = DDI.getExpression();
1428     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1429       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1430                         << printDDI(nullptr, DDI) << "\n");
1431       return true;
1432     }
1433     return false;
1434   };
1435 
1436   for (auto &DDIMI : DanglingDebugInfoMap) {
1437     DanglingDebugInfoVector &DDIV = DDIMI.second;
1438 
1439     // If debug info is to be dropped, run it through final checks to see
1440     // whether it can be salvaged.
1441     for (auto &DDI : DDIV)
1442       if (isMatchingDbgValue(DDI))
1443         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1444 
1445     erase_if(DDIV, isMatchingDbgValue);
1446   }
1447 }
1448 
1449 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1450 // generate the debug data structures now that we've seen its definition.
1451 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1452                                                    SDValue Val) {
1453   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1454   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1455     return;
1456 
1457   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1458   for (auto &DDI : DDIV) {
1459     DebugLoc DL = DDI.getDebugLoc();
1460     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1461     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1462     DILocalVariable *Variable = DDI.getVariable();
1463     DIExpression *Expr = DDI.getExpression();
1464     assert(Variable->isValidLocationForIntrinsic(DL) &&
1465            "Expected inlined-at fields to agree");
1466     SDDbgValue *SDV;
1467     if (Val.getNode()) {
1468       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1469       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1470       // we couldn't resolve it directly when examining the DbgValue intrinsic
1471       // in the first place we should not be more successful here). Unless we
1472       // have some test case that prove this to be correct we should avoid
1473       // calling EmitFuncArgumentDbgValue here.
1474       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1475                                     FuncArgumentDbgValueKind::Value, Val)) {
1476         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1477                           << printDDI(V, DDI) << "\n");
1478         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1479         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1480         // inserted after the definition of Val when emitting the instructions
1481         // after ISel. An alternative could be to teach
1482         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1483         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1484                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1485                    << ValSDNodeOrder << "\n");
1486         SDV = getDbgValue(Val, Variable, Expr, DL,
1487                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1488         DAG.AddDbgValue(SDV, false);
1489       } else
1490         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1491                           << printDDI(V, DDI)
1492                           << " in EmitFuncArgumentDbgValue\n");
1493     } else {
1494       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1495                         << "\n");
1496       auto Undef = UndefValue::get(V->getType());
1497       auto SDV =
1498           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1499       DAG.AddDbgValue(SDV, false);
1500     }
1501   }
1502   DDIV.clear();
1503 }
1504 
1505 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1506                                                     DanglingDebugInfo &DDI) {
1507   // TODO: For the variadic implementation, instead of only checking the fail
1508   // state of `handleDebugValue`, we need know specifically which values were
1509   // invalid, so that we attempt to salvage only those values when processing
1510   // a DIArgList.
1511   const Value *OrigV = V;
1512   DILocalVariable *Var = DDI.getVariable();
1513   DIExpression *Expr = DDI.getExpression();
1514   DebugLoc DL = DDI.getDebugLoc();
1515   unsigned SDOrder = DDI.getSDNodeOrder();
1516 
1517   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1518   // that DW_OP_stack_value is desired.
1519   bool StackValue = true;
1520 
1521   // Can this Value can be encoded without any further work?
1522   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1523     return;
1524 
1525   // Attempt to salvage back through as many instructions as possible. Bail if
1526   // a non-instruction is seen, such as a constant expression or global
1527   // variable. FIXME: Further work could recover those too.
1528   while (isa<Instruction>(V)) {
1529     const Instruction &VAsInst = *cast<const Instruction>(V);
1530     // Temporary "0", awaiting real implementation.
1531     SmallVector<uint64_t, 16> Ops;
1532     SmallVector<Value *, 4> AdditionalValues;
1533     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1534                              Expr->getNumLocationOperands(), Ops,
1535                              AdditionalValues);
1536     // If we cannot salvage any further, and haven't yet found a suitable debug
1537     // expression, bail out.
1538     if (!V)
1539       break;
1540 
1541     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1542     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1543     // here for variadic dbg_values, remove that condition.
1544     if (!AdditionalValues.empty())
1545       break;
1546 
1547     // New value and expr now represent this debuginfo.
1548     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1549 
1550     // Some kind of simplification occurred: check whether the operand of the
1551     // salvaged debug expression can be encoded in this DAG.
1552     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1553       LLVM_DEBUG(
1554           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1555                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1556       return;
1557     }
1558   }
1559 
1560   // This was the final opportunity to salvage this debug information, and it
1561   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1562   // any earlier variable location.
1563   assert(OrigV && "V shouldn't be null");
1564   auto *Undef = UndefValue::get(OrigV->getType());
1565   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1566   DAG.AddDbgValue(SDV, false);
1567   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1568                     << printDDI(OrigV, DDI) << "\n");
1569 }
1570 
1571 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1572                                                DIExpression *Expr,
1573                                                DebugLoc DbgLoc,
1574                                                unsigned Order) {
1575   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1576   DIExpression *NewExpr =
1577       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1578   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1579                    /*IsVariadic*/ false);
1580 }
1581 
1582 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1583                                            DILocalVariable *Var,
1584                                            DIExpression *Expr, DebugLoc DbgLoc,
1585                                            unsigned Order, bool IsVariadic) {
1586   if (Values.empty())
1587     return true;
1588 
1589   // Filter EntryValue locations out early.
1590   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1591     return true;
1592 
1593   SmallVector<SDDbgOperand> LocationOps;
1594   SmallVector<SDNode *> Dependencies;
1595   for (const Value *V : Values) {
1596     // Constant value.
1597     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1598         isa<ConstantPointerNull>(V)) {
1599       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1600       continue;
1601     }
1602 
1603     // Look through IntToPtr constants.
1604     if (auto *CE = dyn_cast<ConstantExpr>(V))
1605       if (CE->getOpcode() == Instruction::IntToPtr) {
1606         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1607         continue;
1608       }
1609 
1610     // If the Value is a frame index, we can create a FrameIndex debug value
1611     // without relying on the DAG at all.
1612     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1613       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1614       if (SI != FuncInfo.StaticAllocaMap.end()) {
1615         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1616         continue;
1617       }
1618     }
1619 
1620     // Do not use getValue() in here; we don't want to generate code at
1621     // this point if it hasn't been done yet.
1622     SDValue N = NodeMap[V];
1623     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1624       N = UnusedArgNodeMap[V];
1625 
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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2823   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2824   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2825       BOp->hasOneUse() && !IsUnpredictable) {
2826     Value *Vec;
2827     const Value *BOp0, *BOp1;
2828     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2829     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2830       Opcode = Instruction::And;
2831     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2832       Opcode = Instruction::Or;
2833 
2834     if (Opcode &&
2835         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2836           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2837         !shouldKeepJumpConditionsTogether(
2838             FuncInfo, I, Opcode, BOp0, BOp1,
2839             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2840                 Opcode, BOp0, BOp1))) {
2841       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2842                            getEdgeProbability(BrMBB, Succ0MBB),
2843                            getEdgeProbability(BrMBB, Succ1MBB),
2844                            /*InvertCond=*/false);
2845       // If the compares in later blocks need to use values not currently
2846       // exported from this block, export them now.  This block should always
2847       // be the first entry.
2848       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2849 
2850       // Allow some cases to be rejected.
2851       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2852         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2854           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2855         }
2856 
2857         // Emit the branch for this block.
2858         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2859         SL->SwitchCases.erase(SL->SwitchCases.begin());
2860         return;
2861       }
2862 
2863       // Okay, we decided not to do this, remove any inserted MBB's and clear
2864       // SwitchCases.
2865       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2866         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2867 
2868       SL->SwitchCases.clear();
2869     }
2870   }
2871 
2872   // Create a CaseBlock record representing this branch.
2873   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2874                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2875                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2876                IsUnpredictable);
2877 
2878   // Use visitSwitchCase to actually insert the fast branch sequence for this
2879   // cond branch.
2880   visitSwitchCase(CB, BrMBB);
2881 }
2882 
2883 /// visitSwitchCase - Emits the necessary code to represent a single node in
2884 /// the binary search tree resulting from lowering a switch instruction.
2885 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2886                                           MachineBasicBlock *SwitchBB) {
2887   SDValue Cond;
2888   SDValue CondLHS = getValue(CB.CmpLHS);
2889   SDLoc dl = CB.DL;
2890 
2891   if (CB.CC == ISD::SETTRUE) {
2892     // Branch or fall through to TrueBB.
2893     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2894     SwitchBB->normalizeSuccProbs();
2895     if (CB.TrueBB != NextBlock(SwitchBB)) {
2896       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2897                               DAG.getBasicBlock(CB.TrueBB)));
2898     }
2899     return;
2900   }
2901 
2902   auto &TLI = DAG.getTargetLoweringInfo();
2903   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2904 
2905   // Build the setcc now.
2906   if (!CB.CmpMHS) {
2907     // Fold "(X == true)" to X and "(X == false)" to !X to
2908     // handle common cases produced by branch lowering.
2909     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2910         CB.CC == ISD::SETEQ)
2911       Cond = CondLHS;
2912     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2913              CB.CC == ISD::SETEQ) {
2914       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2915       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2916     } else {
2917       SDValue CondRHS = getValue(CB.CmpRHS);
2918 
2919       // If a pointer's DAG type is larger than its memory type then the DAG
2920       // values are zero-extended. This breaks signed comparisons so truncate
2921       // back to the underlying type before doing the compare.
2922       if (CondLHS.getValueType() != MemVT) {
2923         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2924         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2925       }
2926       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2927     }
2928   } else {
2929     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2930 
2931     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2932     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2933 
2934     SDValue CmpOp = getValue(CB.CmpMHS);
2935     EVT VT = CmpOp.getValueType();
2936 
2937     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2938       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2939                           ISD::SETLE);
2940     } else {
2941       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2942                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2943       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2944                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2945     }
2946   }
2947 
2948   // Update successor info
2949   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2950   // TrueBB and FalseBB are always different unless the incoming IR is
2951   // degenerate. This only happens when running llc on weird IR.
2952   if (CB.TrueBB != CB.FalseBB)
2953     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2954   SwitchBB->normalizeSuccProbs();
2955 
2956   // If the lhs block is the next block, invert the condition so that we can
2957   // fall through to the lhs instead of the rhs block.
2958   if (CB.TrueBB == NextBlock(SwitchBB)) {
2959     std::swap(CB.TrueBB, CB.FalseBB);
2960     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2961     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2962   }
2963 
2964   SDNodeFlags Flags;
2965   Flags.setUnpredictable(CB.IsUnpredictable);
2966   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2967                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2968 
2969   setValue(CurInst, BrCond);
2970 
2971   // Insert the false branch. Do this even if it's a fall through branch,
2972   // this makes it easier to do DAG optimizations which require inverting
2973   // the branch condition.
2974   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2975                        DAG.getBasicBlock(CB.FalseBB));
2976 
2977   DAG.setRoot(BrCond);
2978 }
2979 
2980 /// visitJumpTable - Emit JumpTable node in the current MBB
2981 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2982   // Emit the code for the jump table
2983   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2984   assert(JT.Reg != -1U && "Should lower JT Header first!");
2985   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2986   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2987   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2988   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2989                                     Index.getValue(1), Table, Index);
2990   DAG.setRoot(BrJumpTable);
2991 }
2992 
2993 /// visitJumpTableHeader - This function emits necessary code to produce index
2994 /// in the JumpTable from switch case.
2995 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2996                                                JumpTableHeader &JTH,
2997                                                MachineBasicBlock *SwitchBB) {
2998   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2999   const SDLoc &dl = *JT.SL;
3000 
3001   // Subtract the lowest switch case value from the value being switched on.
3002   SDValue SwitchOp = getValue(JTH.SValue);
3003   EVT VT = SwitchOp.getValueType();
3004   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3005                             DAG.getConstant(JTH.First, dl, VT));
3006 
3007   // The SDNode we just created, which holds the value being switched on minus
3008   // the smallest case value, needs to be copied to a virtual register so it
3009   // can be used as an index into the jump table in a subsequent basic block.
3010   // This value may be smaller or larger than the target's pointer type, and
3011   // therefore require extension or truncating.
3012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3013   SwitchOp =
3014       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3015 
3016   unsigned JumpTableReg =
3017       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3018   SDValue CopyTo =
3019       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3020   JT.Reg = JumpTableReg;
3021 
3022   if (!JTH.FallthroughUnreachable) {
3023     // Emit the range check for the jump table, and branch to the default block
3024     // for the switch statement if the value being switched on exceeds the
3025     // largest case in the switch.
3026     SDValue CMP = DAG.getSetCC(
3027         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3028                                    Sub.getValueType()),
3029         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3030 
3031     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3032                                  MVT::Other, CopyTo, CMP,
3033                                  DAG.getBasicBlock(JT.Default));
3034 
3035     // Avoid emitting unnecessary branches to the next block.
3036     if (JT.MBB != NextBlock(SwitchBB))
3037       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3038                            DAG.getBasicBlock(JT.MBB));
3039 
3040     DAG.setRoot(BrCond);
3041   } else {
3042     // Avoid emitting unnecessary branches to the next block.
3043     if (JT.MBB != NextBlock(SwitchBB))
3044       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3045                               DAG.getBasicBlock(JT.MBB)));
3046     else
3047       DAG.setRoot(CopyTo);
3048   }
3049 }
3050 
3051 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3052 /// variable if there exists one.
3053 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3054                                  SDValue &Chain) {
3055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3056   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3057   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3058   MachineFunction &MF = DAG.getMachineFunction();
3059   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3060   MachineSDNode *Node =
3061       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3062   if (Global) {
3063     MachinePointerInfo MPInfo(Global);
3064     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3065                  MachineMemOperand::MODereferenceable;
3066     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3067         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3068         DAG.getEVTAlign(PtrTy));
3069     DAG.setNodeMemRefs(Node, {MemRef});
3070   }
3071   if (PtrTy != PtrMemTy)
3072     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3073   return SDValue(Node, 0);
3074 }
3075 
3076 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3077 /// tail spliced into a stack protector check success bb.
3078 ///
3079 /// For a high level explanation of how this fits into the stack protector
3080 /// generation see the comment on the declaration of class
3081 /// StackProtectorDescriptor.
3082 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3083                                                   MachineBasicBlock *ParentBB) {
3084 
3085   // First create the loads to the guard/stack slot for the comparison.
3086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3087   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3088   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3089 
3090   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3091   int FI = MFI.getStackProtectorIndex();
3092 
3093   SDValue Guard;
3094   SDLoc dl = getCurSDLoc();
3095   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3096   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3097   Align Align =
3098       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3099 
3100   // Generate code to load the content of the guard slot.
3101   SDValue GuardVal = DAG.getLoad(
3102       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3103       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3104       MachineMemOperand::MOVolatile);
3105 
3106   if (TLI.useStackGuardXorFP())
3107     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3108 
3109   // Retrieve guard check function, nullptr if instrumentation is inlined.
3110   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3111     // The target provides a guard check function to validate the guard value.
3112     // Generate a call to that function with the content of the guard slot as
3113     // argument.
3114     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3115     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3116 
3117     TargetLowering::ArgListTy Args;
3118     TargetLowering::ArgListEntry Entry;
3119     Entry.Node = GuardVal;
3120     Entry.Ty = FnTy->getParamType(0);
3121     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3122       Entry.IsInReg = true;
3123     Args.push_back(Entry);
3124 
3125     TargetLowering::CallLoweringInfo CLI(DAG);
3126     CLI.setDebugLoc(getCurSDLoc())
3127         .setChain(DAG.getEntryNode())
3128         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3129                    getValue(GuardCheckFn), std::move(Args));
3130 
3131     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3132     DAG.setRoot(Result.second);
3133     return;
3134   }
3135 
3136   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3137   // Otherwise, emit a volatile load to retrieve the stack guard value.
3138   SDValue Chain = DAG.getEntryNode();
3139   if (TLI.useLoadStackGuardNode()) {
3140     Guard = getLoadStackGuard(DAG, dl, Chain);
3141   } else {
3142     const Value *IRGuard = TLI.getSDagStackGuard(M);
3143     SDValue GuardPtr = getValue(IRGuard);
3144 
3145     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3146                         MachinePointerInfo(IRGuard, 0), Align,
3147                         MachineMemOperand::MOVolatile);
3148   }
3149 
3150   // Perform the comparison via a getsetcc.
3151   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3152                                                         *DAG.getContext(),
3153                                                         Guard.getValueType()),
3154                              Guard, GuardVal, ISD::SETNE);
3155 
3156   // If the guard/stackslot do not equal, branch to failure MBB.
3157   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3158                                MVT::Other, GuardVal.getOperand(0),
3159                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3160   // Otherwise branch to success MBB.
3161   SDValue Br = DAG.getNode(ISD::BR, dl,
3162                            MVT::Other, BrCond,
3163                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3164 
3165   DAG.setRoot(Br);
3166 }
3167 
3168 /// Codegen the failure basic block for a stack protector check.
3169 ///
3170 /// A failure stack protector machine basic block consists simply of a call to
3171 /// __stack_chk_fail().
3172 ///
3173 /// For a high level explanation of how this fits into the stack protector
3174 /// generation see the comment on the declaration of class
3175 /// StackProtectorDescriptor.
3176 void
3177 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3179   TargetLowering::MakeLibCallOptions CallOptions;
3180   CallOptions.setDiscardResult(true);
3181   SDValue Chain =
3182       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3183                       std::nullopt, CallOptions, getCurSDLoc())
3184           .second;
3185   // On PS4/PS5, the "return address" must still be within the calling
3186   // function, even if it's at the very end, so emit an explicit TRAP here.
3187   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3188   if (TM.getTargetTriple().isPS())
3189     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3190   // WebAssembly needs an unreachable instruction after a non-returning call,
3191   // because the function return type can be different from __stack_chk_fail's
3192   // return type (void).
3193   if (TM.getTargetTriple().isWasm())
3194     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3195 
3196   DAG.setRoot(Chain);
3197 }
3198 
3199 /// visitBitTestHeader - This function emits necessary code to produce value
3200 /// suitable for "bit tests"
3201 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3202                                              MachineBasicBlock *SwitchBB) {
3203   SDLoc dl = getCurSDLoc();
3204 
3205   // Subtract the minimum value.
3206   SDValue SwitchOp = getValue(B.SValue);
3207   EVT VT = SwitchOp.getValueType();
3208   SDValue RangeSub =
3209       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3210 
3211   // Determine the type of the test operands.
3212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3213   bool UsePtrType = false;
3214   if (!TLI.isTypeLegal(VT)) {
3215     UsePtrType = true;
3216   } else {
3217     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3218       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3219         // Switch table case range are encoded into series of masks.
3220         // Just use pointer type, it's guaranteed to fit.
3221         UsePtrType = true;
3222         break;
3223       }
3224   }
3225   SDValue Sub = RangeSub;
3226   if (UsePtrType) {
3227     VT = TLI.getPointerTy(DAG.getDataLayout());
3228     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3229   }
3230 
3231   B.RegVT = VT.getSimpleVT();
3232   B.Reg = FuncInfo.CreateReg(B.RegVT);
3233   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3234 
3235   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3236 
3237   if (!B.FallthroughUnreachable)
3238     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3239   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3240   SwitchBB->normalizeSuccProbs();
3241 
3242   SDValue Root = CopyTo;
3243   if (!B.FallthroughUnreachable) {
3244     // Conditional branch to the default block.
3245     SDValue RangeCmp = DAG.getSetCC(dl,
3246         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3247                                RangeSub.getValueType()),
3248         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3249         ISD::SETUGT);
3250 
3251     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3252                        DAG.getBasicBlock(B.Default));
3253   }
3254 
3255   // Avoid emitting unnecessary branches to the next block.
3256   if (MBB != NextBlock(SwitchBB))
3257     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3258 
3259   DAG.setRoot(Root);
3260 }
3261 
3262 /// visitBitTestCase - this function produces one "bit test"
3263 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3264                                            MachineBasicBlock* NextMBB,
3265                                            BranchProbability BranchProbToNext,
3266                                            unsigned Reg,
3267                                            BitTestCase &B,
3268                                            MachineBasicBlock *SwitchBB) {
3269   SDLoc dl = getCurSDLoc();
3270   MVT VT = BB.RegVT;
3271   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3272   SDValue Cmp;
3273   unsigned PopCount = llvm::popcount(B.Mask);
3274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275   if (PopCount == 1) {
3276     // Testing for a single bit; just compare the shift count with what it
3277     // would need to be to shift a 1 bit in that position.
3278     Cmp = DAG.getSetCC(
3279         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3280         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3281         ISD::SETEQ);
3282   } else if (PopCount == BB.Range) {
3283     // There is only one zero bit in the range, test for it directly.
3284     Cmp = DAG.getSetCC(
3285         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3286         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3287   } else {
3288     // Make desired shift
3289     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3290                                     DAG.getConstant(1, dl, VT), ShiftOp);
3291 
3292     // Emit bit tests and jumps
3293     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3294                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3295     Cmp = DAG.getSetCC(
3296         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3297         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3298   }
3299 
3300   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3301   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3302   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3303   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3304   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3305   // one as they are relative probabilities (and thus work more like weights),
3306   // and hence we need to normalize them to let the sum of them become one.
3307   SwitchBB->normalizeSuccProbs();
3308 
3309   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3310                               MVT::Other, getControlRoot(),
3311                               Cmp, DAG.getBasicBlock(B.TargetBB));
3312 
3313   // Avoid emitting unnecessary branches to the next block.
3314   if (NextMBB != NextBlock(SwitchBB))
3315     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3316                         DAG.getBasicBlock(NextMBB));
3317 
3318   DAG.setRoot(BrAnd);
3319 }
3320 
3321 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3322   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3323 
3324   // Retrieve successors. Look through artificial IR level blocks like
3325   // catchswitch for successors.
3326   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3327   const BasicBlock *EHPadBB = I.getSuccessor(1);
3328   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3329 
3330   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3331   // have to do anything here to lower funclet bundles.
3332   assert(!I.hasOperandBundlesOtherThan(
3333              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3334               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3335               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3336               LLVMContext::OB_clang_arc_attachedcall}) &&
3337          "Cannot lower invokes with arbitrary operand bundles yet!");
3338 
3339   const Value *Callee(I.getCalledOperand());
3340   const Function *Fn = dyn_cast<Function>(Callee);
3341   if (isa<InlineAsm>(Callee))
3342     visitInlineAsm(I, EHPadBB);
3343   else if (Fn && Fn->isIntrinsic()) {
3344     switch (Fn->getIntrinsicID()) {
3345     default:
3346       llvm_unreachable("Cannot invoke this intrinsic");
3347     case Intrinsic::donothing:
3348       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3349     case Intrinsic::seh_try_begin:
3350     case Intrinsic::seh_scope_begin:
3351     case Intrinsic::seh_try_end:
3352     case Intrinsic::seh_scope_end:
3353       if (EHPadMBB)
3354           // a block referenced by EH table
3355           // so dtor-funclet not removed by opts
3356           EHPadMBB->setMachineBlockAddressTaken();
3357       break;
3358     case Intrinsic::experimental_patchpoint_void:
3359     case Intrinsic::experimental_patchpoint:
3360       visitPatchpoint(I, EHPadBB);
3361       break;
3362     case Intrinsic::experimental_gc_statepoint:
3363       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3364       break;
3365     case Intrinsic::wasm_rethrow: {
3366       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3367       // special because it can be invoked, so we manually lower it to a DAG
3368       // node here.
3369       SmallVector<SDValue, 8> Ops;
3370       Ops.push_back(getControlRoot()); // inchain for the terminator node
3371       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3372       Ops.push_back(
3373           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3374                                 TLI.getPointerTy(DAG.getDataLayout())));
3375       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3376       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3377       break;
3378     }
3379     }
3380   } else if (I.hasDeoptState()) {
3381     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3382     // Eventually we will support lowering the @llvm.experimental.deoptimize
3383     // intrinsic, and right now there are no plans to support other intrinsics
3384     // with deopt state.
3385     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3386   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3387     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3388   } else {
3389     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3390   }
3391 
3392   // If the value of the invoke is used outside of its defining block, make it
3393   // available as a virtual register.
3394   // We already took care of the exported value for the statepoint instruction
3395   // during call to the LowerStatepoint.
3396   if (!isa<GCStatepointInst>(I)) {
3397     CopyToExportRegsIfNeeded(&I);
3398   }
3399 
3400   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3401   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3402   BranchProbability EHPadBBProb =
3403       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3404           : BranchProbability::getZero();
3405   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3406 
3407   // Update successor info.
3408   addSuccessorWithProb(InvokeMBB, Return);
3409   for (auto &UnwindDest : UnwindDests) {
3410     UnwindDest.first->setIsEHPad();
3411     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3412   }
3413   InvokeMBB->normalizeSuccProbs();
3414 
3415   // Drop into normal successor.
3416   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3417                           DAG.getBasicBlock(Return)));
3418 }
3419 
3420 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3421   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3422 
3423   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3424   // have to do anything here to lower funclet bundles.
3425   assert(!I.hasOperandBundlesOtherThan(
3426              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3427          "Cannot lower callbrs with arbitrary operand bundles yet!");
3428 
3429   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3430   visitInlineAsm(I);
3431   CopyToExportRegsIfNeeded(&I);
3432 
3433   // Retrieve successors.
3434   SmallPtrSet<BasicBlock *, 8> Dests;
3435   Dests.insert(I.getDefaultDest());
3436   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3437 
3438   // Update successor info.
3439   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3440   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3441     BasicBlock *Dest = I.getIndirectDest(i);
3442     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3443     Target->setIsInlineAsmBrIndirectTarget();
3444     Target->setMachineBlockAddressTaken();
3445     Target->setLabelMustBeEmitted();
3446     // Don't add duplicate machine successors.
3447     if (Dests.insert(Dest).second)
3448       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3449   }
3450   CallBrMBB->normalizeSuccProbs();
3451 
3452   // Drop into default successor.
3453   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3454                           MVT::Other, getControlRoot(),
3455                           DAG.getBasicBlock(Return)));
3456 }
3457 
3458 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3459   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3460 }
3461 
3462 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3463   assert(FuncInfo.MBB->isEHPad() &&
3464          "Call to landingpad not in landing pad!");
3465 
3466   // If there aren't registers to copy the values into (e.g., during SjLj
3467   // exceptions), then don't bother to create these DAG nodes.
3468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3469   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3470   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3471       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3472     return;
3473 
3474   // If landingpad's return type is token type, we don't create DAG nodes
3475   // for its exception pointer and selector value. The extraction of exception
3476   // pointer or selector value from token type landingpads is not currently
3477   // supported.
3478   if (LP.getType()->isTokenTy())
3479     return;
3480 
3481   SmallVector<EVT, 2> ValueVTs;
3482   SDLoc dl = getCurSDLoc();
3483   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3484   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3485 
3486   // Get the two live-in registers as SDValues. The physregs have already been
3487   // copied into virtual registers.
3488   SDValue Ops[2];
3489   if (FuncInfo.ExceptionPointerVirtReg) {
3490     Ops[0] = DAG.getZExtOrTrunc(
3491         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3492                            FuncInfo.ExceptionPointerVirtReg,
3493                            TLI.getPointerTy(DAG.getDataLayout())),
3494         dl, ValueVTs[0]);
3495   } else {
3496     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3497   }
3498   Ops[1] = DAG.getZExtOrTrunc(
3499       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3500                          FuncInfo.ExceptionSelectorVirtReg,
3501                          TLI.getPointerTy(DAG.getDataLayout())),
3502       dl, ValueVTs[1]);
3503 
3504   // Merge into one.
3505   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3506                             DAG.getVTList(ValueVTs), Ops);
3507   setValue(&LP, Res);
3508 }
3509 
3510 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3511                                            MachineBasicBlock *Last) {
3512   // Update JTCases.
3513   for (JumpTableBlock &JTB : SL->JTCases)
3514     if (JTB.first.HeaderBB == First)
3515       JTB.first.HeaderBB = Last;
3516 
3517   // Update BitTestCases.
3518   for (BitTestBlock &BTB : SL->BitTestCases)
3519     if (BTB.Parent == First)
3520       BTB.Parent = Last;
3521 }
3522 
3523 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3524   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3525 
3526   // Update machine-CFG edges with unique successors.
3527   SmallSet<BasicBlock*, 32> Done;
3528   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3529     BasicBlock *BB = I.getSuccessor(i);
3530     bool Inserted = Done.insert(BB).second;
3531     if (!Inserted)
3532         continue;
3533 
3534     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3535     addSuccessorWithProb(IndirectBrMBB, Succ);
3536   }
3537   IndirectBrMBB->normalizeSuccProbs();
3538 
3539   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3540                           MVT::Other, getControlRoot(),
3541                           getValue(I.getAddress())));
3542 }
3543 
3544 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3545   if (!DAG.getTarget().Options.TrapUnreachable)
3546     return;
3547 
3548   // We may be able to ignore unreachable behind a noreturn call.
3549   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3550       Call && Call->doesNotReturn()) {
3551     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3552       return;
3553     // Do not emit an additional trap instruction.
3554     if (Call->isNonContinuableTrap())
3555       return;
3556   }
3557 
3558   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3559 }
3560 
3561 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3562   SDNodeFlags Flags;
3563   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3564     Flags.copyFMF(*FPOp);
3565 
3566   SDValue Op = getValue(I.getOperand(0));
3567   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3568                                     Op, Flags);
3569   setValue(&I, UnNodeValue);
3570 }
3571 
3572 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3573   SDNodeFlags Flags;
3574   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3575     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3576     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3577   }
3578   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3579     Flags.setExact(ExactOp->isExact());
3580   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3581     Flags.setDisjoint(DisjointOp->isDisjoint());
3582   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3583     Flags.copyFMF(*FPOp);
3584 
3585   SDValue Op1 = getValue(I.getOperand(0));
3586   SDValue Op2 = getValue(I.getOperand(1));
3587   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3588                                      Op1, Op2, Flags);
3589   setValue(&I, BinNodeValue);
3590 }
3591 
3592 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3593   SDValue Op1 = getValue(I.getOperand(0));
3594   SDValue Op2 = getValue(I.getOperand(1));
3595 
3596   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3597       Op1.getValueType(), DAG.getDataLayout());
3598 
3599   // Coerce the shift amount to the right type if we can. This exposes the
3600   // truncate or zext to optimization early.
3601   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3602     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3603            "Unexpected shift type");
3604     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3605   }
3606 
3607   bool nuw = false;
3608   bool nsw = false;
3609   bool exact = false;
3610 
3611   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3612 
3613     if (const OverflowingBinaryOperator *OFBinOp =
3614             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3615       nuw = OFBinOp->hasNoUnsignedWrap();
3616       nsw = OFBinOp->hasNoSignedWrap();
3617     }
3618     if (const PossiblyExactOperator *ExactOp =
3619             dyn_cast<const PossiblyExactOperator>(&I))
3620       exact = ExactOp->isExact();
3621   }
3622   SDNodeFlags Flags;
3623   Flags.setExact(exact);
3624   Flags.setNoSignedWrap(nsw);
3625   Flags.setNoUnsignedWrap(nuw);
3626   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3627                             Flags);
3628   setValue(&I, Res);
3629 }
3630 
3631 void SelectionDAGBuilder::visitSDiv(const User &I) {
3632   SDValue Op1 = getValue(I.getOperand(0));
3633   SDValue Op2 = getValue(I.getOperand(1));
3634 
3635   SDNodeFlags Flags;
3636   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3637                  cast<PossiblyExactOperator>(&I)->isExact());
3638   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3639                            Op2, Flags));
3640 }
3641 
3642 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3643   ICmpInst::Predicate predicate = I.getPredicate();
3644   SDValue Op1 = getValue(I.getOperand(0));
3645   SDValue Op2 = getValue(I.getOperand(1));
3646   ISD::CondCode Opcode = getICmpCondCode(predicate);
3647 
3648   auto &TLI = DAG.getTargetLoweringInfo();
3649   EVT MemVT =
3650       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3651 
3652   // If a pointer's DAG type is larger than its memory type then the DAG values
3653   // are zero-extended. This breaks signed comparisons so truncate back to the
3654   // underlying type before doing the compare.
3655   if (Op1.getValueType() != MemVT) {
3656     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3657     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3658   }
3659 
3660   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3661                                                         I.getType());
3662   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3663 }
3664 
3665 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3666   FCmpInst::Predicate predicate = I.getPredicate();
3667   SDValue Op1 = getValue(I.getOperand(0));
3668   SDValue Op2 = getValue(I.getOperand(1));
3669 
3670   ISD::CondCode Condition = getFCmpCondCode(predicate);
3671   auto *FPMO = cast<FPMathOperator>(&I);
3672   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3673     Condition = getFCmpCodeWithoutNaN(Condition);
3674 
3675   SDNodeFlags Flags;
3676   Flags.copyFMF(*FPMO);
3677   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3678 
3679   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3680                                                         I.getType());
3681   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3682 }
3683 
3684 // Check if the condition of the select has one use or two users that are both
3685 // selects with the same condition.
3686 static bool hasOnlySelectUsers(const Value *Cond) {
3687   return llvm::all_of(Cond->users(), [](const Value *V) {
3688     return isa<SelectInst>(V);
3689   });
3690 }
3691 
3692 void SelectionDAGBuilder::visitSelect(const User &I) {
3693   SmallVector<EVT, 4> ValueVTs;
3694   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3695                   ValueVTs);
3696   unsigned NumValues = ValueVTs.size();
3697   if (NumValues == 0) return;
3698 
3699   SmallVector<SDValue, 4> Values(NumValues);
3700   SDValue Cond     = getValue(I.getOperand(0));
3701   SDValue LHSVal   = getValue(I.getOperand(1));
3702   SDValue RHSVal   = getValue(I.getOperand(2));
3703   SmallVector<SDValue, 1> BaseOps(1, Cond);
3704   ISD::NodeType OpCode =
3705       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3706 
3707   bool IsUnaryAbs = false;
3708   bool Negate = false;
3709 
3710   SDNodeFlags Flags;
3711   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3712     Flags.copyFMF(*FPOp);
3713 
3714   Flags.setUnpredictable(
3715       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3716 
3717   // Min/max matching is only viable if all output VTs are the same.
3718   if (all_equal(ValueVTs)) {
3719     EVT VT = ValueVTs[0];
3720     LLVMContext &Ctx = *DAG.getContext();
3721     auto &TLI = DAG.getTargetLoweringInfo();
3722 
3723     // We care about the legality of the operation after it has been type
3724     // legalized.
3725     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3726       VT = TLI.getTypeToTransformTo(Ctx, VT);
3727 
3728     // If the vselect is legal, assume we want to leave this as a vector setcc +
3729     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3730     // min/max is legal on the scalar type.
3731     bool UseScalarMinMax = VT.isVector() &&
3732       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3733 
3734     // ValueTracking's select pattern matching does not account for -0.0,
3735     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3736     // -0.0 is less than +0.0.
3737     const Value *LHS, *RHS;
3738     auto SPR = matchSelectPattern(&I, LHS, RHS);
3739     ISD::NodeType Opc = ISD::DELETED_NODE;
3740     switch (SPR.Flavor) {
3741     case SPF_UMAX:    Opc = ISD::UMAX; break;
3742     case SPF_UMIN:    Opc = ISD::UMIN; break;
3743     case SPF_SMAX:    Opc = ISD::SMAX; break;
3744     case SPF_SMIN:    Opc = ISD::SMIN; break;
3745     case SPF_FMINNUM:
3746       switch (SPR.NaNBehavior) {
3747       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3748       case SPNB_RETURNS_NAN: break;
3749       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3750       case SPNB_RETURNS_ANY:
3751         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3752             (UseScalarMinMax &&
3753              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3754           Opc = ISD::FMINNUM;
3755         break;
3756       }
3757       break;
3758     case SPF_FMAXNUM:
3759       switch (SPR.NaNBehavior) {
3760       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3761       case SPNB_RETURNS_NAN: break;
3762       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3763       case SPNB_RETURNS_ANY:
3764         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3765             (UseScalarMinMax &&
3766              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3767           Opc = ISD::FMAXNUM;
3768         break;
3769       }
3770       break;
3771     case SPF_NABS:
3772       Negate = true;
3773       [[fallthrough]];
3774     case SPF_ABS:
3775       IsUnaryAbs = true;
3776       Opc = ISD::ABS;
3777       break;
3778     default: break;
3779     }
3780 
3781     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3782         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3783          (UseScalarMinMax &&
3784           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3785         // If the underlying comparison instruction is used by any other
3786         // instruction, the consumed instructions won't be destroyed, so it is
3787         // not profitable to convert to a min/max.
3788         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3789       OpCode = Opc;
3790       LHSVal = getValue(LHS);
3791       RHSVal = getValue(RHS);
3792       BaseOps.clear();
3793     }
3794 
3795     if (IsUnaryAbs) {
3796       OpCode = Opc;
3797       LHSVal = getValue(LHS);
3798       BaseOps.clear();
3799     }
3800   }
3801 
3802   if (IsUnaryAbs) {
3803     for (unsigned i = 0; i != NumValues; ++i) {
3804       SDLoc dl = getCurSDLoc();
3805       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3806       Values[i] =
3807           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3808       if (Negate)
3809         Values[i] = DAG.getNegative(Values[i], dl, VT);
3810     }
3811   } else {
3812     for (unsigned i = 0; i != NumValues; ++i) {
3813       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3814       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3815       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3816       Values[i] = DAG.getNode(
3817           OpCode, getCurSDLoc(),
3818           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3819     }
3820   }
3821 
3822   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3823                            DAG.getVTList(ValueVTs), Values));
3824 }
3825 
3826 void SelectionDAGBuilder::visitTrunc(const User &I) {
3827   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3828   SDValue N = getValue(I.getOperand(0));
3829   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3830                                                         I.getType());
3831   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3832 }
3833 
3834 void SelectionDAGBuilder::visitZExt(const User &I) {
3835   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3836   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3837   SDValue N = getValue(I.getOperand(0));
3838   auto &TLI = DAG.getTargetLoweringInfo();
3839   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3840 
3841   SDNodeFlags Flags;
3842   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3843     Flags.setNonNeg(PNI->hasNonNeg());
3844 
3845   // Eagerly use nonneg information to canonicalize towards sign_extend if
3846   // that is the target's preference.
3847   // TODO: Let the target do this later.
3848   if (Flags.hasNonNeg() &&
3849       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3850     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3851     return;
3852   }
3853 
3854   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3855 }
3856 
3857 void SelectionDAGBuilder::visitSExt(const User &I) {
3858   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3859   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3860   SDValue N = getValue(I.getOperand(0));
3861   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3862                                                         I.getType());
3863   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3864 }
3865 
3866 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3867   // FPTrunc is never a no-op cast, no need to check
3868   SDValue N = getValue(I.getOperand(0));
3869   SDLoc dl = getCurSDLoc();
3870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3871   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3872   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3873                            DAG.getTargetConstant(
3874                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3875 }
3876 
3877 void SelectionDAGBuilder::visitFPExt(const User &I) {
3878   // FPExt is never a no-op cast, no need to check
3879   SDValue N = getValue(I.getOperand(0));
3880   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3881                                                         I.getType());
3882   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3883 }
3884 
3885 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3886   // FPToUI is never a no-op cast, no need to check
3887   SDValue N = getValue(I.getOperand(0));
3888   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3889                                                         I.getType());
3890   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3891 }
3892 
3893 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3894   // FPToSI is never a no-op cast, no need to check
3895   SDValue N = getValue(I.getOperand(0));
3896   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3897                                                         I.getType());
3898   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3899 }
3900 
3901 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3902   // UIToFP is never a no-op cast, no need to check
3903   SDValue N = getValue(I.getOperand(0));
3904   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3905                                                         I.getType());
3906   SDNodeFlags Flags;
3907   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3908     Flags.setNonNeg(PNI->hasNonNeg());
3909 
3910   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3911 }
3912 
3913 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3914   // SIToFP is never a no-op cast, no need to check
3915   SDValue N = getValue(I.getOperand(0));
3916   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3917                                                         I.getType());
3918   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3919 }
3920 
3921 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3922   // What to do depends on the size of the integer and the size of the pointer.
3923   // We can either truncate, zero extend, or no-op, accordingly.
3924   SDValue N = getValue(I.getOperand(0));
3925   auto &TLI = DAG.getTargetLoweringInfo();
3926   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3927                                                         I.getType());
3928   EVT PtrMemVT =
3929       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3930   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3931   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3932   setValue(&I, N);
3933 }
3934 
3935 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3936   // What to do depends on the size of the integer and the size of the pointer.
3937   // We can either truncate, zero extend, or no-op, accordingly.
3938   SDValue N = getValue(I.getOperand(0));
3939   auto &TLI = DAG.getTargetLoweringInfo();
3940   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3941   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3942   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3943   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3944   setValue(&I, N);
3945 }
3946 
3947 void SelectionDAGBuilder::visitBitCast(const User &I) {
3948   SDValue N = getValue(I.getOperand(0));
3949   SDLoc dl = getCurSDLoc();
3950   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3951                                                         I.getType());
3952 
3953   // BitCast assures us that source and destination are the same size so this is
3954   // either a BITCAST or a no-op.
3955   if (DestVT != N.getValueType())
3956     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3957                              DestVT, N)); // convert types.
3958   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3959   // might fold any kind of constant expression to an integer constant and that
3960   // is not what we are looking for. Only recognize a bitcast of a genuine
3961   // constant integer as an opaque constant.
3962   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3963     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3964                                  /*isOpaque*/true));
3965   else
3966     setValue(&I, N);            // noop cast.
3967 }
3968 
3969 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3971   const Value *SV = I.getOperand(0);
3972   SDValue N = getValue(SV);
3973   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3974 
3975   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3976   unsigned DestAS = I.getType()->getPointerAddressSpace();
3977 
3978   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3979     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3980 
3981   setValue(&I, N);
3982 }
3983 
3984 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3986   SDValue InVec = getValue(I.getOperand(0));
3987   SDValue InVal = getValue(I.getOperand(1));
3988   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3989                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3990   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3991                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3992                            InVec, InVal, InIdx));
3993 }
3994 
3995 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3997   SDValue InVec = getValue(I.getOperand(0));
3998   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3999                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4000   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4001                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4002                            InVec, InIdx));
4003 }
4004 
4005 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4006   SDValue Src1 = getValue(I.getOperand(0));
4007   SDValue Src2 = getValue(I.getOperand(1));
4008   ArrayRef<int> Mask;
4009   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4010     Mask = SVI->getShuffleMask();
4011   else
4012     Mask = cast<ConstantExpr>(I).getShuffleMask();
4013   SDLoc DL = getCurSDLoc();
4014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4015   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4016   EVT SrcVT = Src1.getValueType();
4017 
4018   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4019       VT.isScalableVector()) {
4020     // Canonical splat form of first element of first input vector.
4021     SDValue FirstElt =
4022         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4023                     DAG.getVectorIdxConstant(0, DL));
4024     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4025     return;
4026   }
4027 
4028   // For now, we only handle splats for scalable vectors.
4029   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4030   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4031   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4032 
4033   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4034   unsigned MaskNumElts = Mask.size();
4035 
4036   if (SrcNumElts == MaskNumElts) {
4037     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4038     return;
4039   }
4040 
4041   // Normalize the shuffle vector since mask and vector length don't match.
4042   if (SrcNumElts < MaskNumElts) {
4043     // Mask is longer than the source vectors. We can use concatenate vector to
4044     // make the mask and vectors lengths match.
4045 
4046     if (MaskNumElts % SrcNumElts == 0) {
4047       // Mask length is a multiple of the source vector length.
4048       // Check if the shuffle is some kind of concatenation of the input
4049       // vectors.
4050       unsigned NumConcat = MaskNumElts / SrcNumElts;
4051       bool IsConcat = true;
4052       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4053       for (unsigned i = 0; i != MaskNumElts; ++i) {
4054         int Idx = Mask[i];
4055         if (Idx < 0)
4056           continue;
4057         // Ensure the indices in each SrcVT sized piece are sequential and that
4058         // the same source is used for the whole piece.
4059         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4060             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4061              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4062           IsConcat = false;
4063           break;
4064         }
4065         // Remember which source this index came from.
4066         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4067       }
4068 
4069       // The shuffle is concatenating multiple vectors together. Just emit
4070       // a CONCAT_VECTORS operation.
4071       if (IsConcat) {
4072         SmallVector<SDValue, 8> ConcatOps;
4073         for (auto Src : ConcatSrcs) {
4074           if (Src < 0)
4075             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4076           else if (Src == 0)
4077             ConcatOps.push_back(Src1);
4078           else
4079             ConcatOps.push_back(Src2);
4080         }
4081         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4082         return;
4083       }
4084     }
4085 
4086     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4087     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4088     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4089                                     PaddedMaskNumElts);
4090 
4091     // Pad both vectors with undefs to make them the same length as the mask.
4092     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4093 
4094     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4095     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4096     MOps1[0] = Src1;
4097     MOps2[0] = Src2;
4098 
4099     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4100     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4101 
4102     // Readjust mask for new input vector length.
4103     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4104     for (unsigned i = 0; i != MaskNumElts; ++i) {
4105       int Idx = Mask[i];
4106       if (Idx >= (int)SrcNumElts)
4107         Idx -= SrcNumElts - PaddedMaskNumElts;
4108       MappedOps[i] = Idx;
4109     }
4110 
4111     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4112 
4113     // If the concatenated vector was padded, extract a subvector with the
4114     // correct number of elements.
4115     if (MaskNumElts != PaddedMaskNumElts)
4116       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4117                            DAG.getVectorIdxConstant(0, DL));
4118 
4119     setValue(&I, Result);
4120     return;
4121   }
4122 
4123   if (SrcNumElts > MaskNumElts) {
4124     // Analyze the access pattern of the vector to see if we can extract
4125     // two subvectors and do the shuffle.
4126     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4127     bool CanExtract = true;
4128     for (int Idx : Mask) {
4129       unsigned Input = 0;
4130       if (Idx < 0)
4131         continue;
4132 
4133       if (Idx >= (int)SrcNumElts) {
4134         Input = 1;
4135         Idx -= SrcNumElts;
4136       }
4137 
4138       // If all the indices come from the same MaskNumElts sized portion of
4139       // the sources we can use extract. Also make sure the extract wouldn't
4140       // extract past the end of the source.
4141       int NewStartIdx = alignDown(Idx, MaskNumElts);
4142       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4143           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4144         CanExtract = false;
4145       // Make sure we always update StartIdx as we use it to track if all
4146       // elements are undef.
4147       StartIdx[Input] = NewStartIdx;
4148     }
4149 
4150     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4151       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4152       return;
4153     }
4154     if (CanExtract) {
4155       // Extract appropriate subvector and generate a vector shuffle
4156       for (unsigned Input = 0; Input < 2; ++Input) {
4157         SDValue &Src = Input == 0 ? Src1 : Src2;
4158         if (StartIdx[Input] < 0)
4159           Src = DAG.getUNDEF(VT);
4160         else {
4161           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4162                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4163         }
4164       }
4165 
4166       // Calculate new mask.
4167       SmallVector<int, 8> MappedOps(Mask);
4168       for (int &Idx : MappedOps) {
4169         if (Idx >= (int)SrcNumElts)
4170           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4171         else if (Idx >= 0)
4172           Idx -= StartIdx[0];
4173       }
4174 
4175       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4176       return;
4177     }
4178   }
4179 
4180   // We can't use either concat vectors or extract subvectors so fall back to
4181   // replacing the shuffle with extract and build vector.
4182   // to insert and build vector.
4183   EVT EltVT = VT.getVectorElementType();
4184   SmallVector<SDValue,8> Ops;
4185   for (int Idx : Mask) {
4186     SDValue Res;
4187 
4188     if (Idx < 0) {
4189       Res = DAG.getUNDEF(EltVT);
4190     } else {
4191       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4192       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4193 
4194       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4195                         DAG.getVectorIdxConstant(Idx, DL));
4196     }
4197 
4198     Ops.push_back(Res);
4199   }
4200 
4201   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4202 }
4203 
4204 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4205   ArrayRef<unsigned> Indices = I.getIndices();
4206   const Value *Op0 = I.getOperand(0);
4207   const Value *Op1 = I.getOperand(1);
4208   Type *AggTy = I.getType();
4209   Type *ValTy = Op1->getType();
4210   bool IntoUndef = isa<UndefValue>(Op0);
4211   bool FromUndef = isa<UndefValue>(Op1);
4212 
4213   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4214 
4215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4216   SmallVector<EVT, 4> AggValueVTs;
4217   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4218   SmallVector<EVT, 4> ValValueVTs;
4219   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4220 
4221   unsigned NumAggValues = AggValueVTs.size();
4222   unsigned NumValValues = ValValueVTs.size();
4223   SmallVector<SDValue, 4> Values(NumAggValues);
4224 
4225   // Ignore an insertvalue that produces an empty object
4226   if (!NumAggValues) {
4227     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4228     return;
4229   }
4230 
4231   SDValue Agg = getValue(Op0);
4232   unsigned i = 0;
4233   // Copy the beginning value(s) from the original aggregate.
4234   for (; i != LinearIndex; ++i)
4235     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4236                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4237   // Copy values from the inserted value(s).
4238   if (NumValValues) {
4239     SDValue Val = getValue(Op1);
4240     for (; i != LinearIndex + NumValValues; ++i)
4241       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4242                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4243   }
4244   // Copy remaining value(s) from the original aggregate.
4245   for (; i != NumAggValues; ++i)
4246     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4247                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4248 
4249   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4250                            DAG.getVTList(AggValueVTs), Values));
4251 }
4252 
4253 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4254   ArrayRef<unsigned> Indices = I.getIndices();
4255   const Value *Op0 = I.getOperand(0);
4256   Type *AggTy = Op0->getType();
4257   Type *ValTy = I.getType();
4258   bool OutOfUndef = isa<UndefValue>(Op0);
4259 
4260   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4261 
4262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4263   SmallVector<EVT, 4> ValValueVTs;
4264   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4265 
4266   unsigned NumValValues = ValValueVTs.size();
4267 
4268   // Ignore a extractvalue that produces an empty object
4269   if (!NumValValues) {
4270     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4271     return;
4272   }
4273 
4274   SmallVector<SDValue, 4> Values(NumValValues);
4275 
4276   SDValue Agg = getValue(Op0);
4277   // Copy out the selected value(s).
4278   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4279     Values[i - LinearIndex] =
4280       OutOfUndef ?
4281         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4282         SDValue(Agg.getNode(), Agg.getResNo() + i);
4283 
4284   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4285                            DAG.getVTList(ValValueVTs), Values));
4286 }
4287 
4288 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4289   Value *Op0 = I.getOperand(0);
4290   // Note that the pointer operand may be a vector of pointers. Take the scalar
4291   // element which holds a pointer.
4292   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4293   SDValue N = getValue(Op0);
4294   SDLoc dl = getCurSDLoc();
4295   auto &TLI = DAG.getTargetLoweringInfo();
4296   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4297 
4298   // Normalize Vector GEP - all scalar operands should be converted to the
4299   // splat vector.
4300   bool IsVectorGEP = I.getType()->isVectorTy();
4301   ElementCount VectorElementCount =
4302       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4303                   : ElementCount::getFixed(0);
4304 
4305   if (IsVectorGEP && !N.getValueType().isVector()) {
4306     LLVMContext &Context = *DAG.getContext();
4307     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4308     N = DAG.getSplat(VT, dl, N);
4309   }
4310 
4311   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4312        GTI != E; ++GTI) {
4313     const Value *Idx = GTI.getOperand();
4314     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4315       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4316       if (Field) {
4317         // N = N + Offset
4318         uint64_t Offset =
4319             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4320 
4321         // In an inbounds GEP with an offset that is nonnegative even when
4322         // interpreted as signed, assume there is no unsigned overflow.
4323         SDNodeFlags Flags;
4324         if (NW.hasNoUnsignedWrap() ||
4325             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4326           Flags.setNoUnsignedWrap(true);
4327 
4328         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4329                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4330       }
4331     } else {
4332       // IdxSize is the width of the arithmetic according to IR semantics.
4333       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4334       // (and fix up the result later).
4335       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4336       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4337       TypeSize ElementSize =
4338           GTI.getSequentialElementStride(DAG.getDataLayout());
4339       // We intentionally mask away the high bits here; ElementSize may not
4340       // fit in IdxTy.
4341       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4342       bool ElementScalable = ElementSize.isScalable();
4343 
4344       // If this is a scalar constant or a splat vector of constants,
4345       // handle it quickly.
4346       const auto *C = dyn_cast<Constant>(Idx);
4347       if (C && isa<VectorType>(C->getType()))
4348         C = C->getSplatValue();
4349 
4350       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4351       if (CI && CI->isZero())
4352         continue;
4353       if (CI && !ElementScalable) {
4354         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4355         LLVMContext &Context = *DAG.getContext();
4356         SDValue OffsVal;
4357         if (IsVectorGEP)
4358           OffsVal = DAG.getConstant(
4359               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4360         else
4361           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4362 
4363         // In an inbounds GEP with an offset that is nonnegative even when
4364         // interpreted as signed, assume there is no unsigned overflow.
4365         SDNodeFlags Flags;
4366         if (NW.hasNoUnsignedWrap() ||
4367             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4368           Flags.setNoUnsignedWrap(true);
4369 
4370         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4371 
4372         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4373         continue;
4374       }
4375 
4376       // N = N + Idx * ElementMul;
4377       SDValue IdxN = getValue(Idx);
4378 
4379       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4380         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4381                                   VectorElementCount);
4382         IdxN = DAG.getSplat(VT, dl, IdxN);
4383       }
4384 
4385       // If the index is smaller or larger than intptr_t, truncate or extend
4386       // it.
4387       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4388 
4389       if (ElementScalable) {
4390         EVT VScaleTy = N.getValueType().getScalarType();
4391         SDValue VScale = DAG.getNode(
4392             ISD::VSCALE, dl, VScaleTy,
4393             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4394         if (IsVectorGEP)
4395           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4396         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4397       } else {
4398         // If this is a multiply by a power of two, turn it into a shl
4399         // immediately.  This is a very common case.
4400         if (ElementMul != 1) {
4401           if (ElementMul.isPowerOf2()) {
4402             unsigned Amt = ElementMul.logBase2();
4403             IdxN = DAG.getNode(ISD::SHL, dl,
4404                                N.getValueType(), IdxN,
4405                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4406           } else {
4407             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4408                                             IdxN.getValueType());
4409             IdxN = DAG.getNode(ISD::MUL, dl,
4410                                N.getValueType(), IdxN, Scale);
4411           }
4412         }
4413       }
4414 
4415       N = DAG.getNode(ISD::ADD, dl,
4416                       N.getValueType(), N, IdxN);
4417     }
4418   }
4419 
4420   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4421   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4422   if (IsVectorGEP) {
4423     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4424     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4425   }
4426 
4427   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4428     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4429 
4430   setValue(&I, N);
4431 }
4432 
4433 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4434   // If this is a fixed sized alloca in the entry block of the function,
4435   // allocate it statically on the stack.
4436   if (FuncInfo.StaticAllocaMap.count(&I))
4437     return;   // getValue will auto-populate this.
4438 
4439   SDLoc dl = getCurSDLoc();
4440   Type *Ty = I.getAllocatedType();
4441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4442   auto &DL = DAG.getDataLayout();
4443   TypeSize TySize = DL.getTypeAllocSize(Ty);
4444   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4445 
4446   SDValue AllocSize = getValue(I.getArraySize());
4447 
4448   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4449   if (AllocSize.getValueType() != IntPtr)
4450     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4451 
4452   if (TySize.isScalable())
4453     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4454                             DAG.getVScale(dl, IntPtr,
4455                                           APInt(IntPtr.getScalarSizeInBits(),
4456                                                 TySize.getKnownMinValue())));
4457   else {
4458     SDValue TySizeValue =
4459         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4460     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4461                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4462   }
4463 
4464   // Handle alignment.  If the requested alignment is less than or equal to
4465   // the stack alignment, ignore it.  If the size is greater than or equal to
4466   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4467   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4468   if (*Alignment <= StackAlign)
4469     Alignment = std::nullopt;
4470 
4471   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4472   // Round the size of the allocation up to the stack alignment size
4473   // by add SA-1 to the size. This doesn't overflow because we're computing
4474   // an address inside an alloca.
4475   SDNodeFlags Flags;
4476   Flags.setNoUnsignedWrap(true);
4477   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4478                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4479 
4480   // Mask out the low bits for alignment purposes.
4481   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4482                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4483 
4484   SDValue Ops[] = {
4485       getRoot(), AllocSize,
4486       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4487   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4488   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4489   setValue(&I, DSA);
4490   DAG.setRoot(DSA.getValue(1));
4491 
4492   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4493 }
4494 
4495 static const MDNode *getRangeMetadata(const Instruction &I) {
4496   // If !noundef is not present, then !range violation results in a poison
4497   // value rather than immediate undefined behavior. In theory, transferring
4498   // these annotations to SDAG is fine, but in practice there are key SDAG
4499   // transforms that are known not to be poison-safe, such as folding logical
4500   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4501   // also present.
4502   if (!I.hasMetadata(LLVMContext::MD_noundef))
4503     return nullptr;
4504   return I.getMetadata(LLVMContext::MD_range);
4505 }
4506 
4507 static std::optional<ConstantRange> getRange(const Instruction &I) {
4508   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4509     // see comment in getRangeMetadata about this check
4510     if (CB->hasRetAttr(Attribute::NoUndef))
4511       return CB->getRange();
4512   }
4513   if (const MDNode *Range = getRangeMetadata(I))
4514     return getConstantRangeFromMetadata(*Range);
4515   return std::nullopt;
4516 }
4517 
4518 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4519   if (I.isAtomic())
4520     return visitAtomicLoad(I);
4521 
4522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4523   const Value *SV = I.getOperand(0);
4524   if (TLI.supportSwiftError()) {
4525     // Swifterror values can come from either a function parameter with
4526     // swifterror attribute or an alloca with swifterror attribute.
4527     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4528       if (Arg->hasSwiftErrorAttr())
4529         return visitLoadFromSwiftError(I);
4530     }
4531 
4532     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4533       if (Alloca->isSwiftError())
4534         return visitLoadFromSwiftError(I);
4535     }
4536   }
4537 
4538   SDValue Ptr = getValue(SV);
4539 
4540   Type *Ty = I.getType();
4541   SmallVector<EVT, 4> ValueVTs, MemVTs;
4542   SmallVector<TypeSize, 4> Offsets;
4543   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4544   unsigned NumValues = ValueVTs.size();
4545   if (NumValues == 0)
4546     return;
4547 
4548   Align Alignment = I.getAlign();
4549   AAMDNodes AAInfo = I.getAAMetadata();
4550   const MDNode *Ranges = getRangeMetadata(I);
4551   bool isVolatile = I.isVolatile();
4552   MachineMemOperand::Flags MMOFlags =
4553       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4554 
4555   SDValue Root;
4556   bool ConstantMemory = false;
4557   if (isVolatile)
4558     // Serialize volatile loads with other side effects.
4559     Root = getRoot();
4560   else if (NumValues > MaxParallelChains)
4561     Root = getMemoryRoot();
4562   else if (AA &&
4563            AA->pointsToConstantMemory(MemoryLocation(
4564                SV,
4565                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4566                AAInfo))) {
4567     // Do not serialize (non-volatile) loads of constant memory with anything.
4568     Root = DAG.getEntryNode();
4569     ConstantMemory = true;
4570     MMOFlags |= MachineMemOperand::MOInvariant;
4571   } else {
4572     // Do not serialize non-volatile loads against each other.
4573     Root = DAG.getRoot();
4574   }
4575 
4576   SDLoc dl = getCurSDLoc();
4577 
4578   if (isVolatile)
4579     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4580 
4581   SmallVector<SDValue, 4> Values(NumValues);
4582   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4583 
4584   unsigned ChainI = 0;
4585   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4586     // Serializing loads here may result in excessive register pressure, and
4587     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4588     // could recover a bit by hoisting nodes upward in the chain by recognizing
4589     // they are side-effect free or do not alias. The optimizer should really
4590     // avoid this case by converting large object/array copies to llvm.memcpy
4591     // (MaxParallelChains should always remain as failsafe).
4592     if (ChainI == MaxParallelChains) {
4593       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4594       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4595                                   ArrayRef(Chains.data(), ChainI));
4596       Root = Chain;
4597       ChainI = 0;
4598     }
4599 
4600     // TODO: MachinePointerInfo only supports a fixed length offset.
4601     MachinePointerInfo PtrInfo =
4602         !Offsets[i].isScalable() || Offsets[i].isZero()
4603             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4604             : MachinePointerInfo();
4605 
4606     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4607     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4608                             MMOFlags, AAInfo, Ranges);
4609     Chains[ChainI] = L.getValue(1);
4610 
4611     if (MemVTs[i] != ValueVTs[i])
4612       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4613 
4614     Values[i] = L;
4615   }
4616 
4617   if (!ConstantMemory) {
4618     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4619                                 ArrayRef(Chains.data(), ChainI));
4620     if (isVolatile)
4621       DAG.setRoot(Chain);
4622     else
4623       PendingLoads.push_back(Chain);
4624   }
4625 
4626   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4627                            DAG.getVTList(ValueVTs), Values));
4628 }
4629 
4630 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4631   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4632          "call visitStoreToSwiftError when backend supports swifterror");
4633 
4634   SmallVector<EVT, 4> ValueVTs;
4635   SmallVector<uint64_t, 4> Offsets;
4636   const Value *SrcV = I.getOperand(0);
4637   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4638                   SrcV->getType(), ValueVTs, &Offsets, 0);
4639   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4640          "expect a single EVT for swifterror");
4641 
4642   SDValue Src = getValue(SrcV);
4643   // Create a virtual register, then update the virtual register.
4644   Register VReg =
4645       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4646   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4647   // Chain can be getRoot or getControlRoot.
4648   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4649                                       SDValue(Src.getNode(), Src.getResNo()));
4650   DAG.setRoot(CopyNode);
4651 }
4652 
4653 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4654   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4655          "call visitLoadFromSwiftError when backend supports swifterror");
4656 
4657   assert(!I.isVolatile() &&
4658          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4659          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4660          "Support volatile, non temporal, invariant for load_from_swift_error");
4661 
4662   const Value *SV = I.getOperand(0);
4663   Type *Ty = I.getType();
4664   assert(
4665       (!AA ||
4666        !AA->pointsToConstantMemory(MemoryLocation(
4667            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4668            I.getAAMetadata()))) &&
4669       "load_from_swift_error should not be constant memory");
4670 
4671   SmallVector<EVT, 4> ValueVTs;
4672   SmallVector<uint64_t, 4> Offsets;
4673   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4674                   ValueVTs, &Offsets, 0);
4675   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4676          "expect a single EVT for swifterror");
4677 
4678   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4679   SDValue L = DAG.getCopyFromReg(
4680       getRoot(), getCurSDLoc(),
4681       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4682 
4683   setValue(&I, L);
4684 }
4685 
4686 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4687   if (I.isAtomic())
4688     return visitAtomicStore(I);
4689 
4690   const Value *SrcV = I.getOperand(0);
4691   const Value *PtrV = I.getOperand(1);
4692 
4693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4694   if (TLI.supportSwiftError()) {
4695     // Swifterror values can come from either a function parameter with
4696     // swifterror attribute or an alloca with swifterror attribute.
4697     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4698       if (Arg->hasSwiftErrorAttr())
4699         return visitStoreToSwiftError(I);
4700     }
4701 
4702     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4703       if (Alloca->isSwiftError())
4704         return visitStoreToSwiftError(I);
4705     }
4706   }
4707 
4708   SmallVector<EVT, 4> ValueVTs, MemVTs;
4709   SmallVector<TypeSize, 4> Offsets;
4710   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4711                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4712   unsigned NumValues = ValueVTs.size();
4713   if (NumValues == 0)
4714     return;
4715 
4716   // Get the lowered operands. Note that we do this after
4717   // checking if NumResults is zero, because with zero results
4718   // the operands won't have values in the map.
4719   SDValue Src = getValue(SrcV);
4720   SDValue Ptr = getValue(PtrV);
4721 
4722   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4723   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4724   SDLoc dl = getCurSDLoc();
4725   Align Alignment = I.getAlign();
4726   AAMDNodes AAInfo = I.getAAMetadata();
4727 
4728   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4729 
4730   unsigned ChainI = 0;
4731   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4732     // See visitLoad comments.
4733     if (ChainI == MaxParallelChains) {
4734       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4735                                   ArrayRef(Chains.data(), ChainI));
4736       Root = Chain;
4737       ChainI = 0;
4738     }
4739 
4740     // TODO: MachinePointerInfo only supports a fixed length offset.
4741     MachinePointerInfo PtrInfo =
4742         !Offsets[i].isScalable() || Offsets[i].isZero()
4743             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4744             : MachinePointerInfo();
4745 
4746     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4747     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4748     if (MemVTs[i] != ValueVTs[i])
4749       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4750     SDValue St =
4751         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4752     Chains[ChainI] = St;
4753   }
4754 
4755   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4756                                   ArrayRef(Chains.data(), ChainI));
4757   setValue(&I, StoreNode);
4758   DAG.setRoot(StoreNode);
4759 }
4760 
4761 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4762                                            bool IsCompressing) {
4763   SDLoc sdl = getCurSDLoc();
4764 
4765   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4766                                Align &Alignment) {
4767     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4768     Src0 = I.getArgOperand(0);
4769     Ptr = I.getArgOperand(1);
4770     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4771     Mask = I.getArgOperand(3);
4772   };
4773   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4774                                     Align &Alignment) {
4775     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4776     Src0 = I.getArgOperand(0);
4777     Ptr = I.getArgOperand(1);
4778     Mask = I.getArgOperand(2);
4779     Alignment = I.getParamAlign(1).valueOrOne();
4780   };
4781 
4782   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4783   Align Alignment;
4784   if (IsCompressing)
4785     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4786   else
4787     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4788 
4789   SDValue Ptr = getValue(PtrOperand);
4790   SDValue Src0 = getValue(Src0Operand);
4791   SDValue Mask = getValue(MaskOperand);
4792   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4793 
4794   EVT VT = Src0.getValueType();
4795 
4796   auto MMOFlags = MachineMemOperand::MOStore;
4797   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4798     MMOFlags |= MachineMemOperand::MONonTemporal;
4799 
4800   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4801       MachinePointerInfo(PtrOperand), MMOFlags,
4802       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4803 
4804   const auto &TLI = DAG.getTargetLoweringInfo();
4805   const auto &TTI =
4806       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4807   SDValue StoreNode =
4808       !IsCompressing &&
4809               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4810           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4811                                  Mask)
4812           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4813                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4814                                IsCompressing);
4815   DAG.setRoot(StoreNode);
4816   setValue(&I, StoreNode);
4817 }
4818 
4819 // Get a uniform base for the Gather/Scatter intrinsic.
4820 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4821 // We try to represent it as a base pointer + vector of indices.
4822 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4823 // The first operand of the GEP may be a single pointer or a vector of pointers
4824 // Example:
4825 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4826 //  or
4827 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4828 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4829 //
4830 // When the first GEP operand is a single pointer - it is the uniform base we
4831 // are looking for. If first operand of the GEP is a splat vector - we
4832 // extract the splat value and use it as a uniform base.
4833 // In all other cases the function returns 'false'.
4834 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4835                            ISD::MemIndexType &IndexType, SDValue &Scale,
4836                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4837                            uint64_t ElemSize) {
4838   SelectionDAG& DAG = SDB->DAG;
4839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4840   const DataLayout &DL = DAG.getDataLayout();
4841 
4842   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4843 
4844   // Handle splat constant pointer.
4845   if (auto *C = dyn_cast<Constant>(Ptr)) {
4846     C = C->getSplatValue();
4847     if (!C)
4848       return false;
4849 
4850     Base = SDB->getValue(C);
4851 
4852     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4853     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4854     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4855     IndexType = ISD::SIGNED_SCALED;
4856     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4857     return true;
4858   }
4859 
4860   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4861   if (!GEP || GEP->getParent() != CurBB)
4862     return false;
4863 
4864   if (GEP->getNumOperands() != 2)
4865     return false;
4866 
4867   const Value *BasePtr = GEP->getPointerOperand();
4868   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4869 
4870   // Make sure the base is scalar and the index is a vector.
4871   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4872     return false;
4873 
4874   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4875   if (ScaleVal.isScalable())
4876     return false;
4877 
4878   // Target may not support the required addressing mode.
4879   if (ScaleVal != 1 &&
4880       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4881     return false;
4882 
4883   Base = SDB->getValue(BasePtr);
4884   Index = SDB->getValue(IndexVal);
4885   IndexType = ISD::SIGNED_SCALED;
4886 
4887   Scale =
4888       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4889   return true;
4890 }
4891 
4892 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4893   SDLoc sdl = getCurSDLoc();
4894 
4895   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4896   const Value *Ptr = I.getArgOperand(1);
4897   SDValue Src0 = getValue(I.getArgOperand(0));
4898   SDValue Mask = getValue(I.getArgOperand(3));
4899   EVT VT = Src0.getValueType();
4900   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4901                         ->getMaybeAlignValue()
4902                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4904 
4905   SDValue Base;
4906   SDValue Index;
4907   ISD::MemIndexType IndexType;
4908   SDValue Scale;
4909   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4910                                     I.getParent(), VT.getScalarStoreSize());
4911 
4912   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4913   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4914       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4915       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4916   if (!UniformBase) {
4917     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4918     Index = getValue(Ptr);
4919     IndexType = ISD::SIGNED_SCALED;
4920     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4921   }
4922 
4923   EVT IdxVT = Index.getValueType();
4924   EVT EltTy = IdxVT.getVectorElementType();
4925   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4926     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4927     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4928   }
4929 
4930   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4931   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4932                                          Ops, MMO, IndexType, false);
4933   DAG.setRoot(Scatter);
4934   setValue(&I, Scatter);
4935 }
4936 
4937 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4938   SDLoc sdl = getCurSDLoc();
4939 
4940   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4941                               Align &Alignment) {
4942     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4943     Ptr = I.getArgOperand(0);
4944     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4945     Mask = I.getArgOperand(2);
4946     Src0 = I.getArgOperand(3);
4947   };
4948   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4949                                  Align &Alignment) {
4950     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4951     Ptr = I.getArgOperand(0);
4952     Alignment = I.getParamAlign(0).valueOrOne();
4953     Mask = I.getArgOperand(1);
4954     Src0 = I.getArgOperand(2);
4955   };
4956 
4957   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4958   Align Alignment;
4959   if (IsExpanding)
4960     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4961   else
4962     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4963 
4964   SDValue Ptr = getValue(PtrOperand);
4965   SDValue Src0 = getValue(Src0Operand);
4966   SDValue Mask = getValue(MaskOperand);
4967   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4968 
4969   EVT VT = Src0.getValueType();
4970   AAMDNodes AAInfo = I.getAAMetadata();
4971   const MDNode *Ranges = getRangeMetadata(I);
4972 
4973   // Do not serialize masked loads of constant memory with anything.
4974   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4975   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4976 
4977   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4978 
4979   auto MMOFlags = MachineMemOperand::MOLoad;
4980   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4981     MMOFlags |= MachineMemOperand::MONonTemporal;
4982 
4983   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4984       MachinePointerInfo(PtrOperand), MMOFlags,
4985       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4986 
4987   const auto &TLI = DAG.getTargetLoweringInfo();
4988   const auto &TTI =
4989       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4990   // The Load/Res may point to different values and both of them are output
4991   // variables.
4992   SDValue Load;
4993   SDValue Res;
4994   if (!IsExpanding &&
4995       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4996     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4997   else
4998     Res = Load =
4999         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5000                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5001   if (AddToChain)
5002     PendingLoads.push_back(Load.getValue(1));
5003   setValue(&I, Res);
5004 }
5005 
5006 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5007   SDLoc sdl = getCurSDLoc();
5008 
5009   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5010   const Value *Ptr = I.getArgOperand(0);
5011   SDValue Src0 = getValue(I.getArgOperand(3));
5012   SDValue Mask = getValue(I.getArgOperand(2));
5013 
5014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5015   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5016   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5017                         ->getMaybeAlignValue()
5018                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5019 
5020   const MDNode *Ranges = getRangeMetadata(I);
5021 
5022   SDValue Root = DAG.getRoot();
5023   SDValue Base;
5024   SDValue Index;
5025   ISD::MemIndexType IndexType;
5026   SDValue Scale;
5027   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5028                                     I.getParent(), VT.getScalarStoreSize());
5029   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5030   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5031       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5032       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5033       Ranges);
5034 
5035   if (!UniformBase) {
5036     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5037     Index = getValue(Ptr);
5038     IndexType = ISD::SIGNED_SCALED;
5039     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5040   }
5041 
5042   EVT IdxVT = Index.getValueType();
5043   EVT EltTy = IdxVT.getVectorElementType();
5044   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5045     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5046     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5047   }
5048 
5049   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5050   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5051                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5052 
5053   PendingLoads.push_back(Gather.getValue(1));
5054   setValue(&I, Gather);
5055 }
5056 
5057 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5058   SDLoc dl = getCurSDLoc();
5059   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5060   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5061   SyncScope::ID SSID = I.getSyncScopeID();
5062 
5063   SDValue InChain = getRoot();
5064 
5065   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5066   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5067 
5068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5069   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5070 
5071   MachineFunction &MF = DAG.getMachineFunction();
5072   MachineMemOperand *MMO = MF.getMachineMemOperand(
5073       MachinePointerInfo(I.getPointerOperand()), Flags,
5074       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5075       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5076 
5077   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5078                                    dl, MemVT, VTs, InChain,
5079                                    getValue(I.getPointerOperand()),
5080                                    getValue(I.getCompareOperand()),
5081                                    getValue(I.getNewValOperand()), MMO);
5082 
5083   SDValue OutChain = L.getValue(2);
5084 
5085   setValue(&I, L);
5086   DAG.setRoot(OutChain);
5087 }
5088 
5089 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5090   SDLoc dl = getCurSDLoc();
5091   ISD::NodeType NT;
5092   switch (I.getOperation()) {
5093   default: llvm_unreachable("Unknown atomicrmw operation");
5094   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5095   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5096   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5097   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5098   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5099   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5100   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5101   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5102   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5103   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5104   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5105   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5106   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5107   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5108   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5109   case AtomicRMWInst::UIncWrap:
5110     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5111     break;
5112   case AtomicRMWInst::UDecWrap:
5113     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5114     break;
5115   }
5116   AtomicOrdering Ordering = I.getOrdering();
5117   SyncScope::ID SSID = I.getSyncScopeID();
5118 
5119   SDValue InChain = getRoot();
5120 
5121   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5123   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5124 
5125   MachineFunction &MF = DAG.getMachineFunction();
5126   MachineMemOperand *MMO = MF.getMachineMemOperand(
5127       MachinePointerInfo(I.getPointerOperand()), Flags,
5128       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5129       AAMDNodes(), nullptr, SSID, Ordering);
5130 
5131   SDValue L =
5132     DAG.getAtomic(NT, dl, MemVT, InChain,
5133                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5134                   MMO);
5135 
5136   SDValue OutChain = L.getValue(1);
5137 
5138   setValue(&I, L);
5139   DAG.setRoot(OutChain);
5140 }
5141 
5142 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5143   SDLoc dl = getCurSDLoc();
5144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5145   SDValue Ops[3];
5146   Ops[0] = getRoot();
5147   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5148                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5149   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5150                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5151   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5152   setValue(&I, N);
5153   DAG.setRoot(N);
5154 }
5155 
5156 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5157   SDLoc dl = getCurSDLoc();
5158   AtomicOrdering Order = I.getOrdering();
5159   SyncScope::ID SSID = I.getSyncScopeID();
5160 
5161   SDValue InChain = getRoot();
5162 
5163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5164   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5165   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5166 
5167   if (!TLI.supportsUnalignedAtomics() &&
5168       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5169     report_fatal_error("Cannot generate unaligned atomic load");
5170 
5171   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5172 
5173   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5174       MachinePointerInfo(I.getPointerOperand()), Flags,
5175       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5176       nullptr, SSID, Order);
5177 
5178   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5179 
5180   SDValue Ptr = getValue(I.getPointerOperand());
5181   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5182                             Ptr, MMO);
5183 
5184   SDValue OutChain = L.getValue(1);
5185   if (MemVT != VT)
5186     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5187 
5188   setValue(&I, L);
5189   DAG.setRoot(OutChain);
5190 }
5191 
5192 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5193   SDLoc dl = getCurSDLoc();
5194 
5195   AtomicOrdering Ordering = I.getOrdering();
5196   SyncScope::ID SSID = I.getSyncScopeID();
5197 
5198   SDValue InChain = getRoot();
5199 
5200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5201   EVT MemVT =
5202       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5203 
5204   if (!TLI.supportsUnalignedAtomics() &&
5205       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5206     report_fatal_error("Cannot generate unaligned atomic store");
5207 
5208   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5209 
5210   MachineFunction &MF = DAG.getMachineFunction();
5211   MachineMemOperand *MMO = MF.getMachineMemOperand(
5212       MachinePointerInfo(I.getPointerOperand()), Flags,
5213       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5214       nullptr, SSID, Ordering);
5215 
5216   SDValue Val = getValue(I.getValueOperand());
5217   if (Val.getValueType() != MemVT)
5218     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5219   SDValue Ptr = getValue(I.getPointerOperand());
5220 
5221   SDValue OutChain =
5222       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5223 
5224   setValue(&I, OutChain);
5225   DAG.setRoot(OutChain);
5226 }
5227 
5228 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5229 /// node.
5230 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5231                                                unsigned Intrinsic) {
5232   // Ignore the callsite's attributes. A specific call site may be marked with
5233   // readnone, but the lowering code will expect the chain based on the
5234   // definition.
5235   const Function *F = I.getCalledFunction();
5236   bool HasChain = !F->doesNotAccessMemory();
5237   bool OnlyLoad =
5238       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5239 
5240   // Build the operand list.
5241   SmallVector<SDValue, 8> Ops;
5242   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5243     if (OnlyLoad) {
5244       // We don't need to serialize loads against other loads.
5245       Ops.push_back(DAG.getRoot());
5246     } else {
5247       Ops.push_back(getRoot());
5248     }
5249   }
5250 
5251   // Info is set by getTgtMemIntrinsic
5252   TargetLowering::IntrinsicInfo Info;
5253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5254   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5255                                                DAG.getMachineFunction(),
5256                                                Intrinsic);
5257 
5258   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5259   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5260       Info.opc == ISD::INTRINSIC_W_CHAIN)
5261     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5262                                         TLI.getPointerTy(DAG.getDataLayout())));
5263 
5264   // Add all operands of the call to the operand list.
5265   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5266     const Value *Arg = I.getArgOperand(i);
5267     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5268       Ops.push_back(getValue(Arg));
5269       continue;
5270     }
5271 
5272     // Use TargetConstant instead of a regular constant for immarg.
5273     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5274     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5275       assert(CI->getBitWidth() <= 64 &&
5276              "large intrinsic immediates not handled");
5277       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5278     } else {
5279       Ops.push_back(
5280           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5281     }
5282   }
5283 
5284   SmallVector<EVT, 4> ValueVTs;
5285   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5286 
5287   if (HasChain)
5288     ValueVTs.push_back(MVT::Other);
5289 
5290   SDVTList VTs = DAG.getVTList(ValueVTs);
5291 
5292   // Propagate fast-math-flags from IR to node(s).
5293   SDNodeFlags Flags;
5294   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5295     Flags.copyFMF(*FPMO);
5296   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5297 
5298   // Create the node.
5299   SDValue Result;
5300 
5301   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5302     auto *Token = Bundle->Inputs[0].get();
5303     SDValue ConvControlToken = getValue(Token);
5304     assert(Ops.back().getValueType() != MVT::Glue &&
5305            "Did not expected another glue node here.");
5306     ConvControlToken =
5307         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5308     Ops.push_back(ConvControlToken);
5309   }
5310 
5311   // In some cases, custom collection of operands from CallInst I may be needed.
5312   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5313   if (IsTgtIntrinsic) {
5314     // This is target intrinsic that touches memory
5315     //
5316     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5317     //       didn't yield anything useful.
5318     MachinePointerInfo MPI;
5319     if (Info.ptrVal)
5320       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5321     else if (Info.fallbackAddressSpace)
5322       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5323     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5324                                      Info.memVT, MPI, Info.align, Info.flags,
5325                                      Info.size, I.getAAMetadata());
5326   } else if (!HasChain) {
5327     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5328   } else if (!I.getType()->isVoidTy()) {
5329     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5330   } else {
5331     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5332   }
5333 
5334   if (HasChain) {
5335     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5336     if (OnlyLoad)
5337       PendingLoads.push_back(Chain);
5338     else
5339       DAG.setRoot(Chain);
5340   }
5341 
5342   if (!I.getType()->isVoidTy()) {
5343     if (!isa<VectorType>(I.getType()))
5344       Result = lowerRangeToAssertZExt(DAG, I, Result);
5345 
5346     MaybeAlign Alignment = I.getRetAlign();
5347 
5348     // Insert `assertalign` node if there's an alignment.
5349     if (InsertAssertAlign && Alignment) {
5350       Result =
5351           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5352     }
5353   }
5354 
5355   setValue(&I, Result);
5356 }
5357 
5358 /// GetSignificand - Get the significand and build it into a floating-point
5359 /// number with exponent of 1:
5360 ///
5361 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5362 ///
5363 /// where Op is the hexadecimal representation of floating point value.
5364 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5365   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5366                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5367   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5368                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5369   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5370 }
5371 
5372 /// GetExponent - Get the exponent:
5373 ///
5374 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5375 ///
5376 /// where Op is the hexadecimal representation of floating point value.
5377 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5378                            const TargetLowering &TLI, const SDLoc &dl) {
5379   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5380                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5381   SDValue t1 = DAG.getNode(
5382       ISD::SRL, dl, MVT::i32, t0,
5383       DAG.getConstant(23, dl,
5384                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5385   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5386                            DAG.getConstant(127, dl, MVT::i32));
5387   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5388 }
5389 
5390 /// getF32Constant - Get 32-bit floating point constant.
5391 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5392                               const SDLoc &dl) {
5393   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5394                            MVT::f32);
5395 }
5396 
5397 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5398                                        SelectionDAG &DAG) {
5399   // TODO: What fast-math-flags should be set on the floating-point nodes?
5400 
5401   //   IntegerPartOfX = ((int32_t)(t0);
5402   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5403 
5404   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5405   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5406   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5407 
5408   //   IntegerPartOfX <<= 23;
5409   IntegerPartOfX =
5410       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5411                   DAG.getConstant(23, dl,
5412                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5413                                       MVT::i32, DAG.getDataLayout())));
5414 
5415   SDValue TwoToFractionalPartOfX;
5416   if (LimitFloatPrecision <= 6) {
5417     // For floating-point precision of 6:
5418     //
5419     //   TwoToFractionalPartOfX =
5420     //     0.997535578f +
5421     //       (0.735607626f + 0.252464424f * x) * x;
5422     //
5423     // error 0.0144103317, which is 6 bits
5424     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5425                              getF32Constant(DAG, 0x3e814304, dl));
5426     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5427                              getF32Constant(DAG, 0x3f3c50c8, dl));
5428     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5429     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5430                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5431   } else if (LimitFloatPrecision <= 12) {
5432     // For floating-point precision of 12:
5433     //
5434     //   TwoToFractionalPartOfX =
5435     //     0.999892986f +
5436     //       (0.696457318f +
5437     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5438     //
5439     // error 0.000107046256, which is 13 to 14 bits
5440     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5441                              getF32Constant(DAG, 0x3da235e3, dl));
5442     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5443                              getF32Constant(DAG, 0x3e65b8f3, dl));
5444     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5445     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5446                              getF32Constant(DAG, 0x3f324b07, dl));
5447     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5448     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5449                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5450   } else { // LimitFloatPrecision <= 18
5451     // For floating-point precision of 18:
5452     //
5453     //   TwoToFractionalPartOfX =
5454     //     0.999999982f +
5455     //       (0.693148872f +
5456     //         (0.240227044f +
5457     //           (0.554906021e-1f +
5458     //             (0.961591928e-2f +
5459     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5460     // error 2.47208000*10^(-7), which is better than 18 bits
5461     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5462                              getF32Constant(DAG, 0x3924b03e, dl));
5463     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5464                              getF32Constant(DAG, 0x3ab24b87, dl));
5465     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5466     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5467                              getF32Constant(DAG, 0x3c1d8c17, dl));
5468     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5469     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5470                              getF32Constant(DAG, 0x3d634a1d, dl));
5471     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5472     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5473                              getF32Constant(DAG, 0x3e75fe14, dl));
5474     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5475     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5476                               getF32Constant(DAG, 0x3f317234, dl));
5477     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5478     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5479                                          getF32Constant(DAG, 0x3f800000, dl));
5480   }
5481 
5482   // Add the exponent into the result in integer domain.
5483   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5484   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5485                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5486 }
5487 
5488 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5489 /// limited-precision mode.
5490 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5491                          const TargetLowering &TLI, SDNodeFlags Flags) {
5492   if (Op.getValueType() == MVT::f32 &&
5493       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5494 
5495     // Put the exponent in the right bit position for later addition to the
5496     // final result:
5497     //
5498     // t0 = Op * log2(e)
5499 
5500     // TODO: What fast-math-flags should be set here?
5501     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5502                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5503     return getLimitedPrecisionExp2(t0, dl, DAG);
5504   }
5505 
5506   // No special expansion.
5507   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5508 }
5509 
5510 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5511 /// limited-precision mode.
5512 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5513                          const TargetLowering &TLI, SDNodeFlags Flags) {
5514   // TODO: What fast-math-flags should be set on the floating-point nodes?
5515 
5516   if (Op.getValueType() == MVT::f32 &&
5517       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5518     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5519 
5520     // Scale the exponent by log(2).
5521     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5522     SDValue LogOfExponent =
5523         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5524                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5525 
5526     // Get the significand and build it into a floating-point number with
5527     // exponent of 1.
5528     SDValue X = GetSignificand(DAG, Op1, dl);
5529 
5530     SDValue LogOfMantissa;
5531     if (LimitFloatPrecision <= 6) {
5532       // For floating-point precision of 6:
5533       //
5534       //   LogofMantissa =
5535       //     -1.1609546f +
5536       //       (1.4034025f - 0.23903021f * x) * x;
5537       //
5538       // error 0.0034276066, which is better than 8 bits
5539       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5540                                getF32Constant(DAG, 0xbe74c456, dl));
5541       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5542                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5543       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5544       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5545                                   getF32Constant(DAG, 0x3f949a29, dl));
5546     } else if (LimitFloatPrecision <= 12) {
5547       // For floating-point precision of 12:
5548       //
5549       //   LogOfMantissa =
5550       //     -1.7417939f +
5551       //       (2.8212026f +
5552       //         (-1.4699568f +
5553       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5554       //
5555       // error 0.000061011436, which is 14 bits
5556       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5557                                getF32Constant(DAG, 0xbd67b6d6, dl));
5558       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5559                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5560       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5561       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5562                                getF32Constant(DAG, 0x3fbc278b, dl));
5563       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5564       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5565                                getF32Constant(DAG, 0x40348e95, dl));
5566       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5567       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5568                                   getF32Constant(DAG, 0x3fdef31a, dl));
5569     } else { // LimitFloatPrecision <= 18
5570       // For floating-point precision of 18:
5571       //
5572       //   LogOfMantissa =
5573       //     -2.1072184f +
5574       //       (4.2372794f +
5575       //         (-3.7029485f +
5576       //           (2.2781945f +
5577       //             (-0.87823314f +
5578       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5579       //
5580       // error 0.0000023660568, which is better than 18 bits
5581       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5582                                getF32Constant(DAG, 0xbc91e5ac, dl));
5583       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5584                                getF32Constant(DAG, 0x3e4350aa, dl));
5585       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5586       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5587                                getF32Constant(DAG, 0x3f60d3e3, dl));
5588       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5589       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5590                                getF32Constant(DAG, 0x4011cdf0, dl));
5591       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5592       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5593                                getF32Constant(DAG, 0x406cfd1c, dl));
5594       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5595       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5596                                getF32Constant(DAG, 0x408797cb, dl));
5597       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5598       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5599                                   getF32Constant(DAG, 0x4006dcab, dl));
5600     }
5601 
5602     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5603   }
5604 
5605   // No special expansion.
5606   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5607 }
5608 
5609 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5610 /// limited-precision mode.
5611 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5612                           const TargetLowering &TLI, SDNodeFlags Flags) {
5613   // TODO: What fast-math-flags should be set on the floating-point nodes?
5614 
5615   if (Op.getValueType() == MVT::f32 &&
5616       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5617     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5618 
5619     // Get the exponent.
5620     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5621 
5622     // Get the significand and build it into a floating-point number with
5623     // exponent of 1.
5624     SDValue X = GetSignificand(DAG, Op1, dl);
5625 
5626     // Different possible minimax approximations of significand in
5627     // floating-point for various degrees of accuracy over [1,2].
5628     SDValue Log2ofMantissa;
5629     if (LimitFloatPrecision <= 6) {
5630       // For floating-point precision of 6:
5631       //
5632       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5633       //
5634       // error 0.0049451742, which is more than 7 bits
5635       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5636                                getF32Constant(DAG, 0xbeb08fe0, dl));
5637       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5638                                getF32Constant(DAG, 0x40019463, dl));
5639       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5640       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5641                                    getF32Constant(DAG, 0x3fd6633d, dl));
5642     } else if (LimitFloatPrecision <= 12) {
5643       // For floating-point precision of 12:
5644       //
5645       //   Log2ofMantissa =
5646       //     -2.51285454f +
5647       //       (4.07009056f +
5648       //         (-2.12067489f +
5649       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5650       //
5651       // error 0.0000876136000, which is better than 13 bits
5652       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5653                                getF32Constant(DAG, 0xbda7262e, dl));
5654       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5655                                getF32Constant(DAG, 0x3f25280b, dl));
5656       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5657       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5658                                getF32Constant(DAG, 0x4007b923, dl));
5659       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5660       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5661                                getF32Constant(DAG, 0x40823e2f, dl));
5662       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5663       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5664                                    getF32Constant(DAG, 0x4020d29c, dl));
5665     } else { // LimitFloatPrecision <= 18
5666       // For floating-point precision of 18:
5667       //
5668       //   Log2ofMantissa =
5669       //     -3.0400495f +
5670       //       (6.1129976f +
5671       //         (-5.3420409f +
5672       //           (3.2865683f +
5673       //             (-1.2669343f +
5674       //               (0.27515199f -
5675       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5676       //
5677       // error 0.0000018516, which is better than 18 bits
5678       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5679                                getF32Constant(DAG, 0xbcd2769e, dl));
5680       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5681                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5682       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5683       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5684                                getF32Constant(DAG, 0x3fa22ae7, dl));
5685       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5686       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5687                                getF32Constant(DAG, 0x40525723, dl));
5688       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5689       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5690                                getF32Constant(DAG, 0x40aaf200, dl));
5691       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5692       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5693                                getF32Constant(DAG, 0x40c39dad, dl));
5694       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5695       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5696                                    getF32Constant(DAG, 0x4042902c, dl));
5697     }
5698 
5699     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5700   }
5701 
5702   // No special expansion.
5703   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5704 }
5705 
5706 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5707 /// limited-precision mode.
5708 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5709                            const TargetLowering &TLI, SDNodeFlags Flags) {
5710   // TODO: What fast-math-flags should be set on the floating-point nodes?
5711 
5712   if (Op.getValueType() == MVT::f32 &&
5713       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5714     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5715 
5716     // Scale the exponent by log10(2) [0.30102999f].
5717     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5718     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5719                                         getF32Constant(DAG, 0x3e9a209a, dl));
5720 
5721     // Get the significand and build it into a floating-point number with
5722     // exponent of 1.
5723     SDValue X = GetSignificand(DAG, Op1, dl);
5724 
5725     SDValue Log10ofMantissa;
5726     if (LimitFloatPrecision <= 6) {
5727       // For floating-point precision of 6:
5728       //
5729       //   Log10ofMantissa =
5730       //     -0.50419619f +
5731       //       (0.60948995f - 0.10380950f * x) * x;
5732       //
5733       // error 0.0014886165, which is 6 bits
5734       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5735                                getF32Constant(DAG, 0xbdd49a13, dl));
5736       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5737                                getF32Constant(DAG, 0x3f1c0789, dl));
5738       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5739       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5740                                     getF32Constant(DAG, 0x3f011300, dl));
5741     } else if (LimitFloatPrecision <= 12) {
5742       // For floating-point precision of 12:
5743       //
5744       //   Log10ofMantissa =
5745       //     -0.64831180f +
5746       //       (0.91751397f +
5747       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5748       //
5749       // error 0.00019228036, which is better than 12 bits
5750       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5751                                getF32Constant(DAG, 0x3d431f31, dl));
5752       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5753                                getF32Constant(DAG, 0x3ea21fb2, dl));
5754       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5755       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5756                                getF32Constant(DAG, 0x3f6ae232, dl));
5757       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5758       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5759                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5760     } else { // LimitFloatPrecision <= 18
5761       // For floating-point precision of 18:
5762       //
5763       //   Log10ofMantissa =
5764       //     -0.84299375f +
5765       //       (1.5327582f +
5766       //         (-1.0688956f +
5767       //           (0.49102474f +
5768       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5769       //
5770       // error 0.0000037995730, which is better than 18 bits
5771       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5772                                getF32Constant(DAG, 0x3c5d51ce, dl));
5773       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5774                                getF32Constant(DAG, 0x3e00685a, dl));
5775       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5776       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5777                                getF32Constant(DAG, 0x3efb6798, dl));
5778       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5779       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5780                                getF32Constant(DAG, 0x3f88d192, dl));
5781       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5782       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5783                                getF32Constant(DAG, 0x3fc4316c, dl));
5784       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5785       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5786                                     getF32Constant(DAG, 0x3f57ce70, dl));
5787     }
5788 
5789     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5790   }
5791 
5792   // No special expansion.
5793   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5794 }
5795 
5796 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5797 /// limited-precision mode.
5798 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5799                           const TargetLowering &TLI, SDNodeFlags Flags) {
5800   if (Op.getValueType() == MVT::f32 &&
5801       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5802     return getLimitedPrecisionExp2(Op, dl, DAG);
5803 
5804   // No special expansion.
5805   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5806 }
5807 
5808 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5809 /// limited-precision mode with x == 10.0f.
5810 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5811                          SelectionDAG &DAG, const TargetLowering &TLI,
5812                          SDNodeFlags Flags) {
5813   bool IsExp10 = false;
5814   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5815       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5816     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5817       APFloat Ten(10.0f);
5818       IsExp10 = LHSC->isExactlyValue(Ten);
5819     }
5820   }
5821 
5822   // TODO: What fast-math-flags should be set on the FMUL node?
5823   if (IsExp10) {
5824     // Put the exponent in the right bit position for later addition to the
5825     // final result:
5826     //
5827     //   #define LOG2OF10 3.3219281f
5828     //   t0 = Op * LOG2OF10;
5829     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5830                              getF32Constant(DAG, 0x40549a78, dl));
5831     return getLimitedPrecisionExp2(t0, dl, DAG);
5832   }
5833 
5834   // No special expansion.
5835   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5836 }
5837 
5838 /// ExpandPowI - Expand a llvm.powi intrinsic.
5839 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5840                           SelectionDAG &DAG) {
5841   // If RHS is a constant, we can expand this out to a multiplication tree if
5842   // it's beneficial on the target, otherwise we end up lowering to a call to
5843   // __powidf2 (for example).
5844   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5845     unsigned Val = RHSC->getSExtValue();
5846 
5847     // powi(x, 0) -> 1.0
5848     if (Val == 0)
5849       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5850 
5851     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5852             Val, DAG.shouldOptForSize())) {
5853       // Get the exponent as a positive value.
5854       if ((int)Val < 0)
5855         Val = -Val;
5856       // We use the simple binary decomposition method to generate the multiply
5857       // sequence.  There are more optimal ways to do this (for example,
5858       // powi(x,15) generates one more multiply than it should), but this has
5859       // the benefit of being both really simple and much better than a libcall.
5860       SDValue Res; // Logically starts equal to 1.0
5861       SDValue CurSquare = LHS;
5862       // TODO: Intrinsics should have fast-math-flags that propagate to these
5863       // nodes.
5864       while (Val) {
5865         if (Val & 1) {
5866           if (Res.getNode())
5867             Res =
5868                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5869           else
5870             Res = CurSquare; // 1.0*CurSquare.
5871         }
5872 
5873         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5874                                 CurSquare, CurSquare);
5875         Val >>= 1;
5876       }
5877 
5878       // If the original was negative, invert the result, producing 1/(x*x*x).
5879       if (RHSC->getSExtValue() < 0)
5880         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5881                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5882       return Res;
5883     }
5884   }
5885 
5886   // Otherwise, expand to a libcall.
5887   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5888 }
5889 
5890 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5891                             SDValue LHS, SDValue RHS, SDValue Scale,
5892                             SelectionDAG &DAG, const TargetLowering &TLI) {
5893   EVT VT = LHS.getValueType();
5894   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5895   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5896   LLVMContext &Ctx = *DAG.getContext();
5897 
5898   // If the type is legal but the operation isn't, this node might survive all
5899   // the way to operation legalization. If we end up there and we do not have
5900   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5901   // node.
5902 
5903   // Coax the legalizer into expanding the node during type legalization instead
5904   // by bumping the size by one bit. This will force it to Promote, enabling the
5905   // early expansion and avoiding the need to expand later.
5906 
5907   // We don't have to do this if Scale is 0; that can always be expanded, unless
5908   // it's a saturating signed operation. Those can experience true integer
5909   // division overflow, a case which we must avoid.
5910 
5911   // FIXME: We wouldn't have to do this (or any of the early
5912   // expansion/promotion) if it was possible to expand a libcall of an
5913   // illegal type during operation legalization. But it's not, so things
5914   // get a bit hacky.
5915   unsigned ScaleInt = Scale->getAsZExtVal();
5916   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5917       (TLI.isTypeLegal(VT) ||
5918        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5919     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5920         Opcode, VT, ScaleInt);
5921     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5922       EVT PromVT;
5923       if (VT.isScalarInteger())
5924         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5925       else if (VT.isVector()) {
5926         PromVT = VT.getVectorElementType();
5927         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5928         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5929       } else
5930         llvm_unreachable("Wrong VT for DIVFIX?");
5931       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5932       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5933       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5934       // For saturating operations, we need to shift up the LHS to get the
5935       // proper saturation width, and then shift down again afterwards.
5936       if (Saturating)
5937         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5938                           DAG.getConstant(1, DL, ShiftTy));
5939       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5940       if (Saturating)
5941         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5942                           DAG.getConstant(1, DL, ShiftTy));
5943       return DAG.getZExtOrTrunc(Res, DL, VT);
5944     }
5945   }
5946 
5947   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5948 }
5949 
5950 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5951 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5952 static void
5953 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5954                      const SDValue &N) {
5955   switch (N.getOpcode()) {
5956   case ISD::CopyFromReg: {
5957     SDValue Op = N.getOperand(1);
5958     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5959                       Op.getValueType().getSizeInBits());
5960     return;
5961   }
5962   case ISD::BITCAST:
5963   case ISD::AssertZext:
5964   case ISD::AssertSext:
5965   case ISD::TRUNCATE:
5966     getUnderlyingArgRegs(Regs, N.getOperand(0));
5967     return;
5968   case ISD::BUILD_PAIR:
5969   case ISD::BUILD_VECTOR:
5970   case ISD::CONCAT_VECTORS:
5971     for (SDValue Op : N->op_values())
5972       getUnderlyingArgRegs(Regs, Op);
5973     return;
5974   default:
5975     return;
5976   }
5977 }
5978 
5979 /// If the DbgValueInst is a dbg_value of a function argument, create the
5980 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5981 /// instruction selection, they will be inserted to the entry BB.
5982 /// We don't currently support this for variadic dbg_values, as they shouldn't
5983 /// appear for function arguments or in the prologue.
5984 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5985     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5986     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5987   const Argument *Arg = dyn_cast<Argument>(V);
5988   if (!Arg)
5989     return false;
5990 
5991   MachineFunction &MF = DAG.getMachineFunction();
5992   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5993 
5994   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5995   // we've been asked to pursue.
5996   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5997                               bool Indirect) {
5998     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5999       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6000       // pointing at the VReg, which will be patched up later.
6001       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6002       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6003           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6004           /* isKill */ false, /* isDead */ false,
6005           /* isUndef */ false, /* isEarlyClobber */ false,
6006           /* SubReg */ 0, /* isDebug */ true)});
6007 
6008       auto *NewDIExpr = FragExpr;
6009       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6010       // the DIExpression.
6011       if (Indirect)
6012         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6013       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6014       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6015       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6016     } else {
6017       // Create a completely standard DBG_VALUE.
6018       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6019       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6020     }
6021   };
6022 
6023   if (Kind == FuncArgumentDbgValueKind::Value) {
6024     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6025     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6026     // the entry block.
6027     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6028     if (!IsInEntryBlock)
6029       return false;
6030 
6031     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6032     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6033     // variable that also is a param.
6034     //
6035     // Although, if we are at the top of the entry block already, we can still
6036     // emit using ArgDbgValue. This might catch some situations when the
6037     // dbg.value refers to an argument that isn't used in the entry block, so
6038     // any CopyToReg node would be optimized out and the only way to express
6039     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6040     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6041     // we should only emit as ArgDbgValue if the Variable is an argument to the
6042     // current function, and the dbg.value intrinsic is found in the entry
6043     // block.
6044     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6045         !DL->getInlinedAt();
6046     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6047     if (!IsInPrologue && !VariableIsFunctionInputArg)
6048       return false;
6049 
6050     // Here we assume that a function argument on IR level only can be used to
6051     // describe one input parameter on source level. If we for example have
6052     // source code like this
6053     //
6054     //    struct A { long x, y; };
6055     //    void foo(struct A a, long b) {
6056     //      ...
6057     //      b = a.x;
6058     //      ...
6059     //    }
6060     //
6061     // and IR like this
6062     //
6063     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6064     //  entry:
6065     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6066     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6067     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6068     //    ...
6069     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6070     //    ...
6071     //
6072     // then the last dbg.value is describing a parameter "b" using a value that
6073     // is an argument. But since we already has used %a1 to describe a parameter
6074     // we should not handle that last dbg.value here (that would result in an
6075     // incorrect hoisting of the DBG_VALUE to the function entry).
6076     // Notice that we allow one dbg.value per IR level argument, to accommodate
6077     // for the situation with fragments above.
6078     // If there is no node for the value being handled, we return true to skip
6079     // the normal generation of debug info, as it would kill existing debug
6080     // info for the parameter in case of duplicates.
6081     if (VariableIsFunctionInputArg) {
6082       unsigned ArgNo = Arg->getArgNo();
6083       if (ArgNo >= FuncInfo.DescribedArgs.size())
6084         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6085       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6086         return !NodeMap[V].getNode();
6087       FuncInfo.DescribedArgs.set(ArgNo);
6088     }
6089   }
6090 
6091   bool IsIndirect = false;
6092   std::optional<MachineOperand> Op;
6093   // Some arguments' frame index is recorded during argument lowering.
6094   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6095   if (FI != std::numeric_limits<int>::max())
6096     Op = MachineOperand::CreateFI(FI);
6097 
6098   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6099   if (!Op && N.getNode()) {
6100     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6101     Register Reg;
6102     if (ArgRegsAndSizes.size() == 1)
6103       Reg = ArgRegsAndSizes.front().first;
6104 
6105     if (Reg && Reg.isVirtual()) {
6106       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6107       Register PR = RegInfo.getLiveInPhysReg(Reg);
6108       if (PR)
6109         Reg = PR;
6110     }
6111     if (Reg) {
6112       Op = MachineOperand::CreateReg(Reg, false);
6113       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6114     }
6115   }
6116 
6117   if (!Op && N.getNode()) {
6118     // Check if frame index is available.
6119     SDValue LCandidate = peekThroughBitcasts(N);
6120     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6121       if (FrameIndexSDNode *FINode =
6122           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6123         Op = MachineOperand::CreateFI(FINode->getIndex());
6124   }
6125 
6126   if (!Op) {
6127     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6128     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6129                                          SplitRegs) {
6130       unsigned Offset = 0;
6131       for (const auto &RegAndSize : SplitRegs) {
6132         // If the expression is already a fragment, the current register
6133         // offset+size might extend beyond the fragment. In this case, only
6134         // the register bits that are inside the fragment are relevant.
6135         int RegFragmentSizeInBits = RegAndSize.second;
6136         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6137           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6138           // The register is entirely outside the expression fragment,
6139           // so is irrelevant for debug info.
6140           if (Offset >= ExprFragmentSizeInBits)
6141             break;
6142           // The register is partially outside the expression fragment, only
6143           // the low bits within the fragment are relevant for debug info.
6144           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6145             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6146           }
6147         }
6148 
6149         auto FragmentExpr = DIExpression::createFragmentExpression(
6150             Expr, Offset, RegFragmentSizeInBits);
6151         Offset += RegAndSize.second;
6152         // If a valid fragment expression cannot be created, the variable's
6153         // correct value cannot be determined and so it is set as Undef.
6154         if (!FragmentExpr) {
6155           SDDbgValue *SDV = DAG.getConstantDbgValue(
6156               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6157           DAG.AddDbgValue(SDV, false);
6158           continue;
6159         }
6160         MachineInstr *NewMI =
6161             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6162                              Kind != FuncArgumentDbgValueKind::Value);
6163         FuncInfo.ArgDbgValues.push_back(NewMI);
6164       }
6165     };
6166 
6167     // Check if ValueMap has reg number.
6168     DenseMap<const Value *, Register>::const_iterator
6169       VMI = FuncInfo.ValueMap.find(V);
6170     if (VMI != FuncInfo.ValueMap.end()) {
6171       const auto &TLI = DAG.getTargetLoweringInfo();
6172       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6173                        V->getType(), std::nullopt);
6174       if (RFV.occupiesMultipleRegs()) {
6175         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6176         return true;
6177       }
6178 
6179       Op = MachineOperand::CreateReg(VMI->second, false);
6180       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6181     } else if (ArgRegsAndSizes.size() > 1) {
6182       // This was split due to the calling convention, and no virtual register
6183       // mapping exists for the value.
6184       splitMultiRegDbgValue(ArgRegsAndSizes);
6185       return true;
6186     }
6187   }
6188 
6189   if (!Op)
6190     return false;
6191 
6192   assert(Variable->isValidLocationForIntrinsic(DL) &&
6193          "Expected inlined-at fields to agree");
6194   MachineInstr *NewMI = nullptr;
6195 
6196   if (Op->isReg())
6197     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6198   else
6199     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6200                     Variable, Expr);
6201 
6202   // Otherwise, use ArgDbgValues.
6203   FuncInfo.ArgDbgValues.push_back(NewMI);
6204   return true;
6205 }
6206 
6207 /// Return the appropriate SDDbgValue based on N.
6208 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6209                                              DILocalVariable *Variable,
6210                                              DIExpression *Expr,
6211                                              const DebugLoc &dl,
6212                                              unsigned DbgSDNodeOrder) {
6213   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6214     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6215     // stack slot locations.
6216     //
6217     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6218     // debug values here after optimization:
6219     //
6220     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6221     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6222     //
6223     // Both describe the direct values of their associated variables.
6224     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6225                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6226   }
6227   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6228                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6229 }
6230 
6231 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6232   switch (Intrinsic) {
6233   case Intrinsic::smul_fix:
6234     return ISD::SMULFIX;
6235   case Intrinsic::umul_fix:
6236     return ISD::UMULFIX;
6237   case Intrinsic::smul_fix_sat:
6238     return ISD::SMULFIXSAT;
6239   case Intrinsic::umul_fix_sat:
6240     return ISD::UMULFIXSAT;
6241   case Intrinsic::sdiv_fix:
6242     return ISD::SDIVFIX;
6243   case Intrinsic::udiv_fix:
6244     return ISD::UDIVFIX;
6245   case Intrinsic::sdiv_fix_sat:
6246     return ISD::SDIVFIXSAT;
6247   case Intrinsic::udiv_fix_sat:
6248     return ISD::UDIVFIXSAT;
6249   default:
6250     llvm_unreachable("Unhandled fixed point intrinsic");
6251   }
6252 }
6253 
6254 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6255                                            const char *FunctionName) {
6256   assert(FunctionName && "FunctionName must not be nullptr");
6257   SDValue Callee = DAG.getExternalSymbol(
6258       FunctionName,
6259       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6260   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6261 }
6262 
6263 /// Given a @llvm.call.preallocated.setup, return the corresponding
6264 /// preallocated call.
6265 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6266   assert(cast<CallBase>(PreallocatedSetup)
6267                  ->getCalledFunction()
6268                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6269          "expected call_preallocated_setup Value");
6270   for (const auto *U : PreallocatedSetup->users()) {
6271     auto *UseCall = cast<CallBase>(U);
6272     const Function *Fn = UseCall->getCalledFunction();
6273     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6274       return UseCall;
6275     }
6276   }
6277   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6278 }
6279 
6280 /// If DI is a debug value with an EntryValue expression, lower it using the
6281 /// corresponding physical register of the associated Argument value
6282 /// (guaranteed to exist by the verifier).
6283 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6284     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6285     DIExpression *Expr, DebugLoc DbgLoc) {
6286   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6287     return false;
6288 
6289   // These properties are guaranteed by the verifier.
6290   const Argument *Arg = cast<Argument>(Values[0]);
6291   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6292 
6293   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6294   if (ArgIt == FuncInfo.ValueMap.end()) {
6295     LLVM_DEBUG(
6296         dbgs() << "Dropping dbg.value: expression is entry_value but "
6297                   "couldn't find an associated register for the Argument\n");
6298     return true;
6299   }
6300   Register ArgVReg = ArgIt->getSecond();
6301 
6302   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6303     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6304       SDDbgValue *SDV = DAG.getVRegDbgValue(
6305           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6306       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6307       return true;
6308     }
6309   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6310                        "couldn't find a physical register\n");
6311   return true;
6312 }
6313 
6314 /// Lower the call to the specified intrinsic function.
6315 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6316                                                   unsigned Intrinsic) {
6317   SDLoc sdl = getCurSDLoc();
6318   switch (Intrinsic) {
6319   case Intrinsic::experimental_convergence_anchor:
6320     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6321     break;
6322   case Intrinsic::experimental_convergence_entry:
6323     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6324     break;
6325   case Intrinsic::experimental_convergence_loop: {
6326     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6327     auto *Token = Bundle->Inputs[0].get();
6328     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6329                              getValue(Token)));
6330     break;
6331   }
6332   }
6333 }
6334 
6335 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6336                                                unsigned IntrinsicID) {
6337   // For now, we're only lowering an 'add' histogram.
6338   // We can add others later, e.g. saturating adds, min/max.
6339   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6340          "Tried to lower unsupported histogram type");
6341   SDLoc sdl = getCurSDLoc();
6342   Value *Ptr = I.getOperand(0);
6343   SDValue Inc = getValue(I.getOperand(1));
6344   SDValue Mask = getValue(I.getOperand(2));
6345 
6346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6347   DataLayout TargetDL = DAG.getDataLayout();
6348   EVT VT = Inc.getValueType();
6349   Align Alignment = DAG.getEVTAlign(VT);
6350 
6351   const MDNode *Ranges = getRangeMetadata(I);
6352 
6353   SDValue Root = DAG.getRoot();
6354   SDValue Base;
6355   SDValue Index;
6356   ISD::MemIndexType IndexType;
6357   SDValue Scale;
6358   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6359                                     I.getParent(), VT.getScalarStoreSize());
6360 
6361   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6362 
6363   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6364       MachinePointerInfo(AS),
6365       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6366       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6367 
6368   if (!UniformBase) {
6369     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6370     Index = getValue(Ptr);
6371     IndexType = ISD::SIGNED_SCALED;
6372     Scale =
6373         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6374   }
6375 
6376   EVT IdxVT = Index.getValueType();
6377   EVT EltTy = IdxVT.getVectorElementType();
6378   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6379     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6380     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6381   }
6382 
6383   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6384 
6385   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6386   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6387                                              Ops, MMO, IndexType);
6388 
6389   setValue(&I, Histogram);
6390   DAG.setRoot(Histogram);
6391 }
6392 
6393 /// Lower the call to the specified intrinsic function.
6394 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6395                                              unsigned Intrinsic) {
6396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6397   SDLoc sdl = getCurSDLoc();
6398   DebugLoc dl = getCurDebugLoc();
6399   SDValue Res;
6400 
6401   SDNodeFlags Flags;
6402   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6403     Flags.copyFMF(*FPOp);
6404 
6405   switch (Intrinsic) {
6406   default:
6407     // By default, turn this into a target intrinsic node.
6408     visitTargetIntrinsic(I, Intrinsic);
6409     return;
6410   case Intrinsic::vscale: {
6411     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6412     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6413     return;
6414   }
6415   case Intrinsic::vastart:  visitVAStart(I); return;
6416   case Intrinsic::vaend:    visitVAEnd(I); return;
6417   case Intrinsic::vacopy:   visitVACopy(I); return;
6418   case Intrinsic::returnaddress:
6419     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6420                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6421                              getValue(I.getArgOperand(0))));
6422     return;
6423   case Intrinsic::addressofreturnaddress:
6424     setValue(&I,
6425              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6426                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6427     return;
6428   case Intrinsic::sponentry:
6429     setValue(&I,
6430              DAG.getNode(ISD::SPONENTRY, sdl,
6431                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6432     return;
6433   case Intrinsic::frameaddress:
6434     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6435                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6436                              getValue(I.getArgOperand(0))));
6437     return;
6438   case Intrinsic::read_volatile_register:
6439   case Intrinsic::read_register: {
6440     Value *Reg = I.getArgOperand(0);
6441     SDValue Chain = getRoot();
6442     SDValue RegName =
6443         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6444     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6445     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6446       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6447     setValue(&I, Res);
6448     DAG.setRoot(Res.getValue(1));
6449     return;
6450   }
6451   case Intrinsic::write_register: {
6452     Value *Reg = I.getArgOperand(0);
6453     Value *RegValue = I.getArgOperand(1);
6454     SDValue Chain = getRoot();
6455     SDValue RegName =
6456         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6457     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6458                             RegName, getValue(RegValue)));
6459     return;
6460   }
6461   case Intrinsic::memcpy: {
6462     const auto &MCI = cast<MemCpyInst>(I);
6463     SDValue Op1 = getValue(I.getArgOperand(0));
6464     SDValue Op2 = getValue(I.getArgOperand(1));
6465     SDValue Op3 = getValue(I.getArgOperand(2));
6466     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6467     Align DstAlign = MCI.getDestAlign().valueOrOne();
6468     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6469     Align Alignment = std::min(DstAlign, SrcAlign);
6470     bool isVol = MCI.isVolatile();
6471     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6472     // node.
6473     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6474     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6475                                /* AlwaysInline */ false, &I, std::nullopt,
6476                                MachinePointerInfo(I.getArgOperand(0)),
6477                                MachinePointerInfo(I.getArgOperand(1)),
6478                                I.getAAMetadata(), AA);
6479     updateDAGForMaybeTailCall(MC);
6480     return;
6481   }
6482   case Intrinsic::memcpy_inline: {
6483     const auto &MCI = cast<MemCpyInlineInst>(I);
6484     SDValue Dst = getValue(I.getArgOperand(0));
6485     SDValue Src = getValue(I.getArgOperand(1));
6486     SDValue Size = getValue(I.getArgOperand(2));
6487     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6488     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6489     Align DstAlign = MCI.getDestAlign().valueOrOne();
6490     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6491     Align Alignment = std::min(DstAlign, SrcAlign);
6492     bool isVol = MCI.isVolatile();
6493     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6494     // node.
6495     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6496                                /* AlwaysInline */ true, &I, std::nullopt,
6497                                MachinePointerInfo(I.getArgOperand(0)),
6498                                MachinePointerInfo(I.getArgOperand(1)),
6499                                I.getAAMetadata(), AA);
6500     updateDAGForMaybeTailCall(MC);
6501     return;
6502   }
6503   case Intrinsic::memset: {
6504     const auto &MSI = cast<MemSetInst>(I);
6505     SDValue Op1 = getValue(I.getArgOperand(0));
6506     SDValue Op2 = getValue(I.getArgOperand(1));
6507     SDValue Op3 = getValue(I.getArgOperand(2));
6508     // @llvm.memset defines 0 and 1 to both mean no alignment.
6509     Align Alignment = MSI.getDestAlign().valueOrOne();
6510     bool isVol = MSI.isVolatile();
6511     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6512     SDValue MS = DAG.getMemset(
6513         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6514         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6515     updateDAGForMaybeTailCall(MS);
6516     return;
6517   }
6518   case Intrinsic::memset_inline: {
6519     const auto &MSII = cast<MemSetInlineInst>(I);
6520     SDValue Dst = getValue(I.getArgOperand(0));
6521     SDValue Value = getValue(I.getArgOperand(1));
6522     SDValue Size = getValue(I.getArgOperand(2));
6523     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6524     // @llvm.memset defines 0 and 1 to both mean no alignment.
6525     Align DstAlign = MSII.getDestAlign().valueOrOne();
6526     bool isVol = MSII.isVolatile();
6527     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6528     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6529                                /* AlwaysInline */ true, &I,
6530                                MachinePointerInfo(I.getArgOperand(0)),
6531                                I.getAAMetadata());
6532     updateDAGForMaybeTailCall(MC);
6533     return;
6534   }
6535   case Intrinsic::memmove: {
6536     const auto &MMI = cast<MemMoveInst>(I);
6537     SDValue Op1 = getValue(I.getArgOperand(0));
6538     SDValue Op2 = getValue(I.getArgOperand(1));
6539     SDValue Op3 = getValue(I.getArgOperand(2));
6540     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6541     Align DstAlign = MMI.getDestAlign().valueOrOne();
6542     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6543     Align Alignment = std::min(DstAlign, SrcAlign);
6544     bool isVol = MMI.isVolatile();
6545     // FIXME: Support passing different dest/src alignments to the memmove DAG
6546     // node.
6547     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6548     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6549                                 /* OverrideTailCall */ std::nullopt,
6550                                 MachinePointerInfo(I.getArgOperand(0)),
6551                                 MachinePointerInfo(I.getArgOperand(1)),
6552                                 I.getAAMetadata(), AA);
6553     updateDAGForMaybeTailCall(MM);
6554     return;
6555   }
6556   case Intrinsic::memcpy_element_unordered_atomic: {
6557     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6558     SDValue Dst = getValue(MI.getRawDest());
6559     SDValue Src = getValue(MI.getRawSource());
6560     SDValue Length = getValue(MI.getLength());
6561 
6562     Type *LengthTy = MI.getLength()->getType();
6563     unsigned ElemSz = MI.getElementSizeInBytes();
6564     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6565     SDValue MC =
6566         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6567                             isTC, MachinePointerInfo(MI.getRawDest()),
6568                             MachinePointerInfo(MI.getRawSource()));
6569     updateDAGForMaybeTailCall(MC);
6570     return;
6571   }
6572   case Intrinsic::memmove_element_unordered_atomic: {
6573     auto &MI = cast<AtomicMemMoveInst>(I);
6574     SDValue Dst = getValue(MI.getRawDest());
6575     SDValue Src = getValue(MI.getRawSource());
6576     SDValue Length = getValue(MI.getLength());
6577 
6578     Type *LengthTy = MI.getLength()->getType();
6579     unsigned ElemSz = MI.getElementSizeInBytes();
6580     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6581     SDValue MC =
6582         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6583                              isTC, MachinePointerInfo(MI.getRawDest()),
6584                              MachinePointerInfo(MI.getRawSource()));
6585     updateDAGForMaybeTailCall(MC);
6586     return;
6587   }
6588   case Intrinsic::memset_element_unordered_atomic: {
6589     auto &MI = cast<AtomicMemSetInst>(I);
6590     SDValue Dst = getValue(MI.getRawDest());
6591     SDValue Val = getValue(MI.getValue());
6592     SDValue Length = getValue(MI.getLength());
6593 
6594     Type *LengthTy = MI.getLength()->getType();
6595     unsigned ElemSz = MI.getElementSizeInBytes();
6596     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6597     SDValue MC =
6598         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6599                             isTC, MachinePointerInfo(MI.getRawDest()));
6600     updateDAGForMaybeTailCall(MC);
6601     return;
6602   }
6603   case Intrinsic::call_preallocated_setup: {
6604     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6605     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6606     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6607                               getRoot(), SrcValue);
6608     setValue(&I, Res);
6609     DAG.setRoot(Res);
6610     return;
6611   }
6612   case Intrinsic::call_preallocated_arg: {
6613     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6614     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6615     SDValue Ops[3];
6616     Ops[0] = getRoot();
6617     Ops[1] = SrcValue;
6618     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6619                                    MVT::i32); // arg index
6620     SDValue Res = DAG.getNode(
6621         ISD::PREALLOCATED_ARG, sdl,
6622         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6623     setValue(&I, Res);
6624     DAG.setRoot(Res.getValue(1));
6625     return;
6626   }
6627   case Intrinsic::dbg_declare: {
6628     const auto &DI = cast<DbgDeclareInst>(I);
6629     // Debug intrinsics are handled separately in assignment tracking mode.
6630     // Some intrinsics are handled right after Argument lowering.
6631     if (AssignmentTrackingEnabled ||
6632         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6633       return;
6634     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6635     DILocalVariable *Variable = DI.getVariable();
6636     DIExpression *Expression = DI.getExpression();
6637     dropDanglingDebugInfo(Variable, Expression);
6638     // Assume dbg.declare can not currently use DIArgList, i.e.
6639     // it is non-variadic.
6640     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6641     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6642                        DI.getDebugLoc());
6643     return;
6644   }
6645   case Intrinsic::dbg_label: {
6646     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6647     DILabel *Label = DI.getLabel();
6648     assert(Label && "Missing label");
6649 
6650     SDDbgLabel *SDV;
6651     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6652     DAG.AddDbgLabel(SDV);
6653     return;
6654   }
6655   case Intrinsic::dbg_assign: {
6656     // Debug intrinsics are handled separately in assignment tracking mode.
6657     if (AssignmentTrackingEnabled)
6658       return;
6659     // If assignment tracking hasn't been enabled then fall through and treat
6660     // the dbg.assign as a dbg.value.
6661     [[fallthrough]];
6662   }
6663   case Intrinsic::dbg_value: {
6664     // Debug intrinsics are handled separately in assignment tracking mode.
6665     if (AssignmentTrackingEnabled)
6666       return;
6667     const DbgValueInst &DI = cast<DbgValueInst>(I);
6668     assert(DI.getVariable() && "Missing variable");
6669 
6670     DILocalVariable *Variable = DI.getVariable();
6671     DIExpression *Expression = DI.getExpression();
6672     dropDanglingDebugInfo(Variable, Expression);
6673 
6674     if (DI.isKillLocation()) {
6675       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6676       return;
6677     }
6678 
6679     SmallVector<Value *, 4> Values(DI.getValues());
6680     if (Values.empty())
6681       return;
6682 
6683     bool IsVariadic = DI.hasArgList();
6684     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6685                           SDNodeOrder, IsVariadic))
6686       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6687                            DI.getDebugLoc(), SDNodeOrder);
6688     return;
6689   }
6690 
6691   case Intrinsic::eh_typeid_for: {
6692     // Find the type id for the given typeinfo.
6693     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6694     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6695     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6696     setValue(&I, Res);
6697     return;
6698   }
6699 
6700   case Intrinsic::eh_return_i32:
6701   case Intrinsic::eh_return_i64:
6702     DAG.getMachineFunction().setCallsEHReturn(true);
6703     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6704                             MVT::Other,
6705                             getControlRoot(),
6706                             getValue(I.getArgOperand(0)),
6707                             getValue(I.getArgOperand(1))));
6708     return;
6709   case Intrinsic::eh_unwind_init:
6710     DAG.getMachineFunction().setCallsUnwindInit(true);
6711     return;
6712   case Intrinsic::eh_dwarf_cfa:
6713     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6714                              TLI.getPointerTy(DAG.getDataLayout()),
6715                              getValue(I.getArgOperand(0))));
6716     return;
6717   case Intrinsic::eh_sjlj_callsite: {
6718     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6719     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6720 
6721     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6722     return;
6723   }
6724   case Intrinsic::eh_sjlj_functioncontext: {
6725     // Get and store the index of the function context.
6726     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6727     AllocaInst *FnCtx =
6728       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6729     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6730     MFI.setFunctionContextIndex(FI);
6731     return;
6732   }
6733   case Intrinsic::eh_sjlj_setjmp: {
6734     SDValue Ops[2];
6735     Ops[0] = getRoot();
6736     Ops[1] = getValue(I.getArgOperand(0));
6737     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6738                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6739     setValue(&I, Op.getValue(0));
6740     DAG.setRoot(Op.getValue(1));
6741     return;
6742   }
6743   case Intrinsic::eh_sjlj_longjmp:
6744     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6745                             getRoot(), getValue(I.getArgOperand(0))));
6746     return;
6747   case Intrinsic::eh_sjlj_setup_dispatch:
6748     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6749                             getRoot()));
6750     return;
6751   case Intrinsic::masked_gather:
6752     visitMaskedGather(I);
6753     return;
6754   case Intrinsic::masked_load:
6755     visitMaskedLoad(I);
6756     return;
6757   case Intrinsic::masked_scatter:
6758     visitMaskedScatter(I);
6759     return;
6760   case Intrinsic::masked_store:
6761     visitMaskedStore(I);
6762     return;
6763   case Intrinsic::masked_expandload:
6764     visitMaskedLoad(I, true /* IsExpanding */);
6765     return;
6766   case Intrinsic::masked_compressstore:
6767     visitMaskedStore(I, true /* IsCompressing */);
6768     return;
6769   case Intrinsic::powi:
6770     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6771                             getValue(I.getArgOperand(1)), DAG));
6772     return;
6773   case Intrinsic::log:
6774     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6775     return;
6776   case Intrinsic::log2:
6777     setValue(&I,
6778              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6779     return;
6780   case Intrinsic::log10:
6781     setValue(&I,
6782              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6783     return;
6784   case Intrinsic::exp:
6785     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6786     return;
6787   case Intrinsic::exp2:
6788     setValue(&I,
6789              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6790     return;
6791   case Intrinsic::pow:
6792     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6793                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6794     return;
6795   case Intrinsic::sqrt:
6796   case Intrinsic::fabs:
6797   case Intrinsic::sin:
6798   case Intrinsic::cos:
6799   case Intrinsic::tan:
6800   case Intrinsic::asin:
6801   case Intrinsic::acos:
6802   case Intrinsic::atan:
6803   case Intrinsic::sinh:
6804   case Intrinsic::cosh:
6805   case Intrinsic::tanh:
6806   case Intrinsic::exp10:
6807   case Intrinsic::floor:
6808   case Intrinsic::ceil:
6809   case Intrinsic::trunc:
6810   case Intrinsic::rint:
6811   case Intrinsic::nearbyint:
6812   case Intrinsic::round:
6813   case Intrinsic::roundeven:
6814   case Intrinsic::canonicalize: {
6815     unsigned Opcode;
6816     // clang-format off
6817     switch (Intrinsic) {
6818     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6819     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6820     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6821     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6822     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6823     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6824     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6825     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6826     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6827     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6828     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6829     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6830     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6831     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6832     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6833     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6834     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6835     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6836     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6837     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6838     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6839     }
6840     // clang-format on
6841 
6842     setValue(&I, DAG.getNode(Opcode, sdl,
6843                              getValue(I.getArgOperand(0)).getValueType(),
6844                              getValue(I.getArgOperand(0)), Flags));
6845     return;
6846   }
6847   case Intrinsic::lround:
6848   case Intrinsic::llround:
6849   case Intrinsic::lrint:
6850   case Intrinsic::llrint: {
6851     unsigned Opcode;
6852     // clang-format off
6853     switch (Intrinsic) {
6854     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6855     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6856     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6857     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6858     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6859     }
6860     // clang-format on
6861 
6862     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6863     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6864                              getValue(I.getArgOperand(0))));
6865     return;
6866   }
6867   case Intrinsic::minnum:
6868     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6869                              getValue(I.getArgOperand(0)).getValueType(),
6870                              getValue(I.getArgOperand(0)),
6871                              getValue(I.getArgOperand(1)), Flags));
6872     return;
6873   case Intrinsic::maxnum:
6874     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6875                              getValue(I.getArgOperand(0)).getValueType(),
6876                              getValue(I.getArgOperand(0)),
6877                              getValue(I.getArgOperand(1)), Flags));
6878     return;
6879   case Intrinsic::minimum:
6880     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6881                              getValue(I.getArgOperand(0)).getValueType(),
6882                              getValue(I.getArgOperand(0)),
6883                              getValue(I.getArgOperand(1)), Flags));
6884     return;
6885   case Intrinsic::maximum:
6886     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6887                              getValue(I.getArgOperand(0)).getValueType(),
6888                              getValue(I.getArgOperand(0)),
6889                              getValue(I.getArgOperand(1)), Flags));
6890     return;
6891   case Intrinsic::minimumnum:
6892     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6893                              getValue(I.getArgOperand(0)).getValueType(),
6894                              getValue(I.getArgOperand(0)),
6895                              getValue(I.getArgOperand(1)), Flags));
6896     return;
6897   case Intrinsic::maximumnum:
6898     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6899                              getValue(I.getArgOperand(0)).getValueType(),
6900                              getValue(I.getArgOperand(0)),
6901                              getValue(I.getArgOperand(1)), Flags));
6902     return;
6903   case Intrinsic::copysign:
6904     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6905                              getValue(I.getArgOperand(0)).getValueType(),
6906                              getValue(I.getArgOperand(0)),
6907                              getValue(I.getArgOperand(1)), Flags));
6908     return;
6909   case Intrinsic::ldexp:
6910     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6911                              getValue(I.getArgOperand(0)).getValueType(),
6912                              getValue(I.getArgOperand(0)),
6913                              getValue(I.getArgOperand(1)), Flags));
6914     return;
6915   case Intrinsic::frexp: {
6916     SmallVector<EVT, 2> ValueVTs;
6917     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6918     SDVTList VTs = DAG.getVTList(ValueVTs);
6919     setValue(&I,
6920              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6921     return;
6922   }
6923   case Intrinsic::arithmetic_fence: {
6924     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6925                              getValue(I.getArgOperand(0)).getValueType(),
6926                              getValue(I.getArgOperand(0)), Flags));
6927     return;
6928   }
6929   case Intrinsic::fma:
6930     setValue(&I, DAG.getNode(
6931                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6932                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6933                      getValue(I.getArgOperand(2)), Flags));
6934     return;
6935 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6936   case Intrinsic::INTRINSIC:
6937 #include "llvm/IR/ConstrainedOps.def"
6938     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6939     return;
6940 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6941 #include "llvm/IR/VPIntrinsics.def"
6942     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6943     return;
6944   case Intrinsic::fptrunc_round: {
6945     // Get the last argument, the metadata and convert it to an integer in the
6946     // call
6947     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6948     std::optional<RoundingMode> RoundMode =
6949         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6950 
6951     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6952 
6953     // Propagate fast-math-flags from IR to node(s).
6954     SDNodeFlags Flags;
6955     Flags.copyFMF(*cast<FPMathOperator>(&I));
6956     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6957 
6958     SDValue Result;
6959     Result = DAG.getNode(
6960         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6961         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
6962     setValue(&I, Result);
6963 
6964     return;
6965   }
6966   case Intrinsic::fmuladd: {
6967     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6968     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6969         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6970       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6971                                getValue(I.getArgOperand(0)).getValueType(),
6972                                getValue(I.getArgOperand(0)),
6973                                getValue(I.getArgOperand(1)),
6974                                getValue(I.getArgOperand(2)), Flags));
6975     } else {
6976       // TODO: Intrinsic calls should have fast-math-flags.
6977       SDValue Mul = DAG.getNode(
6978           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6979           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6980       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6981                                 getValue(I.getArgOperand(0)).getValueType(),
6982                                 Mul, getValue(I.getArgOperand(2)), Flags);
6983       setValue(&I, Add);
6984     }
6985     return;
6986   }
6987   case Intrinsic::convert_to_fp16:
6988     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6989                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6990                                          getValue(I.getArgOperand(0)),
6991                                          DAG.getTargetConstant(0, sdl,
6992                                                                MVT::i32))));
6993     return;
6994   case Intrinsic::convert_from_fp16:
6995     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6996                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6997                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6998                                          getValue(I.getArgOperand(0)))));
6999     return;
7000   case Intrinsic::fptosi_sat: {
7001     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7002     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7003                              getValue(I.getArgOperand(0)),
7004                              DAG.getValueType(VT.getScalarType())));
7005     return;
7006   }
7007   case Intrinsic::fptoui_sat: {
7008     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7009     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7010                              getValue(I.getArgOperand(0)),
7011                              DAG.getValueType(VT.getScalarType())));
7012     return;
7013   }
7014   case Intrinsic::set_rounding:
7015     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7016                       {getRoot(), getValue(I.getArgOperand(0))});
7017     setValue(&I, Res);
7018     DAG.setRoot(Res.getValue(0));
7019     return;
7020   case Intrinsic::is_fpclass: {
7021     const DataLayout DLayout = DAG.getDataLayout();
7022     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7023     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7024     FPClassTest Test = static_cast<FPClassTest>(
7025         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7026     MachineFunction &MF = DAG.getMachineFunction();
7027     const Function &F = MF.getFunction();
7028     SDValue Op = getValue(I.getArgOperand(0));
7029     SDNodeFlags Flags;
7030     Flags.setNoFPExcept(
7031         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7032     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7033     // expansion can use illegal types. Making expansion early allows
7034     // legalizing these types prior to selection.
7035     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7036         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7037       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7038       setValue(&I, Result);
7039       return;
7040     }
7041 
7042     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7043     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7044     setValue(&I, V);
7045     return;
7046   }
7047   case Intrinsic::get_fpenv: {
7048     const DataLayout DLayout = DAG.getDataLayout();
7049     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7050     Align TempAlign = DAG.getEVTAlign(EnvVT);
7051     SDValue Chain = getRoot();
7052     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7053     // and temporary storage in stack.
7054     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7055       Res = DAG.getNode(
7056           ISD::GET_FPENV, sdl,
7057           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7058                         MVT::Other),
7059           Chain);
7060     } else {
7061       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7062       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7063       auto MPI =
7064           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7065       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7066           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7067           TempAlign);
7068       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7069       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7070     }
7071     setValue(&I, Res);
7072     DAG.setRoot(Res.getValue(1));
7073     return;
7074   }
7075   case Intrinsic::set_fpenv: {
7076     const DataLayout DLayout = DAG.getDataLayout();
7077     SDValue Env = getValue(I.getArgOperand(0));
7078     EVT EnvVT = Env.getValueType();
7079     Align TempAlign = DAG.getEVTAlign(EnvVT);
7080     SDValue Chain = getRoot();
7081     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7082     // environment from memory.
7083     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7084       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7085     } else {
7086       // Allocate space in stack, copy environment bits into it and use this
7087       // memory in SET_FPENV_MEM.
7088       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7089       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7090       auto MPI =
7091           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7092       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7093                            MachineMemOperand::MOStore);
7094       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7095           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7096           TempAlign);
7097       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7098     }
7099     DAG.setRoot(Chain);
7100     return;
7101   }
7102   case Intrinsic::reset_fpenv:
7103     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7104     return;
7105   case Intrinsic::get_fpmode:
7106     Res = DAG.getNode(
7107         ISD::GET_FPMODE, sdl,
7108         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7109                       MVT::Other),
7110         DAG.getRoot());
7111     setValue(&I, Res);
7112     DAG.setRoot(Res.getValue(1));
7113     return;
7114   case Intrinsic::set_fpmode:
7115     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7116                       getValue(I.getArgOperand(0)));
7117     DAG.setRoot(Res);
7118     return;
7119   case Intrinsic::reset_fpmode: {
7120     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7121     DAG.setRoot(Res);
7122     return;
7123   }
7124   case Intrinsic::pcmarker: {
7125     SDValue Tmp = getValue(I.getArgOperand(0));
7126     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7127     return;
7128   }
7129   case Intrinsic::readcyclecounter: {
7130     SDValue Op = getRoot();
7131     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7132                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7133     setValue(&I, Res);
7134     DAG.setRoot(Res.getValue(1));
7135     return;
7136   }
7137   case Intrinsic::readsteadycounter: {
7138     SDValue Op = getRoot();
7139     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7140                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7141     setValue(&I, Res);
7142     DAG.setRoot(Res.getValue(1));
7143     return;
7144   }
7145   case Intrinsic::bitreverse:
7146     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7147                              getValue(I.getArgOperand(0)).getValueType(),
7148                              getValue(I.getArgOperand(0))));
7149     return;
7150   case Intrinsic::bswap:
7151     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7152                              getValue(I.getArgOperand(0)).getValueType(),
7153                              getValue(I.getArgOperand(0))));
7154     return;
7155   case Intrinsic::cttz: {
7156     SDValue Arg = getValue(I.getArgOperand(0));
7157     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7158     EVT Ty = Arg.getValueType();
7159     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7160                              sdl, Ty, Arg));
7161     return;
7162   }
7163   case Intrinsic::ctlz: {
7164     SDValue Arg = getValue(I.getArgOperand(0));
7165     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7166     EVT Ty = Arg.getValueType();
7167     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7168                              sdl, Ty, Arg));
7169     return;
7170   }
7171   case Intrinsic::ctpop: {
7172     SDValue Arg = getValue(I.getArgOperand(0));
7173     EVT Ty = Arg.getValueType();
7174     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7175     return;
7176   }
7177   case Intrinsic::fshl:
7178   case Intrinsic::fshr: {
7179     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7180     SDValue X = getValue(I.getArgOperand(0));
7181     SDValue Y = getValue(I.getArgOperand(1));
7182     SDValue Z = getValue(I.getArgOperand(2));
7183     EVT VT = X.getValueType();
7184 
7185     if (X == Y) {
7186       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7187       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7188     } else {
7189       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7190       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7191     }
7192     return;
7193   }
7194   case Intrinsic::sadd_sat: {
7195     SDValue Op1 = getValue(I.getArgOperand(0));
7196     SDValue Op2 = getValue(I.getArgOperand(1));
7197     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7198     return;
7199   }
7200   case Intrinsic::uadd_sat: {
7201     SDValue Op1 = getValue(I.getArgOperand(0));
7202     SDValue Op2 = getValue(I.getArgOperand(1));
7203     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7204     return;
7205   }
7206   case Intrinsic::ssub_sat: {
7207     SDValue Op1 = getValue(I.getArgOperand(0));
7208     SDValue Op2 = getValue(I.getArgOperand(1));
7209     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7210     return;
7211   }
7212   case Intrinsic::usub_sat: {
7213     SDValue Op1 = getValue(I.getArgOperand(0));
7214     SDValue Op2 = getValue(I.getArgOperand(1));
7215     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7216     return;
7217   }
7218   case Intrinsic::sshl_sat: {
7219     SDValue Op1 = getValue(I.getArgOperand(0));
7220     SDValue Op2 = getValue(I.getArgOperand(1));
7221     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7222     return;
7223   }
7224   case Intrinsic::ushl_sat: {
7225     SDValue Op1 = getValue(I.getArgOperand(0));
7226     SDValue Op2 = getValue(I.getArgOperand(1));
7227     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7228     return;
7229   }
7230   case Intrinsic::smul_fix:
7231   case Intrinsic::umul_fix:
7232   case Intrinsic::smul_fix_sat:
7233   case Intrinsic::umul_fix_sat: {
7234     SDValue Op1 = getValue(I.getArgOperand(0));
7235     SDValue Op2 = getValue(I.getArgOperand(1));
7236     SDValue Op3 = getValue(I.getArgOperand(2));
7237     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7238                              Op1.getValueType(), Op1, Op2, Op3));
7239     return;
7240   }
7241   case Intrinsic::sdiv_fix:
7242   case Intrinsic::udiv_fix:
7243   case Intrinsic::sdiv_fix_sat:
7244   case Intrinsic::udiv_fix_sat: {
7245     SDValue Op1 = getValue(I.getArgOperand(0));
7246     SDValue Op2 = getValue(I.getArgOperand(1));
7247     SDValue Op3 = getValue(I.getArgOperand(2));
7248     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7249                               Op1, Op2, Op3, DAG, TLI));
7250     return;
7251   }
7252   case Intrinsic::smax: {
7253     SDValue Op1 = getValue(I.getArgOperand(0));
7254     SDValue Op2 = getValue(I.getArgOperand(1));
7255     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7256     return;
7257   }
7258   case Intrinsic::smin: {
7259     SDValue Op1 = getValue(I.getArgOperand(0));
7260     SDValue Op2 = getValue(I.getArgOperand(1));
7261     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7262     return;
7263   }
7264   case Intrinsic::umax: {
7265     SDValue Op1 = getValue(I.getArgOperand(0));
7266     SDValue Op2 = getValue(I.getArgOperand(1));
7267     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7268     return;
7269   }
7270   case Intrinsic::umin: {
7271     SDValue Op1 = getValue(I.getArgOperand(0));
7272     SDValue Op2 = getValue(I.getArgOperand(1));
7273     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7274     return;
7275   }
7276   case Intrinsic::abs: {
7277     // TODO: Preserve "int min is poison" arg in SDAG?
7278     SDValue Op1 = getValue(I.getArgOperand(0));
7279     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7280     return;
7281   }
7282   case Intrinsic::scmp: {
7283     SDValue Op1 = getValue(I.getArgOperand(0));
7284     SDValue Op2 = getValue(I.getArgOperand(1));
7285     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7286     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7287     break;
7288   }
7289   case Intrinsic::ucmp: {
7290     SDValue Op1 = getValue(I.getArgOperand(0));
7291     SDValue Op2 = getValue(I.getArgOperand(1));
7292     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7293     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7294     break;
7295   }
7296   case Intrinsic::stacksave: {
7297     SDValue Op = getRoot();
7298     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7299     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7300     setValue(&I, Res);
7301     DAG.setRoot(Res.getValue(1));
7302     return;
7303   }
7304   case Intrinsic::stackrestore:
7305     Res = getValue(I.getArgOperand(0));
7306     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7307     return;
7308   case Intrinsic::get_dynamic_area_offset: {
7309     SDValue Op = getRoot();
7310     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7311     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7312     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7313     // target.
7314     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7315       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7316                          " intrinsic!");
7317     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7318                       Op);
7319     DAG.setRoot(Op);
7320     setValue(&I, Res);
7321     return;
7322   }
7323   case Intrinsic::stackguard: {
7324     MachineFunction &MF = DAG.getMachineFunction();
7325     const Module &M = *MF.getFunction().getParent();
7326     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7327     SDValue Chain = getRoot();
7328     if (TLI.useLoadStackGuardNode()) {
7329       Res = getLoadStackGuard(DAG, sdl, Chain);
7330       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7331     } else {
7332       const Value *Global = TLI.getSDagStackGuard(M);
7333       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7334       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7335                         MachinePointerInfo(Global, 0), Align,
7336                         MachineMemOperand::MOVolatile);
7337     }
7338     if (TLI.useStackGuardXorFP())
7339       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7340     DAG.setRoot(Chain);
7341     setValue(&I, Res);
7342     return;
7343   }
7344   case Intrinsic::stackprotector: {
7345     // Emit code into the DAG to store the stack guard onto the stack.
7346     MachineFunction &MF = DAG.getMachineFunction();
7347     MachineFrameInfo &MFI = MF.getFrameInfo();
7348     SDValue Src, Chain = getRoot();
7349 
7350     if (TLI.useLoadStackGuardNode())
7351       Src = getLoadStackGuard(DAG, sdl, Chain);
7352     else
7353       Src = getValue(I.getArgOperand(0));   // The guard's value.
7354 
7355     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7356 
7357     int FI = FuncInfo.StaticAllocaMap[Slot];
7358     MFI.setStackProtectorIndex(FI);
7359     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7360 
7361     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7362 
7363     // Store the stack protector onto the stack.
7364     Res = DAG.getStore(
7365         Chain, sdl, Src, FIN,
7366         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7367         MaybeAlign(), MachineMemOperand::MOVolatile);
7368     setValue(&I, Res);
7369     DAG.setRoot(Res);
7370     return;
7371   }
7372   case Intrinsic::objectsize:
7373     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7374 
7375   case Intrinsic::is_constant:
7376     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7377 
7378   case Intrinsic::annotation:
7379   case Intrinsic::ptr_annotation:
7380   case Intrinsic::launder_invariant_group:
7381   case Intrinsic::strip_invariant_group:
7382     // Drop the intrinsic, but forward the value
7383     setValue(&I, getValue(I.getOperand(0)));
7384     return;
7385 
7386   case Intrinsic::assume:
7387   case Intrinsic::experimental_noalias_scope_decl:
7388   case Intrinsic::var_annotation:
7389   case Intrinsic::sideeffect:
7390     // Discard annotate attributes, noalias scope declarations, assumptions, and
7391     // artificial side-effects.
7392     return;
7393 
7394   case Intrinsic::codeview_annotation: {
7395     // Emit a label associated with this metadata.
7396     MachineFunction &MF = DAG.getMachineFunction();
7397     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7398     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7399     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7400     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7401     DAG.setRoot(Res);
7402     return;
7403   }
7404 
7405   case Intrinsic::init_trampoline: {
7406     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7407 
7408     SDValue Ops[6];
7409     Ops[0] = getRoot();
7410     Ops[1] = getValue(I.getArgOperand(0));
7411     Ops[2] = getValue(I.getArgOperand(1));
7412     Ops[3] = getValue(I.getArgOperand(2));
7413     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7414     Ops[5] = DAG.getSrcValue(F);
7415 
7416     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7417 
7418     DAG.setRoot(Res);
7419     return;
7420   }
7421   case Intrinsic::adjust_trampoline:
7422     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7423                              TLI.getPointerTy(DAG.getDataLayout()),
7424                              getValue(I.getArgOperand(0))));
7425     return;
7426   case Intrinsic::gcroot: {
7427     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7428            "only valid in functions with gc specified, enforced by Verifier");
7429     assert(GFI && "implied by previous");
7430     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7431     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7432 
7433     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7434     GFI->addStackRoot(FI->getIndex(), TypeMap);
7435     return;
7436   }
7437   case Intrinsic::gcread:
7438   case Intrinsic::gcwrite:
7439     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7440   case Intrinsic::get_rounding:
7441     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7442     setValue(&I, Res);
7443     DAG.setRoot(Res.getValue(1));
7444     return;
7445 
7446   case Intrinsic::expect:
7447     // Just replace __builtin_expect(exp, c) with EXP.
7448     setValue(&I, getValue(I.getArgOperand(0)));
7449     return;
7450 
7451   case Intrinsic::ubsantrap:
7452   case Intrinsic::debugtrap:
7453   case Intrinsic::trap: {
7454     StringRef TrapFuncName =
7455         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7456     if (TrapFuncName.empty()) {
7457       switch (Intrinsic) {
7458       case Intrinsic::trap:
7459         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7460         break;
7461       case Intrinsic::debugtrap:
7462         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7463         break;
7464       case Intrinsic::ubsantrap:
7465         DAG.setRoot(DAG.getNode(
7466             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7467             DAG.getTargetConstant(
7468                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7469                 MVT::i32)));
7470         break;
7471       default: llvm_unreachable("unknown trap intrinsic");
7472       }
7473       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7474                              I.hasFnAttr(Attribute::NoMerge));
7475       return;
7476     }
7477     TargetLowering::ArgListTy Args;
7478     if (Intrinsic == Intrinsic::ubsantrap) {
7479       Args.push_back(TargetLoweringBase::ArgListEntry());
7480       Args[0].Val = I.getArgOperand(0);
7481       Args[0].Node = getValue(Args[0].Val);
7482       Args[0].Ty = Args[0].Val->getType();
7483     }
7484 
7485     TargetLowering::CallLoweringInfo CLI(DAG);
7486     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7487         CallingConv::C, I.getType(),
7488         DAG.getExternalSymbol(TrapFuncName.data(),
7489                               TLI.getPointerTy(DAG.getDataLayout())),
7490         std::move(Args));
7491     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7492     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7493     DAG.setRoot(Result.second);
7494     return;
7495   }
7496 
7497   case Intrinsic::allow_runtime_check:
7498   case Intrinsic::allow_ubsan_check:
7499     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7500     return;
7501 
7502   case Intrinsic::uadd_with_overflow:
7503   case Intrinsic::sadd_with_overflow:
7504   case Intrinsic::usub_with_overflow:
7505   case Intrinsic::ssub_with_overflow:
7506   case Intrinsic::umul_with_overflow:
7507   case Intrinsic::smul_with_overflow: {
7508     ISD::NodeType Op;
7509     switch (Intrinsic) {
7510     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7511     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7512     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7513     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7514     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7515     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7516     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7517     }
7518     SDValue Op1 = getValue(I.getArgOperand(0));
7519     SDValue Op2 = getValue(I.getArgOperand(1));
7520 
7521     EVT ResultVT = Op1.getValueType();
7522     EVT OverflowVT = MVT::i1;
7523     if (ResultVT.isVector())
7524       OverflowVT = EVT::getVectorVT(
7525           *Context, OverflowVT, ResultVT.getVectorElementCount());
7526 
7527     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7528     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7529     return;
7530   }
7531   case Intrinsic::prefetch: {
7532     SDValue Ops[5];
7533     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7534     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7535     Ops[0] = DAG.getRoot();
7536     Ops[1] = getValue(I.getArgOperand(0));
7537     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7538                                    MVT::i32);
7539     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7540                                    MVT::i32);
7541     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7542                                    MVT::i32);
7543     SDValue Result = DAG.getMemIntrinsicNode(
7544         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7545         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7546         /* align */ std::nullopt, Flags);
7547 
7548     // Chain the prefetch in parallel with any pending loads, to stay out of
7549     // the way of later optimizations.
7550     PendingLoads.push_back(Result);
7551     Result = getRoot();
7552     DAG.setRoot(Result);
7553     return;
7554   }
7555   case Intrinsic::lifetime_start:
7556   case Intrinsic::lifetime_end: {
7557     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7558     // Stack coloring is not enabled in O0, discard region information.
7559     if (TM.getOptLevel() == CodeGenOptLevel::None)
7560       return;
7561 
7562     const int64_t ObjectSize =
7563         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7564     Value *const ObjectPtr = I.getArgOperand(1);
7565     SmallVector<const Value *, 4> Allocas;
7566     getUnderlyingObjects(ObjectPtr, Allocas);
7567 
7568     for (const Value *Alloca : Allocas) {
7569       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7570 
7571       // Could not find an Alloca.
7572       if (!LifetimeObject)
7573         continue;
7574 
7575       // First check that the Alloca is static, otherwise it won't have a
7576       // valid frame index.
7577       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7578       if (SI == FuncInfo.StaticAllocaMap.end())
7579         return;
7580 
7581       const int FrameIndex = SI->second;
7582       int64_t Offset;
7583       if (GetPointerBaseWithConstantOffset(
7584               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7585         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7586       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7587                                 Offset);
7588       DAG.setRoot(Res);
7589     }
7590     return;
7591   }
7592   case Intrinsic::pseudoprobe: {
7593     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7594     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7595     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7596     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7597     DAG.setRoot(Res);
7598     return;
7599   }
7600   case Intrinsic::invariant_start:
7601     // Discard region information.
7602     setValue(&I,
7603              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7604     return;
7605   case Intrinsic::invariant_end:
7606     // Discard region information.
7607     return;
7608   case Intrinsic::clear_cache: {
7609     SDValue InputChain = DAG.getRoot();
7610     SDValue StartVal = getValue(I.getArgOperand(0));
7611     SDValue EndVal = getValue(I.getArgOperand(1));
7612     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7613                       {InputChain, StartVal, EndVal});
7614     setValue(&I, Res);
7615     DAG.setRoot(Res);
7616     return;
7617   }
7618   case Intrinsic::donothing:
7619   case Intrinsic::seh_try_begin:
7620   case Intrinsic::seh_scope_begin:
7621   case Intrinsic::seh_try_end:
7622   case Intrinsic::seh_scope_end:
7623     // ignore
7624     return;
7625   case Intrinsic::experimental_stackmap:
7626     visitStackmap(I);
7627     return;
7628   case Intrinsic::experimental_patchpoint_void:
7629   case Intrinsic::experimental_patchpoint:
7630     visitPatchpoint(I);
7631     return;
7632   case Intrinsic::experimental_gc_statepoint:
7633     LowerStatepoint(cast<GCStatepointInst>(I));
7634     return;
7635   case Intrinsic::experimental_gc_result:
7636     visitGCResult(cast<GCResultInst>(I));
7637     return;
7638   case Intrinsic::experimental_gc_relocate:
7639     visitGCRelocate(cast<GCRelocateInst>(I));
7640     return;
7641   case Intrinsic::instrprof_cover:
7642     llvm_unreachable("instrprof failed to lower a cover");
7643   case Intrinsic::instrprof_increment:
7644     llvm_unreachable("instrprof failed to lower an increment");
7645   case Intrinsic::instrprof_timestamp:
7646     llvm_unreachable("instrprof failed to lower a timestamp");
7647   case Intrinsic::instrprof_value_profile:
7648     llvm_unreachable("instrprof failed to lower a value profiling call");
7649   case Intrinsic::instrprof_mcdc_parameters:
7650     llvm_unreachable("instrprof failed to lower mcdc parameters");
7651   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7652     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7653   case Intrinsic::localescape: {
7654     MachineFunction &MF = DAG.getMachineFunction();
7655     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7656 
7657     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7658     // is the same on all targets.
7659     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7660       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7661       if (isa<ConstantPointerNull>(Arg))
7662         continue; // Skip null pointers. They represent a hole in index space.
7663       AllocaInst *Slot = cast<AllocaInst>(Arg);
7664       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7665              "can only escape static allocas");
7666       int FI = FuncInfo.StaticAllocaMap[Slot];
7667       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7668           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7669       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7670               TII->get(TargetOpcode::LOCAL_ESCAPE))
7671           .addSym(FrameAllocSym)
7672           .addFrameIndex(FI);
7673     }
7674 
7675     return;
7676   }
7677 
7678   case Intrinsic::localrecover: {
7679     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7680     MachineFunction &MF = DAG.getMachineFunction();
7681 
7682     // Get the symbol that defines the frame offset.
7683     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7684     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7685     unsigned IdxVal =
7686         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7687     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7688         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7689 
7690     Value *FP = I.getArgOperand(1);
7691     SDValue FPVal = getValue(FP);
7692     EVT PtrVT = FPVal.getValueType();
7693 
7694     // Create a MCSymbol for the label to avoid any target lowering
7695     // that would make this PC relative.
7696     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7697     SDValue OffsetVal =
7698         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7699 
7700     // Add the offset to the FP.
7701     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7702     setValue(&I, Add);
7703 
7704     return;
7705   }
7706 
7707   case Intrinsic::fake_use: {
7708     Value *V = I.getArgOperand(0);
7709     SDValue Ops[2];
7710     // For Values not declared or previously used in this basic block, the
7711     // NodeMap will not have an entry, and `getValue` will assert if V has no
7712     // valid register value.
7713     auto FakeUseValue = [&]() -> SDValue {
7714       SDValue &N = NodeMap[V];
7715       if (N.getNode())
7716         return N;
7717 
7718       // If there's a virtual register allocated and initialized for this
7719       // value, use it.
7720       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7721         return copyFromReg;
7722       // FIXME: Do we want to preserve constants? It seems pointless.
7723       if (isa<Constant>(V))
7724         return getValue(V);
7725       return SDValue();
7726     }();
7727     if (!FakeUseValue || FakeUseValue.isUndef())
7728       return;
7729     Ops[0] = getRoot();
7730     Ops[1] = FakeUseValue;
7731     // Also, do not translate a fake use with an undef operand, or any other
7732     // empty SDValues.
7733     if (!Ops[1] || Ops[1].isUndef())
7734       return;
7735     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7736     return;
7737   }
7738 
7739   case Intrinsic::eh_exceptionpointer:
7740   case Intrinsic::eh_exceptioncode: {
7741     // Get the exception pointer vreg, copy from it, and resize it to fit.
7742     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7743     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7744     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7745     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7746     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7747     if (Intrinsic == Intrinsic::eh_exceptioncode)
7748       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7749     setValue(&I, N);
7750     return;
7751   }
7752   case Intrinsic::xray_customevent: {
7753     // Here we want to make sure that the intrinsic behaves as if it has a
7754     // specific calling convention.
7755     const auto &Triple = DAG.getTarget().getTargetTriple();
7756     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7757       return;
7758 
7759     SmallVector<SDValue, 8> Ops;
7760 
7761     // We want to say that we always want the arguments in registers.
7762     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7763     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7764     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7765     SDValue Chain = getRoot();
7766     Ops.push_back(LogEntryVal);
7767     Ops.push_back(StrSizeVal);
7768     Ops.push_back(Chain);
7769 
7770     // We need to enforce the calling convention for the callsite, so that
7771     // argument ordering is enforced correctly, and that register allocation can
7772     // see that some registers may be assumed clobbered and have to preserve
7773     // them across calls to the intrinsic.
7774     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7775                                            sdl, NodeTys, Ops);
7776     SDValue patchableNode = SDValue(MN, 0);
7777     DAG.setRoot(patchableNode);
7778     setValue(&I, patchableNode);
7779     return;
7780   }
7781   case Intrinsic::xray_typedevent: {
7782     // Here we want to make sure that the intrinsic behaves as if it has a
7783     // specific calling convention.
7784     const auto &Triple = DAG.getTarget().getTargetTriple();
7785     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7786       return;
7787 
7788     SmallVector<SDValue, 8> Ops;
7789 
7790     // We want to say that we always want the arguments in registers.
7791     // It's unclear to me how manipulating the selection DAG here forces callers
7792     // to provide arguments in registers instead of on the stack.
7793     SDValue LogTypeId = getValue(I.getArgOperand(0));
7794     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7795     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7796     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7797     SDValue Chain = getRoot();
7798     Ops.push_back(LogTypeId);
7799     Ops.push_back(LogEntryVal);
7800     Ops.push_back(StrSizeVal);
7801     Ops.push_back(Chain);
7802 
7803     // We need to enforce the calling convention for the callsite, so that
7804     // argument ordering is enforced correctly, and that register allocation can
7805     // see that some registers may be assumed clobbered and have to preserve
7806     // them across calls to the intrinsic.
7807     MachineSDNode *MN = DAG.getMachineNode(
7808         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7809     SDValue patchableNode = SDValue(MN, 0);
7810     DAG.setRoot(patchableNode);
7811     setValue(&I, patchableNode);
7812     return;
7813   }
7814   case Intrinsic::experimental_deoptimize:
7815     LowerDeoptimizeCall(&I);
7816     return;
7817   case Intrinsic::stepvector:
7818     visitStepVector(I);
7819     return;
7820   case Intrinsic::vector_reduce_fadd:
7821   case Intrinsic::vector_reduce_fmul:
7822   case Intrinsic::vector_reduce_add:
7823   case Intrinsic::vector_reduce_mul:
7824   case Intrinsic::vector_reduce_and:
7825   case Intrinsic::vector_reduce_or:
7826   case Intrinsic::vector_reduce_xor:
7827   case Intrinsic::vector_reduce_smax:
7828   case Intrinsic::vector_reduce_smin:
7829   case Intrinsic::vector_reduce_umax:
7830   case Intrinsic::vector_reduce_umin:
7831   case Intrinsic::vector_reduce_fmax:
7832   case Intrinsic::vector_reduce_fmin:
7833   case Intrinsic::vector_reduce_fmaximum:
7834   case Intrinsic::vector_reduce_fminimum:
7835     visitVectorReduce(I, Intrinsic);
7836     return;
7837 
7838   case Intrinsic::icall_branch_funnel: {
7839     SmallVector<SDValue, 16> Ops;
7840     Ops.push_back(getValue(I.getArgOperand(0)));
7841 
7842     int64_t Offset;
7843     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7844         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7845     if (!Base)
7846       report_fatal_error(
7847           "llvm.icall.branch.funnel operand must be a GlobalValue");
7848     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7849 
7850     struct BranchFunnelTarget {
7851       int64_t Offset;
7852       SDValue Target;
7853     };
7854     SmallVector<BranchFunnelTarget, 8> Targets;
7855 
7856     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7857       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7858           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7859       if (ElemBase != Base)
7860         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7861                            "to the same GlobalValue");
7862 
7863       SDValue Val = getValue(I.getArgOperand(Op + 1));
7864       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7865       if (!GA)
7866         report_fatal_error(
7867             "llvm.icall.branch.funnel operand must be a GlobalValue");
7868       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7869                                      GA->getGlobal(), sdl, Val.getValueType(),
7870                                      GA->getOffset())});
7871     }
7872     llvm::sort(Targets,
7873                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7874                  return T1.Offset < T2.Offset;
7875                });
7876 
7877     for (auto &T : Targets) {
7878       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7879       Ops.push_back(T.Target);
7880     }
7881 
7882     Ops.push_back(DAG.getRoot()); // Chain
7883     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7884                                  MVT::Other, Ops),
7885               0);
7886     DAG.setRoot(N);
7887     setValue(&I, N);
7888     HasTailCall = true;
7889     return;
7890   }
7891 
7892   case Intrinsic::wasm_landingpad_index:
7893     // Information this intrinsic contained has been transferred to
7894     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7895     // delete it now.
7896     return;
7897 
7898   case Intrinsic::aarch64_settag:
7899   case Intrinsic::aarch64_settag_zero: {
7900     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7901     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7902     SDValue Val = TSI.EmitTargetCodeForSetTag(
7903         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7904         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7905         ZeroMemory);
7906     DAG.setRoot(Val);
7907     setValue(&I, Val);
7908     return;
7909   }
7910   case Intrinsic::amdgcn_cs_chain: {
7911     assert(I.arg_size() == 5 && "Additional args not supported yet");
7912     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7913            "Non-zero flags not supported yet");
7914 
7915     // At this point we don't care if it's amdgpu_cs_chain or
7916     // amdgpu_cs_chain_preserve.
7917     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7918 
7919     Type *RetTy = I.getType();
7920     assert(RetTy->isVoidTy() && "Should not return");
7921 
7922     SDValue Callee = getValue(I.getOperand(0));
7923 
7924     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7925     // We'll also tack the value of the EXEC mask at the end.
7926     TargetLowering::ArgListTy Args;
7927     Args.reserve(3);
7928 
7929     for (unsigned Idx : {2, 3, 1}) {
7930       TargetLowering::ArgListEntry Arg;
7931       Arg.Node = getValue(I.getOperand(Idx));
7932       Arg.Ty = I.getOperand(Idx)->getType();
7933       Arg.setAttributes(&I, Idx);
7934       Args.push_back(Arg);
7935     }
7936 
7937     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7938     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7939     Args[2].IsInReg = true; // EXEC should be inreg
7940 
7941     TargetLowering::CallLoweringInfo CLI(DAG);
7942     CLI.setDebugLoc(getCurSDLoc())
7943         .setChain(getRoot())
7944         .setCallee(CC, RetTy, Callee, std::move(Args))
7945         .setNoReturn(true)
7946         .setTailCall(true)
7947         .setConvergent(I.isConvergent());
7948     CLI.CB = &I;
7949     std::pair<SDValue, SDValue> Result =
7950         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7951     (void)Result;
7952     assert(!Result.first.getNode() && !Result.second.getNode() &&
7953            "Should've lowered as tail call");
7954 
7955     HasTailCall = true;
7956     return;
7957   }
7958   case Intrinsic::ptrmask: {
7959     SDValue Ptr = getValue(I.getOperand(0));
7960     SDValue Mask = getValue(I.getOperand(1));
7961 
7962     // On arm64_32, pointers are 32 bits when stored in memory, but
7963     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7964     // match the index type, but the pointer is 64 bits, so the the mask must be
7965     // zero-extended up to 64 bits to match the pointer.
7966     EVT PtrVT =
7967         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7968     EVT MemVT =
7969         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7970     assert(PtrVT == Ptr.getValueType());
7971     assert(MemVT == Mask.getValueType());
7972     if (MemVT != PtrVT)
7973       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7974 
7975     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7976     return;
7977   }
7978   case Intrinsic::threadlocal_address: {
7979     setValue(&I, getValue(I.getOperand(0)));
7980     return;
7981   }
7982   case Intrinsic::get_active_lane_mask: {
7983     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7984     SDValue Index = getValue(I.getOperand(0));
7985     EVT ElementVT = Index.getValueType();
7986 
7987     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7988       visitTargetIntrinsic(I, Intrinsic);
7989       return;
7990     }
7991 
7992     SDValue TripCount = getValue(I.getOperand(1));
7993     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7994                                  CCVT.getVectorElementCount());
7995 
7996     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7997     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7998     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7999     SDValue VectorInduction = DAG.getNode(
8000         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8001     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8002                                  VectorTripCount, ISD::CondCode::SETULT);
8003     setValue(&I, SetCC);
8004     return;
8005   }
8006   case Intrinsic::experimental_get_vector_length: {
8007     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8008            "Expected positive VF");
8009     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8010     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8011 
8012     SDValue Count = getValue(I.getOperand(0));
8013     EVT CountVT = Count.getValueType();
8014 
8015     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8016       visitTargetIntrinsic(I, Intrinsic);
8017       return;
8018     }
8019 
8020     // Expand to a umin between the trip count and the maximum elements the type
8021     // can hold.
8022     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8023 
8024     // Extend the trip count to at least the result VT.
8025     if (CountVT.bitsLT(VT)) {
8026       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8027       CountVT = VT;
8028     }
8029 
8030     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8031                                          ElementCount::get(VF, IsScalable));
8032 
8033     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8034     // Clip to the result type if needed.
8035     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8036 
8037     setValue(&I, Trunc);
8038     return;
8039   }
8040   case Intrinsic::experimental_vector_partial_reduce_add: {
8041     SDValue OpNode = getValue(I.getOperand(1));
8042     EVT ReducedTy = EVT::getEVT(I.getType());
8043     EVT FullTy = OpNode.getValueType();
8044 
8045     unsigned Stride = ReducedTy.getVectorMinNumElements();
8046     unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride;
8047 
8048     // Collect all of the subvectors
8049     std::deque<SDValue> Subvectors;
8050     Subvectors.push_back(getValue(I.getOperand(0)));
8051     for (unsigned i = 0; i < ScaleFactor; i++) {
8052       auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl);
8053       Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy,
8054                                        {OpNode, SourceIndex}));
8055     }
8056 
8057     // Flatten the subvector tree
8058     while (Subvectors.size() > 1) {
8059       Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy,
8060                                        {Subvectors[0], Subvectors[1]}));
8061       Subvectors.pop_front();
8062       Subvectors.pop_front();
8063     }
8064 
8065     assert(Subvectors.size() == 1 &&
8066            "There should only be one subvector after tree flattening");
8067 
8068     setValue(&I, Subvectors[0]);
8069     return;
8070   }
8071   case Intrinsic::experimental_cttz_elts: {
8072     auto DL = getCurSDLoc();
8073     SDValue Op = getValue(I.getOperand(0));
8074     EVT OpVT = Op.getValueType();
8075 
8076     if (!TLI.shouldExpandCttzElements(OpVT)) {
8077       visitTargetIntrinsic(I, Intrinsic);
8078       return;
8079     }
8080 
8081     if (OpVT.getScalarType() != MVT::i1) {
8082       // Compare the input vector elements to zero & use to count trailing zeros
8083       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8084       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8085                               OpVT.getVectorElementCount());
8086       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8087     }
8088 
8089     // If the zero-is-poison flag is set, we can assume the upper limit
8090     // of the result is VF-1.
8091     bool ZeroIsPoison =
8092         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8093     ConstantRange VScaleRange(1, true); // Dummy value.
8094     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8095       VScaleRange = getVScaleRange(I.getCaller(), 64);
8096     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8097         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8098 
8099     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8100 
8101     // Create the new vector type & get the vector length
8102     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8103                                  OpVT.getVectorElementCount());
8104 
8105     SDValue VL =
8106         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8107 
8108     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8109     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8110     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8111     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8112     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8113     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8114     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8115 
8116     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8117     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8118 
8119     setValue(&I, Ret);
8120     return;
8121   }
8122   case Intrinsic::vector_insert: {
8123     SDValue Vec = getValue(I.getOperand(0));
8124     SDValue SubVec = getValue(I.getOperand(1));
8125     SDValue Index = getValue(I.getOperand(2));
8126 
8127     // The intrinsic's index type is i64, but the SDNode requires an index type
8128     // suitable for the target. Convert the index as required.
8129     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8130     if (Index.getValueType() != VectorIdxTy)
8131       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8132 
8133     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8134     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8135                              Index));
8136     return;
8137   }
8138   case Intrinsic::vector_extract: {
8139     SDValue Vec = getValue(I.getOperand(0));
8140     SDValue Index = getValue(I.getOperand(1));
8141     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8142 
8143     // The intrinsic's index type is i64, but the SDNode requires an index type
8144     // suitable for the target. Convert the index as required.
8145     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8146     if (Index.getValueType() != VectorIdxTy)
8147       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8148 
8149     setValue(&I,
8150              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8151     return;
8152   }
8153   case Intrinsic::vector_reverse:
8154     visitVectorReverse(I);
8155     return;
8156   case Intrinsic::vector_splice:
8157     visitVectorSplice(I);
8158     return;
8159   case Intrinsic::callbr_landingpad:
8160     visitCallBrLandingPad(I);
8161     return;
8162   case Intrinsic::vector_interleave2:
8163     visitVectorInterleave(I);
8164     return;
8165   case Intrinsic::vector_deinterleave2:
8166     visitVectorDeinterleave(I);
8167     return;
8168   case Intrinsic::experimental_vector_compress:
8169     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8170                              getValue(I.getArgOperand(0)).getValueType(),
8171                              getValue(I.getArgOperand(0)),
8172                              getValue(I.getArgOperand(1)),
8173                              getValue(I.getArgOperand(2)), Flags));
8174     return;
8175   case Intrinsic::experimental_convergence_anchor:
8176   case Intrinsic::experimental_convergence_entry:
8177   case Intrinsic::experimental_convergence_loop:
8178     visitConvergenceControl(I, Intrinsic);
8179     return;
8180   case Intrinsic::experimental_vector_histogram_add: {
8181     visitVectorHistogram(I, Intrinsic);
8182     return;
8183   }
8184   }
8185 }
8186 
8187 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8188     const ConstrainedFPIntrinsic &FPI) {
8189   SDLoc sdl = getCurSDLoc();
8190 
8191   // We do not need to serialize constrained FP intrinsics against
8192   // each other or against (nonvolatile) loads, so they can be
8193   // chained like loads.
8194   SDValue Chain = DAG.getRoot();
8195   SmallVector<SDValue, 4> Opers;
8196   Opers.push_back(Chain);
8197   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8198     Opers.push_back(getValue(FPI.getArgOperand(I)));
8199 
8200   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8201     assert(Result.getNode()->getNumValues() == 2);
8202 
8203     // Push node to the appropriate list so that future instructions can be
8204     // chained up correctly.
8205     SDValue OutChain = Result.getValue(1);
8206     switch (EB) {
8207     case fp::ExceptionBehavior::ebIgnore:
8208       // The only reason why ebIgnore nodes still need to be chained is that
8209       // they might depend on the current rounding mode, and therefore must
8210       // not be moved across instruction that may change that mode.
8211       [[fallthrough]];
8212     case fp::ExceptionBehavior::ebMayTrap:
8213       // These must not be moved across calls or instructions that may change
8214       // floating-point exception masks.
8215       PendingConstrainedFP.push_back(OutChain);
8216       break;
8217     case fp::ExceptionBehavior::ebStrict:
8218       // These must not be moved across calls or instructions that may change
8219       // floating-point exception masks or read floating-point exception flags.
8220       // In addition, they cannot be optimized out even if unused.
8221       PendingConstrainedFPStrict.push_back(OutChain);
8222       break;
8223     }
8224   };
8225 
8226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8227   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8228   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8229   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8230 
8231   SDNodeFlags Flags;
8232   if (EB == fp::ExceptionBehavior::ebIgnore)
8233     Flags.setNoFPExcept(true);
8234 
8235   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8236     Flags.copyFMF(*FPOp);
8237 
8238   unsigned Opcode;
8239   switch (FPI.getIntrinsicID()) {
8240   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8241 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8242   case Intrinsic::INTRINSIC:                                                   \
8243     Opcode = ISD::STRICT_##DAGN;                                               \
8244     break;
8245 #include "llvm/IR/ConstrainedOps.def"
8246   case Intrinsic::experimental_constrained_fmuladd: {
8247     Opcode = ISD::STRICT_FMA;
8248     // Break fmuladd into fmul and fadd.
8249     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8250         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8251       Opers.pop_back();
8252       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8253       pushOutChain(Mul, EB);
8254       Opcode = ISD::STRICT_FADD;
8255       Opers.clear();
8256       Opers.push_back(Mul.getValue(1));
8257       Opers.push_back(Mul.getValue(0));
8258       Opers.push_back(getValue(FPI.getArgOperand(2)));
8259     }
8260     break;
8261   }
8262   }
8263 
8264   // A few strict DAG nodes carry additional operands that are not
8265   // set up by the default code above.
8266   switch (Opcode) {
8267   default: break;
8268   case ISD::STRICT_FP_ROUND:
8269     Opers.push_back(
8270         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8271     break;
8272   case ISD::STRICT_FSETCC:
8273   case ISD::STRICT_FSETCCS: {
8274     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8275     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8276     if (TM.Options.NoNaNsFPMath)
8277       Condition = getFCmpCodeWithoutNaN(Condition);
8278     Opers.push_back(DAG.getCondCode(Condition));
8279     break;
8280   }
8281   }
8282 
8283   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8284   pushOutChain(Result, EB);
8285 
8286   SDValue FPResult = Result.getValue(0);
8287   setValue(&FPI, FPResult);
8288 }
8289 
8290 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8291   std::optional<unsigned> ResOPC;
8292   switch (VPIntrin.getIntrinsicID()) {
8293   case Intrinsic::vp_ctlz: {
8294     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8295     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8296     break;
8297   }
8298   case Intrinsic::vp_cttz: {
8299     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8300     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8301     break;
8302   }
8303   case Intrinsic::vp_cttz_elts: {
8304     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8305     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8306     break;
8307   }
8308 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8309   case Intrinsic::VPID:                                                        \
8310     ResOPC = ISD::VPSD;                                                        \
8311     break;
8312 #include "llvm/IR/VPIntrinsics.def"
8313   }
8314 
8315   if (!ResOPC)
8316     llvm_unreachable(
8317         "Inconsistency: no SDNode available for this VPIntrinsic!");
8318 
8319   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8320       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8321     if (VPIntrin.getFastMathFlags().allowReassoc())
8322       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8323                                                 : ISD::VP_REDUCE_FMUL;
8324   }
8325 
8326   return *ResOPC;
8327 }
8328 
8329 void SelectionDAGBuilder::visitVPLoad(
8330     const VPIntrinsic &VPIntrin, EVT VT,
8331     const SmallVectorImpl<SDValue> &OpValues) {
8332   SDLoc DL = getCurSDLoc();
8333   Value *PtrOperand = VPIntrin.getArgOperand(0);
8334   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8335   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8336   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8337   SDValue LD;
8338   // Do not serialize variable-length loads of constant memory with
8339   // anything.
8340   if (!Alignment)
8341     Alignment = DAG.getEVTAlign(VT);
8342   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8343   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8344   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8345   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8346       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8347       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8348   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8349                      MMO, false /*IsExpanding */);
8350   if (AddToChain)
8351     PendingLoads.push_back(LD.getValue(1));
8352   setValue(&VPIntrin, LD);
8353 }
8354 
8355 void SelectionDAGBuilder::visitVPGather(
8356     const VPIntrinsic &VPIntrin, EVT VT,
8357     const SmallVectorImpl<SDValue> &OpValues) {
8358   SDLoc DL = getCurSDLoc();
8359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8360   Value *PtrOperand = VPIntrin.getArgOperand(0);
8361   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8362   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8363   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8364   SDValue LD;
8365   if (!Alignment)
8366     Alignment = DAG.getEVTAlign(VT.getScalarType());
8367   unsigned AS =
8368     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8369   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8370       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8371       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8372   SDValue Base, Index, Scale;
8373   ISD::MemIndexType IndexType;
8374   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8375                                     this, VPIntrin.getParent(),
8376                                     VT.getScalarStoreSize());
8377   if (!UniformBase) {
8378     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8379     Index = getValue(PtrOperand);
8380     IndexType = ISD::SIGNED_SCALED;
8381     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8382   }
8383   EVT IdxVT = Index.getValueType();
8384   EVT EltTy = IdxVT.getVectorElementType();
8385   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8386     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8387     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8388   }
8389   LD = DAG.getGatherVP(
8390       DAG.getVTList(VT, MVT::Other), VT, DL,
8391       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8392       IndexType);
8393   PendingLoads.push_back(LD.getValue(1));
8394   setValue(&VPIntrin, LD);
8395 }
8396 
8397 void SelectionDAGBuilder::visitVPStore(
8398     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8399   SDLoc DL = getCurSDLoc();
8400   Value *PtrOperand = VPIntrin.getArgOperand(1);
8401   EVT VT = OpValues[0].getValueType();
8402   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8403   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8404   SDValue ST;
8405   if (!Alignment)
8406     Alignment = DAG.getEVTAlign(VT);
8407   SDValue Ptr = OpValues[1];
8408   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8409   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8410       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8411       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8412   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8413                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8414                       /* IsTruncating */ false, /*IsCompressing*/ false);
8415   DAG.setRoot(ST);
8416   setValue(&VPIntrin, ST);
8417 }
8418 
8419 void SelectionDAGBuilder::visitVPScatter(
8420     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8421   SDLoc DL = getCurSDLoc();
8422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8423   Value *PtrOperand = VPIntrin.getArgOperand(1);
8424   EVT VT = OpValues[0].getValueType();
8425   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8426   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8427   SDValue ST;
8428   if (!Alignment)
8429     Alignment = DAG.getEVTAlign(VT.getScalarType());
8430   unsigned AS =
8431       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8432   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8433       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8434       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8435   SDValue Base, Index, Scale;
8436   ISD::MemIndexType IndexType;
8437   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8438                                     this, VPIntrin.getParent(),
8439                                     VT.getScalarStoreSize());
8440   if (!UniformBase) {
8441     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8442     Index = getValue(PtrOperand);
8443     IndexType = ISD::SIGNED_SCALED;
8444     Scale =
8445       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8446   }
8447   EVT IdxVT = Index.getValueType();
8448   EVT EltTy = IdxVT.getVectorElementType();
8449   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8450     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8451     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8452   }
8453   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8454                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8455                          OpValues[2], OpValues[3]},
8456                         MMO, IndexType);
8457   DAG.setRoot(ST);
8458   setValue(&VPIntrin, ST);
8459 }
8460 
8461 void SelectionDAGBuilder::visitVPStridedLoad(
8462     const VPIntrinsic &VPIntrin, EVT VT,
8463     const SmallVectorImpl<SDValue> &OpValues) {
8464   SDLoc DL = getCurSDLoc();
8465   Value *PtrOperand = VPIntrin.getArgOperand(0);
8466   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8467   if (!Alignment)
8468     Alignment = DAG.getEVTAlign(VT.getScalarType());
8469   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8470   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8471   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8472   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8473   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8474   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8475   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8476       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8477       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8478 
8479   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8480                                     OpValues[2], OpValues[3], MMO,
8481                                     false /*IsExpanding*/);
8482 
8483   if (AddToChain)
8484     PendingLoads.push_back(LD.getValue(1));
8485   setValue(&VPIntrin, LD);
8486 }
8487 
8488 void SelectionDAGBuilder::visitVPStridedStore(
8489     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8490   SDLoc DL = getCurSDLoc();
8491   Value *PtrOperand = VPIntrin.getArgOperand(1);
8492   EVT VT = OpValues[0].getValueType();
8493   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8494   if (!Alignment)
8495     Alignment = DAG.getEVTAlign(VT.getScalarType());
8496   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8497   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8498   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8499       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8500       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8501 
8502   SDValue ST = DAG.getStridedStoreVP(
8503       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8504       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8505       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8506       /*IsCompressing*/ false);
8507 
8508   DAG.setRoot(ST);
8509   setValue(&VPIntrin, ST);
8510 }
8511 
8512 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8514   SDLoc DL = getCurSDLoc();
8515 
8516   ISD::CondCode Condition;
8517   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8518   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8519   if (IsFP) {
8520     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8521     // flags, but calls that don't return floating-point types can't be
8522     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8523     Condition = getFCmpCondCode(CondCode);
8524     if (TM.Options.NoNaNsFPMath)
8525       Condition = getFCmpCodeWithoutNaN(Condition);
8526   } else {
8527     Condition = getICmpCondCode(CondCode);
8528   }
8529 
8530   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8531   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8532   // #2 is the condition code
8533   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8534   SDValue EVL = getValue(VPIntrin.getOperand(4));
8535   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8536   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8537          "Unexpected target EVL type");
8538   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8539 
8540   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8541                                                         VPIntrin.getType());
8542   setValue(&VPIntrin,
8543            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8544 }
8545 
8546 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8547     const VPIntrinsic &VPIntrin) {
8548   SDLoc DL = getCurSDLoc();
8549   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8550 
8551   auto IID = VPIntrin.getIntrinsicID();
8552 
8553   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8554     return visitVPCmp(*CmpI);
8555 
8556   SmallVector<EVT, 4> ValueVTs;
8557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8558   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8559   SDVTList VTs = DAG.getVTList(ValueVTs);
8560 
8561   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8562 
8563   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8564   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8565          "Unexpected target EVL type");
8566 
8567   // Request operands.
8568   SmallVector<SDValue, 7> OpValues;
8569   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8570     auto Op = getValue(VPIntrin.getArgOperand(I));
8571     if (I == EVLParamPos)
8572       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8573     OpValues.push_back(Op);
8574   }
8575 
8576   switch (Opcode) {
8577   default: {
8578     SDNodeFlags SDFlags;
8579     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8580       SDFlags.copyFMF(*FPMO);
8581     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8582     setValue(&VPIntrin, Result);
8583     break;
8584   }
8585   case ISD::VP_LOAD:
8586     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8587     break;
8588   case ISD::VP_GATHER:
8589     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8590     break;
8591   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8592     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8593     break;
8594   case ISD::VP_STORE:
8595     visitVPStore(VPIntrin, OpValues);
8596     break;
8597   case ISD::VP_SCATTER:
8598     visitVPScatter(VPIntrin, OpValues);
8599     break;
8600   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8601     visitVPStridedStore(VPIntrin, OpValues);
8602     break;
8603   case ISD::VP_FMULADD: {
8604     assert(OpValues.size() == 5 && "Unexpected number of operands");
8605     SDNodeFlags SDFlags;
8606     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8607       SDFlags.copyFMF(*FPMO);
8608     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8609         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8610       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8611     } else {
8612       SDValue Mul = DAG.getNode(
8613           ISD::VP_FMUL, DL, VTs,
8614           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8615       SDValue Add =
8616           DAG.getNode(ISD::VP_FADD, DL, VTs,
8617                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8618       setValue(&VPIntrin, Add);
8619     }
8620     break;
8621   }
8622   case ISD::VP_IS_FPCLASS: {
8623     const DataLayout DLayout = DAG.getDataLayout();
8624     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8625     auto Constant = OpValues[1]->getAsZExtVal();
8626     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8627     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8628                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8629     setValue(&VPIntrin, V);
8630     return;
8631   }
8632   case ISD::VP_INTTOPTR: {
8633     SDValue N = OpValues[0];
8634     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8635     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8636     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8637                                OpValues[2]);
8638     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8639                              OpValues[2]);
8640     setValue(&VPIntrin, N);
8641     break;
8642   }
8643   case ISD::VP_PTRTOINT: {
8644     SDValue N = OpValues[0];
8645     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8646                                                           VPIntrin.getType());
8647     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8648                                        VPIntrin.getOperand(0)->getType());
8649     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8650                                OpValues[2]);
8651     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8652                              OpValues[2]);
8653     setValue(&VPIntrin, N);
8654     break;
8655   }
8656   case ISD::VP_ABS:
8657   case ISD::VP_CTLZ:
8658   case ISD::VP_CTLZ_ZERO_UNDEF:
8659   case ISD::VP_CTTZ:
8660   case ISD::VP_CTTZ_ZERO_UNDEF:
8661   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8662   case ISD::VP_CTTZ_ELTS: {
8663     SDValue Result =
8664         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8665     setValue(&VPIntrin, Result);
8666     break;
8667   }
8668   }
8669 }
8670 
8671 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8672                                           const BasicBlock *EHPadBB,
8673                                           MCSymbol *&BeginLabel) {
8674   MachineFunction &MF = DAG.getMachineFunction();
8675 
8676   // Insert a label before the invoke call to mark the try range.  This can be
8677   // used to detect deletion of the invoke via the MachineModuleInfo.
8678   BeginLabel = MF.getContext().createTempSymbol();
8679 
8680   // For SjLj, keep track of which landing pads go with which invokes
8681   // so as to maintain the ordering of pads in the LSDA.
8682   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8683   if (CallSiteIndex) {
8684     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8685     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8686 
8687     // Now that the call site is handled, stop tracking it.
8688     FuncInfo.setCurrentCallSite(0);
8689   }
8690 
8691   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8692 }
8693 
8694 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8695                                         const BasicBlock *EHPadBB,
8696                                         MCSymbol *BeginLabel) {
8697   assert(BeginLabel && "BeginLabel should've been set");
8698 
8699   MachineFunction &MF = DAG.getMachineFunction();
8700 
8701   // Insert a label at the end of the invoke call to mark the try range.  This
8702   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8703   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8704   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8705 
8706   // Inform MachineModuleInfo of range.
8707   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8708   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8709   // actually use outlined funclets and their LSDA info style.
8710   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8711     assert(II && "II should've been set");
8712     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8713     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8714   } else if (!isScopedEHPersonality(Pers)) {
8715     assert(EHPadBB);
8716     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8717   }
8718 
8719   return Chain;
8720 }
8721 
8722 std::pair<SDValue, SDValue>
8723 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8724                                     const BasicBlock *EHPadBB) {
8725   MCSymbol *BeginLabel = nullptr;
8726 
8727   if (EHPadBB) {
8728     // Both PendingLoads and PendingExports must be flushed here;
8729     // this call might not return.
8730     (void)getRoot();
8731     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8732     CLI.setChain(getRoot());
8733   }
8734 
8735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8736   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8737 
8738   assert((CLI.IsTailCall || Result.second.getNode()) &&
8739          "Non-null chain expected with non-tail call!");
8740   assert((Result.second.getNode() || !Result.first.getNode()) &&
8741          "Null value expected with tail call!");
8742 
8743   if (!Result.second.getNode()) {
8744     // As a special case, a null chain means that a tail call has been emitted
8745     // and the DAG root is already updated.
8746     HasTailCall = true;
8747 
8748     // Since there's no actual continuation from this block, nothing can be
8749     // relying on us setting vregs for them.
8750     PendingExports.clear();
8751   } else {
8752     DAG.setRoot(Result.second);
8753   }
8754 
8755   if (EHPadBB) {
8756     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8757                            BeginLabel));
8758     Result.second = getRoot();
8759   }
8760 
8761   return Result;
8762 }
8763 
8764 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8765                                       bool isTailCall, bool isMustTailCall,
8766                                       const BasicBlock *EHPadBB,
8767                                       const TargetLowering::PtrAuthInfo *PAI) {
8768   auto &DL = DAG.getDataLayout();
8769   FunctionType *FTy = CB.getFunctionType();
8770   Type *RetTy = CB.getType();
8771 
8772   TargetLowering::ArgListTy Args;
8773   Args.reserve(CB.arg_size());
8774 
8775   const Value *SwiftErrorVal = nullptr;
8776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8777 
8778   if (isTailCall) {
8779     // Avoid emitting tail calls in functions with the disable-tail-calls
8780     // attribute.
8781     auto *Caller = CB.getParent()->getParent();
8782     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8783         "true" && !isMustTailCall)
8784       isTailCall = false;
8785 
8786     // We can't tail call inside a function with a swifterror argument. Lowering
8787     // does not support this yet. It would have to move into the swifterror
8788     // register before the call.
8789     if (TLI.supportSwiftError() &&
8790         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8791       isTailCall = false;
8792   }
8793 
8794   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8795     TargetLowering::ArgListEntry Entry;
8796     const Value *V = *I;
8797 
8798     // Skip empty types
8799     if (V->getType()->isEmptyTy())
8800       continue;
8801 
8802     SDValue ArgNode = getValue(V);
8803     Entry.Node = ArgNode; Entry.Ty = V->getType();
8804 
8805     Entry.setAttributes(&CB, I - CB.arg_begin());
8806 
8807     // Use swifterror virtual register as input to the call.
8808     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8809       SwiftErrorVal = V;
8810       // We find the virtual register for the actual swifterror argument.
8811       // Instead of using the Value, we use the virtual register instead.
8812       Entry.Node =
8813           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8814                           EVT(TLI.getPointerTy(DL)));
8815     }
8816 
8817     Args.push_back(Entry);
8818 
8819     // If we have an explicit sret argument that is an Instruction, (i.e., it
8820     // might point to function-local memory), we can't meaningfully tail-call.
8821     if (Entry.IsSRet && isa<Instruction>(V))
8822       isTailCall = false;
8823   }
8824 
8825   // If call site has a cfguardtarget operand bundle, create and add an
8826   // additional ArgListEntry.
8827   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8828     TargetLowering::ArgListEntry Entry;
8829     Value *V = Bundle->Inputs[0];
8830     SDValue ArgNode = getValue(V);
8831     Entry.Node = ArgNode;
8832     Entry.Ty = V->getType();
8833     Entry.IsCFGuardTarget = true;
8834     Args.push_back(Entry);
8835   }
8836 
8837   // Check if target-independent constraints permit a tail call here.
8838   // Target-dependent constraints are checked within TLI->LowerCallTo.
8839   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8840     isTailCall = false;
8841 
8842   // Disable tail calls if there is an swifterror argument. Targets have not
8843   // been updated to support tail calls.
8844   if (TLI.supportSwiftError() && SwiftErrorVal)
8845     isTailCall = false;
8846 
8847   ConstantInt *CFIType = nullptr;
8848   if (CB.isIndirectCall()) {
8849     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8850       if (!TLI.supportKCFIBundles())
8851         report_fatal_error(
8852             "Target doesn't support calls with kcfi operand bundles.");
8853       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8854       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8855     }
8856   }
8857 
8858   SDValue ConvControlToken;
8859   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8860     auto *Token = Bundle->Inputs[0].get();
8861     ConvControlToken = getValue(Token);
8862   }
8863 
8864   TargetLowering::CallLoweringInfo CLI(DAG);
8865   CLI.setDebugLoc(getCurSDLoc())
8866       .setChain(getRoot())
8867       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8868       .setTailCall(isTailCall)
8869       .setConvergent(CB.isConvergent())
8870       .setIsPreallocated(
8871           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8872       .setCFIType(CFIType)
8873       .setConvergenceControlToken(ConvControlToken);
8874 
8875   // Set the pointer authentication info if we have it.
8876   if (PAI) {
8877     if (!TLI.supportPtrAuthBundles())
8878       report_fatal_error(
8879           "This target doesn't support calls with ptrauth operand bundles.");
8880     CLI.setPtrAuth(*PAI);
8881   }
8882 
8883   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8884 
8885   if (Result.first.getNode()) {
8886     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8887     setValue(&CB, Result.first);
8888   }
8889 
8890   // The last element of CLI.InVals has the SDValue for swifterror return.
8891   // Here we copy it to a virtual register and update SwiftErrorMap for
8892   // book-keeping.
8893   if (SwiftErrorVal && TLI.supportSwiftError()) {
8894     // Get the last element of InVals.
8895     SDValue Src = CLI.InVals.back();
8896     Register VReg =
8897         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8898     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8899     DAG.setRoot(CopyNode);
8900   }
8901 }
8902 
8903 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8904                              SelectionDAGBuilder &Builder) {
8905   // Check to see if this load can be trivially constant folded, e.g. if the
8906   // input is from a string literal.
8907   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8908     // Cast pointer to the type we really want to load.
8909     Type *LoadTy =
8910         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8911     if (LoadVT.isVector())
8912       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8913 
8914     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8915                                          PointerType::getUnqual(LoadTy));
8916 
8917     if (const Constant *LoadCst =
8918             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8919                                          LoadTy, Builder.DAG.getDataLayout()))
8920       return Builder.getValue(LoadCst);
8921   }
8922 
8923   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8924   // still constant memory, the input chain can be the entry node.
8925   SDValue Root;
8926   bool ConstantMemory = false;
8927 
8928   // Do not serialize (non-volatile) loads of constant memory with anything.
8929   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8930     Root = Builder.DAG.getEntryNode();
8931     ConstantMemory = true;
8932   } else {
8933     // Do not serialize non-volatile loads against each other.
8934     Root = Builder.DAG.getRoot();
8935   }
8936 
8937   SDValue Ptr = Builder.getValue(PtrVal);
8938   SDValue LoadVal =
8939       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8940                           MachinePointerInfo(PtrVal), Align(1));
8941 
8942   if (!ConstantMemory)
8943     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8944   return LoadVal;
8945 }
8946 
8947 /// Record the value for an instruction that produces an integer result,
8948 /// converting the type where necessary.
8949 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8950                                                   SDValue Value,
8951                                                   bool IsSigned) {
8952   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8953                                                     I.getType(), true);
8954   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8955   setValue(&I, Value);
8956 }
8957 
8958 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8959 /// true and lower it. Otherwise return false, and it will be lowered like a
8960 /// normal call.
8961 /// The caller already checked that \p I calls the appropriate LibFunc with a
8962 /// correct prototype.
8963 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8964   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8965   const Value *Size = I.getArgOperand(2);
8966   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8967   if (CSize && CSize->getZExtValue() == 0) {
8968     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8969                                                           I.getType(), true);
8970     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8971     return true;
8972   }
8973 
8974   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8975   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8976       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8977       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8978   if (Res.first.getNode()) {
8979     processIntegerCallValue(I, Res.first, true);
8980     PendingLoads.push_back(Res.second);
8981     return true;
8982   }
8983 
8984   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8985   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8986   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8987     return false;
8988 
8989   // If the target has a fast compare for the given size, it will return a
8990   // preferred load type for that size. Require that the load VT is legal and
8991   // that the target supports unaligned loads of that type. Otherwise, return
8992   // INVALID.
8993   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8994     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8995     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8996     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8997       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8998       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8999       // TODO: Check alignment of src and dest ptrs.
9000       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9001       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9002       if (!TLI.isTypeLegal(LVT) ||
9003           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9004           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9005         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9006     }
9007 
9008     return LVT;
9009   };
9010 
9011   // This turns into unaligned loads. We only do this if the target natively
9012   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9013   // we'll only produce a small number of byte loads.
9014   MVT LoadVT;
9015   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9016   switch (NumBitsToCompare) {
9017   default:
9018     return false;
9019   case 16:
9020     LoadVT = MVT::i16;
9021     break;
9022   case 32:
9023     LoadVT = MVT::i32;
9024     break;
9025   case 64:
9026   case 128:
9027   case 256:
9028     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9029     break;
9030   }
9031 
9032   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9033     return false;
9034 
9035   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9036   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9037 
9038   // Bitcast to a wide integer type if the loads are vectors.
9039   if (LoadVT.isVector()) {
9040     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9041     LoadL = DAG.getBitcast(CmpVT, LoadL);
9042     LoadR = DAG.getBitcast(CmpVT, LoadR);
9043   }
9044 
9045   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9046   processIntegerCallValue(I, Cmp, false);
9047   return true;
9048 }
9049 
9050 /// See if we can lower a memchr call into an optimized form. If so, return
9051 /// true and lower it. Otherwise return false, and it will be lowered like a
9052 /// normal call.
9053 /// The caller already checked that \p I calls the appropriate LibFunc with a
9054 /// correct prototype.
9055 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9056   const Value *Src = I.getArgOperand(0);
9057   const Value *Char = I.getArgOperand(1);
9058   const Value *Length = I.getArgOperand(2);
9059 
9060   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9061   std::pair<SDValue, SDValue> Res =
9062     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9063                                 getValue(Src), getValue(Char), getValue(Length),
9064                                 MachinePointerInfo(Src));
9065   if (Res.first.getNode()) {
9066     setValue(&I, Res.first);
9067     PendingLoads.push_back(Res.second);
9068     return true;
9069   }
9070 
9071   return false;
9072 }
9073 
9074 /// See if we can lower a mempcpy call into an optimized form. If so, return
9075 /// true and lower it. Otherwise return false, and it will be lowered like a
9076 /// normal call.
9077 /// The caller already checked that \p I calls the appropriate LibFunc with a
9078 /// correct prototype.
9079 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9080   SDValue Dst = getValue(I.getArgOperand(0));
9081   SDValue Src = getValue(I.getArgOperand(1));
9082   SDValue Size = getValue(I.getArgOperand(2));
9083 
9084   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9085   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9086   // DAG::getMemcpy needs Alignment to be defined.
9087   Align Alignment = std::min(DstAlign, SrcAlign);
9088 
9089   SDLoc sdl = getCurSDLoc();
9090 
9091   // In the mempcpy context we need to pass in a false value for isTailCall
9092   // because the return pointer needs to be adjusted by the size of
9093   // the copied memory.
9094   SDValue Root = getMemoryRoot();
9095   SDValue MC = DAG.getMemcpy(
9096       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9097       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9098       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9099   assert(MC.getNode() != nullptr &&
9100          "** memcpy should not be lowered as TailCall in mempcpy context **");
9101   DAG.setRoot(MC);
9102 
9103   // Check if Size needs to be truncated or extended.
9104   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9105 
9106   // Adjust return pointer to point just past the last dst byte.
9107   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9108                                     Dst, Size);
9109   setValue(&I, DstPlusSize);
9110   return true;
9111 }
9112 
9113 /// See if we can lower a strcpy call into an optimized form.  If so, return
9114 /// true and lower it, otherwise return false and it will be lowered like a
9115 /// normal call.
9116 /// The caller already checked that \p I calls the appropriate LibFunc with a
9117 /// correct prototype.
9118 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9119   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9120 
9121   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9122   std::pair<SDValue, SDValue> Res =
9123     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9124                                 getValue(Arg0), getValue(Arg1),
9125                                 MachinePointerInfo(Arg0),
9126                                 MachinePointerInfo(Arg1), isStpcpy);
9127   if (Res.first.getNode()) {
9128     setValue(&I, Res.first);
9129     DAG.setRoot(Res.second);
9130     return true;
9131   }
9132 
9133   return false;
9134 }
9135 
9136 /// See if we can lower a strcmp call into an optimized form.  If so, return
9137 /// true and lower it, otherwise return false and it will be lowered like a
9138 /// normal call.
9139 /// The caller already checked that \p I calls the appropriate LibFunc with a
9140 /// correct prototype.
9141 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9142   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9143 
9144   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9145   std::pair<SDValue, SDValue> Res =
9146     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9147                                 getValue(Arg0), getValue(Arg1),
9148                                 MachinePointerInfo(Arg0),
9149                                 MachinePointerInfo(Arg1));
9150   if (Res.first.getNode()) {
9151     processIntegerCallValue(I, Res.first, true);
9152     PendingLoads.push_back(Res.second);
9153     return true;
9154   }
9155 
9156   return false;
9157 }
9158 
9159 /// See if we can lower a strlen call into an optimized form.  If so, return
9160 /// true and lower it, otherwise return false and it will be lowered like a
9161 /// normal call.
9162 /// The caller already checked that \p I calls the appropriate LibFunc with a
9163 /// correct prototype.
9164 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9165   const Value *Arg0 = I.getArgOperand(0);
9166 
9167   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9168   std::pair<SDValue, SDValue> Res =
9169     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9170                                 getValue(Arg0), MachinePointerInfo(Arg0));
9171   if (Res.first.getNode()) {
9172     processIntegerCallValue(I, Res.first, false);
9173     PendingLoads.push_back(Res.second);
9174     return true;
9175   }
9176 
9177   return false;
9178 }
9179 
9180 /// See if we can lower a strnlen call into an optimized form.  If so, return
9181 /// true and lower it, otherwise return false and it will be lowered like a
9182 /// normal call.
9183 /// The caller already checked that \p I calls the appropriate LibFunc with a
9184 /// correct prototype.
9185 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9186   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9187 
9188   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9189   std::pair<SDValue, SDValue> Res =
9190     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9191                                  getValue(Arg0), getValue(Arg1),
9192                                  MachinePointerInfo(Arg0));
9193   if (Res.first.getNode()) {
9194     processIntegerCallValue(I, Res.first, false);
9195     PendingLoads.push_back(Res.second);
9196     return true;
9197   }
9198 
9199   return false;
9200 }
9201 
9202 /// See if we can lower a unary floating-point operation into an SDNode with
9203 /// the specified Opcode.  If so, return true and lower it, otherwise return
9204 /// false and it will be lowered like a normal call.
9205 /// The caller already checked that \p I calls the appropriate LibFunc with a
9206 /// correct prototype.
9207 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9208                                               unsigned Opcode) {
9209   // We already checked this call's prototype; verify it doesn't modify errno.
9210   if (!I.onlyReadsMemory())
9211     return false;
9212 
9213   SDNodeFlags Flags;
9214   Flags.copyFMF(cast<FPMathOperator>(I));
9215 
9216   SDValue Tmp = getValue(I.getArgOperand(0));
9217   setValue(&I,
9218            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9219   return true;
9220 }
9221 
9222 /// See if we can lower a binary floating-point operation into an SDNode with
9223 /// the specified Opcode. If so, return true and lower it. Otherwise return
9224 /// false, and it will be lowered like a normal call.
9225 /// The caller already checked that \p I calls the appropriate LibFunc with a
9226 /// correct prototype.
9227 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9228                                                unsigned Opcode) {
9229   // We already checked this call's prototype; verify it doesn't modify errno.
9230   if (!I.onlyReadsMemory())
9231     return false;
9232 
9233   SDNodeFlags Flags;
9234   Flags.copyFMF(cast<FPMathOperator>(I));
9235 
9236   SDValue Tmp0 = getValue(I.getArgOperand(0));
9237   SDValue Tmp1 = getValue(I.getArgOperand(1));
9238   EVT VT = Tmp0.getValueType();
9239   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9240   return true;
9241 }
9242 
9243 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9244   // Handle inline assembly differently.
9245   if (I.isInlineAsm()) {
9246     visitInlineAsm(I);
9247     return;
9248   }
9249 
9250   diagnoseDontCall(I);
9251 
9252   if (Function *F = I.getCalledFunction()) {
9253     if (F->isDeclaration()) {
9254       // Is this an LLVM intrinsic or a target-specific intrinsic?
9255       unsigned IID = F->getIntrinsicID();
9256       if (!IID)
9257         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9258           IID = II->getIntrinsicID(F);
9259 
9260       if (IID) {
9261         visitIntrinsicCall(I, IID);
9262         return;
9263       }
9264     }
9265 
9266     // Check for well-known libc/libm calls.  If the function is internal, it
9267     // can't be a library call.  Don't do the check if marked as nobuiltin for
9268     // some reason or the call site requires strict floating point semantics.
9269     LibFunc Func;
9270     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9271         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9272         LibInfo->hasOptimizedCodeGen(Func)) {
9273       switch (Func) {
9274       default: break;
9275       case LibFunc_bcmp:
9276         if (visitMemCmpBCmpCall(I))
9277           return;
9278         break;
9279       case LibFunc_copysign:
9280       case LibFunc_copysignf:
9281       case LibFunc_copysignl:
9282         // We already checked this call's prototype; verify it doesn't modify
9283         // errno.
9284         if (I.onlyReadsMemory()) {
9285           SDValue LHS = getValue(I.getArgOperand(0));
9286           SDValue RHS = getValue(I.getArgOperand(1));
9287           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9288                                    LHS.getValueType(), LHS, RHS));
9289           return;
9290         }
9291         break;
9292       case LibFunc_fabs:
9293       case LibFunc_fabsf:
9294       case LibFunc_fabsl:
9295         if (visitUnaryFloatCall(I, ISD::FABS))
9296           return;
9297         break;
9298       case LibFunc_fmin:
9299       case LibFunc_fminf:
9300       case LibFunc_fminl:
9301         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9302           return;
9303         break;
9304       case LibFunc_fmax:
9305       case LibFunc_fmaxf:
9306       case LibFunc_fmaxl:
9307         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9308           return;
9309         break;
9310       case LibFunc_fminimum_num:
9311       case LibFunc_fminimum_numf:
9312       case LibFunc_fminimum_numl:
9313         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9314           return;
9315         break;
9316       case LibFunc_fmaximum_num:
9317       case LibFunc_fmaximum_numf:
9318       case LibFunc_fmaximum_numl:
9319         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9320           return;
9321         break;
9322       case LibFunc_sin:
9323       case LibFunc_sinf:
9324       case LibFunc_sinl:
9325         if (visitUnaryFloatCall(I, ISD::FSIN))
9326           return;
9327         break;
9328       case LibFunc_cos:
9329       case LibFunc_cosf:
9330       case LibFunc_cosl:
9331         if (visitUnaryFloatCall(I, ISD::FCOS))
9332           return;
9333         break;
9334       case LibFunc_tan:
9335       case LibFunc_tanf:
9336       case LibFunc_tanl:
9337         if (visitUnaryFloatCall(I, ISD::FTAN))
9338           return;
9339         break;
9340       case LibFunc_asin:
9341       case LibFunc_asinf:
9342       case LibFunc_asinl:
9343         if (visitUnaryFloatCall(I, ISD::FASIN))
9344           return;
9345         break;
9346       case LibFunc_acos:
9347       case LibFunc_acosf:
9348       case LibFunc_acosl:
9349         if (visitUnaryFloatCall(I, ISD::FACOS))
9350           return;
9351         break;
9352       case LibFunc_atan:
9353       case LibFunc_atanf:
9354       case LibFunc_atanl:
9355         if (visitUnaryFloatCall(I, ISD::FATAN))
9356           return;
9357         break;
9358       case LibFunc_sinh:
9359       case LibFunc_sinhf:
9360       case LibFunc_sinhl:
9361         if (visitUnaryFloatCall(I, ISD::FSINH))
9362           return;
9363         break;
9364       case LibFunc_cosh:
9365       case LibFunc_coshf:
9366       case LibFunc_coshl:
9367         if (visitUnaryFloatCall(I, ISD::FCOSH))
9368           return;
9369         break;
9370       case LibFunc_tanh:
9371       case LibFunc_tanhf:
9372       case LibFunc_tanhl:
9373         if (visitUnaryFloatCall(I, ISD::FTANH))
9374           return;
9375         break;
9376       case LibFunc_sqrt:
9377       case LibFunc_sqrtf:
9378       case LibFunc_sqrtl:
9379       case LibFunc_sqrt_finite:
9380       case LibFunc_sqrtf_finite:
9381       case LibFunc_sqrtl_finite:
9382         if (visitUnaryFloatCall(I, ISD::FSQRT))
9383           return;
9384         break;
9385       case LibFunc_floor:
9386       case LibFunc_floorf:
9387       case LibFunc_floorl:
9388         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9389           return;
9390         break;
9391       case LibFunc_nearbyint:
9392       case LibFunc_nearbyintf:
9393       case LibFunc_nearbyintl:
9394         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9395           return;
9396         break;
9397       case LibFunc_ceil:
9398       case LibFunc_ceilf:
9399       case LibFunc_ceill:
9400         if (visitUnaryFloatCall(I, ISD::FCEIL))
9401           return;
9402         break;
9403       case LibFunc_rint:
9404       case LibFunc_rintf:
9405       case LibFunc_rintl:
9406         if (visitUnaryFloatCall(I, ISD::FRINT))
9407           return;
9408         break;
9409       case LibFunc_round:
9410       case LibFunc_roundf:
9411       case LibFunc_roundl:
9412         if (visitUnaryFloatCall(I, ISD::FROUND))
9413           return;
9414         break;
9415       case LibFunc_trunc:
9416       case LibFunc_truncf:
9417       case LibFunc_truncl:
9418         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9419           return;
9420         break;
9421       case LibFunc_log2:
9422       case LibFunc_log2f:
9423       case LibFunc_log2l:
9424         if (visitUnaryFloatCall(I, ISD::FLOG2))
9425           return;
9426         break;
9427       case LibFunc_exp2:
9428       case LibFunc_exp2f:
9429       case LibFunc_exp2l:
9430         if (visitUnaryFloatCall(I, ISD::FEXP2))
9431           return;
9432         break;
9433       case LibFunc_exp10:
9434       case LibFunc_exp10f:
9435       case LibFunc_exp10l:
9436         if (visitUnaryFloatCall(I, ISD::FEXP10))
9437           return;
9438         break;
9439       case LibFunc_ldexp:
9440       case LibFunc_ldexpf:
9441       case LibFunc_ldexpl:
9442         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9443           return;
9444         break;
9445       case LibFunc_memcmp:
9446         if (visitMemCmpBCmpCall(I))
9447           return;
9448         break;
9449       case LibFunc_mempcpy:
9450         if (visitMemPCpyCall(I))
9451           return;
9452         break;
9453       case LibFunc_memchr:
9454         if (visitMemChrCall(I))
9455           return;
9456         break;
9457       case LibFunc_strcpy:
9458         if (visitStrCpyCall(I, false))
9459           return;
9460         break;
9461       case LibFunc_stpcpy:
9462         if (visitStrCpyCall(I, true))
9463           return;
9464         break;
9465       case LibFunc_strcmp:
9466         if (visitStrCmpCall(I))
9467           return;
9468         break;
9469       case LibFunc_strlen:
9470         if (visitStrLenCall(I))
9471           return;
9472         break;
9473       case LibFunc_strnlen:
9474         if (visitStrNLenCall(I))
9475           return;
9476         break;
9477       }
9478     }
9479   }
9480 
9481   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9482     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9483     return;
9484   }
9485 
9486   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9487   // have to do anything here to lower funclet bundles.
9488   // CFGuardTarget bundles are lowered in LowerCallTo.
9489   assert(!I.hasOperandBundlesOtherThan(
9490              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9491               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9492               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9493               LLVMContext::OB_convergencectrl}) &&
9494          "Cannot lower calls with arbitrary operand bundles!");
9495 
9496   SDValue Callee = getValue(I.getCalledOperand());
9497 
9498   if (I.hasDeoptState())
9499     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9500   else
9501     // Check if we can potentially perform a tail call. More detailed checking
9502     // is be done within LowerCallTo, after more information about the call is
9503     // known.
9504     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9505 }
9506 
9507 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9508     const CallBase &CB, const BasicBlock *EHPadBB) {
9509   auto PAB = CB.getOperandBundle("ptrauth");
9510   const Value *CalleeV = CB.getCalledOperand();
9511 
9512   // Gather the call ptrauth data from the operand bundle:
9513   //   [ i32 <key>, i64 <discriminator> ]
9514   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9515   const Value *Discriminator = PAB->Inputs[1];
9516 
9517   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9518   assert(Discriminator->getType()->isIntegerTy(64) &&
9519          "Invalid ptrauth discriminator");
9520 
9521   // Look through ptrauth constants to find the raw callee.
9522   // Do a direct unauthenticated call if we found it and everything matches.
9523   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9524     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9525                                          DAG.getDataLayout()))
9526       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9527                          CB.isMustTailCall(), EHPadBB);
9528 
9529   // Functions should never be ptrauth-called directly.
9530   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9531 
9532   // Otherwise, do an authenticated indirect call.
9533   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9534                                      getValue(Discriminator)};
9535 
9536   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9537               EHPadBB, &PAI);
9538 }
9539 
9540 namespace {
9541 
9542 /// AsmOperandInfo - This contains information for each constraint that we are
9543 /// lowering.
9544 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9545 public:
9546   /// CallOperand - If this is the result output operand or a clobber
9547   /// this is null, otherwise it is the incoming operand to the CallInst.
9548   /// This gets modified as the asm is processed.
9549   SDValue CallOperand;
9550 
9551   /// AssignedRegs - If this is a register or register class operand, this
9552   /// contains the set of register corresponding to the operand.
9553   RegsForValue AssignedRegs;
9554 
9555   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9556     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9557   }
9558 
9559   /// Whether or not this operand accesses memory
9560   bool hasMemory(const TargetLowering &TLI) const {
9561     // Indirect operand accesses access memory.
9562     if (isIndirect)
9563       return true;
9564 
9565     for (const auto &Code : Codes)
9566       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9567         return true;
9568 
9569     return false;
9570   }
9571 };
9572 
9573 
9574 } // end anonymous namespace
9575 
9576 /// Make sure that the output operand \p OpInfo and its corresponding input
9577 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9578 /// out).
9579 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9580                                SDISelAsmOperandInfo &MatchingOpInfo,
9581                                SelectionDAG &DAG) {
9582   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9583     return;
9584 
9585   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9586   const auto &TLI = DAG.getTargetLoweringInfo();
9587 
9588   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9589       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9590                                        OpInfo.ConstraintVT);
9591   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9592       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9593                                        MatchingOpInfo.ConstraintVT);
9594   if ((OpInfo.ConstraintVT.isInteger() !=
9595        MatchingOpInfo.ConstraintVT.isInteger()) ||
9596       (MatchRC.second != InputRC.second)) {
9597     // FIXME: error out in a more elegant fashion
9598     report_fatal_error("Unsupported asm: input constraint"
9599                        " with a matching output constraint of"
9600                        " incompatible type!");
9601   }
9602   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9603 }
9604 
9605 /// Get a direct memory input to behave well as an indirect operand.
9606 /// This may introduce stores, hence the need for a \p Chain.
9607 /// \return The (possibly updated) chain.
9608 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9609                                         SDISelAsmOperandInfo &OpInfo,
9610                                         SelectionDAG &DAG) {
9611   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9612 
9613   // If we don't have an indirect input, put it in the constpool if we can,
9614   // otherwise spill it to a stack slot.
9615   // TODO: This isn't quite right. We need to handle these according to
9616   // the addressing mode that the constraint wants. Also, this may take
9617   // an additional register for the computation and we don't want that
9618   // either.
9619 
9620   // If the operand is a float, integer, or vector constant, spill to a
9621   // constant pool entry to get its address.
9622   const Value *OpVal = OpInfo.CallOperandVal;
9623   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9624       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9625     OpInfo.CallOperand = DAG.getConstantPool(
9626         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9627     return Chain;
9628   }
9629 
9630   // Otherwise, create a stack slot and emit a store to it before the asm.
9631   Type *Ty = OpVal->getType();
9632   auto &DL = DAG.getDataLayout();
9633   TypeSize TySize = DL.getTypeAllocSize(Ty);
9634   MachineFunction &MF = DAG.getMachineFunction();
9635   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9636   int StackID = 0;
9637   if (TySize.isScalable())
9638     StackID = TFI->getStackIDForScalableVectors();
9639   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9640                                                  DL.getPrefTypeAlign(Ty), false,
9641                                                  nullptr, StackID);
9642   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9643   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9644                             MachinePointerInfo::getFixedStack(MF, SSFI),
9645                             TLI.getMemValueType(DL, Ty));
9646   OpInfo.CallOperand = StackSlot;
9647 
9648   return Chain;
9649 }
9650 
9651 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9652 /// specified operand.  We prefer to assign virtual registers, to allow the
9653 /// register allocator to handle the assignment process.  However, if the asm
9654 /// uses features that we can't model on machineinstrs, we have SDISel do the
9655 /// allocation.  This produces generally horrible, but correct, code.
9656 ///
9657 ///   OpInfo describes the operand
9658 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9659 static std::optional<unsigned>
9660 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9661                      SDISelAsmOperandInfo &OpInfo,
9662                      SDISelAsmOperandInfo &RefOpInfo) {
9663   LLVMContext &Context = *DAG.getContext();
9664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9665 
9666   MachineFunction &MF = DAG.getMachineFunction();
9667   SmallVector<unsigned, 4> Regs;
9668   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9669 
9670   // No work to do for memory/address operands.
9671   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9672       OpInfo.ConstraintType == TargetLowering::C_Address)
9673     return std::nullopt;
9674 
9675   // If this is a constraint for a single physreg, or a constraint for a
9676   // register class, find it.
9677   unsigned AssignedReg;
9678   const TargetRegisterClass *RC;
9679   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9680       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9681   // RC is unset only on failure. Return immediately.
9682   if (!RC)
9683     return std::nullopt;
9684 
9685   // Get the actual register value type.  This is important, because the user
9686   // may have asked for (e.g.) the AX register in i32 type.  We need to
9687   // remember that AX is actually i16 to get the right extension.
9688   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9689 
9690   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9691     // If this is an FP operand in an integer register (or visa versa), or more
9692     // generally if the operand value disagrees with the register class we plan
9693     // to stick it in, fix the operand type.
9694     //
9695     // If this is an input value, the bitcast to the new type is done now.
9696     // Bitcast for output value is done at the end of visitInlineAsm().
9697     if ((OpInfo.Type == InlineAsm::isOutput ||
9698          OpInfo.Type == InlineAsm::isInput) &&
9699         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9700       // Try to convert to the first EVT that the reg class contains.  If the
9701       // types are identical size, use a bitcast to convert (e.g. two differing
9702       // vector types).  Note: output bitcast is done at the end of
9703       // visitInlineAsm().
9704       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9705         // Exclude indirect inputs while they are unsupported because the code
9706         // to perform the load is missing and thus OpInfo.CallOperand still
9707         // refers to the input address rather than the pointed-to value.
9708         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9709           OpInfo.CallOperand =
9710               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9711         OpInfo.ConstraintVT = RegVT;
9712         // If the operand is an FP value and we want it in integer registers,
9713         // use the corresponding integer type. This turns an f64 value into
9714         // i64, which can be passed with two i32 values on a 32-bit machine.
9715       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9716         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9717         if (OpInfo.Type == InlineAsm::isInput)
9718           OpInfo.CallOperand =
9719               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9720         OpInfo.ConstraintVT = VT;
9721       }
9722     }
9723   }
9724 
9725   // No need to allocate a matching input constraint since the constraint it's
9726   // matching to has already been allocated.
9727   if (OpInfo.isMatchingInputConstraint())
9728     return std::nullopt;
9729 
9730   EVT ValueVT = OpInfo.ConstraintVT;
9731   if (OpInfo.ConstraintVT == MVT::Other)
9732     ValueVT = RegVT;
9733 
9734   // Initialize NumRegs.
9735   unsigned NumRegs = 1;
9736   if (OpInfo.ConstraintVT != MVT::Other)
9737     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9738 
9739   // If this is a constraint for a specific physical register, like {r17},
9740   // assign it now.
9741 
9742   // If this associated to a specific register, initialize iterator to correct
9743   // place. If virtual, make sure we have enough registers
9744 
9745   // Initialize iterator if necessary
9746   TargetRegisterClass::iterator I = RC->begin();
9747   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9748 
9749   // Do not check for single registers.
9750   if (AssignedReg) {
9751     I = std::find(I, RC->end(), AssignedReg);
9752     if (I == RC->end()) {
9753       // RC does not contain the selected register, which indicates a
9754       // mismatch between the register and the required type/bitwidth.
9755       return {AssignedReg};
9756     }
9757   }
9758 
9759   for (; NumRegs; --NumRegs, ++I) {
9760     assert(I != RC->end() && "Ran out of registers to allocate!");
9761     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9762     Regs.push_back(R);
9763   }
9764 
9765   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9766   return std::nullopt;
9767 }
9768 
9769 static unsigned
9770 findMatchingInlineAsmOperand(unsigned OperandNo,
9771                              const std::vector<SDValue> &AsmNodeOperands) {
9772   // Scan until we find the definition we already emitted of this operand.
9773   unsigned CurOp = InlineAsm::Op_FirstOperand;
9774   for (; OperandNo; --OperandNo) {
9775     // Advance to the next operand.
9776     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9777     const InlineAsm::Flag F(OpFlag);
9778     assert(
9779         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9780         "Skipped past definitions?");
9781     CurOp += F.getNumOperandRegisters() + 1;
9782   }
9783   return CurOp;
9784 }
9785 
9786 namespace {
9787 
9788 class ExtraFlags {
9789   unsigned Flags = 0;
9790 
9791 public:
9792   explicit ExtraFlags(const CallBase &Call) {
9793     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9794     if (IA->hasSideEffects())
9795       Flags |= InlineAsm::Extra_HasSideEffects;
9796     if (IA->isAlignStack())
9797       Flags |= InlineAsm::Extra_IsAlignStack;
9798     if (Call.isConvergent())
9799       Flags |= InlineAsm::Extra_IsConvergent;
9800     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9801   }
9802 
9803   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9804     // Ideally, we would only check against memory constraints.  However, the
9805     // meaning of an Other constraint can be target-specific and we can't easily
9806     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9807     // for Other constraints as well.
9808     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9809         OpInfo.ConstraintType == TargetLowering::C_Other) {
9810       if (OpInfo.Type == InlineAsm::isInput)
9811         Flags |= InlineAsm::Extra_MayLoad;
9812       else if (OpInfo.Type == InlineAsm::isOutput)
9813         Flags |= InlineAsm::Extra_MayStore;
9814       else if (OpInfo.Type == InlineAsm::isClobber)
9815         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9816     }
9817   }
9818 
9819   unsigned get() const { return Flags; }
9820 };
9821 
9822 } // end anonymous namespace
9823 
9824 static bool isFunction(SDValue Op) {
9825   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9826     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9827       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9828 
9829       // In normal "call dllimport func" instruction (non-inlineasm) it force
9830       // indirect access by specifing call opcode. And usually specially print
9831       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9832       // not do in this way now. (In fact, this is similar with "Data Access"
9833       // action). So here we ignore dllimport function.
9834       if (Fn && !Fn->hasDLLImportStorageClass())
9835         return true;
9836     }
9837   }
9838   return false;
9839 }
9840 
9841 /// visitInlineAsm - Handle a call to an InlineAsm object.
9842 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9843                                          const BasicBlock *EHPadBB) {
9844   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9845 
9846   /// ConstraintOperands - Information about all of the constraints.
9847   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9848 
9849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9850   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9851       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9852 
9853   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9854   // AsmDialect, MayLoad, MayStore).
9855   bool HasSideEffect = IA->hasSideEffects();
9856   ExtraFlags ExtraInfo(Call);
9857 
9858   for (auto &T : TargetConstraints) {
9859     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9860     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9861 
9862     if (OpInfo.CallOperandVal)
9863       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9864 
9865     if (!HasSideEffect)
9866       HasSideEffect = OpInfo.hasMemory(TLI);
9867 
9868     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9869     // FIXME: Could we compute this on OpInfo rather than T?
9870 
9871     // Compute the constraint code and ConstraintType to use.
9872     TLI.ComputeConstraintToUse(T, SDValue());
9873 
9874     if (T.ConstraintType == TargetLowering::C_Immediate &&
9875         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9876       // We've delayed emitting a diagnostic like the "n" constraint because
9877       // inlining could cause an integer showing up.
9878       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9879                                           "' expects an integer constant "
9880                                           "expression");
9881 
9882     ExtraInfo.update(T);
9883   }
9884 
9885   // We won't need to flush pending loads if this asm doesn't touch
9886   // memory and is nonvolatile.
9887   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9888 
9889   bool EmitEHLabels = isa<InvokeInst>(Call);
9890   if (EmitEHLabels) {
9891     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9892   }
9893   bool IsCallBr = isa<CallBrInst>(Call);
9894 
9895   if (IsCallBr || EmitEHLabels) {
9896     // If this is a callbr or invoke we need to flush pending exports since
9897     // inlineasm_br and invoke are terminators.
9898     // We need to do this before nodes are glued to the inlineasm_br node.
9899     Chain = getControlRoot();
9900   }
9901 
9902   MCSymbol *BeginLabel = nullptr;
9903   if (EmitEHLabels) {
9904     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9905   }
9906 
9907   int OpNo = -1;
9908   SmallVector<StringRef> AsmStrs;
9909   IA->collectAsmStrs(AsmStrs);
9910 
9911   // Second pass over the constraints: compute which constraint option to use.
9912   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9913     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9914       OpNo++;
9915 
9916     // If this is an output operand with a matching input operand, look up the
9917     // matching input. If their types mismatch, e.g. one is an integer, the
9918     // other is floating point, or their sizes are different, flag it as an
9919     // error.
9920     if (OpInfo.hasMatchingInput()) {
9921       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9922       patchMatchingInput(OpInfo, Input, DAG);
9923     }
9924 
9925     // Compute the constraint code and ConstraintType to use.
9926     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9927 
9928     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9929          OpInfo.Type == InlineAsm::isClobber) ||
9930         OpInfo.ConstraintType == TargetLowering::C_Address)
9931       continue;
9932 
9933     // In Linux PIC model, there are 4 cases about value/label addressing:
9934     //
9935     // 1: Function call or Label jmp inside the module.
9936     // 2: Data access (such as global variable, static variable) inside module.
9937     // 3: Function call or Label jmp outside the module.
9938     // 4: Data access (such as global variable) outside the module.
9939     //
9940     // Due to current llvm inline asm architecture designed to not "recognize"
9941     // the asm code, there are quite troubles for us to treat mem addressing
9942     // differently for same value/adress used in different instuctions.
9943     // For example, in pic model, call a func may in plt way or direclty
9944     // pc-related, but lea/mov a function adress may use got.
9945     //
9946     // Here we try to "recognize" function call for the case 1 and case 3 in
9947     // inline asm. And try to adjust the constraint for them.
9948     //
9949     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9950     // label, so here we don't handle jmp function label now, but we need to
9951     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9952     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9953         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9954         TM.getCodeModel() != CodeModel::Large) {
9955       OpInfo.isIndirect = false;
9956       OpInfo.ConstraintType = TargetLowering::C_Address;
9957     }
9958 
9959     // If this is a memory input, and if the operand is not indirect, do what we
9960     // need to provide an address for the memory input.
9961     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9962         !OpInfo.isIndirect) {
9963       assert((OpInfo.isMultipleAlternative ||
9964               (OpInfo.Type == InlineAsm::isInput)) &&
9965              "Can only indirectify direct input operands!");
9966 
9967       // Memory operands really want the address of the value.
9968       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9969 
9970       // There is no longer a Value* corresponding to this operand.
9971       OpInfo.CallOperandVal = nullptr;
9972 
9973       // It is now an indirect operand.
9974       OpInfo.isIndirect = true;
9975     }
9976 
9977   }
9978 
9979   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9980   std::vector<SDValue> AsmNodeOperands;
9981   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9982   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9983       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9984 
9985   // If we have a !srcloc metadata node associated with it, we want to attach
9986   // this to the ultimately generated inline asm machineinstr.  To do this, we
9987   // pass in the third operand as this (potentially null) inline asm MDNode.
9988   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9989   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9990 
9991   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9992   // bits as operand 3.
9993   AsmNodeOperands.push_back(DAG.getTargetConstant(
9994       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9995 
9996   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9997   // this, assign virtual and physical registers for inputs and otput.
9998   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9999     // Assign Registers.
10000     SDISelAsmOperandInfo &RefOpInfo =
10001         OpInfo.isMatchingInputConstraint()
10002             ? ConstraintOperands[OpInfo.getMatchedOperand()]
10003             : OpInfo;
10004     const auto RegError =
10005         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
10006     if (RegError) {
10007       const MachineFunction &MF = DAG.getMachineFunction();
10008       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10009       const char *RegName = TRI.getName(*RegError);
10010       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10011                                    "' allocated for constraint '" +
10012                                    Twine(OpInfo.ConstraintCode) +
10013                                    "' does not match required type");
10014       return;
10015     }
10016 
10017     auto DetectWriteToReservedRegister = [&]() {
10018       const MachineFunction &MF = DAG.getMachineFunction();
10019       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10020       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10021         if (Register::isPhysicalRegister(Reg) &&
10022             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10023           const char *RegName = TRI.getName(Reg);
10024           emitInlineAsmError(Call, "write to reserved register '" +
10025                                        Twine(RegName) + "'");
10026           return true;
10027         }
10028       }
10029       return false;
10030     };
10031     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10032             (OpInfo.Type == InlineAsm::isInput &&
10033              !OpInfo.isMatchingInputConstraint())) &&
10034            "Only address as input operand is allowed.");
10035 
10036     switch (OpInfo.Type) {
10037     case InlineAsm::isOutput:
10038       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10039         const InlineAsm::ConstraintCode ConstraintID =
10040             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10041         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10042                "Failed to convert memory constraint code to constraint id.");
10043 
10044         // Add information to the INLINEASM node to know about this output.
10045         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10046         OpFlags.setMemConstraint(ConstraintID);
10047         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10048                                                         MVT::i32));
10049         AsmNodeOperands.push_back(OpInfo.CallOperand);
10050       } else {
10051         // Otherwise, this outputs to a register (directly for C_Register /
10052         // C_RegisterClass, and a target-defined fashion for
10053         // C_Immediate/C_Other). Find a register that we can use.
10054         if (OpInfo.AssignedRegs.Regs.empty()) {
10055           emitInlineAsmError(
10056               Call, "couldn't allocate output register for constraint '" +
10057                         Twine(OpInfo.ConstraintCode) + "'");
10058           return;
10059         }
10060 
10061         if (DetectWriteToReservedRegister())
10062           return;
10063 
10064         // Add information to the INLINEASM node to know that this register is
10065         // set.
10066         OpInfo.AssignedRegs.AddInlineAsmOperands(
10067             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10068                                   : InlineAsm::Kind::RegDef,
10069             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10070       }
10071       break;
10072 
10073     case InlineAsm::isInput:
10074     case InlineAsm::isLabel: {
10075       SDValue InOperandVal = OpInfo.CallOperand;
10076 
10077       if (OpInfo.isMatchingInputConstraint()) {
10078         // If this is required to match an output register we have already set,
10079         // just use its register.
10080         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10081                                                   AsmNodeOperands);
10082         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10083         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10084           if (OpInfo.isIndirect) {
10085             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10086             emitInlineAsmError(Call, "inline asm not supported yet: "
10087                                      "don't know how to handle tied "
10088                                      "indirect register inputs");
10089             return;
10090           }
10091 
10092           SmallVector<unsigned, 4> Regs;
10093           MachineFunction &MF = DAG.getMachineFunction();
10094           MachineRegisterInfo &MRI = MF.getRegInfo();
10095           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10096           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10097           Register TiedReg = R->getReg();
10098           MVT RegVT = R->getSimpleValueType(0);
10099           const TargetRegisterClass *RC =
10100               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10101               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10102                                       : TRI.getMinimalPhysRegClass(TiedReg);
10103           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10104             Regs.push_back(MRI.createVirtualRegister(RC));
10105 
10106           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10107 
10108           SDLoc dl = getCurSDLoc();
10109           // Use the produced MatchedRegs object to
10110           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10111           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10112                                            OpInfo.getMatchedOperand(), dl, DAG,
10113                                            AsmNodeOperands);
10114           break;
10115         }
10116 
10117         assert(Flag.isMemKind() && "Unknown matching constraint!");
10118         assert(Flag.getNumOperandRegisters() == 1 &&
10119                "Unexpected number of operands");
10120         // Add information to the INLINEASM node to know about this input.
10121         // See InlineAsm.h isUseOperandTiedToDef.
10122         Flag.clearMemConstraint();
10123         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10124         AsmNodeOperands.push_back(DAG.getTargetConstant(
10125             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10126         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10127         break;
10128       }
10129 
10130       // Treat indirect 'X' constraint as memory.
10131       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10132           OpInfo.isIndirect)
10133         OpInfo.ConstraintType = TargetLowering::C_Memory;
10134 
10135       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10136           OpInfo.ConstraintType == TargetLowering::C_Other) {
10137         std::vector<SDValue> Ops;
10138         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10139                                           Ops, DAG);
10140         if (Ops.empty()) {
10141           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10142             if (isa<ConstantSDNode>(InOperandVal)) {
10143               emitInlineAsmError(Call, "value out of range for constraint '" +
10144                                            Twine(OpInfo.ConstraintCode) + "'");
10145               return;
10146             }
10147 
10148           emitInlineAsmError(Call,
10149                              "invalid operand for inline asm constraint '" +
10150                                  Twine(OpInfo.ConstraintCode) + "'");
10151           return;
10152         }
10153 
10154         // Add information to the INLINEASM node to know about this input.
10155         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10156         AsmNodeOperands.push_back(DAG.getTargetConstant(
10157             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10158         llvm::append_range(AsmNodeOperands, Ops);
10159         break;
10160       }
10161 
10162       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10163         assert((OpInfo.isIndirect ||
10164                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10165                "Operand must be indirect to be a mem!");
10166         assert(InOperandVal.getValueType() ==
10167                    TLI.getPointerTy(DAG.getDataLayout()) &&
10168                "Memory operands expect pointer values");
10169 
10170         const InlineAsm::ConstraintCode ConstraintID =
10171             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10172         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10173                "Failed to convert memory constraint code to constraint id.");
10174 
10175         // Add information to the INLINEASM node to know about this input.
10176         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10177         ResOpType.setMemConstraint(ConstraintID);
10178         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10179                                                         getCurSDLoc(),
10180                                                         MVT::i32));
10181         AsmNodeOperands.push_back(InOperandVal);
10182         break;
10183       }
10184 
10185       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10186         const InlineAsm::ConstraintCode ConstraintID =
10187             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10188         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10189                "Failed to convert memory constraint code to constraint id.");
10190 
10191         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10192 
10193         SDValue AsmOp = InOperandVal;
10194         if (isFunction(InOperandVal)) {
10195           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10196           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10197           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10198                                              InOperandVal.getValueType(),
10199                                              GA->getOffset());
10200         }
10201 
10202         // Add information to the INLINEASM node to know about this input.
10203         ResOpType.setMemConstraint(ConstraintID);
10204 
10205         AsmNodeOperands.push_back(
10206             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10207 
10208         AsmNodeOperands.push_back(AsmOp);
10209         break;
10210       }
10211 
10212       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10213           OpInfo.ConstraintType != TargetLowering::C_Register) {
10214         emitInlineAsmError(Call, "unknown asm constraint '" +
10215                                      Twine(OpInfo.ConstraintCode) + "'");
10216         return;
10217       }
10218 
10219       // TODO: Support this.
10220       if (OpInfo.isIndirect) {
10221         emitInlineAsmError(
10222             Call, "Don't know how to handle indirect register inputs yet "
10223                   "for constraint '" +
10224                       Twine(OpInfo.ConstraintCode) + "'");
10225         return;
10226       }
10227 
10228       // Copy the input into the appropriate registers.
10229       if (OpInfo.AssignedRegs.Regs.empty()) {
10230         emitInlineAsmError(Call,
10231                            "couldn't allocate input reg for constraint '" +
10232                                Twine(OpInfo.ConstraintCode) + "'");
10233         return;
10234       }
10235 
10236       if (DetectWriteToReservedRegister())
10237         return;
10238 
10239       SDLoc dl = getCurSDLoc();
10240 
10241       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10242                                         &Call);
10243 
10244       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10245                                                0, dl, DAG, AsmNodeOperands);
10246       break;
10247     }
10248     case InlineAsm::isClobber:
10249       // Add the clobbered value to the operand list, so that the register
10250       // allocator is aware that the physreg got clobbered.
10251       if (!OpInfo.AssignedRegs.Regs.empty())
10252         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10253                                                  false, 0, getCurSDLoc(), DAG,
10254                                                  AsmNodeOperands);
10255       break;
10256     }
10257   }
10258 
10259   // Finish up input operands.  Set the input chain and add the flag last.
10260   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10261   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10262 
10263   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10264   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10265                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10266   Glue = Chain.getValue(1);
10267 
10268   // Do additional work to generate outputs.
10269 
10270   SmallVector<EVT, 1> ResultVTs;
10271   SmallVector<SDValue, 1> ResultValues;
10272   SmallVector<SDValue, 8> OutChains;
10273 
10274   llvm::Type *CallResultType = Call.getType();
10275   ArrayRef<Type *> ResultTypes;
10276   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10277     ResultTypes = StructResult->elements();
10278   else if (!CallResultType->isVoidTy())
10279     ResultTypes = ArrayRef(CallResultType);
10280 
10281   auto CurResultType = ResultTypes.begin();
10282   auto handleRegAssign = [&](SDValue V) {
10283     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10284     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10285     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10286     ++CurResultType;
10287     // If the type of the inline asm call site return value is different but has
10288     // same size as the type of the asm output bitcast it.  One example of this
10289     // is for vectors with different width / number of elements.  This can
10290     // happen for register classes that can contain multiple different value
10291     // types.  The preg or vreg allocated may not have the same VT as was
10292     // expected.
10293     //
10294     // This can also happen for a return value that disagrees with the register
10295     // class it is put in, eg. a double in a general-purpose register on a
10296     // 32-bit machine.
10297     if (ResultVT != V.getValueType() &&
10298         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10299       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10300     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10301              V.getValueType().isInteger()) {
10302       // If a result value was tied to an input value, the computed result
10303       // may have a wider width than the expected result.  Extract the
10304       // relevant portion.
10305       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10306     }
10307     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10308     ResultVTs.push_back(ResultVT);
10309     ResultValues.push_back(V);
10310   };
10311 
10312   // Deal with output operands.
10313   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10314     if (OpInfo.Type == InlineAsm::isOutput) {
10315       SDValue Val;
10316       // Skip trivial output operands.
10317       if (OpInfo.AssignedRegs.Regs.empty())
10318         continue;
10319 
10320       switch (OpInfo.ConstraintType) {
10321       case TargetLowering::C_Register:
10322       case TargetLowering::C_RegisterClass:
10323         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10324                                                   Chain, &Glue, &Call);
10325         break;
10326       case TargetLowering::C_Immediate:
10327       case TargetLowering::C_Other:
10328         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10329                                               OpInfo, DAG);
10330         break;
10331       case TargetLowering::C_Memory:
10332         break; // Already handled.
10333       case TargetLowering::C_Address:
10334         break; // Silence warning.
10335       case TargetLowering::C_Unknown:
10336         assert(false && "Unexpected unknown constraint");
10337       }
10338 
10339       // Indirect output manifest as stores. Record output chains.
10340       if (OpInfo.isIndirect) {
10341         const Value *Ptr = OpInfo.CallOperandVal;
10342         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10343         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10344                                      MachinePointerInfo(Ptr));
10345         OutChains.push_back(Store);
10346       } else {
10347         // generate CopyFromRegs to associated registers.
10348         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10349         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10350           for (const SDValue &V : Val->op_values())
10351             handleRegAssign(V);
10352         } else
10353           handleRegAssign(Val);
10354       }
10355     }
10356   }
10357 
10358   // Set results.
10359   if (!ResultValues.empty()) {
10360     assert(CurResultType == ResultTypes.end() &&
10361            "Mismatch in number of ResultTypes");
10362     assert(ResultValues.size() == ResultTypes.size() &&
10363            "Mismatch in number of output operands in asm result");
10364 
10365     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10366                             DAG.getVTList(ResultVTs), ResultValues);
10367     setValue(&Call, V);
10368   }
10369 
10370   // Collect store chains.
10371   if (!OutChains.empty())
10372     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10373 
10374   if (EmitEHLabels) {
10375     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10376   }
10377 
10378   // Only Update Root if inline assembly has a memory effect.
10379   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10380       EmitEHLabels)
10381     DAG.setRoot(Chain);
10382 }
10383 
10384 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10385                                              const Twine &Message) {
10386   LLVMContext &Ctx = *DAG.getContext();
10387   Ctx.emitError(&Call, Message);
10388 
10389   // Make sure we leave the DAG in a valid state
10390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10391   SmallVector<EVT, 1> ValueVTs;
10392   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10393 
10394   if (ValueVTs.empty())
10395     return;
10396 
10397   SmallVector<SDValue, 1> Ops;
10398   for (const EVT &VT : ValueVTs)
10399     Ops.push_back(DAG.getUNDEF(VT));
10400 
10401   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10402 }
10403 
10404 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10405   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10406                           MVT::Other, getRoot(),
10407                           getValue(I.getArgOperand(0)),
10408                           DAG.getSrcValue(I.getArgOperand(0))));
10409 }
10410 
10411 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10413   const DataLayout &DL = DAG.getDataLayout();
10414   SDValue V = DAG.getVAArg(
10415       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10416       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10417       DL.getABITypeAlign(I.getType()).value());
10418   DAG.setRoot(V.getValue(1));
10419 
10420   if (I.getType()->isPointerTy())
10421     V = DAG.getPtrExtOrTrunc(
10422         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10423   setValue(&I, V);
10424 }
10425 
10426 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10427   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10428                           MVT::Other, getRoot(),
10429                           getValue(I.getArgOperand(0)),
10430                           DAG.getSrcValue(I.getArgOperand(0))));
10431 }
10432 
10433 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10434   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10435                           MVT::Other, getRoot(),
10436                           getValue(I.getArgOperand(0)),
10437                           getValue(I.getArgOperand(1)),
10438                           DAG.getSrcValue(I.getArgOperand(0)),
10439                           DAG.getSrcValue(I.getArgOperand(1))));
10440 }
10441 
10442 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10443                                                     const Instruction &I,
10444                                                     SDValue Op) {
10445   std::optional<ConstantRange> CR = getRange(I);
10446 
10447   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10448     return Op;
10449 
10450   APInt Lo = CR->getUnsignedMin();
10451   if (!Lo.isMinValue())
10452     return Op;
10453 
10454   APInt Hi = CR->getUnsignedMax();
10455   unsigned Bits = std::max(Hi.getActiveBits(),
10456                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10457 
10458   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10459 
10460   SDLoc SL = getCurSDLoc();
10461 
10462   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10463                              DAG.getValueType(SmallVT));
10464   unsigned NumVals = Op.getNode()->getNumValues();
10465   if (NumVals == 1)
10466     return ZExt;
10467 
10468   SmallVector<SDValue, 4> Ops;
10469 
10470   Ops.push_back(ZExt);
10471   for (unsigned I = 1; I != NumVals; ++I)
10472     Ops.push_back(Op.getValue(I));
10473 
10474   return DAG.getMergeValues(Ops, SL);
10475 }
10476 
10477 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10478 /// the call being lowered.
10479 ///
10480 /// This is a helper for lowering intrinsics that follow a target calling
10481 /// convention or require stack pointer adjustment. Only a subset of the
10482 /// intrinsic's operands need to participate in the calling convention.
10483 void SelectionDAGBuilder::populateCallLoweringInfo(
10484     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10485     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10486     AttributeSet RetAttrs, bool IsPatchPoint) {
10487   TargetLowering::ArgListTy Args;
10488   Args.reserve(NumArgs);
10489 
10490   // Populate the argument list.
10491   // Attributes for args start at offset 1, after the return attribute.
10492   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10493        ArgI != ArgE; ++ArgI) {
10494     const Value *V = Call->getOperand(ArgI);
10495 
10496     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10497 
10498     TargetLowering::ArgListEntry Entry;
10499     Entry.Node = getValue(V);
10500     Entry.Ty = V->getType();
10501     Entry.setAttributes(Call, ArgI);
10502     Args.push_back(Entry);
10503   }
10504 
10505   CLI.setDebugLoc(getCurSDLoc())
10506       .setChain(getRoot())
10507       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10508                  RetAttrs)
10509       .setDiscardResult(Call->use_empty())
10510       .setIsPatchPoint(IsPatchPoint)
10511       .setIsPreallocated(
10512           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10513 }
10514 
10515 /// Add a stack map intrinsic call's live variable operands to a stackmap
10516 /// or patchpoint target node's operand list.
10517 ///
10518 /// Constants are converted to TargetConstants purely as an optimization to
10519 /// avoid constant materialization and register allocation.
10520 ///
10521 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10522 /// generate addess computation nodes, and so FinalizeISel can convert the
10523 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10524 /// address materialization and register allocation, but may also be required
10525 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10526 /// alloca in the entry block, then the runtime may assume that the alloca's
10527 /// StackMap location can be read immediately after compilation and that the
10528 /// location is valid at any point during execution (this is similar to the
10529 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10530 /// only available in a register, then the runtime would need to trap when
10531 /// execution reaches the StackMap in order to read the alloca's location.
10532 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10533                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10534                                 SelectionDAGBuilder &Builder) {
10535   SelectionDAG &DAG = Builder.DAG;
10536   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10537     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10538 
10539     // Things on the stack are pointer-typed, meaning that they are already
10540     // legal and can be emitted directly to target nodes.
10541     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10542       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10543     } else {
10544       // Otherwise emit a target independent node to be legalised.
10545       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10546     }
10547   }
10548 }
10549 
10550 /// Lower llvm.experimental.stackmap.
10551 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10552   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10553   //                                  [live variables...])
10554 
10555   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10556 
10557   SDValue Chain, InGlue, Callee;
10558   SmallVector<SDValue, 32> Ops;
10559 
10560   SDLoc DL = getCurSDLoc();
10561   Callee = getValue(CI.getCalledOperand());
10562 
10563   // The stackmap intrinsic only records the live variables (the arguments
10564   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10565   // intrinsic, this won't be lowered to a function call. This means we don't
10566   // have to worry about calling conventions and target specific lowering code.
10567   // Instead we perform the call lowering right here.
10568   //
10569   // chain, flag = CALLSEQ_START(chain, 0, 0)
10570   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10571   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10572   //
10573   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10574   InGlue = Chain.getValue(1);
10575 
10576   // Add the STACKMAP operands, starting with DAG house-keeping.
10577   Ops.push_back(Chain);
10578   Ops.push_back(InGlue);
10579 
10580   // Add the <id>, <numShadowBytes> operands.
10581   //
10582   // These do not require legalisation, and can be emitted directly to target
10583   // constant nodes.
10584   SDValue ID = getValue(CI.getArgOperand(0));
10585   assert(ID.getValueType() == MVT::i64);
10586   SDValue IDConst =
10587       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10588   Ops.push_back(IDConst);
10589 
10590   SDValue Shad = getValue(CI.getArgOperand(1));
10591   assert(Shad.getValueType() == MVT::i32);
10592   SDValue ShadConst =
10593       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10594   Ops.push_back(ShadConst);
10595 
10596   // Add the live variables.
10597   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10598 
10599   // Create the STACKMAP node.
10600   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10601   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10602   InGlue = Chain.getValue(1);
10603 
10604   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10605 
10606   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10607 
10608   // Set the root to the target-lowered call chain.
10609   DAG.setRoot(Chain);
10610 
10611   // Inform the Frame Information that we have a stackmap in this function.
10612   FuncInfo.MF->getFrameInfo().setHasStackMap();
10613 }
10614 
10615 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10616 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10617                                           const BasicBlock *EHPadBB) {
10618   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10619   //                                         i32 <numBytes>,
10620   //                                         i8* <target>,
10621   //                                         i32 <numArgs>,
10622   //                                         [Args...],
10623   //                                         [live variables...])
10624 
10625   CallingConv::ID CC = CB.getCallingConv();
10626   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10627   bool HasDef = !CB.getType()->isVoidTy();
10628   SDLoc dl = getCurSDLoc();
10629   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10630 
10631   // Handle immediate and symbolic callees.
10632   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10633     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10634                                    /*isTarget=*/true);
10635   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10636     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10637                                          SDLoc(SymbolicCallee),
10638                                          SymbolicCallee->getValueType(0));
10639 
10640   // Get the real number of arguments participating in the call <numArgs>
10641   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10642   unsigned NumArgs = NArgVal->getAsZExtVal();
10643 
10644   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10645   // Intrinsics include all meta-operands up to but not including CC.
10646   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10647   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10648          "Not enough arguments provided to the patchpoint intrinsic");
10649 
10650   // For AnyRegCC the arguments are lowered later on manually.
10651   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10652   Type *ReturnTy =
10653       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10654 
10655   TargetLowering::CallLoweringInfo CLI(DAG);
10656   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10657                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10658   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10659 
10660   SDNode *CallEnd = Result.second.getNode();
10661   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10662     CallEnd = CallEnd->getOperand(0).getNode();
10663   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10664     CallEnd = CallEnd->getOperand(0).getNode();
10665 
10666   /// Get a call instruction from the call sequence chain.
10667   /// Tail calls are not allowed.
10668   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10669          "Expected a callseq node.");
10670   SDNode *Call = CallEnd->getOperand(0).getNode();
10671   bool HasGlue = Call->getGluedNode();
10672 
10673   // Replace the target specific call node with the patchable intrinsic.
10674   SmallVector<SDValue, 8> Ops;
10675 
10676   // Push the chain.
10677   Ops.push_back(*(Call->op_begin()));
10678 
10679   // Optionally, push the glue (if any).
10680   if (HasGlue)
10681     Ops.push_back(*(Call->op_end() - 1));
10682 
10683   // Push the register mask info.
10684   if (HasGlue)
10685     Ops.push_back(*(Call->op_end() - 2));
10686   else
10687     Ops.push_back(*(Call->op_end() - 1));
10688 
10689   // Add the <id> and <numBytes> constants.
10690   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10691   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10692   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10693   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10694 
10695   // Add the callee.
10696   Ops.push_back(Callee);
10697 
10698   // Adjust <numArgs> to account for any arguments that have been passed on the
10699   // stack instead.
10700   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10701   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10702   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10703   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10704 
10705   // Add the calling convention
10706   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10707 
10708   // Add the arguments we omitted previously. The register allocator should
10709   // place these in any free register.
10710   if (IsAnyRegCC)
10711     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10712       Ops.push_back(getValue(CB.getArgOperand(i)));
10713 
10714   // Push the arguments from the call instruction.
10715   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10716   Ops.append(Call->op_begin() + 2, e);
10717 
10718   // Push live variables for the stack map.
10719   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10720 
10721   SDVTList NodeTys;
10722   if (IsAnyRegCC && HasDef) {
10723     // Create the return types based on the intrinsic definition
10724     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10725     SmallVector<EVT, 3> ValueVTs;
10726     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10727     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10728 
10729     // There is always a chain and a glue type at the end
10730     ValueVTs.push_back(MVT::Other);
10731     ValueVTs.push_back(MVT::Glue);
10732     NodeTys = DAG.getVTList(ValueVTs);
10733   } else
10734     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10735 
10736   // Replace the target specific call node with a PATCHPOINT node.
10737   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10738 
10739   // Update the NodeMap.
10740   if (HasDef) {
10741     if (IsAnyRegCC)
10742       setValue(&CB, SDValue(PPV.getNode(), 0));
10743     else
10744       setValue(&CB, Result.first);
10745   }
10746 
10747   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10748   // call sequence. Furthermore the location of the chain and glue can change
10749   // when the AnyReg calling convention is used and the intrinsic returns a
10750   // value.
10751   if (IsAnyRegCC && HasDef) {
10752     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10753     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10754     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10755   } else
10756     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10757   DAG.DeleteNode(Call);
10758 
10759   // Inform the Frame Information that we have a patchpoint in this function.
10760   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10761 }
10762 
10763 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10764                                             unsigned Intrinsic) {
10765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10766   SDValue Op1 = getValue(I.getArgOperand(0));
10767   SDValue Op2;
10768   if (I.arg_size() > 1)
10769     Op2 = getValue(I.getArgOperand(1));
10770   SDLoc dl = getCurSDLoc();
10771   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10772   SDValue Res;
10773   SDNodeFlags SDFlags;
10774   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10775     SDFlags.copyFMF(*FPMO);
10776 
10777   switch (Intrinsic) {
10778   case Intrinsic::vector_reduce_fadd:
10779     if (SDFlags.hasAllowReassociation())
10780       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10781                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10782                         SDFlags);
10783     else
10784       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10785     break;
10786   case Intrinsic::vector_reduce_fmul:
10787     if (SDFlags.hasAllowReassociation())
10788       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10789                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10790                         SDFlags);
10791     else
10792       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10793     break;
10794   case Intrinsic::vector_reduce_add:
10795     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10796     break;
10797   case Intrinsic::vector_reduce_mul:
10798     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10799     break;
10800   case Intrinsic::vector_reduce_and:
10801     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10802     break;
10803   case Intrinsic::vector_reduce_or:
10804     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10805     break;
10806   case Intrinsic::vector_reduce_xor:
10807     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10808     break;
10809   case Intrinsic::vector_reduce_smax:
10810     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10811     break;
10812   case Intrinsic::vector_reduce_smin:
10813     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10814     break;
10815   case Intrinsic::vector_reduce_umax:
10816     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10817     break;
10818   case Intrinsic::vector_reduce_umin:
10819     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10820     break;
10821   case Intrinsic::vector_reduce_fmax:
10822     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10823     break;
10824   case Intrinsic::vector_reduce_fmin:
10825     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10826     break;
10827   case Intrinsic::vector_reduce_fmaximum:
10828     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10829     break;
10830   case Intrinsic::vector_reduce_fminimum:
10831     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10832     break;
10833   default:
10834     llvm_unreachable("Unhandled vector reduce intrinsic");
10835   }
10836   setValue(&I, Res);
10837 }
10838 
10839 /// Returns an AttributeList representing the attributes applied to the return
10840 /// value of the given call.
10841 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10842   SmallVector<Attribute::AttrKind, 2> Attrs;
10843   if (CLI.RetSExt)
10844     Attrs.push_back(Attribute::SExt);
10845   if (CLI.RetZExt)
10846     Attrs.push_back(Attribute::ZExt);
10847   if (CLI.IsInReg)
10848     Attrs.push_back(Attribute::InReg);
10849 
10850   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10851                             Attrs);
10852 }
10853 
10854 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10855 /// implementation, which just calls LowerCall.
10856 /// FIXME: When all targets are
10857 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10858 std::pair<SDValue, SDValue>
10859 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10860   // Handle the incoming return values from the call.
10861   CLI.Ins.clear();
10862   Type *OrigRetTy = CLI.RetTy;
10863   SmallVector<EVT, 4> RetTys;
10864   SmallVector<TypeSize, 4> Offsets;
10865   auto &DL = CLI.DAG.getDataLayout();
10866   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10867 
10868   if (CLI.IsPostTypeLegalization) {
10869     // If we are lowering a libcall after legalization, split the return type.
10870     SmallVector<EVT, 4> OldRetTys;
10871     SmallVector<TypeSize, 4> OldOffsets;
10872     RetTys.swap(OldRetTys);
10873     Offsets.swap(OldOffsets);
10874 
10875     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10876       EVT RetVT = OldRetTys[i];
10877       uint64_t Offset = OldOffsets[i];
10878       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10879       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10880       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10881       RetTys.append(NumRegs, RegisterVT);
10882       for (unsigned j = 0; j != NumRegs; ++j)
10883         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10884     }
10885   }
10886 
10887   SmallVector<ISD::OutputArg, 4> Outs;
10888   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10889 
10890   bool CanLowerReturn =
10891       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10892                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10893 
10894   SDValue DemoteStackSlot;
10895   int DemoteStackIdx = -100;
10896   if (!CanLowerReturn) {
10897     // FIXME: equivalent assert?
10898     // assert(!CS.hasInAllocaArgument() &&
10899     //        "sret demotion is incompatible with inalloca");
10900     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10901     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10902     MachineFunction &MF = CLI.DAG.getMachineFunction();
10903     DemoteStackIdx =
10904         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10905     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10906                                               DL.getAllocaAddrSpace());
10907 
10908     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10909     ArgListEntry Entry;
10910     Entry.Node = DemoteStackSlot;
10911     Entry.Ty = StackSlotPtrType;
10912     Entry.IsSExt = false;
10913     Entry.IsZExt = false;
10914     Entry.IsInReg = false;
10915     Entry.IsSRet = true;
10916     Entry.IsNest = false;
10917     Entry.IsByVal = false;
10918     Entry.IsByRef = false;
10919     Entry.IsReturned = false;
10920     Entry.IsSwiftSelf = false;
10921     Entry.IsSwiftAsync = false;
10922     Entry.IsSwiftError = false;
10923     Entry.IsCFGuardTarget = false;
10924     Entry.Alignment = Alignment;
10925     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10926     CLI.NumFixedArgs += 1;
10927     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10928     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10929 
10930     // sret demotion isn't compatible with tail-calls, since the sret argument
10931     // points into the callers stack frame.
10932     CLI.IsTailCall = false;
10933   } else {
10934     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10935         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10936     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10937       ISD::ArgFlagsTy Flags;
10938       if (NeedsRegBlock) {
10939         Flags.setInConsecutiveRegs();
10940         if (I == RetTys.size() - 1)
10941           Flags.setInConsecutiveRegsLast();
10942       }
10943       EVT VT = RetTys[I];
10944       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10945                                                      CLI.CallConv, VT);
10946       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10947                                                        CLI.CallConv, VT);
10948       for (unsigned i = 0; i != NumRegs; ++i) {
10949         ISD::InputArg MyFlags;
10950         MyFlags.Flags = Flags;
10951         MyFlags.VT = RegisterVT;
10952         MyFlags.ArgVT = VT;
10953         MyFlags.Used = CLI.IsReturnValueUsed;
10954         if (CLI.RetTy->isPointerTy()) {
10955           MyFlags.Flags.setPointer();
10956           MyFlags.Flags.setPointerAddrSpace(
10957               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10958         }
10959         if (CLI.RetSExt)
10960           MyFlags.Flags.setSExt();
10961         if (CLI.RetZExt)
10962           MyFlags.Flags.setZExt();
10963         if (CLI.IsInReg)
10964           MyFlags.Flags.setInReg();
10965         CLI.Ins.push_back(MyFlags);
10966       }
10967     }
10968   }
10969 
10970   // We push in swifterror return as the last element of CLI.Ins.
10971   ArgListTy &Args = CLI.getArgs();
10972   if (supportSwiftError()) {
10973     for (const ArgListEntry &Arg : Args) {
10974       if (Arg.IsSwiftError) {
10975         ISD::InputArg MyFlags;
10976         MyFlags.VT = getPointerTy(DL);
10977         MyFlags.ArgVT = EVT(getPointerTy(DL));
10978         MyFlags.Flags.setSwiftError();
10979         CLI.Ins.push_back(MyFlags);
10980       }
10981     }
10982   }
10983 
10984   // Handle all of the outgoing arguments.
10985   CLI.Outs.clear();
10986   CLI.OutVals.clear();
10987   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10988     SmallVector<EVT, 4> ValueVTs;
10989     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10990     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10991     Type *FinalType = Args[i].Ty;
10992     if (Args[i].IsByVal)
10993       FinalType = Args[i].IndirectType;
10994     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10995         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10996     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10997          ++Value) {
10998       EVT VT = ValueVTs[Value];
10999       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
11000       SDValue Op = SDValue(Args[i].Node.getNode(),
11001                            Args[i].Node.getResNo() + Value);
11002       ISD::ArgFlagsTy Flags;
11003 
11004       // Certain targets (such as MIPS), may have a different ABI alignment
11005       // for a type depending on the context. Give the target a chance to
11006       // specify the alignment it wants.
11007       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11008       Flags.setOrigAlign(OriginalAlignment);
11009 
11010       if (Args[i].Ty->isPointerTy()) {
11011         Flags.setPointer();
11012         Flags.setPointerAddrSpace(
11013             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11014       }
11015       if (Args[i].IsZExt)
11016         Flags.setZExt();
11017       if (Args[i].IsSExt)
11018         Flags.setSExt();
11019       if (Args[i].IsInReg) {
11020         // If we are using vectorcall calling convention, a structure that is
11021         // passed InReg - is surely an HVA
11022         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11023             isa<StructType>(FinalType)) {
11024           // The first value of a structure is marked
11025           if (0 == Value)
11026             Flags.setHvaStart();
11027           Flags.setHva();
11028         }
11029         // Set InReg Flag
11030         Flags.setInReg();
11031       }
11032       if (Args[i].IsSRet)
11033         Flags.setSRet();
11034       if (Args[i].IsSwiftSelf)
11035         Flags.setSwiftSelf();
11036       if (Args[i].IsSwiftAsync)
11037         Flags.setSwiftAsync();
11038       if (Args[i].IsSwiftError)
11039         Flags.setSwiftError();
11040       if (Args[i].IsCFGuardTarget)
11041         Flags.setCFGuardTarget();
11042       if (Args[i].IsByVal)
11043         Flags.setByVal();
11044       if (Args[i].IsByRef)
11045         Flags.setByRef();
11046       if (Args[i].IsPreallocated) {
11047         Flags.setPreallocated();
11048         // Set the byval flag for CCAssignFn callbacks that don't know about
11049         // preallocated.  This way we can know how many bytes we should've
11050         // allocated and how many bytes a callee cleanup function will pop.  If
11051         // we port preallocated to more targets, we'll have to add custom
11052         // preallocated handling in the various CC lowering callbacks.
11053         Flags.setByVal();
11054       }
11055       if (Args[i].IsInAlloca) {
11056         Flags.setInAlloca();
11057         // Set the byval flag for CCAssignFn callbacks that don't know about
11058         // inalloca.  This way we can know how many bytes we should've allocated
11059         // and how many bytes a callee cleanup function will pop.  If we port
11060         // inalloca to more targets, we'll have to add custom inalloca handling
11061         // in the various CC lowering callbacks.
11062         Flags.setByVal();
11063       }
11064       Align MemAlign;
11065       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11066         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11067         Flags.setByValSize(FrameSize);
11068 
11069         // info is not there but there are cases it cannot get right.
11070         if (auto MA = Args[i].Alignment)
11071           MemAlign = *MA;
11072         else
11073           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11074       } else if (auto MA = Args[i].Alignment) {
11075         MemAlign = *MA;
11076       } else {
11077         MemAlign = OriginalAlignment;
11078       }
11079       Flags.setMemAlign(MemAlign);
11080       if (Args[i].IsNest)
11081         Flags.setNest();
11082       if (NeedsRegBlock)
11083         Flags.setInConsecutiveRegs();
11084 
11085       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11086                                                  CLI.CallConv, VT);
11087       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11088                                                         CLI.CallConv, VT);
11089       SmallVector<SDValue, 4> Parts(NumParts);
11090       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11091 
11092       if (Args[i].IsSExt)
11093         ExtendKind = ISD::SIGN_EXTEND;
11094       else if (Args[i].IsZExt)
11095         ExtendKind = ISD::ZERO_EXTEND;
11096 
11097       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11098       // for now.
11099       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11100           CanLowerReturn) {
11101         assert((CLI.RetTy == Args[i].Ty ||
11102                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11103                  CLI.RetTy->getPointerAddressSpace() ==
11104                      Args[i].Ty->getPointerAddressSpace())) &&
11105                RetTys.size() == NumValues && "unexpected use of 'returned'");
11106         // Before passing 'returned' to the target lowering code, ensure that
11107         // either the register MVT and the actual EVT are the same size or that
11108         // the return value and argument are extended in the same way; in these
11109         // cases it's safe to pass the argument register value unchanged as the
11110         // return register value (although it's at the target's option whether
11111         // to do so)
11112         // TODO: allow code generation to take advantage of partially preserved
11113         // registers rather than clobbering the entire register when the
11114         // parameter extension method is not compatible with the return
11115         // extension method
11116         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11117             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11118              CLI.RetZExt == Args[i].IsZExt))
11119           Flags.setReturned();
11120       }
11121 
11122       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11123                      CLI.CallConv, ExtendKind);
11124 
11125       for (unsigned j = 0; j != NumParts; ++j) {
11126         // if it isn't first piece, alignment must be 1
11127         // For scalable vectors the scalable part is currently handled
11128         // by individual targets, so we just use the known minimum size here.
11129         ISD::OutputArg MyFlags(
11130             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11131             i < CLI.NumFixedArgs, i,
11132             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11133         if (NumParts > 1 && j == 0)
11134           MyFlags.Flags.setSplit();
11135         else if (j != 0) {
11136           MyFlags.Flags.setOrigAlign(Align(1));
11137           if (j == NumParts - 1)
11138             MyFlags.Flags.setSplitEnd();
11139         }
11140 
11141         CLI.Outs.push_back(MyFlags);
11142         CLI.OutVals.push_back(Parts[j]);
11143       }
11144 
11145       if (NeedsRegBlock && Value == NumValues - 1)
11146         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11147     }
11148   }
11149 
11150   SmallVector<SDValue, 4> InVals;
11151   CLI.Chain = LowerCall(CLI, InVals);
11152 
11153   // Update CLI.InVals to use outside of this function.
11154   CLI.InVals = InVals;
11155 
11156   // Verify that the target's LowerCall behaved as expected.
11157   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11158          "LowerCall didn't return a valid chain!");
11159   assert((!CLI.IsTailCall || InVals.empty()) &&
11160          "LowerCall emitted a return value for a tail call!");
11161   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11162          "LowerCall didn't emit the correct number of values!");
11163 
11164   // For a tail call, the return value is merely live-out and there aren't
11165   // any nodes in the DAG representing it. Return a special value to
11166   // indicate that a tail call has been emitted and no more Instructions
11167   // should be processed in the current block.
11168   if (CLI.IsTailCall) {
11169     CLI.DAG.setRoot(CLI.Chain);
11170     return std::make_pair(SDValue(), SDValue());
11171   }
11172 
11173 #ifndef NDEBUG
11174   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11175     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11176     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11177            "LowerCall emitted a value with the wrong type!");
11178   }
11179 #endif
11180 
11181   SmallVector<SDValue, 4> ReturnValues;
11182   if (!CanLowerReturn) {
11183     // The instruction result is the result of loading from the
11184     // hidden sret parameter.
11185     SmallVector<EVT, 1> PVTs;
11186     Type *PtrRetTy =
11187         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11188 
11189     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11190     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11191     EVT PtrVT = PVTs[0];
11192 
11193     unsigned NumValues = RetTys.size();
11194     ReturnValues.resize(NumValues);
11195     SmallVector<SDValue, 4> Chains(NumValues);
11196 
11197     // An aggregate return value cannot wrap around the address space, so
11198     // offsets to its parts don't wrap either.
11199     SDNodeFlags Flags;
11200     Flags.setNoUnsignedWrap(true);
11201 
11202     MachineFunction &MF = CLI.DAG.getMachineFunction();
11203     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11204     for (unsigned i = 0; i < NumValues; ++i) {
11205       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11206                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11207                                                         PtrVT), Flags);
11208       SDValue L = CLI.DAG.getLoad(
11209           RetTys[i], CLI.DL, CLI.Chain, Add,
11210           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11211                                             DemoteStackIdx, Offsets[i]),
11212           HiddenSRetAlign);
11213       ReturnValues[i] = L;
11214       Chains[i] = L.getValue(1);
11215     }
11216 
11217     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11218   } else {
11219     // Collect the legal value parts into potentially illegal values
11220     // that correspond to the original function's return values.
11221     std::optional<ISD::NodeType> AssertOp;
11222     if (CLI.RetSExt)
11223       AssertOp = ISD::AssertSext;
11224     else if (CLI.RetZExt)
11225       AssertOp = ISD::AssertZext;
11226     unsigned CurReg = 0;
11227     for (EVT VT : RetTys) {
11228       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11229                                                      CLI.CallConv, VT);
11230       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11231                                                        CLI.CallConv, VT);
11232 
11233       ReturnValues.push_back(getCopyFromParts(
11234           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11235           CLI.Chain, CLI.CallConv, AssertOp));
11236       CurReg += NumRegs;
11237     }
11238 
11239     // For a function returning void, there is no return value. We can't create
11240     // such a node, so we just return a null return value in that case. In
11241     // that case, nothing will actually look at the value.
11242     if (ReturnValues.empty())
11243       return std::make_pair(SDValue(), CLI.Chain);
11244   }
11245 
11246   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11247                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11248   return std::make_pair(Res, CLI.Chain);
11249 }
11250 
11251 /// Places new result values for the node in Results (their number
11252 /// and types must exactly match those of the original return values of
11253 /// the node), or leaves Results empty, which indicates that the node is not
11254 /// to be custom lowered after all.
11255 void TargetLowering::LowerOperationWrapper(SDNode *N,
11256                                            SmallVectorImpl<SDValue> &Results,
11257                                            SelectionDAG &DAG) const {
11258   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11259 
11260   if (!Res.getNode())
11261     return;
11262 
11263   // If the original node has one result, take the return value from
11264   // LowerOperation as is. It might not be result number 0.
11265   if (N->getNumValues() == 1) {
11266     Results.push_back(Res);
11267     return;
11268   }
11269 
11270   // If the original node has multiple results, then the return node should
11271   // have the same number of results.
11272   assert((N->getNumValues() == Res->getNumValues()) &&
11273       "Lowering returned the wrong number of results!");
11274 
11275   // Places new result values base on N result number.
11276   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11277     Results.push_back(Res.getValue(I));
11278 }
11279 
11280 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11281   llvm_unreachable("LowerOperation not implemented for this target!");
11282 }
11283 
11284 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11285                                                      unsigned Reg,
11286                                                      ISD::NodeType ExtendType) {
11287   SDValue Op = getNonRegisterValue(V);
11288   assert((Op.getOpcode() != ISD::CopyFromReg ||
11289           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11290          "Copy from a reg to the same reg!");
11291   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11292 
11293   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11294   // If this is an InlineAsm we have to match the registers required, not the
11295   // notional registers required by the type.
11296 
11297   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11298                    std::nullopt); // This is not an ABI copy.
11299   SDValue Chain = DAG.getEntryNode();
11300 
11301   if (ExtendType == ISD::ANY_EXTEND) {
11302     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11303     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11304       ExtendType = PreferredExtendIt->second;
11305   }
11306   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11307   PendingExports.push_back(Chain);
11308 }
11309 
11310 #include "llvm/CodeGen/SelectionDAGISel.h"
11311 
11312 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11313 /// entry block, return true.  This includes arguments used by switches, since
11314 /// the switch may expand into multiple basic blocks.
11315 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11316   // With FastISel active, we may be splitting blocks, so force creation
11317   // of virtual registers for all non-dead arguments.
11318   if (FastISel)
11319     return A->use_empty();
11320 
11321   const BasicBlock &Entry = A->getParent()->front();
11322   for (const User *U : A->users())
11323     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11324       return false;  // Use not in entry block.
11325 
11326   return true;
11327 }
11328 
11329 using ArgCopyElisionMapTy =
11330     DenseMap<const Argument *,
11331              std::pair<const AllocaInst *, const StoreInst *>>;
11332 
11333 /// Scan the entry block of the function in FuncInfo for arguments that look
11334 /// like copies into a local alloca. Record any copied arguments in
11335 /// ArgCopyElisionCandidates.
11336 static void
11337 findArgumentCopyElisionCandidates(const DataLayout &DL,
11338                                   FunctionLoweringInfo *FuncInfo,
11339                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11340   // Record the state of every static alloca used in the entry block. Argument
11341   // allocas are all used in the entry block, so we need approximately as many
11342   // entries as we have arguments.
11343   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11344   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11345   unsigned NumArgs = FuncInfo->Fn->arg_size();
11346   StaticAllocas.reserve(NumArgs * 2);
11347 
11348   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11349     if (!V)
11350       return nullptr;
11351     V = V->stripPointerCasts();
11352     const auto *AI = dyn_cast<AllocaInst>(V);
11353     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11354       return nullptr;
11355     auto Iter = StaticAllocas.insert({AI, Unknown});
11356     return &Iter.first->second;
11357   };
11358 
11359   // Look for stores of arguments to static allocas. Look through bitcasts and
11360   // GEPs to handle type coercions, as long as the alloca is fully initialized
11361   // by the store. Any non-store use of an alloca escapes it and any subsequent
11362   // unanalyzed store might write it.
11363   // FIXME: Handle structs initialized with multiple stores.
11364   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11365     // Look for stores, and handle non-store uses conservatively.
11366     const auto *SI = dyn_cast<StoreInst>(&I);
11367     if (!SI) {
11368       // We will look through cast uses, so ignore them completely.
11369       if (I.isCast())
11370         continue;
11371       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11372       // to allocas.
11373       if (I.isDebugOrPseudoInst())
11374         continue;
11375       // This is an unknown instruction. Assume it escapes or writes to all
11376       // static alloca operands.
11377       for (const Use &U : I.operands()) {
11378         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11379           *Info = StaticAllocaInfo::Clobbered;
11380       }
11381       continue;
11382     }
11383 
11384     // If the stored value is a static alloca, mark it as escaped.
11385     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11386       *Info = StaticAllocaInfo::Clobbered;
11387 
11388     // Check if the destination is a static alloca.
11389     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11390     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11391     if (!Info)
11392       continue;
11393     const AllocaInst *AI = cast<AllocaInst>(Dst);
11394 
11395     // Skip allocas that have been initialized or clobbered.
11396     if (*Info != StaticAllocaInfo::Unknown)
11397       continue;
11398 
11399     // Check if the stored value is an argument, and that this store fully
11400     // initializes the alloca.
11401     // If the argument type has padding bits we can't directly forward a pointer
11402     // as the upper bits may contain garbage.
11403     // Don't elide copies from the same argument twice.
11404     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11405     const auto *Arg = dyn_cast<Argument>(Val);
11406     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11407         Arg->getType()->isEmptyTy() ||
11408         DL.getTypeStoreSize(Arg->getType()) !=
11409             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11410         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11411         ArgCopyElisionCandidates.count(Arg)) {
11412       *Info = StaticAllocaInfo::Clobbered;
11413       continue;
11414     }
11415 
11416     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11417                       << '\n');
11418 
11419     // Mark this alloca and store for argument copy elision.
11420     *Info = StaticAllocaInfo::Elidable;
11421     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11422 
11423     // Stop scanning if we've seen all arguments. This will happen early in -O0
11424     // builds, which is useful, because -O0 builds have large entry blocks and
11425     // many allocas.
11426     if (ArgCopyElisionCandidates.size() == NumArgs)
11427       break;
11428   }
11429 }
11430 
11431 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11432 /// ArgVal is a load from a suitable fixed stack object.
11433 static void tryToElideArgumentCopy(
11434     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11435     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11436     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11437     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11438     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11439   // Check if this is a load from a fixed stack object.
11440   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11441   if (!LNode)
11442     return;
11443   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11444   if (!FINode)
11445     return;
11446 
11447   // Check that the fixed stack object is the right size and alignment.
11448   // Look at the alignment that the user wrote on the alloca instead of looking
11449   // at the stack object.
11450   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11451   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11452   const AllocaInst *AI = ArgCopyIter->second.first;
11453   int FixedIndex = FINode->getIndex();
11454   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11455   int OldIndex = AllocaIndex;
11456   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11457   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11458     LLVM_DEBUG(
11459         dbgs() << "  argument copy elision failed due to bad fixed stack "
11460                   "object size\n");
11461     return;
11462   }
11463   Align RequiredAlignment = AI->getAlign();
11464   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11465     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11466                          "greater than stack argument alignment ("
11467                       << DebugStr(RequiredAlignment) << " vs "
11468                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11469     return;
11470   }
11471 
11472   // Perform the elision. Delete the old stack object and replace its only use
11473   // in the variable info map. Mark the stack object as mutable and aliased.
11474   LLVM_DEBUG({
11475     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11476            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11477            << '\n';
11478   });
11479   MFI.RemoveStackObject(OldIndex);
11480   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11481   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11482   AllocaIndex = FixedIndex;
11483   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11484   for (SDValue ArgVal : ArgVals)
11485     Chains.push_back(ArgVal.getValue(1));
11486 
11487   // Avoid emitting code for the store implementing the copy.
11488   const StoreInst *SI = ArgCopyIter->second.second;
11489   ElidedArgCopyInstrs.insert(SI);
11490 
11491   // Check for uses of the argument again so that we can avoid exporting ArgVal
11492   // if it is't used by anything other than the store.
11493   for (const Value *U : Arg.users()) {
11494     if (U != SI) {
11495       ArgHasUses = true;
11496       break;
11497     }
11498   }
11499 }
11500 
11501 void SelectionDAGISel::LowerArguments(const Function &F) {
11502   SelectionDAG &DAG = SDB->DAG;
11503   SDLoc dl = SDB->getCurSDLoc();
11504   const DataLayout &DL = DAG.getDataLayout();
11505   SmallVector<ISD::InputArg, 16> Ins;
11506 
11507   // In Naked functions we aren't going to save any registers.
11508   if (F.hasFnAttribute(Attribute::Naked))
11509     return;
11510 
11511   if (!FuncInfo->CanLowerReturn) {
11512     // Put in an sret pointer parameter before all the other parameters.
11513     SmallVector<EVT, 1> ValueVTs;
11514     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11515                     PointerType::get(F.getContext(),
11516                                      DAG.getDataLayout().getAllocaAddrSpace()),
11517                     ValueVTs);
11518 
11519     // NOTE: Assuming that a pointer will never break down to more than one VT
11520     // or one register.
11521     ISD::ArgFlagsTy Flags;
11522     Flags.setSRet();
11523     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11524     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11525                          ISD::InputArg::NoArgIndex, 0);
11526     Ins.push_back(RetArg);
11527   }
11528 
11529   // Look for stores of arguments to static allocas. Mark such arguments with a
11530   // flag to ask the target to give us the memory location of that argument if
11531   // available.
11532   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11533   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11534                                     ArgCopyElisionCandidates);
11535 
11536   // Set up the incoming argument description vector.
11537   for (const Argument &Arg : F.args()) {
11538     unsigned ArgNo = Arg.getArgNo();
11539     SmallVector<EVT, 4> ValueVTs;
11540     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11541     bool isArgValueUsed = !Arg.use_empty();
11542     unsigned PartBase = 0;
11543     Type *FinalType = Arg.getType();
11544     if (Arg.hasAttribute(Attribute::ByVal))
11545       FinalType = Arg.getParamByValType();
11546     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11547         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11548     for (unsigned Value = 0, NumValues = ValueVTs.size();
11549          Value != NumValues; ++Value) {
11550       EVT VT = ValueVTs[Value];
11551       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11552       ISD::ArgFlagsTy Flags;
11553 
11554 
11555       if (Arg.getType()->isPointerTy()) {
11556         Flags.setPointer();
11557         Flags.setPointerAddrSpace(
11558             cast<PointerType>(Arg.getType())->getAddressSpace());
11559       }
11560       if (Arg.hasAttribute(Attribute::ZExt))
11561         Flags.setZExt();
11562       if (Arg.hasAttribute(Attribute::SExt))
11563         Flags.setSExt();
11564       if (Arg.hasAttribute(Attribute::InReg)) {
11565         // If we are using vectorcall calling convention, a structure that is
11566         // passed InReg - is surely an HVA
11567         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11568             isa<StructType>(Arg.getType())) {
11569           // The first value of a structure is marked
11570           if (0 == Value)
11571             Flags.setHvaStart();
11572           Flags.setHva();
11573         }
11574         // Set InReg Flag
11575         Flags.setInReg();
11576       }
11577       if (Arg.hasAttribute(Attribute::StructRet))
11578         Flags.setSRet();
11579       if (Arg.hasAttribute(Attribute::SwiftSelf))
11580         Flags.setSwiftSelf();
11581       if (Arg.hasAttribute(Attribute::SwiftAsync))
11582         Flags.setSwiftAsync();
11583       if (Arg.hasAttribute(Attribute::SwiftError))
11584         Flags.setSwiftError();
11585       if (Arg.hasAttribute(Attribute::ByVal))
11586         Flags.setByVal();
11587       if (Arg.hasAttribute(Attribute::ByRef))
11588         Flags.setByRef();
11589       if (Arg.hasAttribute(Attribute::InAlloca)) {
11590         Flags.setInAlloca();
11591         // Set the byval flag for CCAssignFn callbacks that don't know about
11592         // inalloca.  This way we can know how many bytes we should've allocated
11593         // and how many bytes a callee cleanup function will pop.  If we port
11594         // inalloca to more targets, we'll have to add custom inalloca handling
11595         // in the various CC lowering callbacks.
11596         Flags.setByVal();
11597       }
11598       if (Arg.hasAttribute(Attribute::Preallocated)) {
11599         Flags.setPreallocated();
11600         // Set the byval flag for CCAssignFn callbacks that don't know about
11601         // preallocated.  This way we can know how many bytes we should've
11602         // allocated and how many bytes a callee cleanup function will pop.  If
11603         // we port preallocated to more targets, we'll have to add custom
11604         // preallocated handling in the various CC lowering callbacks.
11605         Flags.setByVal();
11606       }
11607 
11608       // Certain targets (such as MIPS), may have a different ABI alignment
11609       // for a type depending on the context. Give the target a chance to
11610       // specify the alignment it wants.
11611       const Align OriginalAlignment(
11612           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11613       Flags.setOrigAlign(OriginalAlignment);
11614 
11615       Align MemAlign;
11616       Type *ArgMemTy = nullptr;
11617       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11618           Flags.isByRef()) {
11619         if (!ArgMemTy)
11620           ArgMemTy = Arg.getPointeeInMemoryValueType();
11621 
11622         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11623 
11624         // For in-memory arguments, size and alignment should be passed from FE.
11625         // BE will guess if this info is not there but there are cases it cannot
11626         // get right.
11627         if (auto ParamAlign = Arg.getParamStackAlign())
11628           MemAlign = *ParamAlign;
11629         else if ((ParamAlign = Arg.getParamAlign()))
11630           MemAlign = *ParamAlign;
11631         else
11632           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11633         if (Flags.isByRef())
11634           Flags.setByRefSize(MemSize);
11635         else
11636           Flags.setByValSize(MemSize);
11637       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11638         MemAlign = *ParamAlign;
11639       } else {
11640         MemAlign = OriginalAlignment;
11641       }
11642       Flags.setMemAlign(MemAlign);
11643 
11644       if (Arg.hasAttribute(Attribute::Nest))
11645         Flags.setNest();
11646       if (NeedsRegBlock)
11647         Flags.setInConsecutiveRegs();
11648       if (ArgCopyElisionCandidates.count(&Arg))
11649         Flags.setCopyElisionCandidate();
11650       if (Arg.hasAttribute(Attribute::Returned))
11651         Flags.setReturned();
11652 
11653       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11654           *CurDAG->getContext(), F.getCallingConv(), VT);
11655       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11656           *CurDAG->getContext(), F.getCallingConv(), VT);
11657       for (unsigned i = 0; i != NumRegs; ++i) {
11658         // For scalable vectors, use the minimum size; individual targets
11659         // are responsible for handling scalable vector arguments and
11660         // return values.
11661         ISD::InputArg MyFlags(
11662             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11663             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11664         if (NumRegs > 1 && i == 0)
11665           MyFlags.Flags.setSplit();
11666         // if it isn't first piece, alignment must be 1
11667         else if (i > 0) {
11668           MyFlags.Flags.setOrigAlign(Align(1));
11669           if (i == NumRegs - 1)
11670             MyFlags.Flags.setSplitEnd();
11671         }
11672         Ins.push_back(MyFlags);
11673       }
11674       if (NeedsRegBlock && Value == NumValues - 1)
11675         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11676       PartBase += VT.getStoreSize().getKnownMinValue();
11677     }
11678   }
11679 
11680   // Call the target to set up the argument values.
11681   SmallVector<SDValue, 8> InVals;
11682   SDValue NewRoot = TLI->LowerFormalArguments(
11683       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11684 
11685   // Verify that the target's LowerFormalArguments behaved as expected.
11686   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11687          "LowerFormalArguments didn't return a valid chain!");
11688   assert(InVals.size() == Ins.size() &&
11689          "LowerFormalArguments didn't emit the correct number of values!");
11690   LLVM_DEBUG({
11691     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11692       assert(InVals[i].getNode() &&
11693              "LowerFormalArguments emitted a null value!");
11694       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11695              "LowerFormalArguments emitted a value with the wrong type!");
11696     }
11697   });
11698 
11699   // Update the DAG with the new chain value resulting from argument lowering.
11700   DAG.setRoot(NewRoot);
11701 
11702   // Set up the argument values.
11703   unsigned i = 0;
11704   if (!FuncInfo->CanLowerReturn) {
11705     // Create a virtual register for the sret pointer, and put in a copy
11706     // from the sret argument into it.
11707     SmallVector<EVT, 1> ValueVTs;
11708     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11709                     PointerType::get(F.getContext(),
11710                                      DAG.getDataLayout().getAllocaAddrSpace()),
11711                     ValueVTs);
11712     MVT VT = ValueVTs[0].getSimpleVT();
11713     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11714     std::optional<ISD::NodeType> AssertOp;
11715     SDValue ArgValue =
11716         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11717                          F.getCallingConv(), AssertOp);
11718 
11719     MachineFunction& MF = SDB->DAG.getMachineFunction();
11720     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11721     Register SRetReg =
11722         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11723     FuncInfo->DemoteRegister = SRetReg;
11724     NewRoot =
11725         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11726     DAG.setRoot(NewRoot);
11727 
11728     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11729     ++i;
11730   }
11731 
11732   SmallVector<SDValue, 4> Chains;
11733   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11734   for (const Argument &Arg : F.args()) {
11735     SmallVector<SDValue, 4> ArgValues;
11736     SmallVector<EVT, 4> ValueVTs;
11737     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11738     unsigned NumValues = ValueVTs.size();
11739     if (NumValues == 0)
11740       continue;
11741 
11742     bool ArgHasUses = !Arg.use_empty();
11743 
11744     // Elide the copying store if the target loaded this argument from a
11745     // suitable fixed stack object.
11746     if (Ins[i].Flags.isCopyElisionCandidate()) {
11747       unsigned NumParts = 0;
11748       for (EVT VT : ValueVTs)
11749         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11750                                                        F.getCallingConv(), VT);
11751 
11752       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11753                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11754                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11755     }
11756 
11757     // If this argument is unused then remember its value. It is used to generate
11758     // debugging information.
11759     bool isSwiftErrorArg =
11760         TLI->supportSwiftError() &&
11761         Arg.hasAttribute(Attribute::SwiftError);
11762     if (!ArgHasUses && !isSwiftErrorArg) {
11763       SDB->setUnusedArgValue(&Arg, InVals[i]);
11764 
11765       // Also remember any frame index for use in FastISel.
11766       if (FrameIndexSDNode *FI =
11767           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11768         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11769     }
11770 
11771     for (unsigned Val = 0; Val != NumValues; ++Val) {
11772       EVT VT = ValueVTs[Val];
11773       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11774                                                       F.getCallingConv(), VT);
11775       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11776           *CurDAG->getContext(), F.getCallingConv(), VT);
11777 
11778       // Even an apparent 'unused' swifterror argument needs to be returned. So
11779       // we do generate a copy for it that can be used on return from the
11780       // function.
11781       if (ArgHasUses || isSwiftErrorArg) {
11782         std::optional<ISD::NodeType> AssertOp;
11783         if (Arg.hasAttribute(Attribute::SExt))
11784           AssertOp = ISD::AssertSext;
11785         else if (Arg.hasAttribute(Attribute::ZExt))
11786           AssertOp = ISD::AssertZext;
11787 
11788         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11789                                              PartVT, VT, nullptr, NewRoot,
11790                                              F.getCallingConv(), AssertOp));
11791       }
11792 
11793       i += NumParts;
11794     }
11795 
11796     // We don't need to do anything else for unused arguments.
11797     if (ArgValues.empty())
11798       continue;
11799 
11800     // Note down frame index.
11801     if (FrameIndexSDNode *FI =
11802         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11803       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11804 
11805     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11806                                      SDB->getCurSDLoc());
11807 
11808     SDB->setValue(&Arg, Res);
11809     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11810       // We want to associate the argument with the frame index, among
11811       // involved operands, that correspond to the lowest address. The
11812       // getCopyFromParts function, called earlier, is swapping the order of
11813       // the operands to BUILD_PAIR depending on endianness. The result of
11814       // that swapping is that the least significant bits of the argument will
11815       // be in the first operand of the BUILD_PAIR node, and the most
11816       // significant bits will be in the second operand.
11817       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11818       if (LoadSDNode *LNode =
11819           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11820         if (FrameIndexSDNode *FI =
11821             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11822           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11823     }
11824 
11825     // Analyses past this point are naive and don't expect an assertion.
11826     if (Res.getOpcode() == ISD::AssertZext)
11827       Res = Res.getOperand(0);
11828 
11829     // Update the SwiftErrorVRegDefMap.
11830     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11831       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11832       if (Register::isVirtualRegister(Reg))
11833         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11834                                    Reg);
11835     }
11836 
11837     // If this argument is live outside of the entry block, insert a copy from
11838     // wherever we got it to the vreg that other BB's will reference it as.
11839     if (Res.getOpcode() == ISD::CopyFromReg) {
11840       // If we can, though, try to skip creating an unnecessary vreg.
11841       // FIXME: This isn't very clean... it would be nice to make this more
11842       // general.
11843       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11844       if (Register::isVirtualRegister(Reg)) {
11845         FuncInfo->ValueMap[&Arg] = Reg;
11846         continue;
11847       }
11848     }
11849     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11850       FuncInfo->InitializeRegForValue(&Arg);
11851       SDB->CopyToExportRegsIfNeeded(&Arg);
11852     }
11853   }
11854 
11855   if (!Chains.empty()) {
11856     Chains.push_back(NewRoot);
11857     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11858   }
11859 
11860   DAG.setRoot(NewRoot);
11861 
11862   assert(i == InVals.size() && "Argument register count mismatch!");
11863 
11864   // If any argument copy elisions occurred and we have debug info, update the
11865   // stale frame indices used in the dbg.declare variable info table.
11866   if (!ArgCopyElisionFrameIndexMap.empty()) {
11867     for (MachineFunction::VariableDbgInfo &VI :
11868          MF->getInStackSlotVariableDbgInfo()) {
11869       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11870       if (I != ArgCopyElisionFrameIndexMap.end())
11871         VI.updateStackSlot(I->second);
11872     }
11873   }
11874 
11875   // Finally, if the target has anything special to do, allow it to do so.
11876   emitFunctionEntryCode();
11877 }
11878 
11879 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11880 /// ensure constants are generated when needed.  Remember the virtual registers
11881 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11882 /// directly add them, because expansion might result in multiple MBB's for one
11883 /// BB.  As such, the start of the BB might correspond to a different MBB than
11884 /// the end.
11885 void
11886 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11888 
11889   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11890 
11891   // Check PHI nodes in successors that expect a value to be available from this
11892   // block.
11893   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11894     if (!isa<PHINode>(SuccBB->begin())) continue;
11895     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11896 
11897     // If this terminator has multiple identical successors (common for
11898     // switches), only handle each succ once.
11899     if (!SuccsHandled.insert(SuccMBB).second)
11900       continue;
11901 
11902     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11903 
11904     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11905     // nodes and Machine PHI nodes, but the incoming operands have not been
11906     // emitted yet.
11907     for (const PHINode &PN : SuccBB->phis()) {
11908       // Ignore dead phi's.
11909       if (PN.use_empty())
11910         continue;
11911 
11912       // Skip empty types
11913       if (PN.getType()->isEmptyTy())
11914         continue;
11915 
11916       unsigned Reg;
11917       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11918 
11919       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11920         unsigned &RegOut = ConstantsOut[C];
11921         if (RegOut == 0) {
11922           RegOut = FuncInfo.CreateRegs(C);
11923           // We need to zero/sign extend ConstantInt phi operands to match
11924           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11925           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11926           if (auto *CI = dyn_cast<ConstantInt>(C))
11927             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11928                                                     : ISD::ZERO_EXTEND;
11929           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11930         }
11931         Reg = RegOut;
11932       } else {
11933         DenseMap<const Value *, Register>::iterator I =
11934           FuncInfo.ValueMap.find(PHIOp);
11935         if (I != FuncInfo.ValueMap.end())
11936           Reg = I->second;
11937         else {
11938           assert(isa<AllocaInst>(PHIOp) &&
11939                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11940                  "Didn't codegen value into a register!??");
11941           Reg = FuncInfo.CreateRegs(PHIOp);
11942           CopyValueToVirtualRegister(PHIOp, Reg);
11943         }
11944       }
11945 
11946       // Remember that this register needs to added to the machine PHI node as
11947       // the input for this MBB.
11948       SmallVector<EVT, 4> ValueVTs;
11949       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11950       for (EVT VT : ValueVTs) {
11951         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11952         for (unsigned i = 0; i != NumRegisters; ++i)
11953           FuncInfo.PHINodesToUpdate.push_back(
11954               std::make_pair(&*MBBI++, Reg + i));
11955         Reg += NumRegisters;
11956       }
11957     }
11958   }
11959 
11960   ConstantsOut.clear();
11961 }
11962 
11963 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11964   MachineFunction::iterator I(MBB);
11965   if (++I == FuncInfo.MF->end())
11966     return nullptr;
11967   return &*I;
11968 }
11969 
11970 /// During lowering new call nodes can be created (such as memset, etc.).
11971 /// Those will become new roots of the current DAG, but complications arise
11972 /// when they are tail calls. In such cases, the call lowering will update
11973 /// the root, but the builder still needs to know that a tail call has been
11974 /// lowered in order to avoid generating an additional return.
11975 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11976   // If the node is null, we do have a tail call.
11977   if (MaybeTC.getNode() != nullptr)
11978     DAG.setRoot(MaybeTC);
11979   else
11980     HasTailCall = true;
11981 }
11982 
11983 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11984                                         MachineBasicBlock *SwitchMBB,
11985                                         MachineBasicBlock *DefaultMBB) {
11986   MachineFunction *CurMF = FuncInfo.MF;
11987   MachineBasicBlock *NextMBB = nullptr;
11988   MachineFunction::iterator BBI(W.MBB);
11989   if (++BBI != FuncInfo.MF->end())
11990     NextMBB = &*BBI;
11991 
11992   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11993 
11994   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11995 
11996   if (Size == 2 && W.MBB == SwitchMBB) {
11997     // If any two of the cases has the same destination, and if one value
11998     // is the same as the other, but has one bit unset that the other has set,
11999     // use bit manipulation to do two compares at once.  For example:
12000     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12001     // TODO: This could be extended to merge any 2 cases in switches with 3
12002     // cases.
12003     // TODO: Handle cases where W.CaseBB != SwitchBB.
12004     CaseCluster &Small = *W.FirstCluster;
12005     CaseCluster &Big = *W.LastCluster;
12006 
12007     if (Small.Low == Small.High && Big.Low == Big.High &&
12008         Small.MBB == Big.MBB) {
12009       const APInt &SmallValue = Small.Low->getValue();
12010       const APInt &BigValue = Big.Low->getValue();
12011 
12012       // Check that there is only one bit different.
12013       APInt CommonBit = BigValue ^ SmallValue;
12014       if (CommonBit.isPowerOf2()) {
12015         SDValue CondLHS = getValue(Cond);
12016         EVT VT = CondLHS.getValueType();
12017         SDLoc DL = getCurSDLoc();
12018 
12019         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12020                                  DAG.getConstant(CommonBit, DL, VT));
12021         SDValue Cond = DAG.getSetCC(
12022             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12023             ISD::SETEQ);
12024 
12025         // Update successor info.
12026         // Both Small and Big will jump to Small.BB, so we sum up the
12027         // probabilities.
12028         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12029         if (BPI)
12030           addSuccessorWithProb(
12031               SwitchMBB, DefaultMBB,
12032               // The default destination is the first successor in IR.
12033               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12034         else
12035           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12036 
12037         // Insert the true branch.
12038         SDValue BrCond =
12039             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12040                         DAG.getBasicBlock(Small.MBB));
12041         // Insert the false branch.
12042         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12043                              DAG.getBasicBlock(DefaultMBB));
12044 
12045         DAG.setRoot(BrCond);
12046         return;
12047       }
12048     }
12049   }
12050 
12051   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12052     // Here, we order cases by probability so the most likely case will be
12053     // checked first. However, two clusters can have the same probability in
12054     // which case their relative ordering is non-deterministic. So we use Low
12055     // as a tie-breaker as clusters are guaranteed to never overlap.
12056     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12057                [](const CaseCluster &a, const CaseCluster &b) {
12058       return a.Prob != b.Prob ?
12059              a.Prob > b.Prob :
12060              a.Low->getValue().slt(b.Low->getValue());
12061     });
12062 
12063     // Rearrange the case blocks so that the last one falls through if possible
12064     // without changing the order of probabilities.
12065     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12066       --I;
12067       if (I->Prob > W.LastCluster->Prob)
12068         break;
12069       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12070         std::swap(*I, *W.LastCluster);
12071         break;
12072       }
12073     }
12074   }
12075 
12076   // Compute total probability.
12077   BranchProbability DefaultProb = W.DefaultProb;
12078   BranchProbability UnhandledProbs = DefaultProb;
12079   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12080     UnhandledProbs += I->Prob;
12081 
12082   MachineBasicBlock *CurMBB = W.MBB;
12083   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12084     bool FallthroughUnreachable = false;
12085     MachineBasicBlock *Fallthrough;
12086     if (I == W.LastCluster) {
12087       // For the last cluster, fall through to the default destination.
12088       Fallthrough = DefaultMBB;
12089       FallthroughUnreachable = isa<UnreachableInst>(
12090           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12091     } else {
12092       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12093       CurMF->insert(BBI, Fallthrough);
12094       // Put Cond in a virtual register to make it available from the new blocks.
12095       ExportFromCurrentBlock(Cond);
12096     }
12097     UnhandledProbs -= I->Prob;
12098 
12099     switch (I->Kind) {
12100       case CC_JumpTable: {
12101         // FIXME: Optimize away range check based on pivot comparisons.
12102         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12103         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12104 
12105         // The jump block hasn't been inserted yet; insert it here.
12106         MachineBasicBlock *JumpMBB = JT->MBB;
12107         CurMF->insert(BBI, JumpMBB);
12108 
12109         auto JumpProb = I->Prob;
12110         auto FallthroughProb = UnhandledProbs;
12111 
12112         // If the default statement is a target of the jump table, we evenly
12113         // distribute the default probability to successors of CurMBB. Also
12114         // update the probability on the edge from JumpMBB to Fallthrough.
12115         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12116                                               SE = JumpMBB->succ_end();
12117              SI != SE; ++SI) {
12118           if (*SI == DefaultMBB) {
12119             JumpProb += DefaultProb / 2;
12120             FallthroughProb -= DefaultProb / 2;
12121             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12122             JumpMBB->normalizeSuccProbs();
12123             break;
12124           }
12125         }
12126 
12127         // If the default clause is unreachable, propagate that knowledge into
12128         // JTH->FallthroughUnreachable which will use it to suppress the range
12129         // check.
12130         //
12131         // However, don't do this if we're doing branch target enforcement,
12132         // because a table branch _without_ a range check can be a tempting JOP
12133         // gadget - out-of-bounds inputs that are impossible in correct
12134         // execution become possible again if an attacker can influence the
12135         // control flow. So if an attacker doesn't already have a BTI bypass
12136         // available, we don't want them to be able to get one out of this
12137         // table branch.
12138         if (FallthroughUnreachable) {
12139           Function &CurFunc = CurMF->getFunction();
12140           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12141             JTH->FallthroughUnreachable = true;
12142         }
12143 
12144         if (!JTH->FallthroughUnreachable)
12145           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12146         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12147         CurMBB->normalizeSuccProbs();
12148 
12149         // The jump table header will be inserted in our current block, do the
12150         // range check, and fall through to our fallthrough block.
12151         JTH->HeaderBB = CurMBB;
12152         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12153 
12154         // If we're in the right place, emit the jump table header right now.
12155         if (CurMBB == SwitchMBB) {
12156           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12157           JTH->Emitted = true;
12158         }
12159         break;
12160       }
12161       case CC_BitTests: {
12162         // FIXME: Optimize away range check based on pivot comparisons.
12163         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12164 
12165         // The bit test blocks haven't been inserted yet; insert them here.
12166         for (BitTestCase &BTC : BTB->Cases)
12167           CurMF->insert(BBI, BTC.ThisBB);
12168 
12169         // Fill in fields of the BitTestBlock.
12170         BTB->Parent = CurMBB;
12171         BTB->Default = Fallthrough;
12172 
12173         BTB->DefaultProb = UnhandledProbs;
12174         // If the cases in bit test don't form a contiguous range, we evenly
12175         // distribute the probability on the edge to Fallthrough to two
12176         // successors of CurMBB.
12177         if (!BTB->ContiguousRange) {
12178           BTB->Prob += DefaultProb / 2;
12179           BTB->DefaultProb -= DefaultProb / 2;
12180         }
12181 
12182         if (FallthroughUnreachable)
12183           BTB->FallthroughUnreachable = true;
12184 
12185         // If we're in the right place, emit the bit test header right now.
12186         if (CurMBB == SwitchMBB) {
12187           visitBitTestHeader(*BTB, SwitchMBB);
12188           BTB->Emitted = true;
12189         }
12190         break;
12191       }
12192       case CC_Range: {
12193         const Value *RHS, *LHS, *MHS;
12194         ISD::CondCode CC;
12195         if (I->Low == I->High) {
12196           // Check Cond == I->Low.
12197           CC = ISD::SETEQ;
12198           LHS = Cond;
12199           RHS=I->Low;
12200           MHS = nullptr;
12201         } else {
12202           // Check I->Low <= Cond <= I->High.
12203           CC = ISD::SETLE;
12204           LHS = I->Low;
12205           MHS = Cond;
12206           RHS = I->High;
12207         }
12208 
12209         // If Fallthrough is unreachable, fold away the comparison.
12210         if (FallthroughUnreachable)
12211           CC = ISD::SETTRUE;
12212 
12213         // The false probability is the sum of all unhandled cases.
12214         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12215                      getCurSDLoc(), I->Prob, UnhandledProbs);
12216 
12217         if (CurMBB == SwitchMBB)
12218           visitSwitchCase(CB, SwitchMBB);
12219         else
12220           SL->SwitchCases.push_back(CB);
12221 
12222         break;
12223       }
12224     }
12225     CurMBB = Fallthrough;
12226   }
12227 }
12228 
12229 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12230                                         const SwitchWorkListItem &W,
12231                                         Value *Cond,
12232                                         MachineBasicBlock *SwitchMBB) {
12233   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12234          "Clusters not sorted?");
12235   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12236 
12237   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12238       SL->computeSplitWorkItemInfo(W);
12239 
12240   // Use the first element on the right as pivot since we will make less-than
12241   // comparisons against it.
12242   CaseClusterIt PivotCluster = FirstRight;
12243   assert(PivotCluster > W.FirstCluster);
12244   assert(PivotCluster <= W.LastCluster);
12245 
12246   CaseClusterIt FirstLeft = W.FirstCluster;
12247   CaseClusterIt LastRight = W.LastCluster;
12248 
12249   const ConstantInt *Pivot = PivotCluster->Low;
12250 
12251   // New blocks will be inserted immediately after the current one.
12252   MachineFunction::iterator BBI(W.MBB);
12253   ++BBI;
12254 
12255   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12256   // we can branch to its destination directly if it's squeezed exactly in
12257   // between the known lower bound and Pivot - 1.
12258   MachineBasicBlock *LeftMBB;
12259   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12260       FirstLeft->Low == W.GE &&
12261       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12262     LeftMBB = FirstLeft->MBB;
12263   } else {
12264     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12265     FuncInfo.MF->insert(BBI, LeftMBB);
12266     WorkList.push_back(
12267         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12268     // Put Cond in a virtual register to make it available from the new blocks.
12269     ExportFromCurrentBlock(Cond);
12270   }
12271 
12272   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12273   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12274   // directly if RHS.High equals the current upper bound.
12275   MachineBasicBlock *RightMBB;
12276   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12277       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12278     RightMBB = FirstRight->MBB;
12279   } else {
12280     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12281     FuncInfo.MF->insert(BBI, RightMBB);
12282     WorkList.push_back(
12283         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12284     // Put Cond in a virtual register to make it available from the new blocks.
12285     ExportFromCurrentBlock(Cond);
12286   }
12287 
12288   // Create the CaseBlock record that will be used to lower the branch.
12289   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12290                getCurSDLoc(), LeftProb, RightProb);
12291 
12292   if (W.MBB == SwitchMBB)
12293     visitSwitchCase(CB, SwitchMBB);
12294   else
12295     SL->SwitchCases.push_back(CB);
12296 }
12297 
12298 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12299 // from the swith statement.
12300 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12301                                             BranchProbability PeeledCaseProb) {
12302   if (PeeledCaseProb == BranchProbability::getOne())
12303     return BranchProbability::getZero();
12304   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12305 
12306   uint32_t Numerator = CaseProb.getNumerator();
12307   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12308   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12309 }
12310 
12311 // Try to peel the top probability case if it exceeds the threshold.
12312 // Return current MachineBasicBlock for the switch statement if the peeling
12313 // does not occur.
12314 // If the peeling is performed, return the newly created MachineBasicBlock
12315 // for the peeled switch statement. Also update Clusters to remove the peeled
12316 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12317 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12318     const SwitchInst &SI, CaseClusterVector &Clusters,
12319     BranchProbability &PeeledCaseProb) {
12320   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12321   // Don't perform if there is only one cluster or optimizing for size.
12322   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12323       TM.getOptLevel() == CodeGenOptLevel::None ||
12324       SwitchMBB->getParent()->getFunction().hasMinSize())
12325     return SwitchMBB;
12326 
12327   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12328   unsigned PeeledCaseIndex = 0;
12329   bool SwitchPeeled = false;
12330   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12331     CaseCluster &CC = Clusters[Index];
12332     if (CC.Prob < TopCaseProb)
12333       continue;
12334     TopCaseProb = CC.Prob;
12335     PeeledCaseIndex = Index;
12336     SwitchPeeled = true;
12337   }
12338   if (!SwitchPeeled)
12339     return SwitchMBB;
12340 
12341   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12342                     << TopCaseProb << "\n");
12343 
12344   // Record the MBB for the peeled switch statement.
12345   MachineFunction::iterator BBI(SwitchMBB);
12346   ++BBI;
12347   MachineBasicBlock *PeeledSwitchMBB =
12348       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12349   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12350 
12351   ExportFromCurrentBlock(SI.getCondition());
12352   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12353   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12354                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12355   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12356 
12357   Clusters.erase(PeeledCaseIt);
12358   for (CaseCluster &CC : Clusters) {
12359     LLVM_DEBUG(
12360         dbgs() << "Scale the probablity for one cluster, before scaling: "
12361                << CC.Prob << "\n");
12362     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12363     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12364   }
12365   PeeledCaseProb = TopCaseProb;
12366   return PeeledSwitchMBB;
12367 }
12368 
12369 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12370   // Extract cases from the switch.
12371   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12372   CaseClusterVector Clusters;
12373   Clusters.reserve(SI.getNumCases());
12374   for (auto I : SI.cases()) {
12375     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12376     const ConstantInt *CaseVal = I.getCaseValue();
12377     BranchProbability Prob =
12378         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12379             : BranchProbability(1, SI.getNumCases() + 1);
12380     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12381   }
12382 
12383   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12384 
12385   // Cluster adjacent cases with the same destination. We do this at all
12386   // optimization levels because it's cheap to do and will make codegen faster
12387   // if there are many clusters.
12388   sortAndRangeify(Clusters);
12389 
12390   // The branch probablity of the peeled case.
12391   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12392   MachineBasicBlock *PeeledSwitchMBB =
12393       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12394 
12395   // If there is only the default destination, jump there directly.
12396   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12397   if (Clusters.empty()) {
12398     assert(PeeledSwitchMBB == SwitchMBB);
12399     SwitchMBB->addSuccessor(DefaultMBB);
12400     if (DefaultMBB != NextBlock(SwitchMBB)) {
12401       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12402                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12403     }
12404     return;
12405   }
12406 
12407   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12408                      DAG.getBFI());
12409   SL->findBitTestClusters(Clusters, &SI);
12410 
12411   LLVM_DEBUG({
12412     dbgs() << "Case clusters: ";
12413     for (const CaseCluster &C : Clusters) {
12414       if (C.Kind == CC_JumpTable)
12415         dbgs() << "JT:";
12416       if (C.Kind == CC_BitTests)
12417         dbgs() << "BT:";
12418 
12419       C.Low->getValue().print(dbgs(), true);
12420       if (C.Low != C.High) {
12421         dbgs() << '-';
12422         C.High->getValue().print(dbgs(), true);
12423       }
12424       dbgs() << ' ';
12425     }
12426     dbgs() << '\n';
12427   });
12428 
12429   assert(!Clusters.empty());
12430   SwitchWorkList WorkList;
12431   CaseClusterIt First = Clusters.begin();
12432   CaseClusterIt Last = Clusters.end() - 1;
12433   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12434   // Scale the branchprobability for DefaultMBB if the peel occurs and
12435   // DefaultMBB is not replaced.
12436   if (PeeledCaseProb != BranchProbability::getZero() &&
12437       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12438     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12439   WorkList.push_back(
12440       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12441 
12442   while (!WorkList.empty()) {
12443     SwitchWorkListItem W = WorkList.pop_back_val();
12444     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12445 
12446     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12447         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12448       // For optimized builds, lower large range as a balanced binary tree.
12449       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12450       continue;
12451     }
12452 
12453     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12454   }
12455 }
12456 
12457 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12459   auto DL = getCurSDLoc();
12460   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12461   setValue(&I, DAG.getStepVector(DL, ResultVT));
12462 }
12463 
12464 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12466   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12467 
12468   SDLoc DL = getCurSDLoc();
12469   SDValue V = getValue(I.getOperand(0));
12470   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12471 
12472   if (VT.isScalableVector()) {
12473     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12474     return;
12475   }
12476 
12477   // Use VECTOR_SHUFFLE for the fixed-length vector
12478   // to maintain existing behavior.
12479   SmallVector<int, 8> Mask;
12480   unsigned NumElts = VT.getVectorMinNumElements();
12481   for (unsigned i = 0; i != NumElts; ++i)
12482     Mask.push_back(NumElts - 1 - i);
12483 
12484   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12485 }
12486 
12487 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12488   auto DL = getCurSDLoc();
12489   SDValue InVec = getValue(I.getOperand(0));
12490   EVT OutVT =
12491       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12492 
12493   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12494 
12495   // ISD Node needs the input vectors split into two equal parts
12496   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12497                            DAG.getVectorIdxConstant(0, DL));
12498   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12499                            DAG.getVectorIdxConstant(OutNumElts, DL));
12500 
12501   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12502   // legalisation and combines.
12503   if (OutVT.isFixedLengthVector()) {
12504     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12505                                         createStrideMask(0, 2, OutNumElts));
12506     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12507                                        createStrideMask(1, 2, OutNumElts));
12508     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12509     setValue(&I, Res);
12510     return;
12511   }
12512 
12513   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12514                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12515   setValue(&I, Res);
12516 }
12517 
12518 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12519   auto DL = getCurSDLoc();
12520   EVT InVT = getValue(I.getOperand(0)).getValueType();
12521   SDValue InVec0 = getValue(I.getOperand(0));
12522   SDValue InVec1 = getValue(I.getOperand(1));
12523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12524   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12525 
12526   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12527   // legalisation and combines.
12528   if (OutVT.isFixedLengthVector()) {
12529     unsigned NumElts = InVT.getVectorMinNumElements();
12530     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12531     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12532                                       createInterleaveMask(NumElts, 2)));
12533     return;
12534   }
12535 
12536   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12537                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12538   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12539                     Res.getValue(1));
12540   setValue(&I, Res);
12541 }
12542 
12543 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12544   SmallVector<EVT, 4> ValueVTs;
12545   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12546                   ValueVTs);
12547   unsigned NumValues = ValueVTs.size();
12548   if (NumValues == 0) return;
12549 
12550   SmallVector<SDValue, 4> Values(NumValues);
12551   SDValue Op = getValue(I.getOperand(0));
12552 
12553   for (unsigned i = 0; i != NumValues; ++i)
12554     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12555                             SDValue(Op.getNode(), Op.getResNo() + i));
12556 
12557   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12558                            DAG.getVTList(ValueVTs), Values));
12559 }
12560 
12561 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12562   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12563   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12564 
12565   SDLoc DL = getCurSDLoc();
12566   SDValue V1 = getValue(I.getOperand(0));
12567   SDValue V2 = getValue(I.getOperand(1));
12568   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12569 
12570   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12571   if (VT.isScalableVector()) {
12572     setValue(
12573         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12574                         DAG.getSignedConstant(
12575                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12576     return;
12577   }
12578 
12579   unsigned NumElts = VT.getVectorNumElements();
12580 
12581   uint64_t Idx = (NumElts + Imm) % NumElts;
12582 
12583   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12584   SmallVector<int, 8> Mask;
12585   for (unsigned i = 0; i < NumElts; ++i)
12586     Mask.push_back(Idx + i);
12587   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12588 }
12589 
12590 // Consider the following MIR after SelectionDAG, which produces output in
12591 // phyregs in the first case or virtregs in the second case.
12592 //
12593 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12594 // %5:gr32 = COPY $ebx
12595 // %6:gr32 = COPY $edx
12596 // %1:gr32 = COPY %6:gr32
12597 // %0:gr32 = COPY %5:gr32
12598 //
12599 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12600 // %1:gr32 = COPY %6:gr32
12601 // %0:gr32 = COPY %5:gr32
12602 //
12603 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12604 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12605 //
12606 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12607 // to a single virtreg (such as %0). The remaining outputs monotonically
12608 // increase in virtreg number from there. If a callbr has no outputs, then it
12609 // should not have a corresponding callbr landingpad; in fact, the callbr
12610 // landingpad would not even be able to refer to such a callbr.
12611 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12612   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12613   // There is definitely at least one copy.
12614   assert(MI->getOpcode() == TargetOpcode::COPY &&
12615          "start of copy chain MUST be COPY");
12616   Reg = MI->getOperand(1).getReg();
12617   MI = MRI.def_begin(Reg)->getParent();
12618   // There may be an optional second copy.
12619   if (MI->getOpcode() == TargetOpcode::COPY) {
12620     assert(Reg.isVirtual() && "expected COPY of virtual register");
12621     Reg = MI->getOperand(1).getReg();
12622     assert(Reg.isPhysical() && "expected COPY of physical register");
12623     MI = MRI.def_begin(Reg)->getParent();
12624   }
12625   // The start of the chain must be an INLINEASM_BR.
12626   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12627          "end of copy chain MUST be INLINEASM_BR");
12628   return Reg;
12629 }
12630 
12631 // We must do this walk rather than the simpler
12632 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12633 // otherwise we will end up with copies of virtregs only valid along direct
12634 // edges.
12635 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12636   SmallVector<EVT, 8> ResultVTs;
12637   SmallVector<SDValue, 8> ResultValues;
12638   const auto *CBR =
12639       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12640 
12641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12642   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12643   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12644 
12645   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12646   SDValue Chain = DAG.getRoot();
12647 
12648   // Re-parse the asm constraints string.
12649   TargetLowering::AsmOperandInfoVector TargetConstraints =
12650       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12651   for (auto &T : TargetConstraints) {
12652     SDISelAsmOperandInfo OpInfo(T);
12653     if (OpInfo.Type != InlineAsm::isOutput)
12654       continue;
12655 
12656     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12657     // individual constraint.
12658     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12659 
12660     switch (OpInfo.ConstraintType) {
12661     case TargetLowering::C_Register:
12662     case TargetLowering::C_RegisterClass: {
12663       // Fill in OpInfo.AssignedRegs.Regs.
12664       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12665 
12666       // getRegistersForValue may produce 1 to many registers based on whether
12667       // the OpInfo.ConstraintVT is legal on the target or not.
12668       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12669         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12670         if (Register::isPhysicalRegister(OriginalDef))
12671           FuncInfo.MBB->addLiveIn(OriginalDef);
12672         // Update the assigned registers to use the original defs.
12673         Reg = OriginalDef;
12674       }
12675 
12676       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12677           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12678       ResultValues.push_back(V);
12679       ResultVTs.push_back(OpInfo.ConstraintVT);
12680       break;
12681     }
12682     case TargetLowering::C_Other: {
12683       SDValue Flag;
12684       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12685                                                   OpInfo, DAG);
12686       ++InitialDef;
12687       ResultValues.push_back(V);
12688       ResultVTs.push_back(OpInfo.ConstraintVT);
12689       break;
12690     }
12691     default:
12692       break;
12693     }
12694   }
12695   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12696                           DAG.getVTList(ResultVTs), ResultValues);
12697   setValue(&I, V);
12698 }
12699