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