xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 1d1de7467c32d52926ca56b9167a2c65c451ecfa)
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/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/BranchProbabilityInfo.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/EHPersonalities.h"
29 #include "llvm/Analysis/Loads.h"
30 #include "llvm/Analysis/MemoryLocation.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
35 #include "llvm/CodeGen/CodeGenCommonISel.h"
36 #include "llvm/CodeGen/FunctionLoweringInfo.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GetElementPtrTypeIterator.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/InstrTypes.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/IntrinsicsAArch64.h"
79 #include "llvm/IR/IntrinsicsWebAssembly.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Metadata.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/Operator.h"
84 #include "llvm/IR/PatternMatch.h"
85 #include "llvm/IR/Statepoint.h"
86 #include "llvm/IR/Type.h"
87 #include "llvm/IR/User.h"
88 #include "llvm/IR/Value.h"
89 #include "llvm/MC/MCContext.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/Casting.h"
92 #include "llvm/Support/CommandLine.h"
93 #include "llvm/Support/Compiler.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/MathExtras.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Target/TargetIntrinsicInfo.h"
98 #include "llvm/Target/TargetMachine.h"
99 #include "llvm/Target/TargetOptions.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include <cstddef>
102 #include <iterator>
103 #include <limits>
104 #include <optional>
105 #include <tuple>
106 
107 using namespace llvm;
108 using namespace PatternMatch;
109 using namespace SwitchCG;
110 
111 #define DEBUG_TYPE "isel"
112 
113 /// LimitFloatPrecision - Generate low-precision inline sequences for
114 /// some float libcalls (6, 8 or 12 bits).
115 static unsigned LimitFloatPrecision;
116 
117 static cl::opt<bool>
118     InsertAssertAlign("insert-assert-align", cl::init(true),
119                       cl::desc("Insert the experimental `assertalign` node."),
120                       cl::ReallyHidden);
121 
122 static cl::opt<unsigned, true>
123     LimitFPPrecision("limit-float-precision",
124                      cl::desc("Generate low-precision inline sequences "
125                               "for some float libcalls"),
126                      cl::location(LimitFloatPrecision), cl::Hidden,
127                      cl::init(0));
128 
129 static cl::opt<unsigned> SwitchPeelThreshold(
130     "switch-peel-threshold", cl::Hidden, cl::init(66),
131     cl::desc("Set the case probability threshold for peeling the case from a "
132              "switch statement. A value greater than 100 will void this "
133              "optimization"));
134 
135 // Limit the width of DAG chains. This is important in general to prevent
136 // DAG-based analysis from blowing up. For example, alias analysis and
137 // load clustering may not complete in reasonable time. It is difficult to
138 // recognize and avoid this situation within each individual analysis, and
139 // future analyses are likely to have the same behavior. Limiting DAG width is
140 // the safe approach and will be especially important with global DAGs.
141 //
142 // MaxParallelChains default is arbitrarily high to avoid affecting
143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
144 // sequence over this should have been converted to llvm.memcpy by the
145 // frontend. It is easy to induce this behavior with .ll code such as:
146 // %buffer = alloca [4096 x i8]
147 // %data = load [4096 x i8]* %argPtr
148 // store [4096 x i8] %data, [4096 x i8]* %buffer
149 static const unsigned MaxParallelChains = 64;
150 
151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
152                                       const SDValue *Parts, unsigned NumParts,
153                                       MVT PartVT, EVT ValueVT, const Value *V,
154                                       std::optional<CallingConv::ID> CC);
155 
156 /// getCopyFromParts - Create a value that contains the specified legal parts
157 /// combined into the value they represent.  If the parts combine to a type
158 /// larger than ValueVT then AssertOp can be used to specify whether the extra
159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
160 /// (ISD::AssertSext).
161 static SDValue
162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
163                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
164                  std::optional<CallingConv::ID> CC = std::nullopt,
165                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
166   // Let the target assemble the parts if it wants to
167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
168   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
169                                                    PartVT, ValueVT, CC))
170     return Val;
171 
172   if (ValueVT.isVector())
173     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
174                                   CC);
175 
176   assert(NumParts > 0 && "No parts to assemble!");
177   SDValue Val = Parts[0];
178 
179   if (NumParts > 1) {
180     // Assemble the value from multiple parts.
181     if (ValueVT.isInteger()) {
182       unsigned PartBits = PartVT.getSizeInBits();
183       unsigned ValueBits = ValueVT.getSizeInBits();
184 
185       // Assemble the power of 2 part.
186       unsigned RoundParts =
187           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
188       unsigned RoundBits = PartBits * RoundParts;
189       EVT RoundVT = RoundBits == ValueBits ?
190         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
191       SDValue Lo, Hi;
192 
193       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
194 
195       if (RoundParts > 2) {
196         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
197                               PartVT, HalfVT, V);
198         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
199                               RoundParts / 2, PartVT, HalfVT, V);
200       } else {
201         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
202         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
203       }
204 
205       if (DAG.getDataLayout().isBigEndian())
206         std::swap(Lo, Hi);
207 
208       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
209 
210       if (RoundParts < NumParts) {
211         // Assemble the trailing non-power-of-2 part.
212         unsigned OddParts = NumParts - RoundParts;
213         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
214         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
215                               OddVT, V, CC);
216 
217         // Combine the round and odd parts.
218         Lo = Val;
219         if (DAG.getDataLayout().isBigEndian())
220           std::swap(Lo, Hi);
221         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
222         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
223         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
224                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
225                                          TLI.getShiftAmountTy(
226                                              TotalVT, DAG.getDataLayout())));
227         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
228         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
229       }
230     } else if (PartVT.isFloatingPoint()) {
231       // FP split into multiple FP parts (for ppcf128)
232       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
233              "Unexpected split");
234       SDValue Lo, Hi;
235       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
236       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
237       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
238         std::swap(Lo, Hi);
239       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
240     } else {
241       // FP split into integer parts (soft fp)
242       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
243              !PartVT.isVector() && "Unexpected split");
244       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
245       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
246     }
247   }
248 
249   // There is now one part, held in Val.  Correct it to match ValueVT.
250   // PartEVT is the type of the register class that holds the value.
251   // ValueVT is the type of the inline asm operation.
252   EVT PartEVT = Val.getValueType();
253 
254   if (PartEVT == ValueVT)
255     return Val;
256 
257   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
258       ValueVT.bitsLT(PartEVT)) {
259     // For an FP value in an integer part, we need to truncate to the right
260     // width first.
261     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
262     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
263   }
264 
265   // Handle types that have the same size.
266   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
267     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
268 
269   // Handle types with different sizes.
270   if (PartEVT.isInteger() && ValueVT.isInteger()) {
271     if (ValueVT.bitsLT(PartEVT)) {
272       // For a truncate, see if we have any information to
273       // indicate whether the truncated bits will always be
274       // zero or sign-extension.
275       if (AssertOp)
276         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
277                           DAG.getValueType(ValueVT));
278       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
279     }
280     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
281   }
282 
283   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
284     // FP_ROUND's are always exact here.
285     if (ValueVT.bitsLT(Val.getValueType()))
286       return DAG.getNode(
287           ISD::FP_ROUND, DL, ValueVT, Val,
288           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
289 
290     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
291   }
292 
293   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
294   // then truncating.
295   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
296       ValueVT.bitsLT(PartEVT)) {
297     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
298     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
299   }
300 
301   report_fatal_error("Unknown mismatch in getCopyFromParts!");
302 }
303 
304 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
305                                               const Twine &ErrMsg) {
306   const Instruction *I = dyn_cast_or_null<Instruction>(V);
307   if (!V)
308     return Ctx.emitError(ErrMsg);
309 
310   const char *AsmError = ", possible invalid constraint for vector type";
311   if (const CallInst *CI = dyn_cast<CallInst>(I))
312     if (CI->isInlineAsm())
313       return Ctx.emitError(I, ErrMsg + AsmError);
314 
315   return Ctx.emitError(I, ErrMsg);
316 }
317 
318 /// getCopyFromPartsVector - Create a value that contains the specified legal
319 /// parts combined into the value they represent.  If the parts combine to a
320 /// type larger than ValueVT then AssertOp can be used to specify whether the
321 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
322 /// ValueVT (ISD::AssertSext).
323 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
324                                       const SDValue *Parts, unsigned NumParts,
325                                       MVT PartVT, EVT ValueVT, const Value *V,
326                                       std::optional<CallingConv::ID> CallConv) {
327   assert(ValueVT.isVector() && "Not a vector value");
328   assert(NumParts > 0 && "No parts to assemble!");
329   const bool IsABIRegCopy = CallConv.has_value();
330 
331   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
332   SDValue Val = Parts[0];
333 
334   // Handle a multi-element vector.
335   if (NumParts > 1) {
336     EVT IntermediateVT;
337     MVT RegisterVT;
338     unsigned NumIntermediates;
339     unsigned NumRegs;
340 
341     if (IsABIRegCopy) {
342       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
343           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
344           NumIntermediates, RegisterVT);
345     } else {
346       NumRegs =
347           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
348                                      NumIntermediates, RegisterVT);
349     }
350 
351     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
352     NumParts = NumRegs; // Silence a compiler warning.
353     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
354     assert(RegisterVT.getSizeInBits() ==
355            Parts[0].getSimpleValueType().getSizeInBits() &&
356            "Part type sizes don't match!");
357 
358     // Assemble the parts into intermediate operands.
359     SmallVector<SDValue, 8> Ops(NumIntermediates);
360     if (NumIntermediates == NumParts) {
361       // If the register was not expanded, truncate or copy the value,
362       // as appropriate.
363       for (unsigned i = 0; i != NumParts; ++i)
364         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
365                                   PartVT, IntermediateVT, V, CallConv);
366     } else if (NumParts > 0) {
367       // If the intermediate type was expanded, build the intermediate
368       // operands from the parts.
369       assert(NumParts % NumIntermediates == 0 &&
370              "Must expand into a divisible number of parts!");
371       unsigned Factor = NumParts / NumIntermediates;
372       for (unsigned i = 0; i != NumIntermediates; ++i)
373         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
374                                   PartVT, IntermediateVT, V, CallConv);
375     }
376 
377     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
378     // intermediate operands.
379     EVT BuiltVectorTy =
380         IntermediateVT.isVector()
381             ? EVT::getVectorVT(
382                   *DAG.getContext(), IntermediateVT.getScalarType(),
383                   IntermediateVT.getVectorElementCount() * NumParts)
384             : EVT::getVectorVT(*DAG.getContext(),
385                                IntermediateVT.getScalarType(),
386                                NumIntermediates);
387     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
388                                                 : ISD::BUILD_VECTOR,
389                       DL, BuiltVectorTy, Ops);
390   }
391 
392   // There is now one part, held in Val.  Correct it to match ValueVT.
393   EVT PartEVT = Val.getValueType();
394 
395   if (PartEVT == ValueVT)
396     return Val;
397 
398   if (PartEVT.isVector()) {
399     // Vector/Vector bitcast.
400     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
401       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
402 
403     // If the parts vector has more elements than the value vector, then we
404     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
405     // Extract the elements we want.
406     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       PartEVT =
413           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
414                            ValueVT.getVectorElementCount());
415       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
416                         DAG.getVectorIdxConstant(0, DL));
417       if (PartEVT == ValueVT)
418         return Val;
419       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
420         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421     }
422 
423     // Promoted vector extract
424     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
440        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
441        // Drop the extra bits.
442        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
443        return DAG.getBitcast(ValueVT, Val);
444      }
445 
446      diagnosePossiblyInvalidConstraint(
447          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
448      return DAG.getUNDEF(ValueVT);
449   }
450 
451   // Handle cases such as i8 -> <1 x i1>
452   EVT ValueSVT = ValueVT.getVectorElementType();
453   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
454     unsigned ValueSize = ValueSVT.getSizeInBits();
455     if (ValueSize == PartEVT.getSizeInBits()) {
456       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
457     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
458       // It's possible a scalar floating point type gets softened to integer and
459       // then promoted to a larger integer. If PartEVT is the larger integer
460       // we need to truncate it and then bitcast to the FP type.
461       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
462       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
463       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
464       Val = DAG.getBitcast(ValueSVT, Val);
465     } else {
466       Val = ValueVT.isFloatingPoint()
467                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
468                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
469     }
470   }
471 
472   return DAG.getBuildVector(ValueVT, DL, Val);
473 }
474 
475 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
476                                  SDValue Val, SDValue *Parts, unsigned NumParts,
477                                  MVT PartVT, const Value *V,
478                                  std::optional<CallingConv::ID> CallConv);
479 
480 /// getCopyToParts - Create a series of nodes that contain the specified value
481 /// split into legal parts.  If the parts contain more bits than Val, then, for
482 /// integers, ExtendKind can be used to specify how to generate the extra bits.
483 static void
484 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
485                unsigned NumParts, MVT PartVT, const Value *V,
486                std::optional<CallingConv::ID> CallConv = std::nullopt,
487                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
488   // Let the target split the parts if it wants to
489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
490   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
491                                       CallConv))
492     return;
493   EVT ValueVT = Val.getValueType();
494 
495   // Handle the vector case separately.
496   if (ValueVT.isVector())
497     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
498                                 CallConv);
499 
500   unsigned PartBits = PartVT.getSizeInBits();
501   unsigned OrigNumParts = NumParts;
502   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
503          "Copying to an illegal type!");
504 
505   if (NumParts == 0)
506     return;
507 
508   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
509   EVT PartEVT = PartVT;
510   if (PartEVT == ValueVT) {
511     assert(NumParts == 1 && "No-op copy with multiple parts!");
512     Parts[0] = Val;
513     return;
514   }
515 
516   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
517     // If the parts cover more bits than the value has, promote the value.
518     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
519       assert(NumParts == 1 && "Do not know what to promote to!");
520       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
521     } else {
522       if (ValueVT.isFloatingPoint()) {
523         // FP values need to be bitcast, then extended if they are being put
524         // into a larger container.
525         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
526         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
527       }
528       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529              ValueVT.isInteger() &&
530              "Unknown mismatch!");
531       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
533       if (PartVT == MVT::x86mmx)
534         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535     }
536   } else if (PartBits == ValueVT.getSizeInBits()) {
537     // Different types of the same size.
538     assert(NumParts == 1 && PartEVT != ValueVT);
539     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541     // If the parts cover less bits than value has, truncate the value.
542     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543            ValueVT.isInteger() &&
544            "Unknown mismatch!");
545     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
547     if (PartVT == MVT::x86mmx)
548       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   }
550 
551   // The value may have changed - recompute ValueVT.
552   ValueVT = Val.getValueType();
553   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
554          "Failed to tile the value with PartVT!");
555 
556   if (NumParts == 1) {
557     if (PartEVT != ValueVT) {
558       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
559                                         "scalar-to-vector conversion failed");
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561     }
562 
563     Parts[0] = Val;
564     return;
565   }
566 
567   // Expand the value into multiple parts.
568   if (NumParts & (NumParts - 1)) {
569     // The number of parts is not a power of 2.  Split off and copy the tail.
570     assert(PartVT.isInteger() && ValueVT.isInteger() &&
571            "Do not know what to expand to!");
572     unsigned RoundParts = 1 << Log2_32(NumParts);
573     unsigned RoundBits = RoundParts * PartBits;
574     unsigned OddParts = NumParts - RoundParts;
575     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
576       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
577 
578     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
579                    CallConv);
580 
581     if (DAG.getDataLayout().isBigEndian())
582       // The odd parts were reversed by getCopyToParts - unreverse them.
583       std::reverse(Parts + RoundParts, Parts + NumParts);
584 
585     NumParts = RoundParts;
586     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
587     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
588   }
589 
590   // The number of parts is a power of 2.  Repeatedly bisect the value using
591   // EXTRACT_ELEMENT.
592   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
593                          EVT::getIntegerVT(*DAG.getContext(),
594                                            ValueVT.getSizeInBits()),
595                          Val);
596 
597   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
598     for (unsigned i = 0; i < NumParts; i += StepSize) {
599       unsigned ThisBits = StepSize * PartBits / 2;
600       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
601       SDValue &Part0 = Parts[i];
602       SDValue &Part1 = Parts[i+StepSize/2];
603 
604       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
606       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
607                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
608 
609       if (ThisBits == PartBits && ThisVT != PartVT) {
610         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
611         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
612       }
613     }
614   }
615 
616   if (DAG.getDataLayout().isBigEndian())
617     std::reverse(Parts, Parts + OrigNumParts);
618 }
619 
620 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
621                                      const SDLoc &DL, EVT PartVT) {
622   if (!PartVT.isVector())
623     return SDValue();
624 
625   EVT ValueVT = Val.getValueType();
626   ElementCount PartNumElts = PartVT.getVectorElementCount();
627   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
628 
629   // We only support widening vectors with equivalent element types and
630   // fixed/scalable properties. If a target needs to widen a fixed-length type
631   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
632   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
633       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
634       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
635     return SDValue();
636 
637   // Widening a scalable vector to another scalable vector is done by inserting
638   // the vector into a larger undef one.
639   if (PartNumElts.isScalable())
640     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
641                        Val, DAG.getVectorIdxConstant(0, DL));
642 
643   EVT ElementVT = PartVT.getVectorElementType();
644   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
645   // undef elements.
646   SmallVector<SDValue, 16> Ops;
647   DAG.ExtractVectorElements(Val, Ops);
648   SDValue EltUndef = DAG.getUNDEF(ElementVT);
649   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
650 
651   // FIXME: Use CONCAT for 2x -> 4x.
652   return DAG.getBuildVector(PartVT, DL, Ops);
653 }
654 
655 /// getCopyToPartsVector - Create a series of nodes that contain the specified
656 /// value split into legal parts.
657 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
658                                  SDValue Val, SDValue *Parts, unsigned NumParts,
659                                  MVT PartVT, const Value *V,
660                                  std::optional<CallingConv::ID> CallConv) {
661   EVT ValueVT = Val.getValueType();
662   assert(ValueVT.isVector() && "Not a vector");
663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
664   const bool IsABIRegCopy = CallConv.has_value();
665 
666   if (NumParts == 1) {
667     EVT PartEVT = PartVT;
668     if (PartEVT == ValueVT) {
669       // Nothing to do.
670     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
671       // Bitconvert vector->vector case.
672       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
673     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
674       Val = Widened;
675     } else if (PartVT.isVector() &&
676                PartEVT.getVectorElementType().bitsGE(
677                    ValueVT.getVectorElementType()) &&
678                PartEVT.getVectorElementCount() ==
679                    ValueVT.getVectorElementCount()) {
680 
681       // Promoted vector extract
682       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683     } else if (PartEVT.isVector() &&
684                PartEVT.getVectorElementType() !=
685                    ValueVT.getVectorElementType() &&
686                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
687                    TargetLowering::TypeWidenVector) {
688       // Combination of widening and promotion.
689       EVT WidenVT =
690           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
691                            PartVT.getVectorElementCount());
692       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
693       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
694     } else {
695       // Don't extract an integer from a float vector. This can happen if the
696       // FP type gets softened to integer and then promoted. The promotion
697       // prevents it from being picked up by the earlier bitcast case.
698       if (ValueVT.getVectorElementCount().isScalar() &&
699           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
700         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
701                           DAG.getVectorIdxConstant(0, DL));
702       } else {
703         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
704         assert(PartVT.getFixedSizeInBits() > ValueSize &&
705                "lossy conversion of vector to scalar type");
706         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
707         Val = DAG.getBitcast(IntermediateType, Val);
708         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
709       }
710     }
711 
712     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
713     Parts[0] = Val;
714     return;
715   }
716 
717   // Handle a multi-element vector.
718   EVT IntermediateVT;
719   MVT RegisterVT;
720   unsigned NumIntermediates;
721   unsigned NumRegs;
722   if (IsABIRegCopy) {
723     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
724         *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT,
725         NumIntermediates, RegisterVT);
726   } else {
727     NumRegs =
728         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
729                                    NumIntermediates, RegisterVT);
730   }
731 
732   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
733   NumParts = NumRegs; // Silence a compiler warning.
734   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
735 
736   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
737          "Mixing scalable and fixed vectors when copying in parts");
738 
739   std::optional<ElementCount> DestEltCnt;
740 
741   if (IntermediateVT.isVector())
742     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
743   else
744     DestEltCnt = ElementCount::getFixed(NumIntermediates);
745 
746   EVT BuiltVectorTy = EVT::getVectorVT(
747       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
748 
749   if (ValueVT == BuiltVectorTy) {
750     // Nothing to do.
751   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
752     // Bitconvert vector->vector case.
753     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
754   } else {
755     if (BuiltVectorTy.getVectorElementType().bitsGT(
756             ValueVT.getVectorElementType())) {
757       // Integer promotion.
758       ValueVT = EVT::getVectorVT(*DAG.getContext(),
759                                  BuiltVectorTy.getVectorElementType(),
760                                  ValueVT.getVectorElementCount());
761       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
762     }
763 
764     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
765       Val = Widened;
766     }
767   }
768 
769   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
770 
771   // Split the vector into intermediate operands.
772   SmallVector<SDValue, 8> Ops(NumIntermediates);
773   for (unsigned i = 0; i != NumIntermediates; ++i) {
774     if (IntermediateVT.isVector()) {
775       // This does something sensible for scalable vectors - see the
776       // definition of EXTRACT_SUBVECTOR for further details.
777       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
778       Ops[i] =
779           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
780                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
781     } else {
782       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
783                            DAG.getVectorIdxConstant(i, DL));
784     }
785   }
786 
787   // Split the intermediate operands into legal parts.
788   if (NumParts == NumIntermediates) {
789     // If the register was not expanded, promote or copy the value,
790     // as appropriate.
791     for (unsigned i = 0; i != NumParts; ++i)
792       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
793   } else if (NumParts > 0) {
794     // If the intermediate type was expanded, split each the value into
795     // legal parts.
796     assert(NumIntermediates != 0 && "division by zero");
797     assert(NumParts % NumIntermediates == 0 &&
798            "Must expand into a divisible number of parts!");
799     unsigned Factor = NumParts / NumIntermediates;
800     for (unsigned i = 0; i != NumIntermediates; ++i)
801       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
802                      CallConv);
803   }
804 }
805 
806 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
807                            EVT valuevt, std::optional<CallingConv::ID> CC)
808     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
809       RegCount(1, regs.size()), CallConv(CC) {}
810 
811 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
812                            const DataLayout &DL, unsigned Reg, Type *Ty,
813                            std::optional<CallingConv::ID> CC) {
814   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
815 
816   CallConv = CC;
817 
818   for (EVT ValueVT : ValueVTs) {
819     unsigned NumRegs =
820         isABIMangled()
821             ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT)
822             : TLI.getNumRegisters(Context, ValueVT);
823     MVT RegisterVT =
824         isABIMangled()
825             ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT)
826             : TLI.getRegisterType(Context, ValueVT);
827     for (unsigned i = 0; i != NumRegs; ++i)
828       Regs.push_back(Reg + i);
829     RegVTs.push_back(RegisterVT);
830     RegCount.push_back(NumRegs);
831     Reg += NumRegs;
832   }
833 }
834 
835 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
836                                       FunctionLoweringInfo &FuncInfo,
837                                       const SDLoc &dl, SDValue &Chain,
838                                       SDValue *Flag, const Value *V) const {
839   // A Value with type {} or [0 x %t] needs no registers.
840   if (ValueVTs.empty())
841     return SDValue();
842 
843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
844 
845   // Assemble the legal parts into the final values.
846   SmallVector<SDValue, 4> Values(ValueVTs.size());
847   SmallVector<SDValue, 8> Parts;
848   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
849     // Copy the legal parts from the registers.
850     EVT ValueVT = ValueVTs[Value];
851     unsigned NumRegs = RegCount[Value];
852     MVT RegisterVT =
853         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
854                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
855                        : RegVTs[Value];
856 
857     Parts.resize(NumRegs);
858     for (unsigned i = 0; i != NumRegs; ++i) {
859       SDValue P;
860       if (!Flag) {
861         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
862       } else {
863         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
864         *Flag = P.getValue(2);
865       }
866 
867       Chain = P.getValue(1);
868       Parts[i] = P;
869 
870       // If the source register was virtual and if we know something about it,
871       // add an assert node.
872       if (!Register::isVirtualRegister(Regs[Part + i]) ||
873           !RegisterVT.isInteger())
874         continue;
875 
876       const FunctionLoweringInfo::LiveOutInfo *LOI =
877         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
878       if (!LOI)
879         continue;
880 
881       unsigned RegSize = RegisterVT.getScalarSizeInBits();
882       unsigned NumSignBits = LOI->NumSignBits;
883       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
884 
885       if (NumZeroBits == RegSize) {
886         // The current value is a zero.
887         // Explicitly express that as it would be easier for
888         // optimizations to kick in.
889         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
890         continue;
891       }
892 
893       // FIXME: We capture more information than the dag can represent.  For
894       // now, just use the tightest assertzext/assertsext possible.
895       bool isSExt;
896       EVT FromVT(MVT::Other);
897       if (NumZeroBits) {
898         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
899         isSExt = false;
900       } else if (NumSignBits > 1) {
901         FromVT =
902             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
903         isSExt = true;
904       } else {
905         continue;
906       }
907       // Add an assertion node.
908       assert(FromVT != MVT::Other);
909       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
910                              RegisterVT, P, DAG.getValueType(FromVT));
911     }
912 
913     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
914                                      RegisterVT, ValueVT, V, CallConv);
915     Part += NumRegs;
916     Parts.clear();
917   }
918 
919   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
920 }
921 
922 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
923                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
924                                  const Value *V,
925                                  ISD::NodeType PreferredExtendType) const {
926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
927   ISD::NodeType ExtendKind = PreferredExtendType;
928 
929   // Get the list of the values's legal parts.
930   unsigned NumRegs = Regs.size();
931   SmallVector<SDValue, 8> Parts(NumRegs);
932   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
933     unsigned NumParts = RegCount[Value];
934 
935     MVT RegisterVT =
936         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
937                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
938                        : RegVTs[Value];
939 
940     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
941       ExtendKind = ISD::ZERO_EXTEND;
942 
943     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
944                    NumParts, RegisterVT, V, CallConv, ExtendKind);
945     Part += NumParts;
946   }
947 
948   // Copy the parts into the registers.
949   SmallVector<SDValue, 8> Chains(NumRegs);
950   for (unsigned i = 0; i != NumRegs; ++i) {
951     SDValue Part;
952     if (!Flag) {
953       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
954     } else {
955       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
956       *Flag = Part.getValue(1);
957     }
958 
959     Chains[i] = Part.getValue(0);
960   }
961 
962   if (NumRegs == 1 || Flag)
963     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
964     // flagged to it. That is the CopyToReg nodes and the user are considered
965     // a single scheduling unit. If we create a TokenFactor and return it as
966     // chain, then the TokenFactor is both a predecessor (operand) of the
967     // user as well as a successor (the TF operands are flagged to the user).
968     // c1, f1 = CopyToReg
969     // c2, f2 = CopyToReg
970     // c3     = TokenFactor c1, c2
971     // ...
972     //        = op c3, ..., f2
973     Chain = Chains[NumRegs-1];
974   else
975     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
976 }
977 
978 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
979                                         unsigned MatchingIdx, const SDLoc &dl,
980                                         SelectionDAG &DAG,
981                                         std::vector<SDValue> &Ops) const {
982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 
984   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
985   if (HasMatching)
986     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
987   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
988     // Put the register class of the virtual registers in the flag word.  That
989     // way, later passes can recompute register class constraints for inline
990     // assembly as well as normal instructions.
991     // Don't do this for tied operands that can use the regclass information
992     // from the def.
993     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
994     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
995     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
996   }
997 
998   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
999   Ops.push_back(Res);
1000 
1001   if (Code == InlineAsm::Kind_Clobber) {
1002     // Clobbers should always have a 1:1 mapping with registers, and may
1003     // reference registers that have illegal (e.g. vector) types. Hence, we
1004     // shouldn't try to apply any sort of splitting logic to them.
1005     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1006            "No 1:1 mapping from clobbers to regs?");
1007     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1008     (void)SP;
1009     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1010       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1011       assert(
1012           (Regs[I] != SP ||
1013            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1014           "If we clobbered the stack pointer, MFI should know about it.");
1015     }
1016     return;
1017   }
1018 
1019   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1020     MVT RegisterVT = RegVTs[Value];
1021     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1022                                            RegisterVT);
1023     for (unsigned i = 0; i != NumRegs; ++i) {
1024       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1025       unsigned TheReg = Regs[Reg++];
1026       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1027     }
1028   }
1029 }
1030 
1031 SmallVector<std::pair<unsigned, TypeSize>, 4>
1032 RegsForValue::getRegsAndSizes() const {
1033   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1034   unsigned I = 0;
1035   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1036     unsigned RegCount = std::get<0>(CountAndVT);
1037     MVT RegisterVT = std::get<1>(CountAndVT);
1038     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1039     for (unsigned E = I + RegCount; I != E; ++I)
1040       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1041   }
1042   return OutVec;
1043 }
1044 
1045 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1046                                AssumptionCache *ac,
1047                                const TargetLibraryInfo *li) {
1048   AA = aa;
1049   AC = ac;
1050   GFI = gfi;
1051   LibInfo = li;
1052   Context = DAG.getContext();
1053   LPadToCallSiteMap.clear();
1054   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1055 }
1056 
1057 void SelectionDAGBuilder::clear() {
1058   NodeMap.clear();
1059   UnusedArgNodeMap.clear();
1060   PendingLoads.clear();
1061   PendingExports.clear();
1062   PendingConstrainedFP.clear();
1063   PendingConstrainedFPStrict.clear();
1064   CurInst = nullptr;
1065   HasTailCall = false;
1066   SDNodeOrder = LowestSDNodeOrder;
1067   StatepointLowering.clear();
1068 }
1069 
1070 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1071   DanglingDebugInfoMap.clear();
1072 }
1073 
1074 // Update DAG root to include dependencies on Pending chains.
1075 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1076   SDValue Root = DAG.getRoot();
1077 
1078   if (Pending.empty())
1079     return Root;
1080 
1081   // Add current root to PendingChains, unless we already indirectly
1082   // depend on it.
1083   if (Root.getOpcode() != ISD::EntryToken) {
1084     unsigned i = 0, e = Pending.size();
1085     for (; i != e; ++i) {
1086       assert(Pending[i].getNode()->getNumOperands() > 1);
1087       if (Pending[i].getNode()->getOperand(0) == Root)
1088         break;  // Don't add the root if we already indirectly depend on it.
1089     }
1090 
1091     if (i == e)
1092       Pending.push_back(Root);
1093   }
1094 
1095   if (Pending.size() == 1)
1096     Root = Pending[0];
1097   else
1098     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1099 
1100   DAG.setRoot(Root);
1101   Pending.clear();
1102   return Root;
1103 }
1104 
1105 SDValue SelectionDAGBuilder::getMemoryRoot() {
1106   return updateRoot(PendingLoads);
1107 }
1108 
1109 SDValue SelectionDAGBuilder::getRoot() {
1110   // Chain up all pending constrained intrinsics together with all
1111   // pending loads, by simply appending them to PendingLoads and
1112   // then calling getMemoryRoot().
1113   PendingLoads.reserve(PendingLoads.size() +
1114                        PendingConstrainedFP.size() +
1115                        PendingConstrainedFPStrict.size());
1116   PendingLoads.append(PendingConstrainedFP.begin(),
1117                       PendingConstrainedFP.end());
1118   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1119                       PendingConstrainedFPStrict.end());
1120   PendingConstrainedFP.clear();
1121   PendingConstrainedFPStrict.clear();
1122   return getMemoryRoot();
1123 }
1124 
1125 SDValue SelectionDAGBuilder::getControlRoot() {
1126   // We need to emit pending fpexcept.strict constrained intrinsics,
1127   // so append them to the PendingExports list.
1128   PendingExports.append(PendingConstrainedFPStrict.begin(),
1129                         PendingConstrainedFPStrict.end());
1130   PendingConstrainedFPStrict.clear();
1131   return updateRoot(PendingExports);
1132 }
1133 
1134 void SelectionDAGBuilder::visit(const Instruction &I) {
1135   // Set up outgoing PHI node register values before emitting the terminator.
1136   if (I.isTerminator()) {
1137     HandlePHINodesInSuccessorBlocks(I.getParent());
1138   }
1139 
1140   // Add SDDbgValue nodes for any var locs here. Do so before updating
1141   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1142   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1143     // Add SDDbgValue nodes for any var locs here. Do so before updating
1144     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1145     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1146          It != End; ++It) {
1147       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1148       dropDanglingDebugInfo(Var, It->Expr);
1149       if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder,
1150                             /*IsVariadic=*/false))
1151         addDanglingDebugInfo(It, SDNodeOrder);
1152     }
1153   }
1154 
1155   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1156   if (!isa<DbgInfoIntrinsic>(I))
1157     ++SDNodeOrder;
1158 
1159   CurInst = &I;
1160 
1161   // Set inserted listener only if required.
1162   bool NodeInserted = false;
1163   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1164   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1165   if (PCSectionsMD) {
1166     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1167         DAG, [&](SDNode *) { NodeInserted = true; });
1168   }
1169 
1170   visit(I.getOpcode(), I);
1171 
1172   if (!I.isTerminator() && !HasTailCall &&
1173       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1174     CopyToExportRegsIfNeeded(&I);
1175 
1176   // Handle metadata.
1177   if (PCSectionsMD) {
1178     auto It = NodeMap.find(&I);
1179     if (It != NodeMap.end()) {
1180       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1181     } else if (NodeInserted) {
1182       // This should not happen; if it does, don't let it go unnoticed so we can
1183       // fix it. Relevant visit*() function is probably missing a setValue().
1184       errs() << "warning: loosing !pcsections metadata ["
1185              << I.getModule()->getName() << "]\n";
1186       LLVM_DEBUG(I.dump());
1187       assert(false);
1188     }
1189   }
1190 
1191   CurInst = nullptr;
1192 }
1193 
1194 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1195   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1196 }
1197 
1198 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1199   // Note: this doesn't use InstVisitor, because it has to work with
1200   // ConstantExpr's in addition to instructions.
1201   switch (Opcode) {
1202   default: llvm_unreachable("Unknown instruction type encountered!");
1203     // Build the switch statement using the Instruction.def file.
1204 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1205     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1206 #include "llvm/IR/Instruction.def"
1207   }
1208 }
1209 
1210 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1211                                                unsigned Order) {
1212   DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order);
1213 }
1214 
1215 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1216                                                unsigned Order) {
1217   // We treat variadic dbg_values differently at this stage.
1218   if (DI->hasArgList()) {
1219     // For variadic dbg_values we will now insert an undef.
1220     // FIXME: We can potentially recover these!
1221     SmallVector<SDDbgOperand, 2> Locs;
1222     for (const Value *V : DI->getValues()) {
1223       auto Undef = UndefValue::get(V->getType());
1224       Locs.push_back(SDDbgOperand::fromConst(Undef));
1225     }
1226     SDDbgValue *SDV = DAG.getDbgValueList(
1227         DI->getVariable(), DI->getExpression(), Locs, {},
1228         /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true);
1229     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1230   } else {
1231     // TODO: Dangling debug info will eventually either be resolved or produce
1232     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1233     // between the original dbg.value location and its resolved DBG_VALUE,
1234     // which we should ideally fill with an extra Undef DBG_VALUE.
1235     assert(DI->getNumVariableLocationOps() == 1 &&
1236            "DbgValueInst without an ArgList should have a single location "
1237            "operand.");
1238     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1239   }
1240 }
1241 
1242 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1243                                                 const DIExpression *Expr) {
1244   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1245     DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1246     DIExpression *DanglingExpr = DDI.getExpression();
1247     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1248       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1249                         << "\n");
1250       return true;
1251     }
1252     return false;
1253   };
1254 
1255   for (auto &DDIMI : DanglingDebugInfoMap) {
1256     DanglingDebugInfoVector &DDIV = DDIMI.second;
1257 
1258     // If debug info is to be dropped, run it through final checks to see
1259     // whether it can be salvaged.
1260     for (auto &DDI : DDIV)
1261       if (isMatchingDbgValue(DDI))
1262         salvageUnresolvedDbgValue(DDI);
1263 
1264     erase_if(DDIV, isMatchingDbgValue);
1265   }
1266 }
1267 
1268 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1269 // generate the debug data structures now that we've seen its definition.
1270 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1271                                                    SDValue Val) {
1272   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1273   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1274     return;
1275 
1276   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1277   for (auto &DDI : DDIV) {
1278     DebugLoc DL = DDI.getDebugLoc();
1279     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1280     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1281     DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1282     DIExpression *Expr = DDI.getExpression();
1283     assert(Variable->isValidLocationForIntrinsic(DL) &&
1284            "Expected inlined-at fields to agree");
1285     SDDbgValue *SDV;
1286     if (Val.getNode()) {
1287       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1288       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1289       // we couldn't resolve it directly when examining the DbgValue intrinsic
1290       // in the first place we should not be more successful here). Unless we
1291       // have some test case that prove this to be correct we should avoid
1292       // calling EmitFuncArgumentDbgValue here.
1293       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1294                                     FuncArgumentDbgValueKind::Value, Val)) {
1295         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1296                           << "\n");
1297         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1298         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1299         // inserted after the definition of Val when emitting the instructions
1300         // after ISel. An alternative could be to teach
1301         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1302         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1303                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1304                    << ValSDNodeOrder << "\n");
1305         SDV = getDbgValue(Val, Variable, Expr, DL,
1306                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1307         DAG.AddDbgValue(SDV, false);
1308       } else
1309         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1310                           << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1311     } else {
1312       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1313       auto Undef = UndefValue::get(V->getType());
1314       auto SDV =
1315           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1316       DAG.AddDbgValue(SDV, false);
1317     }
1318   }
1319   DDIV.clear();
1320 }
1321 
1322 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1323   // TODO: For the variadic implementation, instead of only checking the fail
1324   // state of `handleDebugValue`, we need know specifically which values were
1325   // invalid, so that we attempt to salvage only those values when processing
1326   // a DIArgList.
1327   Value *V = DDI.getVariableLocationOp(0);
1328   Value *OrigV = V;
1329   DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1330   DIExpression *Expr = DDI.getExpression();
1331   DebugLoc DL = DDI.getDebugLoc();
1332   unsigned SDOrder = DDI.getSDNodeOrder();
1333 
1334   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1335   // that DW_OP_stack_value is desired.
1336   bool StackValue = true;
1337 
1338   // Can this Value can be encoded without any further work?
1339   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1340     return;
1341 
1342   // Attempt to salvage back through as many instructions as possible. Bail if
1343   // a non-instruction is seen, such as a constant expression or global
1344   // variable. FIXME: Further work could recover those too.
1345   while (isa<Instruction>(V)) {
1346     Instruction &VAsInst = *cast<Instruction>(V);
1347     // Temporary "0", awaiting real implementation.
1348     SmallVector<uint64_t, 16> Ops;
1349     SmallVector<Value *, 4> AdditionalValues;
1350     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1351                              AdditionalValues);
1352     // If we cannot salvage any further, and haven't yet found a suitable debug
1353     // expression, bail out.
1354     if (!V)
1355       break;
1356 
1357     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1358     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1359     // here for variadic dbg_values, remove that condition.
1360     if (!AdditionalValues.empty())
1361       break;
1362 
1363     // New value and expr now represent this debuginfo.
1364     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1365 
1366     // Some kind of simplification occurred: check whether the operand of the
1367     // salvaged debug expression can be encoded in this DAG.
1368     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1369       LLVM_DEBUG(
1370           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1371                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1372       return;
1373     }
1374   }
1375 
1376   // This was the final opportunity to salvage this debug information, and it
1377   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1378   // any earlier variable location.
1379   assert(OrigV && "V shouldn't be null");
1380   auto *Undef = UndefValue::get(OrigV->getType());
1381   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1382   DAG.AddDbgValue(SDV, false);
1383   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << printDDI(DDI)
1384                     << "\n");
1385 }
1386 
1387 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1388                                            DILocalVariable *Var,
1389                                            DIExpression *Expr, DebugLoc DbgLoc,
1390                                            unsigned Order, bool IsVariadic) {
1391   if (Values.empty())
1392     return true;
1393   SmallVector<SDDbgOperand> LocationOps;
1394   SmallVector<SDNode *> Dependencies;
1395   for (const Value *V : Values) {
1396     // Constant value.
1397     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1398         isa<ConstantPointerNull>(V)) {
1399       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1400       continue;
1401     }
1402 
1403     // Look through IntToPtr constants.
1404     if (auto *CE = dyn_cast<ConstantExpr>(V))
1405       if (CE->getOpcode() == Instruction::IntToPtr) {
1406         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1407         continue;
1408       }
1409 
1410     // If the Value is a frame index, we can create a FrameIndex debug value
1411     // without relying on the DAG at all.
1412     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1413       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1414       if (SI != FuncInfo.StaticAllocaMap.end()) {
1415         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1416         continue;
1417       }
1418     }
1419 
1420     // Do not use getValue() in here; we don't want to generate code at
1421     // this point if it hasn't been done yet.
1422     SDValue N = NodeMap[V];
1423     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1424       N = UnusedArgNodeMap[V];
1425     if (N.getNode()) {
1426       // Only emit func arg dbg value for non-variadic dbg.values for now.
1427       if (!IsVariadic &&
1428           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1429                                    FuncArgumentDbgValueKind::Value, N))
1430         return true;
1431       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1432         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1433         // describe stack slot locations.
1434         //
1435         // Consider "int x = 0; int *px = &x;". There are two kinds of
1436         // interesting debug values here after optimization:
1437         //
1438         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1439         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1440         //
1441         // Both describe the direct values of their associated variables.
1442         Dependencies.push_back(N.getNode());
1443         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1444         continue;
1445       }
1446       LocationOps.emplace_back(
1447           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1448       continue;
1449     }
1450 
1451     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1452     // Special rules apply for the first dbg.values of parameter variables in a
1453     // function. Identify them by the fact they reference Argument Values, that
1454     // they're parameters, and they are parameters of the current function. We
1455     // need to let them dangle until they get an SDNode.
1456     bool IsParamOfFunc =
1457         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1458     if (IsParamOfFunc)
1459       return false;
1460 
1461     // The value is not used in this block yet (or it would have an SDNode).
1462     // We still want the value to appear for the user if possible -- if it has
1463     // an associated VReg, we can refer to that instead.
1464     auto VMI = FuncInfo.ValueMap.find(V);
1465     if (VMI != FuncInfo.ValueMap.end()) {
1466       unsigned Reg = VMI->second;
1467       // If this is a PHI node, it may be split up into several MI PHI nodes
1468       // (in FunctionLoweringInfo::set).
1469       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1470                        V->getType(), std::nullopt);
1471       if (RFV.occupiesMultipleRegs()) {
1472         // FIXME: We could potentially support variadic dbg_values here.
1473         if (IsVariadic)
1474           return false;
1475         unsigned Offset = 0;
1476         unsigned BitsToDescribe = 0;
1477         if (auto VarSize = Var->getSizeInBits())
1478           BitsToDescribe = *VarSize;
1479         if (auto Fragment = Expr->getFragmentInfo())
1480           BitsToDescribe = Fragment->SizeInBits;
1481         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1482           // Bail out if all bits are described already.
1483           if (Offset >= BitsToDescribe)
1484             break;
1485           // TODO: handle scalable vectors.
1486           unsigned RegisterSize = RegAndSize.second;
1487           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1488                                       ? BitsToDescribe - Offset
1489                                       : RegisterSize;
1490           auto FragmentExpr = DIExpression::createFragmentExpression(
1491               Expr, Offset, FragmentSize);
1492           if (!FragmentExpr)
1493             continue;
1494           SDDbgValue *SDV = DAG.getVRegDbgValue(
1495               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1496           DAG.AddDbgValue(SDV, false);
1497           Offset += RegisterSize;
1498         }
1499         return true;
1500       }
1501       // We can use simple vreg locations for variadic dbg_values as well.
1502       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1503       continue;
1504     }
1505     // We failed to create a SDDbgOperand for V.
1506     return false;
1507   }
1508 
1509   // We have created a SDDbgOperand for each Value in Values.
1510   // Should use Order instead of SDNodeOrder?
1511   assert(!LocationOps.empty());
1512   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1513                                         /*IsIndirect=*/false, DbgLoc,
1514                                         SDNodeOrder, IsVariadic);
1515   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1516   return true;
1517 }
1518 
1519 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1520   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1521   for (auto &Pair : DanglingDebugInfoMap)
1522     for (auto &DDI : Pair.second)
1523       salvageUnresolvedDbgValue(DDI);
1524   clearDanglingDebugInfo();
1525 }
1526 
1527 /// getCopyFromRegs - If there was virtual register allocated for the value V
1528 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1529 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1530   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1531   SDValue Result;
1532 
1533   if (It != FuncInfo.ValueMap.end()) {
1534     Register InReg = It->second;
1535 
1536     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1537                      DAG.getDataLayout(), InReg, Ty,
1538                      std::nullopt); // This is not an ABI copy.
1539     SDValue Chain = DAG.getEntryNode();
1540     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1541                                  V);
1542     resolveDanglingDebugInfo(V, Result);
1543   }
1544 
1545   return Result;
1546 }
1547 
1548 /// getValue - Return an SDValue for the given Value.
1549 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1550   // If we already have an SDValue for this value, use it. It's important
1551   // to do this first, so that we don't create a CopyFromReg if we already
1552   // have a regular SDValue.
1553   SDValue &N = NodeMap[V];
1554   if (N.getNode()) return N;
1555 
1556   // If there's a virtual register allocated and initialized for this
1557   // value, use it.
1558   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1559     return copyFromReg;
1560 
1561   // Otherwise create a new SDValue and remember it.
1562   SDValue Val = getValueImpl(V);
1563   NodeMap[V] = Val;
1564   resolveDanglingDebugInfo(V, Val);
1565   return Val;
1566 }
1567 
1568 /// getNonRegisterValue - Return an SDValue for the given Value, but
1569 /// don't look in FuncInfo.ValueMap for a virtual register.
1570 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1571   // If we already have an SDValue for this value, use it.
1572   SDValue &N = NodeMap[V];
1573   if (N.getNode()) {
1574     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1575       // Remove the debug location from the node as the node is about to be used
1576       // in a location which may differ from the original debug location.  This
1577       // is relevant to Constant and ConstantFP nodes because they can appear
1578       // as constant expressions inside PHI nodes.
1579       N->setDebugLoc(DebugLoc());
1580     }
1581     return N;
1582   }
1583 
1584   // Otherwise create a new SDValue and remember it.
1585   SDValue Val = getValueImpl(V);
1586   NodeMap[V] = Val;
1587   resolveDanglingDebugInfo(V, Val);
1588   return Val;
1589 }
1590 
1591 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1592 /// Create an SDValue for the given value.
1593 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1595 
1596   if (const Constant *C = dyn_cast<Constant>(V)) {
1597     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1598 
1599     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1600       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1601 
1602     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1603       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1604 
1605     if (isa<ConstantPointerNull>(C)) {
1606       unsigned AS = V->getType()->getPointerAddressSpace();
1607       return DAG.getConstant(0, getCurSDLoc(),
1608                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1609     }
1610 
1611     if (match(C, m_VScale(DAG.getDataLayout())))
1612       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1613 
1614     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1615       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1616 
1617     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1618       return DAG.getUNDEF(VT);
1619 
1620     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1621       visit(CE->getOpcode(), *CE);
1622       SDValue N1 = NodeMap[V];
1623       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1624       return N1;
1625     }
1626 
1627     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1628       SmallVector<SDValue, 4> Constants;
1629       for (const Use &U : C->operands()) {
1630         SDNode *Val = getValue(U).getNode();
1631         // If the operand is an empty aggregate, there are no values.
1632         if (!Val) continue;
1633         // Add each leaf value from the operand to the Constants list
1634         // to form a flattened list of all the values.
1635         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1636           Constants.push_back(SDValue(Val, i));
1637       }
1638 
1639       return DAG.getMergeValues(Constants, getCurSDLoc());
1640     }
1641 
1642     if (const ConstantDataSequential *CDS =
1643           dyn_cast<ConstantDataSequential>(C)) {
1644       SmallVector<SDValue, 4> Ops;
1645       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1646         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1647         // Add each leaf value from the operand to the Constants list
1648         // to form a flattened list of all the values.
1649         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1650           Ops.push_back(SDValue(Val, i));
1651       }
1652 
1653       if (isa<ArrayType>(CDS->getType()))
1654         return DAG.getMergeValues(Ops, getCurSDLoc());
1655       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1656     }
1657 
1658     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1659       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1660              "Unknown struct or array constant!");
1661 
1662       SmallVector<EVT, 4> ValueVTs;
1663       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1664       unsigned NumElts = ValueVTs.size();
1665       if (NumElts == 0)
1666         return SDValue(); // empty struct
1667       SmallVector<SDValue, 4> Constants(NumElts);
1668       for (unsigned i = 0; i != NumElts; ++i) {
1669         EVT EltVT = ValueVTs[i];
1670         if (isa<UndefValue>(C))
1671           Constants[i] = DAG.getUNDEF(EltVT);
1672         else if (EltVT.isFloatingPoint())
1673           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1674         else
1675           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1676       }
1677 
1678       return DAG.getMergeValues(Constants, getCurSDLoc());
1679     }
1680 
1681     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1682       return DAG.getBlockAddress(BA, VT);
1683 
1684     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1685       return getValue(Equiv->getGlobalValue());
1686 
1687     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1688       return getValue(NC->getGlobalValue());
1689 
1690     VectorType *VecTy = cast<VectorType>(V->getType());
1691 
1692     // Now that we know the number and type of the elements, get that number of
1693     // elements into the Ops array based on what kind of constant it is.
1694     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1695       SmallVector<SDValue, 16> Ops;
1696       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1697       for (unsigned i = 0; i != NumElements; ++i)
1698         Ops.push_back(getValue(CV->getOperand(i)));
1699 
1700       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1701     }
1702 
1703     if (isa<ConstantAggregateZero>(C)) {
1704       EVT EltVT =
1705           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1706 
1707       SDValue Op;
1708       if (EltVT.isFloatingPoint())
1709         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1710       else
1711         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1712 
1713       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1714     }
1715 
1716     llvm_unreachable("Unknown vector constant");
1717   }
1718 
1719   // If this is a static alloca, generate it as the frameindex instead of
1720   // computation.
1721   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1722     DenseMap<const AllocaInst*, int>::iterator SI =
1723       FuncInfo.StaticAllocaMap.find(AI);
1724     if (SI != FuncInfo.StaticAllocaMap.end())
1725       return DAG.getFrameIndex(
1726           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1727   }
1728 
1729   // If this is an instruction which fast-isel has deferred, select it now.
1730   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1731     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1732 
1733     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1734                      Inst->getType(), std::nullopt);
1735     SDValue Chain = DAG.getEntryNode();
1736     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1737   }
1738 
1739   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1740     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1741 
1742   if (const auto *BB = dyn_cast<BasicBlock>(V))
1743     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1744 
1745   llvm_unreachable("Can't get register for value!");
1746 }
1747 
1748 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1749   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1750   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1751   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1752   bool IsSEH = isAsynchronousEHPersonality(Pers);
1753   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1754   if (!IsSEH)
1755     CatchPadMBB->setIsEHScopeEntry();
1756   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1757   if (IsMSVCCXX || IsCoreCLR)
1758     CatchPadMBB->setIsEHFuncletEntry();
1759 }
1760 
1761 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1762   // Update machine-CFG edge.
1763   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1764   FuncInfo.MBB->addSuccessor(TargetMBB);
1765   TargetMBB->setIsEHCatchretTarget(true);
1766   DAG.getMachineFunction().setHasEHCatchret(true);
1767 
1768   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1769   bool IsSEH = isAsynchronousEHPersonality(Pers);
1770   if (IsSEH) {
1771     // If this is not a fall-through branch or optimizations are switched off,
1772     // emit the branch.
1773     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1774         TM.getOptLevel() == CodeGenOpt::None)
1775       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1776                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1777     return;
1778   }
1779 
1780   // Figure out the funclet membership for the catchret's successor.
1781   // This will be used by the FuncletLayout pass to determine how to order the
1782   // BB's.
1783   // A 'catchret' returns to the outer scope's color.
1784   Value *ParentPad = I.getCatchSwitchParentPad();
1785   const BasicBlock *SuccessorColor;
1786   if (isa<ConstantTokenNone>(ParentPad))
1787     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1788   else
1789     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1790   assert(SuccessorColor && "No parent funclet for catchret!");
1791   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1792   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1793 
1794   // Create the terminator node.
1795   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1796                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1797                             DAG.getBasicBlock(SuccessorColorMBB));
1798   DAG.setRoot(Ret);
1799 }
1800 
1801 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1802   // Don't emit any special code for the cleanuppad instruction. It just marks
1803   // the start of an EH scope/funclet.
1804   FuncInfo.MBB->setIsEHScopeEntry();
1805   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1806   if (Pers != EHPersonality::Wasm_CXX) {
1807     FuncInfo.MBB->setIsEHFuncletEntry();
1808     FuncInfo.MBB->setIsCleanupFuncletEntry();
1809   }
1810 }
1811 
1812 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1813 // not match, it is OK to add only the first unwind destination catchpad to the
1814 // successors, because there will be at least one invoke instruction within the
1815 // catch scope that points to the next unwind destination, if one exists, so
1816 // CFGSort cannot mess up with BB sorting order.
1817 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1818 // call within them, and catchpads only consisting of 'catch (...)' have a
1819 // '__cxa_end_catch' call within them, both of which generate invokes in case
1820 // the next unwind destination exists, i.e., the next unwind destination is not
1821 // the caller.)
1822 //
1823 // Having at most one EH pad successor is also simpler and helps later
1824 // transformations.
1825 //
1826 // For example,
1827 // current:
1828 //   invoke void @foo to ... unwind label %catch.dispatch
1829 // catch.dispatch:
1830 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1831 // catch.start:
1832 //   ...
1833 //   ... in this BB or some other child BB dominated by this BB there will be an
1834 //   invoke that points to 'next' BB as an unwind destination
1835 //
1836 // next: ; We don't need to add this to 'current' BB's successor
1837 //   ...
1838 static void findWasmUnwindDestinations(
1839     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1840     BranchProbability Prob,
1841     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1842         &UnwindDests) {
1843   while (EHPadBB) {
1844     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1845     if (isa<CleanupPadInst>(Pad)) {
1846       // Stop on cleanup pads.
1847       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1848       UnwindDests.back().first->setIsEHScopeEntry();
1849       break;
1850     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1851       // Add the catchpad handlers to the possible destinations. We don't
1852       // continue to the unwind destination of the catchswitch for wasm.
1853       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1854         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1855         UnwindDests.back().first->setIsEHScopeEntry();
1856       }
1857       break;
1858     } else {
1859       continue;
1860     }
1861   }
1862 }
1863 
1864 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1865 /// many places it could ultimately go. In the IR, we have a single unwind
1866 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1867 /// This function skips over imaginary basic blocks that hold catchswitch
1868 /// instructions, and finds all the "real" machine
1869 /// basic block destinations. As those destinations may not be successors of
1870 /// EHPadBB, here we also calculate the edge probability to those destinations.
1871 /// The passed-in Prob is the edge probability to EHPadBB.
1872 static void findUnwindDestinations(
1873     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1874     BranchProbability Prob,
1875     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1876         &UnwindDests) {
1877   EHPersonality Personality =
1878     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1879   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1880   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1881   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1882   bool IsSEH = isAsynchronousEHPersonality(Personality);
1883 
1884   if (IsWasmCXX) {
1885     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1886     assert(UnwindDests.size() <= 1 &&
1887            "There should be at most one unwind destination for wasm");
1888     return;
1889   }
1890 
1891   while (EHPadBB) {
1892     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1893     BasicBlock *NewEHPadBB = nullptr;
1894     if (isa<LandingPadInst>(Pad)) {
1895       // Stop on landingpads. They are not funclets.
1896       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1897       break;
1898     } else if (isa<CleanupPadInst>(Pad)) {
1899       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1900       // personalities.
1901       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1902       UnwindDests.back().first->setIsEHScopeEntry();
1903       UnwindDests.back().first->setIsEHFuncletEntry();
1904       break;
1905     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1906       // Add the catchpad handlers to the possible destinations.
1907       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1908         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1909         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1910         if (IsMSVCCXX || IsCoreCLR)
1911           UnwindDests.back().first->setIsEHFuncletEntry();
1912         if (!IsSEH)
1913           UnwindDests.back().first->setIsEHScopeEntry();
1914       }
1915       NewEHPadBB = CatchSwitch->getUnwindDest();
1916     } else {
1917       continue;
1918     }
1919 
1920     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1921     if (BPI && NewEHPadBB)
1922       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1923     EHPadBB = NewEHPadBB;
1924   }
1925 }
1926 
1927 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1928   // Update successor info.
1929   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1930   auto UnwindDest = I.getUnwindDest();
1931   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1932   BranchProbability UnwindDestProb =
1933       (BPI && UnwindDest)
1934           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1935           : BranchProbability::getZero();
1936   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1937   for (auto &UnwindDest : UnwindDests) {
1938     UnwindDest.first->setIsEHPad();
1939     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1940   }
1941   FuncInfo.MBB->normalizeSuccProbs();
1942 
1943   // Create the terminator node.
1944   SDValue Ret =
1945       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1946   DAG.setRoot(Ret);
1947 }
1948 
1949 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1950   report_fatal_error("visitCatchSwitch not yet implemented!");
1951 }
1952 
1953 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1955   auto &DL = DAG.getDataLayout();
1956   SDValue Chain = getControlRoot();
1957   SmallVector<ISD::OutputArg, 8> Outs;
1958   SmallVector<SDValue, 8> OutVals;
1959 
1960   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1961   // lower
1962   //
1963   //   %val = call <ty> @llvm.experimental.deoptimize()
1964   //   ret <ty> %val
1965   //
1966   // differently.
1967   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1968     LowerDeoptimizingReturn();
1969     return;
1970   }
1971 
1972   if (!FuncInfo.CanLowerReturn) {
1973     unsigned DemoteReg = FuncInfo.DemoteRegister;
1974     const Function *F = I.getParent()->getParent();
1975 
1976     // Emit a store of the return value through the virtual register.
1977     // Leave Outs empty so that LowerReturn won't try to load return
1978     // registers the usual way.
1979     SmallVector<EVT, 1> PtrValueVTs;
1980     ComputeValueVTs(TLI, DL,
1981                     F->getReturnType()->getPointerTo(
1982                         DAG.getDataLayout().getAllocaAddrSpace()),
1983                     PtrValueVTs);
1984 
1985     SDValue RetPtr =
1986         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1987     SDValue RetOp = getValue(I.getOperand(0));
1988 
1989     SmallVector<EVT, 4> ValueVTs, MemVTs;
1990     SmallVector<uint64_t, 4> Offsets;
1991     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1992                     &Offsets);
1993     unsigned NumValues = ValueVTs.size();
1994 
1995     SmallVector<SDValue, 4> Chains(NumValues);
1996     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1997     for (unsigned i = 0; i != NumValues; ++i) {
1998       // An aggregate return value cannot wrap around the address space, so
1999       // offsets to its parts don't wrap either.
2000       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2001                                            TypeSize::Fixed(Offsets[i]));
2002 
2003       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2004       if (MemVTs[i] != ValueVTs[i])
2005         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2006       Chains[i] = DAG.getStore(
2007           Chain, getCurSDLoc(), Val,
2008           // FIXME: better loc info would be nice.
2009           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2010           commonAlignment(BaseAlign, Offsets[i]));
2011     }
2012 
2013     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2014                         MVT::Other, Chains);
2015   } else if (I.getNumOperands() != 0) {
2016     SmallVector<EVT, 4> ValueVTs;
2017     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2018     unsigned NumValues = ValueVTs.size();
2019     if (NumValues) {
2020       SDValue RetOp = getValue(I.getOperand(0));
2021 
2022       const Function *F = I.getParent()->getParent();
2023 
2024       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2025           I.getOperand(0)->getType(), F->getCallingConv(),
2026           /*IsVarArg*/ false, DL);
2027 
2028       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2029       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2030         ExtendKind = ISD::SIGN_EXTEND;
2031       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2032         ExtendKind = ISD::ZERO_EXTEND;
2033 
2034       LLVMContext &Context = F->getContext();
2035       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2036 
2037       for (unsigned j = 0; j != NumValues; ++j) {
2038         EVT VT = ValueVTs[j];
2039 
2040         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2041           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2042 
2043         CallingConv::ID CC = F->getCallingConv();
2044 
2045         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2046         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2047         SmallVector<SDValue, 4> Parts(NumParts);
2048         getCopyToParts(DAG, getCurSDLoc(),
2049                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2050                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2051 
2052         // 'inreg' on function refers to return value
2053         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2054         if (RetInReg)
2055           Flags.setInReg();
2056 
2057         if (I.getOperand(0)->getType()->isPointerTy()) {
2058           Flags.setPointer();
2059           Flags.setPointerAddrSpace(
2060               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2061         }
2062 
2063         if (NeedsRegBlock) {
2064           Flags.setInConsecutiveRegs();
2065           if (j == NumValues - 1)
2066             Flags.setInConsecutiveRegsLast();
2067         }
2068 
2069         // Propagate extension type if any
2070         if (ExtendKind == ISD::SIGN_EXTEND)
2071           Flags.setSExt();
2072         else if (ExtendKind == ISD::ZERO_EXTEND)
2073           Flags.setZExt();
2074 
2075         for (unsigned i = 0; i < NumParts; ++i) {
2076           Outs.push_back(ISD::OutputArg(Flags,
2077                                         Parts[i].getValueType().getSimpleVT(),
2078                                         VT, /*isfixed=*/true, 0, 0));
2079           OutVals.push_back(Parts[i]);
2080         }
2081       }
2082     }
2083   }
2084 
2085   // Push in swifterror virtual register as the last element of Outs. This makes
2086   // sure swifterror virtual register will be returned in the swifterror
2087   // physical register.
2088   const Function *F = I.getParent()->getParent();
2089   if (TLI.supportSwiftError() &&
2090       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2091     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2092     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2093     Flags.setSwiftError();
2094     Outs.push_back(ISD::OutputArg(
2095         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2096         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2097     // Create SDNode for the swifterror virtual register.
2098     OutVals.push_back(
2099         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2100                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2101                         EVT(TLI.getPointerTy(DL))));
2102   }
2103 
2104   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2105   CallingConv::ID CallConv =
2106     DAG.getMachineFunction().getFunction().getCallingConv();
2107   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2108       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2109 
2110   // Verify that the target's LowerReturn behaved as expected.
2111   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2112          "LowerReturn didn't return a valid chain!");
2113 
2114   // Update the DAG with the new chain value resulting from return lowering.
2115   DAG.setRoot(Chain);
2116 }
2117 
2118 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2119 /// created for it, emit nodes to copy the value into the virtual
2120 /// registers.
2121 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2122   // Skip empty types
2123   if (V->getType()->isEmptyTy())
2124     return;
2125 
2126   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2127   if (VMI != FuncInfo.ValueMap.end()) {
2128     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2129     CopyValueToVirtualRegister(V, VMI->second);
2130   }
2131 }
2132 
2133 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2134 /// the current basic block, add it to ValueMap now so that we'll get a
2135 /// CopyTo/FromReg.
2136 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2137   // No need to export constants.
2138   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2139 
2140   // Already exported?
2141   if (FuncInfo.isExportedInst(V)) return;
2142 
2143   Register Reg = FuncInfo.InitializeRegForValue(V);
2144   CopyValueToVirtualRegister(V, Reg);
2145 }
2146 
2147 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2148                                                      const BasicBlock *FromBB) {
2149   // The operands of the setcc have to be in this block.  We don't know
2150   // how to export them from some other block.
2151   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2152     // Can export from current BB.
2153     if (VI->getParent() == FromBB)
2154       return true;
2155 
2156     // Is already exported, noop.
2157     return FuncInfo.isExportedInst(V);
2158   }
2159 
2160   // If this is an argument, we can export it if the BB is the entry block or
2161   // if it is already exported.
2162   if (isa<Argument>(V)) {
2163     if (FromBB->isEntryBlock())
2164       return true;
2165 
2166     // Otherwise, can only export this if it is already exported.
2167     return FuncInfo.isExportedInst(V);
2168   }
2169 
2170   // Otherwise, constants can always be exported.
2171   return true;
2172 }
2173 
2174 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2175 BranchProbability
2176 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2177                                         const MachineBasicBlock *Dst) const {
2178   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2179   const BasicBlock *SrcBB = Src->getBasicBlock();
2180   const BasicBlock *DstBB = Dst->getBasicBlock();
2181   if (!BPI) {
2182     // If BPI is not available, set the default probability as 1 / N, where N is
2183     // the number of successors.
2184     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2185     return BranchProbability(1, SuccSize);
2186   }
2187   return BPI->getEdgeProbability(SrcBB, DstBB);
2188 }
2189 
2190 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2191                                                MachineBasicBlock *Dst,
2192                                                BranchProbability Prob) {
2193   if (!FuncInfo.BPI)
2194     Src->addSuccessorWithoutProb(Dst);
2195   else {
2196     if (Prob.isUnknown())
2197       Prob = getEdgeProbability(Src, Dst);
2198     Src->addSuccessor(Dst, Prob);
2199   }
2200 }
2201 
2202 static bool InBlock(const Value *V, const BasicBlock *BB) {
2203   if (const Instruction *I = dyn_cast<Instruction>(V))
2204     return I->getParent() == BB;
2205   return true;
2206 }
2207 
2208 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2209 /// This function emits a branch and is used at the leaves of an OR or an
2210 /// AND operator tree.
2211 void
2212 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2213                                                   MachineBasicBlock *TBB,
2214                                                   MachineBasicBlock *FBB,
2215                                                   MachineBasicBlock *CurBB,
2216                                                   MachineBasicBlock *SwitchBB,
2217                                                   BranchProbability TProb,
2218                                                   BranchProbability FProb,
2219                                                   bool InvertCond) {
2220   const BasicBlock *BB = CurBB->getBasicBlock();
2221 
2222   // If the leaf of the tree is a comparison, merge the condition into
2223   // the caseblock.
2224   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2225     // The operands of the cmp have to be in this block.  We don't know
2226     // how to export them from some other block.  If this is the first block
2227     // of the sequence, no exporting is needed.
2228     if (CurBB == SwitchBB ||
2229         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2230          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2231       ISD::CondCode Condition;
2232       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2233         ICmpInst::Predicate Pred =
2234             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2235         Condition = getICmpCondCode(Pred);
2236       } else {
2237         const FCmpInst *FC = cast<FCmpInst>(Cond);
2238         FCmpInst::Predicate Pred =
2239             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2240         Condition = getFCmpCondCode(Pred);
2241         if (TM.Options.NoNaNsFPMath)
2242           Condition = getFCmpCodeWithoutNaN(Condition);
2243       }
2244 
2245       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2246                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2247       SL->SwitchCases.push_back(CB);
2248       return;
2249     }
2250   }
2251 
2252   // Create a CaseBlock record representing this branch.
2253   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2254   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2255                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2256   SL->SwitchCases.push_back(CB);
2257 }
2258 
2259 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2260                                                MachineBasicBlock *TBB,
2261                                                MachineBasicBlock *FBB,
2262                                                MachineBasicBlock *CurBB,
2263                                                MachineBasicBlock *SwitchBB,
2264                                                Instruction::BinaryOps Opc,
2265                                                BranchProbability TProb,
2266                                                BranchProbability FProb,
2267                                                bool InvertCond) {
2268   // Skip over not part of the tree and remember to invert op and operands at
2269   // next level.
2270   Value *NotCond;
2271   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2272       InBlock(NotCond, CurBB->getBasicBlock())) {
2273     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2274                          !InvertCond);
2275     return;
2276   }
2277 
2278   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2279   const Value *BOpOp0, *BOpOp1;
2280   // Compute the effective opcode for Cond, taking into account whether it needs
2281   // to be inverted, e.g.
2282   //   and (not (or A, B)), C
2283   // gets lowered as
2284   //   and (and (not A, not B), C)
2285   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2286   if (BOp) {
2287     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2288                ? Instruction::And
2289                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2290                       ? Instruction::Or
2291                       : (Instruction::BinaryOps)0);
2292     if (InvertCond) {
2293       if (BOpc == Instruction::And)
2294         BOpc = Instruction::Or;
2295       else if (BOpc == Instruction::Or)
2296         BOpc = Instruction::And;
2297     }
2298   }
2299 
2300   // If this node is not part of the or/and tree, emit it as a branch.
2301   // Note that all nodes in the tree should have same opcode.
2302   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2303   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2304       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2305       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2306     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2307                                  TProb, FProb, InvertCond);
2308     return;
2309   }
2310 
2311   //  Create TmpBB after CurBB.
2312   MachineFunction::iterator BBI(CurBB);
2313   MachineFunction &MF = DAG.getMachineFunction();
2314   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2315   CurBB->getParent()->insert(++BBI, TmpBB);
2316 
2317   if (Opc == Instruction::Or) {
2318     // Codegen X | Y as:
2319     // BB1:
2320     //   jmp_if_X TBB
2321     //   jmp TmpBB
2322     // TmpBB:
2323     //   jmp_if_Y TBB
2324     //   jmp FBB
2325     //
2326 
2327     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2328     // The requirement is that
2329     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2330     //     = TrueProb for original BB.
2331     // Assuming the original probabilities are A and B, one choice is to set
2332     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2333     // A/(1+B) and 2B/(1+B). This choice assumes that
2334     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2335     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2336     // TmpBB, but the math is more complicated.
2337 
2338     auto NewTrueProb = TProb / 2;
2339     auto NewFalseProb = TProb / 2 + FProb;
2340     // Emit the LHS condition.
2341     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2342                          NewFalseProb, InvertCond);
2343 
2344     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2345     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2346     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2347     // Emit the RHS condition into TmpBB.
2348     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2349                          Probs[1], InvertCond);
2350   } else {
2351     assert(Opc == Instruction::And && "Unknown merge op!");
2352     // Codegen X & Y as:
2353     // BB1:
2354     //   jmp_if_X TmpBB
2355     //   jmp FBB
2356     // TmpBB:
2357     //   jmp_if_Y TBB
2358     //   jmp FBB
2359     //
2360     //  This requires creation of TmpBB after CurBB.
2361 
2362     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2363     // The requirement is that
2364     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2365     //     = FalseProb for original BB.
2366     // Assuming the original probabilities are A and B, one choice is to set
2367     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2368     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2369     // TrueProb for BB1 * FalseProb for TmpBB.
2370 
2371     auto NewTrueProb = TProb + FProb / 2;
2372     auto NewFalseProb = FProb / 2;
2373     // Emit the LHS condition.
2374     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2375                          NewFalseProb, InvertCond);
2376 
2377     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2378     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2379     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2380     // Emit the RHS condition into TmpBB.
2381     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2382                          Probs[1], InvertCond);
2383   }
2384 }
2385 
2386 /// If the set of cases should be emitted as a series of branches, return true.
2387 /// If we should emit this as a bunch of and/or'd together conditions, return
2388 /// false.
2389 bool
2390 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2391   if (Cases.size() != 2) return true;
2392 
2393   // If this is two comparisons of the same values or'd or and'd together, they
2394   // will get folded into a single comparison, so don't emit two blocks.
2395   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2396        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2397       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2398        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2399     return false;
2400   }
2401 
2402   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2403   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2404   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2405       Cases[0].CC == Cases[1].CC &&
2406       isa<Constant>(Cases[0].CmpRHS) &&
2407       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2408     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2409       return false;
2410     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2411       return false;
2412   }
2413 
2414   return true;
2415 }
2416 
2417 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2418   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2419 
2420   // Update machine-CFG edges.
2421   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2422 
2423   if (I.isUnconditional()) {
2424     // Update machine-CFG edges.
2425     BrMBB->addSuccessor(Succ0MBB);
2426 
2427     // If this is not a fall-through branch or optimizations are switched off,
2428     // emit the branch.
2429     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2430       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2431                               MVT::Other, getControlRoot(),
2432                               DAG.getBasicBlock(Succ0MBB)));
2433 
2434     return;
2435   }
2436 
2437   // If this condition is one of the special cases we handle, do special stuff
2438   // now.
2439   const Value *CondVal = I.getCondition();
2440   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2441 
2442   // If this is a series of conditions that are or'd or and'd together, emit
2443   // this as a sequence of branches instead of setcc's with and/or operations.
2444   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2445   // unpredictable branches, and vector extracts because those jumps are likely
2446   // expensive for any target), this should improve performance.
2447   // For example, instead of something like:
2448   //     cmp A, B
2449   //     C = seteq
2450   //     cmp D, E
2451   //     F = setle
2452   //     or C, F
2453   //     jnz foo
2454   // Emit:
2455   //     cmp A, B
2456   //     je foo
2457   //     cmp D, E
2458   //     jle foo
2459   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2460   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2461       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2462     Value *Vec;
2463     const Value *BOp0, *BOp1;
2464     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2465     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2466       Opcode = Instruction::And;
2467     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2468       Opcode = Instruction::Or;
2469 
2470     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2471                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2472       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2473                            getEdgeProbability(BrMBB, Succ0MBB),
2474                            getEdgeProbability(BrMBB, Succ1MBB),
2475                            /*InvertCond=*/false);
2476       // If the compares in later blocks need to use values not currently
2477       // exported from this block, export them now.  This block should always
2478       // be the first entry.
2479       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2480 
2481       // Allow some cases to be rejected.
2482       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2483         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2484           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2485           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2486         }
2487 
2488         // Emit the branch for this block.
2489         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2490         SL->SwitchCases.erase(SL->SwitchCases.begin());
2491         return;
2492       }
2493 
2494       // Okay, we decided not to do this, remove any inserted MBB's and clear
2495       // SwitchCases.
2496       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2497         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2498 
2499       SL->SwitchCases.clear();
2500     }
2501   }
2502 
2503   // Create a CaseBlock record representing this branch.
2504   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2505                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2506 
2507   // Use visitSwitchCase to actually insert the fast branch sequence for this
2508   // cond branch.
2509   visitSwitchCase(CB, BrMBB);
2510 }
2511 
2512 /// visitSwitchCase - Emits the necessary code to represent a single node in
2513 /// the binary search tree resulting from lowering a switch instruction.
2514 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2515                                           MachineBasicBlock *SwitchBB) {
2516   SDValue Cond;
2517   SDValue CondLHS = getValue(CB.CmpLHS);
2518   SDLoc dl = CB.DL;
2519 
2520   if (CB.CC == ISD::SETTRUE) {
2521     // Branch or fall through to TrueBB.
2522     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2523     SwitchBB->normalizeSuccProbs();
2524     if (CB.TrueBB != NextBlock(SwitchBB)) {
2525       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2526                               DAG.getBasicBlock(CB.TrueBB)));
2527     }
2528     return;
2529   }
2530 
2531   auto &TLI = DAG.getTargetLoweringInfo();
2532   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2533 
2534   // Build the setcc now.
2535   if (!CB.CmpMHS) {
2536     // Fold "(X == true)" to X and "(X == false)" to !X to
2537     // handle common cases produced by branch lowering.
2538     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2539         CB.CC == ISD::SETEQ)
2540       Cond = CondLHS;
2541     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2542              CB.CC == ISD::SETEQ) {
2543       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2544       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2545     } else {
2546       SDValue CondRHS = getValue(CB.CmpRHS);
2547 
2548       // If a pointer's DAG type is larger than its memory type then the DAG
2549       // values are zero-extended. This breaks signed comparisons so truncate
2550       // back to the underlying type before doing the compare.
2551       if (CondLHS.getValueType() != MemVT) {
2552         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2553         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2554       }
2555       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2556     }
2557   } else {
2558     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2559 
2560     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2561     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2562 
2563     SDValue CmpOp = getValue(CB.CmpMHS);
2564     EVT VT = CmpOp.getValueType();
2565 
2566     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2567       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2568                           ISD::SETLE);
2569     } else {
2570       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2571                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2572       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2573                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2574     }
2575   }
2576 
2577   // Update successor info
2578   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2579   // TrueBB and FalseBB are always different unless the incoming IR is
2580   // degenerate. This only happens when running llc on weird IR.
2581   if (CB.TrueBB != CB.FalseBB)
2582     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2583   SwitchBB->normalizeSuccProbs();
2584 
2585   // If the lhs block is the next block, invert the condition so that we can
2586   // fall through to the lhs instead of the rhs block.
2587   if (CB.TrueBB == NextBlock(SwitchBB)) {
2588     std::swap(CB.TrueBB, CB.FalseBB);
2589     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2590     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2591   }
2592 
2593   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2594                                MVT::Other, getControlRoot(), Cond,
2595                                DAG.getBasicBlock(CB.TrueBB));
2596 
2597   setValue(CurInst, BrCond);
2598 
2599   // Insert the false branch. Do this even if it's a fall through branch,
2600   // this makes it easier to do DAG optimizations which require inverting
2601   // the branch condition.
2602   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2603                        DAG.getBasicBlock(CB.FalseBB));
2604 
2605   DAG.setRoot(BrCond);
2606 }
2607 
2608 /// visitJumpTable - Emit JumpTable node in the current MBB
2609 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2610   // Emit the code for the jump table
2611   assert(JT.Reg != -1U && "Should lower JT Header first!");
2612   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2613   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2614                                      JT.Reg, PTy);
2615   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2616   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2617                                     MVT::Other, Index.getValue(1),
2618                                     Table, Index);
2619   DAG.setRoot(BrJumpTable);
2620 }
2621 
2622 /// visitJumpTableHeader - This function emits necessary code to produce index
2623 /// in the JumpTable from switch case.
2624 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2625                                                JumpTableHeader &JTH,
2626                                                MachineBasicBlock *SwitchBB) {
2627   SDLoc dl = getCurSDLoc();
2628 
2629   // Subtract the lowest switch case value from the value being switched on.
2630   SDValue SwitchOp = getValue(JTH.SValue);
2631   EVT VT = SwitchOp.getValueType();
2632   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2633                             DAG.getConstant(JTH.First, dl, VT));
2634 
2635   // The SDNode we just created, which holds the value being switched on minus
2636   // the smallest case value, needs to be copied to a virtual register so it
2637   // can be used as an index into the jump table in a subsequent basic block.
2638   // This value may be smaller or larger than the target's pointer type, and
2639   // therefore require extension or truncating.
2640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2641   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2642 
2643   unsigned JumpTableReg =
2644       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2645   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2646                                     JumpTableReg, SwitchOp);
2647   JT.Reg = JumpTableReg;
2648 
2649   if (!JTH.FallthroughUnreachable) {
2650     // Emit the range check for the jump table, and branch to the default block
2651     // for the switch statement if the value being switched on exceeds the
2652     // largest case in the switch.
2653     SDValue CMP = DAG.getSetCC(
2654         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2655                                    Sub.getValueType()),
2656         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2657 
2658     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2659                                  MVT::Other, CopyTo, CMP,
2660                                  DAG.getBasicBlock(JT.Default));
2661 
2662     // Avoid emitting unnecessary branches to the next block.
2663     if (JT.MBB != NextBlock(SwitchBB))
2664       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2665                            DAG.getBasicBlock(JT.MBB));
2666 
2667     DAG.setRoot(BrCond);
2668   } else {
2669     // Avoid emitting unnecessary branches to the next block.
2670     if (JT.MBB != NextBlock(SwitchBB))
2671       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2672                               DAG.getBasicBlock(JT.MBB)));
2673     else
2674       DAG.setRoot(CopyTo);
2675   }
2676 }
2677 
2678 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2679 /// variable if there exists one.
2680 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2681                                  SDValue &Chain) {
2682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2683   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2684   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2687   MachineSDNode *Node =
2688       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2689   if (Global) {
2690     MachinePointerInfo MPInfo(Global);
2691     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2692                  MachineMemOperand::MODereferenceable;
2693     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2694         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2695     DAG.setNodeMemRefs(Node, {MemRef});
2696   }
2697   if (PtrTy != PtrMemTy)
2698     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2699   return SDValue(Node, 0);
2700 }
2701 
2702 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2703 /// tail spliced into a stack protector check success bb.
2704 ///
2705 /// For a high level explanation of how this fits into the stack protector
2706 /// generation see the comment on the declaration of class
2707 /// StackProtectorDescriptor.
2708 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2709                                                   MachineBasicBlock *ParentBB) {
2710 
2711   // First create the loads to the guard/stack slot for the comparison.
2712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2713   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2714   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2715 
2716   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2717   int FI = MFI.getStackProtectorIndex();
2718 
2719   SDValue Guard;
2720   SDLoc dl = getCurSDLoc();
2721   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2722   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2723   Align Align =
2724       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2725 
2726   // Generate code to load the content of the guard slot.
2727   SDValue GuardVal = DAG.getLoad(
2728       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2729       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2730       MachineMemOperand::MOVolatile);
2731 
2732   if (TLI.useStackGuardXorFP())
2733     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2734 
2735   // Retrieve guard check function, nullptr if instrumentation is inlined.
2736   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2737     // The target provides a guard check function to validate the guard value.
2738     // Generate a call to that function with the content of the guard slot as
2739     // argument.
2740     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2741     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2742 
2743     TargetLowering::ArgListTy Args;
2744     TargetLowering::ArgListEntry Entry;
2745     Entry.Node = GuardVal;
2746     Entry.Ty = FnTy->getParamType(0);
2747     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2748       Entry.IsInReg = true;
2749     Args.push_back(Entry);
2750 
2751     TargetLowering::CallLoweringInfo CLI(DAG);
2752     CLI.setDebugLoc(getCurSDLoc())
2753         .setChain(DAG.getEntryNode())
2754         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2755                    getValue(GuardCheckFn), std::move(Args));
2756 
2757     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2758     DAG.setRoot(Result.second);
2759     return;
2760   }
2761 
2762   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2763   // Otherwise, emit a volatile load to retrieve the stack guard value.
2764   SDValue Chain = DAG.getEntryNode();
2765   if (TLI.useLoadStackGuardNode()) {
2766     Guard = getLoadStackGuard(DAG, dl, Chain);
2767   } else {
2768     const Value *IRGuard = TLI.getSDagStackGuard(M);
2769     SDValue GuardPtr = getValue(IRGuard);
2770 
2771     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2772                         MachinePointerInfo(IRGuard, 0), Align,
2773                         MachineMemOperand::MOVolatile);
2774   }
2775 
2776   // Perform the comparison via a getsetcc.
2777   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2778                                                         *DAG.getContext(),
2779                                                         Guard.getValueType()),
2780                              Guard, GuardVal, ISD::SETNE);
2781 
2782   // If the guard/stackslot do not equal, branch to failure MBB.
2783   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2784                                MVT::Other, GuardVal.getOperand(0),
2785                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2786   // Otherwise branch to success MBB.
2787   SDValue Br = DAG.getNode(ISD::BR, dl,
2788                            MVT::Other, BrCond,
2789                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2790 
2791   DAG.setRoot(Br);
2792 }
2793 
2794 /// Codegen the failure basic block for a stack protector check.
2795 ///
2796 /// A failure stack protector machine basic block consists simply of a call to
2797 /// __stack_chk_fail().
2798 ///
2799 /// For a high level explanation of how this fits into the stack protector
2800 /// generation see the comment on the declaration of class
2801 /// StackProtectorDescriptor.
2802 void
2803 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2805   TargetLowering::MakeLibCallOptions CallOptions;
2806   CallOptions.setDiscardResult(true);
2807   SDValue Chain =
2808       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2809                       std::nullopt, CallOptions, getCurSDLoc())
2810           .second;
2811   // On PS4/PS5, the "return address" must still be within the calling
2812   // function, even if it's at the very end, so emit an explicit TRAP here.
2813   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2814   if (TM.getTargetTriple().isPS())
2815     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2816   // WebAssembly needs an unreachable instruction after a non-returning call,
2817   // because the function return type can be different from __stack_chk_fail's
2818   // return type (void).
2819   if (TM.getTargetTriple().isWasm())
2820     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2821 
2822   DAG.setRoot(Chain);
2823 }
2824 
2825 /// visitBitTestHeader - This function emits necessary code to produce value
2826 /// suitable for "bit tests"
2827 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2828                                              MachineBasicBlock *SwitchBB) {
2829   SDLoc dl = getCurSDLoc();
2830 
2831   // Subtract the minimum value.
2832   SDValue SwitchOp = getValue(B.SValue);
2833   EVT VT = SwitchOp.getValueType();
2834   SDValue RangeSub =
2835       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2836 
2837   // Determine the type of the test operands.
2838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839   bool UsePtrType = false;
2840   if (!TLI.isTypeLegal(VT)) {
2841     UsePtrType = true;
2842   } else {
2843     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2844       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2845         // Switch table case range are encoded into series of masks.
2846         // Just use pointer type, it's guaranteed to fit.
2847         UsePtrType = true;
2848         break;
2849       }
2850   }
2851   SDValue Sub = RangeSub;
2852   if (UsePtrType) {
2853     VT = TLI.getPointerTy(DAG.getDataLayout());
2854     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2855   }
2856 
2857   B.RegVT = VT.getSimpleVT();
2858   B.Reg = FuncInfo.CreateReg(B.RegVT);
2859   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2860 
2861   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2862 
2863   if (!B.FallthroughUnreachable)
2864     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2865   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2866   SwitchBB->normalizeSuccProbs();
2867 
2868   SDValue Root = CopyTo;
2869   if (!B.FallthroughUnreachable) {
2870     // Conditional branch to the default block.
2871     SDValue RangeCmp = DAG.getSetCC(dl,
2872         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2873                                RangeSub.getValueType()),
2874         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2875         ISD::SETUGT);
2876 
2877     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2878                        DAG.getBasicBlock(B.Default));
2879   }
2880 
2881   // Avoid emitting unnecessary branches to the next block.
2882   if (MBB != NextBlock(SwitchBB))
2883     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2884 
2885   DAG.setRoot(Root);
2886 }
2887 
2888 /// visitBitTestCase - this function produces one "bit test"
2889 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2890                                            MachineBasicBlock* NextMBB,
2891                                            BranchProbability BranchProbToNext,
2892                                            unsigned Reg,
2893                                            BitTestCase &B,
2894                                            MachineBasicBlock *SwitchBB) {
2895   SDLoc dl = getCurSDLoc();
2896   MVT VT = BB.RegVT;
2897   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2898   SDValue Cmp;
2899   unsigned PopCount = countPopulation(B.Mask);
2900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2901   if (PopCount == 1) {
2902     // Testing for a single bit; just compare the shift count with what it
2903     // would need to be to shift a 1 bit in that position.
2904     Cmp = DAG.getSetCC(
2905         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2906         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2907         ISD::SETEQ);
2908   } else if (PopCount == BB.Range) {
2909     // There is only one zero bit in the range, test for it directly.
2910     Cmp = DAG.getSetCC(
2911         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2912         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2913         ISD::SETNE);
2914   } else {
2915     // Make desired shift
2916     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2917                                     DAG.getConstant(1, dl, VT), ShiftOp);
2918 
2919     // Emit bit tests and jumps
2920     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2921                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2922     Cmp = DAG.getSetCC(
2923         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2924         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2925   }
2926 
2927   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2928   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2929   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2930   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2931   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2932   // one as they are relative probabilities (and thus work more like weights),
2933   // and hence we need to normalize them to let the sum of them become one.
2934   SwitchBB->normalizeSuccProbs();
2935 
2936   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2937                               MVT::Other, getControlRoot(),
2938                               Cmp, DAG.getBasicBlock(B.TargetBB));
2939 
2940   // Avoid emitting unnecessary branches to the next block.
2941   if (NextMBB != NextBlock(SwitchBB))
2942     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2943                         DAG.getBasicBlock(NextMBB));
2944 
2945   DAG.setRoot(BrAnd);
2946 }
2947 
2948 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2949   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2950 
2951   // Retrieve successors. Look through artificial IR level blocks like
2952   // catchswitch for successors.
2953   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2954   const BasicBlock *EHPadBB = I.getSuccessor(1);
2955 
2956   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2957   // have to do anything here to lower funclet bundles.
2958   assert(!I.hasOperandBundlesOtherThan(
2959              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2960               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2961               LLVMContext::OB_cfguardtarget,
2962               LLVMContext::OB_clang_arc_attachedcall}) &&
2963          "Cannot lower invokes with arbitrary operand bundles yet!");
2964 
2965   const Value *Callee(I.getCalledOperand());
2966   const Function *Fn = dyn_cast<Function>(Callee);
2967   if (isa<InlineAsm>(Callee))
2968     visitInlineAsm(I, EHPadBB);
2969   else if (Fn && Fn->isIntrinsic()) {
2970     switch (Fn->getIntrinsicID()) {
2971     default:
2972       llvm_unreachable("Cannot invoke this intrinsic");
2973     case Intrinsic::donothing:
2974       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2975     case Intrinsic::seh_try_begin:
2976     case Intrinsic::seh_scope_begin:
2977     case Intrinsic::seh_try_end:
2978     case Intrinsic::seh_scope_end:
2979       break;
2980     case Intrinsic::experimental_patchpoint_void:
2981     case Intrinsic::experimental_patchpoint_i64:
2982       visitPatchpoint(I, EHPadBB);
2983       break;
2984     case Intrinsic::experimental_gc_statepoint:
2985       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2986       break;
2987     case Intrinsic::wasm_rethrow: {
2988       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2989       // special because it can be invoked, so we manually lower it to a DAG
2990       // node here.
2991       SmallVector<SDValue, 8> Ops;
2992       Ops.push_back(getRoot()); // inchain
2993       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2994       Ops.push_back(
2995           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2996                                 TLI.getPointerTy(DAG.getDataLayout())));
2997       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2998       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2999       break;
3000     }
3001     }
3002   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3003     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3004     // Eventually we will support lowering the @llvm.experimental.deoptimize
3005     // intrinsic, and right now there are no plans to support other intrinsics
3006     // with deopt state.
3007     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3008   } else {
3009     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3010   }
3011 
3012   // If the value of the invoke is used outside of its defining block, make it
3013   // available as a virtual register.
3014   // We already took care of the exported value for the statepoint instruction
3015   // during call to the LowerStatepoint.
3016   if (!isa<GCStatepointInst>(I)) {
3017     CopyToExportRegsIfNeeded(&I);
3018   }
3019 
3020   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3021   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3022   BranchProbability EHPadBBProb =
3023       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3024           : BranchProbability::getZero();
3025   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3026 
3027   // Update successor info.
3028   addSuccessorWithProb(InvokeMBB, Return);
3029   for (auto &UnwindDest : UnwindDests) {
3030     UnwindDest.first->setIsEHPad();
3031     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3032   }
3033   InvokeMBB->normalizeSuccProbs();
3034 
3035   // Drop into normal successor.
3036   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3037                           DAG.getBasicBlock(Return)));
3038 }
3039 
3040 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3041   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3042 
3043   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3044   // have to do anything here to lower funclet bundles.
3045   assert(!I.hasOperandBundlesOtherThan(
3046              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3047          "Cannot lower callbrs with arbitrary operand bundles yet!");
3048 
3049   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3050   visitInlineAsm(I);
3051   CopyToExportRegsIfNeeded(&I);
3052 
3053   // Retrieve successors.
3054   SmallPtrSet<BasicBlock *, 8> Dests;
3055   Dests.insert(I.getDefaultDest());
3056   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3057 
3058   // Update successor info.
3059   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3060   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3061     BasicBlock *Dest = I.getIndirectDest(i);
3062     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3063     Target->setIsInlineAsmBrIndirectTarget();
3064     Target->setMachineBlockAddressTaken();
3065     Target->setLabelMustBeEmitted();
3066     // Don't add duplicate machine successors.
3067     if (Dests.insert(Dest).second)
3068       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3069   }
3070   CallBrMBB->normalizeSuccProbs();
3071 
3072   // Drop into default successor.
3073   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3074                           MVT::Other, getControlRoot(),
3075                           DAG.getBasicBlock(Return)));
3076 }
3077 
3078 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3079   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3080 }
3081 
3082 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3083   assert(FuncInfo.MBB->isEHPad() &&
3084          "Call to landingpad not in landing pad!");
3085 
3086   // If there aren't registers to copy the values into (e.g., during SjLj
3087   // exceptions), then don't bother to create these DAG nodes.
3088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3089   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3090   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3091       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3092     return;
3093 
3094   // If landingpad's return type is token type, we don't create DAG nodes
3095   // for its exception pointer and selector value. The extraction of exception
3096   // pointer or selector value from token type landingpads is not currently
3097   // supported.
3098   if (LP.getType()->isTokenTy())
3099     return;
3100 
3101   SmallVector<EVT, 2> ValueVTs;
3102   SDLoc dl = getCurSDLoc();
3103   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3104   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3105 
3106   // Get the two live-in registers as SDValues. The physregs have already been
3107   // copied into virtual registers.
3108   SDValue Ops[2];
3109   if (FuncInfo.ExceptionPointerVirtReg) {
3110     Ops[0] = DAG.getZExtOrTrunc(
3111         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3112                            FuncInfo.ExceptionPointerVirtReg,
3113                            TLI.getPointerTy(DAG.getDataLayout())),
3114         dl, ValueVTs[0]);
3115   } else {
3116     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3117   }
3118   Ops[1] = DAG.getZExtOrTrunc(
3119       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3120                          FuncInfo.ExceptionSelectorVirtReg,
3121                          TLI.getPointerTy(DAG.getDataLayout())),
3122       dl, ValueVTs[1]);
3123 
3124   // Merge into one.
3125   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3126                             DAG.getVTList(ValueVTs), Ops);
3127   setValue(&LP, Res);
3128 }
3129 
3130 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3131                                            MachineBasicBlock *Last) {
3132   // Update JTCases.
3133   for (JumpTableBlock &JTB : SL->JTCases)
3134     if (JTB.first.HeaderBB == First)
3135       JTB.first.HeaderBB = Last;
3136 
3137   // Update BitTestCases.
3138   for (BitTestBlock &BTB : SL->BitTestCases)
3139     if (BTB.Parent == First)
3140       BTB.Parent = Last;
3141 }
3142 
3143 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3144   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3145 
3146   // Update machine-CFG edges with unique successors.
3147   SmallSet<BasicBlock*, 32> Done;
3148   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3149     BasicBlock *BB = I.getSuccessor(i);
3150     bool Inserted = Done.insert(BB).second;
3151     if (!Inserted)
3152         continue;
3153 
3154     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3155     addSuccessorWithProb(IndirectBrMBB, Succ);
3156   }
3157   IndirectBrMBB->normalizeSuccProbs();
3158 
3159   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3160                           MVT::Other, getControlRoot(),
3161                           getValue(I.getAddress())));
3162 }
3163 
3164 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3165   if (!DAG.getTarget().Options.TrapUnreachable)
3166     return;
3167 
3168   // We may be able to ignore unreachable behind a noreturn call.
3169   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3170     const BasicBlock &BB = *I.getParent();
3171     if (&I != &BB.front()) {
3172       BasicBlock::const_iterator PredI =
3173         std::prev(BasicBlock::const_iterator(&I));
3174       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3175         if (Call->doesNotReturn())
3176           return;
3177       }
3178     }
3179   }
3180 
3181   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3182 }
3183 
3184 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3185   SDNodeFlags Flags;
3186   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3187     Flags.copyFMF(*FPOp);
3188 
3189   SDValue Op = getValue(I.getOperand(0));
3190   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3191                                     Op, Flags);
3192   setValue(&I, UnNodeValue);
3193 }
3194 
3195 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3196   SDNodeFlags Flags;
3197   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3198     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3199     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3200   }
3201   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3202     Flags.setExact(ExactOp->isExact());
3203   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3204     Flags.copyFMF(*FPOp);
3205 
3206   SDValue Op1 = getValue(I.getOperand(0));
3207   SDValue Op2 = getValue(I.getOperand(1));
3208   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3209                                      Op1, Op2, Flags);
3210   setValue(&I, BinNodeValue);
3211 }
3212 
3213 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3214   SDValue Op1 = getValue(I.getOperand(0));
3215   SDValue Op2 = getValue(I.getOperand(1));
3216 
3217   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3218       Op1.getValueType(), DAG.getDataLayout());
3219 
3220   // Coerce the shift amount to the right type if we can. This exposes the
3221   // truncate or zext to optimization early.
3222   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3223     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3224            "Unexpected shift type");
3225     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3226   }
3227 
3228   bool nuw = false;
3229   bool nsw = false;
3230   bool exact = false;
3231 
3232   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3233 
3234     if (const OverflowingBinaryOperator *OFBinOp =
3235             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3236       nuw = OFBinOp->hasNoUnsignedWrap();
3237       nsw = OFBinOp->hasNoSignedWrap();
3238     }
3239     if (const PossiblyExactOperator *ExactOp =
3240             dyn_cast<const PossiblyExactOperator>(&I))
3241       exact = ExactOp->isExact();
3242   }
3243   SDNodeFlags Flags;
3244   Flags.setExact(exact);
3245   Flags.setNoSignedWrap(nsw);
3246   Flags.setNoUnsignedWrap(nuw);
3247   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3248                             Flags);
3249   setValue(&I, Res);
3250 }
3251 
3252 void SelectionDAGBuilder::visitSDiv(const User &I) {
3253   SDValue Op1 = getValue(I.getOperand(0));
3254   SDValue Op2 = getValue(I.getOperand(1));
3255 
3256   SDNodeFlags Flags;
3257   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3258                  cast<PossiblyExactOperator>(&I)->isExact());
3259   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3260                            Op2, Flags));
3261 }
3262 
3263 void SelectionDAGBuilder::visitICmp(const User &I) {
3264   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3265   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3266     predicate = IC->getPredicate();
3267   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3268     predicate = ICmpInst::Predicate(IC->getPredicate());
3269   SDValue Op1 = getValue(I.getOperand(0));
3270   SDValue Op2 = getValue(I.getOperand(1));
3271   ISD::CondCode Opcode = getICmpCondCode(predicate);
3272 
3273   auto &TLI = DAG.getTargetLoweringInfo();
3274   EVT MemVT =
3275       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3276 
3277   // If a pointer's DAG type is larger than its memory type then the DAG values
3278   // are zero-extended. This breaks signed comparisons so truncate back to the
3279   // underlying type before doing the compare.
3280   if (Op1.getValueType() != MemVT) {
3281     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3282     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3283   }
3284 
3285   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3286                                                         I.getType());
3287   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3288 }
3289 
3290 void SelectionDAGBuilder::visitFCmp(const User &I) {
3291   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3292   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3293     predicate = FC->getPredicate();
3294   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3295     predicate = FCmpInst::Predicate(FC->getPredicate());
3296   SDValue Op1 = getValue(I.getOperand(0));
3297   SDValue Op2 = getValue(I.getOperand(1));
3298 
3299   ISD::CondCode Condition = getFCmpCondCode(predicate);
3300   auto *FPMO = cast<FPMathOperator>(&I);
3301   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3302     Condition = getFCmpCodeWithoutNaN(Condition);
3303 
3304   SDNodeFlags Flags;
3305   Flags.copyFMF(*FPMO);
3306   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3307 
3308   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3309                                                         I.getType());
3310   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3311 }
3312 
3313 // Check if the condition of the select has one use or two users that are both
3314 // selects with the same condition.
3315 static bool hasOnlySelectUsers(const Value *Cond) {
3316   return llvm::all_of(Cond->users(), [](const Value *V) {
3317     return isa<SelectInst>(V);
3318   });
3319 }
3320 
3321 void SelectionDAGBuilder::visitSelect(const User &I) {
3322   SmallVector<EVT, 4> ValueVTs;
3323   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3324                   ValueVTs);
3325   unsigned NumValues = ValueVTs.size();
3326   if (NumValues == 0) return;
3327 
3328   SmallVector<SDValue, 4> Values(NumValues);
3329   SDValue Cond     = getValue(I.getOperand(0));
3330   SDValue LHSVal   = getValue(I.getOperand(1));
3331   SDValue RHSVal   = getValue(I.getOperand(2));
3332   SmallVector<SDValue, 1> BaseOps(1, Cond);
3333   ISD::NodeType OpCode =
3334       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3335 
3336   bool IsUnaryAbs = false;
3337   bool Negate = false;
3338 
3339   SDNodeFlags Flags;
3340   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3341     Flags.copyFMF(*FPOp);
3342 
3343   // Min/max matching is only viable if all output VTs are the same.
3344   if (all_equal(ValueVTs)) {
3345     EVT VT = ValueVTs[0];
3346     LLVMContext &Ctx = *DAG.getContext();
3347     auto &TLI = DAG.getTargetLoweringInfo();
3348 
3349     // We care about the legality of the operation after it has been type
3350     // legalized.
3351     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3352       VT = TLI.getTypeToTransformTo(Ctx, VT);
3353 
3354     // If the vselect is legal, assume we want to leave this as a vector setcc +
3355     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3356     // min/max is legal on the scalar type.
3357     bool UseScalarMinMax = VT.isVector() &&
3358       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3359 
3360     Value *LHS, *RHS;
3361     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3362     ISD::NodeType Opc = ISD::DELETED_NODE;
3363     switch (SPR.Flavor) {
3364     case SPF_UMAX:    Opc = ISD::UMAX; break;
3365     case SPF_UMIN:    Opc = ISD::UMIN; break;
3366     case SPF_SMAX:    Opc = ISD::SMAX; break;
3367     case SPF_SMIN:    Opc = ISD::SMIN; break;
3368     case SPF_FMINNUM:
3369       switch (SPR.NaNBehavior) {
3370       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3371       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3372       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3373       case SPNB_RETURNS_ANY: {
3374         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3375           Opc = ISD::FMINNUM;
3376         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3377           Opc = ISD::FMINIMUM;
3378         else if (UseScalarMinMax)
3379           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3380             ISD::FMINNUM : ISD::FMINIMUM;
3381         break;
3382       }
3383       }
3384       break;
3385     case SPF_FMAXNUM:
3386       switch (SPR.NaNBehavior) {
3387       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3388       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3389       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3390       case SPNB_RETURNS_ANY:
3391 
3392         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3393           Opc = ISD::FMAXNUM;
3394         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3395           Opc = ISD::FMAXIMUM;
3396         else if (UseScalarMinMax)
3397           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3398             ISD::FMAXNUM : ISD::FMAXIMUM;
3399         break;
3400       }
3401       break;
3402     case SPF_NABS:
3403       Negate = true;
3404       [[fallthrough]];
3405     case SPF_ABS:
3406       IsUnaryAbs = true;
3407       Opc = ISD::ABS;
3408       break;
3409     default: break;
3410     }
3411 
3412     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3413         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3414          (UseScalarMinMax &&
3415           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3416         // If the underlying comparison instruction is used by any other
3417         // instruction, the consumed instructions won't be destroyed, so it is
3418         // not profitable to convert to a min/max.
3419         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3420       OpCode = Opc;
3421       LHSVal = getValue(LHS);
3422       RHSVal = getValue(RHS);
3423       BaseOps.clear();
3424     }
3425 
3426     if (IsUnaryAbs) {
3427       OpCode = Opc;
3428       LHSVal = getValue(LHS);
3429       BaseOps.clear();
3430     }
3431   }
3432 
3433   if (IsUnaryAbs) {
3434     for (unsigned i = 0; i != NumValues; ++i) {
3435       SDLoc dl = getCurSDLoc();
3436       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3437       Values[i] =
3438           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3439       if (Negate)
3440         Values[i] = DAG.getNegative(Values[i], dl, VT);
3441     }
3442   } else {
3443     for (unsigned i = 0; i != NumValues; ++i) {
3444       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3445       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3446       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3447       Values[i] = DAG.getNode(
3448           OpCode, getCurSDLoc(),
3449           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3450     }
3451   }
3452 
3453   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3454                            DAG.getVTList(ValueVTs), Values));
3455 }
3456 
3457 void SelectionDAGBuilder::visitTrunc(const User &I) {
3458   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3459   SDValue N = getValue(I.getOperand(0));
3460   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3461                                                         I.getType());
3462   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3463 }
3464 
3465 void SelectionDAGBuilder::visitZExt(const User &I) {
3466   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3467   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3468   SDValue N = getValue(I.getOperand(0));
3469   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3470                                                         I.getType());
3471   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3472 }
3473 
3474 void SelectionDAGBuilder::visitSExt(const User &I) {
3475   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3476   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3477   SDValue N = getValue(I.getOperand(0));
3478   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3479                                                         I.getType());
3480   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3481 }
3482 
3483 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3484   // FPTrunc is never a no-op cast, no need to check
3485   SDValue N = getValue(I.getOperand(0));
3486   SDLoc dl = getCurSDLoc();
3487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3488   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3489   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3490                            DAG.getTargetConstant(
3491                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3492 }
3493 
3494 void SelectionDAGBuilder::visitFPExt(const User &I) {
3495   // FPExt is never a no-op cast, no need to check
3496   SDValue N = getValue(I.getOperand(0));
3497   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3498                                                         I.getType());
3499   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3500 }
3501 
3502 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3503   // FPToUI is never a no-op cast, no need to check
3504   SDValue N = getValue(I.getOperand(0));
3505   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3506                                                         I.getType());
3507   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3508 }
3509 
3510 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3511   // FPToSI is never a no-op cast, no need to check
3512   SDValue N = getValue(I.getOperand(0));
3513   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3514                                                         I.getType());
3515   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3516 }
3517 
3518 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3519   // UIToFP is never a no-op cast, no need to check
3520   SDValue N = getValue(I.getOperand(0));
3521   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3522                                                         I.getType());
3523   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3524 }
3525 
3526 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3527   // SIToFP is never a no-op cast, no need to check
3528   SDValue N = getValue(I.getOperand(0));
3529   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3530                                                         I.getType());
3531   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3532 }
3533 
3534 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3535   // What to do depends on the size of the integer and the size of the pointer.
3536   // We can either truncate, zero extend, or no-op, accordingly.
3537   SDValue N = getValue(I.getOperand(0));
3538   auto &TLI = DAG.getTargetLoweringInfo();
3539   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3540                                                         I.getType());
3541   EVT PtrMemVT =
3542       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3543   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3544   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3545   setValue(&I, N);
3546 }
3547 
3548 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3549   // What to do depends on the size of the integer and the size of the pointer.
3550   // We can either truncate, zero extend, or no-op, accordingly.
3551   SDValue N = getValue(I.getOperand(0));
3552   auto &TLI = DAG.getTargetLoweringInfo();
3553   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3554   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3555   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3556   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3557   setValue(&I, N);
3558 }
3559 
3560 void SelectionDAGBuilder::visitBitCast(const User &I) {
3561   SDValue N = getValue(I.getOperand(0));
3562   SDLoc dl = getCurSDLoc();
3563   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3564                                                         I.getType());
3565 
3566   // BitCast assures us that source and destination are the same size so this is
3567   // either a BITCAST or a no-op.
3568   if (DestVT != N.getValueType())
3569     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3570                              DestVT, N)); // convert types.
3571   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3572   // might fold any kind of constant expression to an integer constant and that
3573   // is not what we are looking for. Only recognize a bitcast of a genuine
3574   // constant integer as an opaque constant.
3575   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3576     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3577                                  /*isOpaque*/true));
3578   else
3579     setValue(&I, N);            // noop cast.
3580 }
3581 
3582 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3584   const Value *SV = I.getOperand(0);
3585   SDValue N = getValue(SV);
3586   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3587 
3588   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3589   unsigned DestAS = I.getType()->getPointerAddressSpace();
3590 
3591   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3592     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3593 
3594   setValue(&I, N);
3595 }
3596 
3597 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3599   SDValue InVec = getValue(I.getOperand(0));
3600   SDValue InVal = getValue(I.getOperand(1));
3601   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3602                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3603   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3604                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3605                            InVec, InVal, InIdx));
3606 }
3607 
3608 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3610   SDValue InVec = getValue(I.getOperand(0));
3611   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3612                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3613   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3614                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3615                            InVec, InIdx));
3616 }
3617 
3618 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3619   SDValue Src1 = getValue(I.getOperand(0));
3620   SDValue Src2 = getValue(I.getOperand(1));
3621   ArrayRef<int> Mask;
3622   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3623     Mask = SVI->getShuffleMask();
3624   else
3625     Mask = cast<ConstantExpr>(I).getShuffleMask();
3626   SDLoc DL = getCurSDLoc();
3627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3628   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3629   EVT SrcVT = Src1.getValueType();
3630 
3631   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3632       VT.isScalableVector()) {
3633     // Canonical splat form of first element of first input vector.
3634     SDValue FirstElt =
3635         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3636                     DAG.getVectorIdxConstant(0, DL));
3637     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3638     return;
3639   }
3640 
3641   // For now, we only handle splats for scalable vectors.
3642   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3643   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3644   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3645 
3646   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3647   unsigned MaskNumElts = Mask.size();
3648 
3649   if (SrcNumElts == MaskNumElts) {
3650     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3651     return;
3652   }
3653 
3654   // Normalize the shuffle vector since mask and vector length don't match.
3655   if (SrcNumElts < MaskNumElts) {
3656     // Mask is longer than the source vectors. We can use concatenate vector to
3657     // make the mask and vectors lengths match.
3658 
3659     if (MaskNumElts % SrcNumElts == 0) {
3660       // Mask length is a multiple of the source vector length.
3661       // Check if the shuffle is some kind of concatenation of the input
3662       // vectors.
3663       unsigned NumConcat = MaskNumElts / SrcNumElts;
3664       bool IsConcat = true;
3665       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3666       for (unsigned i = 0; i != MaskNumElts; ++i) {
3667         int Idx = Mask[i];
3668         if (Idx < 0)
3669           continue;
3670         // Ensure the indices in each SrcVT sized piece are sequential and that
3671         // the same source is used for the whole piece.
3672         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3673             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3674              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3675           IsConcat = false;
3676           break;
3677         }
3678         // Remember which source this index came from.
3679         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3680       }
3681 
3682       // The shuffle is concatenating multiple vectors together. Just emit
3683       // a CONCAT_VECTORS operation.
3684       if (IsConcat) {
3685         SmallVector<SDValue, 8> ConcatOps;
3686         for (auto Src : ConcatSrcs) {
3687           if (Src < 0)
3688             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3689           else if (Src == 0)
3690             ConcatOps.push_back(Src1);
3691           else
3692             ConcatOps.push_back(Src2);
3693         }
3694         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3695         return;
3696       }
3697     }
3698 
3699     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3700     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3701     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3702                                     PaddedMaskNumElts);
3703 
3704     // Pad both vectors with undefs to make them the same length as the mask.
3705     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3706 
3707     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3708     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3709     MOps1[0] = Src1;
3710     MOps2[0] = Src2;
3711 
3712     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3713     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3714 
3715     // Readjust mask for new input vector length.
3716     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3717     for (unsigned i = 0; i != MaskNumElts; ++i) {
3718       int Idx = Mask[i];
3719       if (Idx >= (int)SrcNumElts)
3720         Idx -= SrcNumElts - PaddedMaskNumElts;
3721       MappedOps[i] = Idx;
3722     }
3723 
3724     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3725 
3726     // If the concatenated vector was padded, extract a subvector with the
3727     // correct number of elements.
3728     if (MaskNumElts != PaddedMaskNumElts)
3729       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3730                            DAG.getVectorIdxConstant(0, DL));
3731 
3732     setValue(&I, Result);
3733     return;
3734   }
3735 
3736   if (SrcNumElts > MaskNumElts) {
3737     // Analyze the access pattern of the vector to see if we can extract
3738     // two subvectors and do the shuffle.
3739     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3740     bool CanExtract = true;
3741     for (int Idx : Mask) {
3742       unsigned Input = 0;
3743       if (Idx < 0)
3744         continue;
3745 
3746       if (Idx >= (int)SrcNumElts) {
3747         Input = 1;
3748         Idx -= SrcNumElts;
3749       }
3750 
3751       // If all the indices come from the same MaskNumElts sized portion of
3752       // the sources we can use extract. Also make sure the extract wouldn't
3753       // extract past the end of the source.
3754       int NewStartIdx = alignDown(Idx, MaskNumElts);
3755       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3756           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3757         CanExtract = false;
3758       // Make sure we always update StartIdx as we use it to track if all
3759       // elements are undef.
3760       StartIdx[Input] = NewStartIdx;
3761     }
3762 
3763     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3764       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3765       return;
3766     }
3767     if (CanExtract) {
3768       // Extract appropriate subvector and generate a vector shuffle
3769       for (unsigned Input = 0; Input < 2; ++Input) {
3770         SDValue &Src = Input == 0 ? Src1 : Src2;
3771         if (StartIdx[Input] < 0)
3772           Src = DAG.getUNDEF(VT);
3773         else {
3774           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3775                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3776         }
3777       }
3778 
3779       // Calculate new mask.
3780       SmallVector<int, 8> MappedOps(Mask);
3781       for (int &Idx : MappedOps) {
3782         if (Idx >= (int)SrcNumElts)
3783           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3784         else if (Idx >= 0)
3785           Idx -= StartIdx[0];
3786       }
3787 
3788       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3789       return;
3790     }
3791   }
3792 
3793   // We can't use either concat vectors or extract subvectors so fall back to
3794   // replacing the shuffle with extract and build vector.
3795   // to insert and build vector.
3796   EVT EltVT = VT.getVectorElementType();
3797   SmallVector<SDValue,8> Ops;
3798   for (int Idx : Mask) {
3799     SDValue Res;
3800 
3801     if (Idx < 0) {
3802       Res = DAG.getUNDEF(EltVT);
3803     } else {
3804       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3805       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3806 
3807       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3808                         DAG.getVectorIdxConstant(Idx, DL));
3809     }
3810 
3811     Ops.push_back(Res);
3812   }
3813 
3814   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3815 }
3816 
3817 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3818   ArrayRef<unsigned> Indices = I.getIndices();
3819   const Value *Op0 = I.getOperand(0);
3820   const Value *Op1 = I.getOperand(1);
3821   Type *AggTy = I.getType();
3822   Type *ValTy = Op1->getType();
3823   bool IntoUndef = isa<UndefValue>(Op0);
3824   bool FromUndef = isa<UndefValue>(Op1);
3825 
3826   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3827 
3828   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3829   SmallVector<EVT, 4> AggValueVTs;
3830   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3831   SmallVector<EVT, 4> ValValueVTs;
3832   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3833 
3834   unsigned NumAggValues = AggValueVTs.size();
3835   unsigned NumValValues = ValValueVTs.size();
3836   SmallVector<SDValue, 4> Values(NumAggValues);
3837 
3838   // Ignore an insertvalue that produces an empty object
3839   if (!NumAggValues) {
3840     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3841     return;
3842   }
3843 
3844   SDValue Agg = getValue(Op0);
3845   unsigned i = 0;
3846   // Copy the beginning value(s) from the original aggregate.
3847   for (; i != LinearIndex; ++i)
3848     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3849                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3850   // Copy values from the inserted value(s).
3851   if (NumValValues) {
3852     SDValue Val = getValue(Op1);
3853     for (; i != LinearIndex + NumValValues; ++i)
3854       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3855                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3856   }
3857   // Copy remaining value(s) from the original aggregate.
3858   for (; i != NumAggValues; ++i)
3859     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3860                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3861 
3862   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3863                            DAG.getVTList(AggValueVTs), Values));
3864 }
3865 
3866 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3867   ArrayRef<unsigned> Indices = I.getIndices();
3868   const Value *Op0 = I.getOperand(0);
3869   Type *AggTy = Op0->getType();
3870   Type *ValTy = I.getType();
3871   bool OutOfUndef = isa<UndefValue>(Op0);
3872 
3873   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3874 
3875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3876   SmallVector<EVT, 4> ValValueVTs;
3877   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3878 
3879   unsigned NumValValues = ValValueVTs.size();
3880 
3881   // Ignore a extractvalue that produces an empty object
3882   if (!NumValValues) {
3883     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3884     return;
3885   }
3886 
3887   SmallVector<SDValue, 4> Values(NumValValues);
3888 
3889   SDValue Agg = getValue(Op0);
3890   // Copy out the selected value(s).
3891   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3892     Values[i - LinearIndex] =
3893       OutOfUndef ?
3894         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3895         SDValue(Agg.getNode(), Agg.getResNo() + i);
3896 
3897   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3898                            DAG.getVTList(ValValueVTs), Values));
3899 }
3900 
3901 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3902   Value *Op0 = I.getOperand(0);
3903   // Note that the pointer operand may be a vector of pointers. Take the scalar
3904   // element which holds a pointer.
3905   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3906   SDValue N = getValue(Op0);
3907   SDLoc dl = getCurSDLoc();
3908   auto &TLI = DAG.getTargetLoweringInfo();
3909 
3910   // Normalize Vector GEP - all scalar operands should be converted to the
3911   // splat vector.
3912   bool IsVectorGEP = I.getType()->isVectorTy();
3913   ElementCount VectorElementCount =
3914       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3915                   : ElementCount::getFixed(0);
3916 
3917   if (IsVectorGEP && !N.getValueType().isVector()) {
3918     LLVMContext &Context = *DAG.getContext();
3919     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3920     N = DAG.getSplat(VT, dl, N);
3921   }
3922 
3923   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3924        GTI != E; ++GTI) {
3925     const Value *Idx = GTI.getOperand();
3926     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3927       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3928       if (Field) {
3929         // N = N + Offset
3930         uint64_t Offset =
3931             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3932 
3933         // In an inbounds GEP with an offset that is nonnegative even when
3934         // interpreted as signed, assume there is no unsigned overflow.
3935         SDNodeFlags Flags;
3936         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3937           Flags.setNoUnsignedWrap(true);
3938 
3939         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3940                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3941       }
3942     } else {
3943       // IdxSize is the width of the arithmetic according to IR semantics.
3944       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3945       // (and fix up the result later).
3946       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3947       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3948       TypeSize ElementSize =
3949           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3950       // We intentionally mask away the high bits here; ElementSize may not
3951       // fit in IdxTy.
3952       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3953       bool ElementScalable = ElementSize.isScalable();
3954 
3955       // If this is a scalar constant or a splat vector of constants,
3956       // handle it quickly.
3957       const auto *C = dyn_cast<Constant>(Idx);
3958       if (C && isa<VectorType>(C->getType()))
3959         C = C->getSplatValue();
3960 
3961       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3962       if (CI && CI->isZero())
3963         continue;
3964       if (CI && !ElementScalable) {
3965         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3966         LLVMContext &Context = *DAG.getContext();
3967         SDValue OffsVal;
3968         if (IsVectorGEP)
3969           OffsVal = DAG.getConstant(
3970               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3971         else
3972           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3973 
3974         // In an inbounds GEP with an offset that is nonnegative even when
3975         // interpreted as signed, assume there is no unsigned overflow.
3976         SDNodeFlags Flags;
3977         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3978           Flags.setNoUnsignedWrap(true);
3979 
3980         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3981 
3982         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3983         continue;
3984       }
3985 
3986       // N = N + Idx * ElementMul;
3987       SDValue IdxN = getValue(Idx);
3988 
3989       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3990         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3991                                   VectorElementCount);
3992         IdxN = DAG.getSplat(VT, dl, IdxN);
3993       }
3994 
3995       // If the index is smaller or larger than intptr_t, truncate or extend
3996       // it.
3997       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3998 
3999       if (ElementScalable) {
4000         EVT VScaleTy = N.getValueType().getScalarType();
4001         SDValue VScale = DAG.getNode(
4002             ISD::VSCALE, dl, VScaleTy,
4003             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4004         if (IsVectorGEP)
4005           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4006         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4007       } else {
4008         // If this is a multiply by a power of two, turn it into a shl
4009         // immediately.  This is a very common case.
4010         if (ElementMul != 1) {
4011           if (ElementMul.isPowerOf2()) {
4012             unsigned Amt = ElementMul.logBase2();
4013             IdxN = DAG.getNode(ISD::SHL, dl,
4014                                N.getValueType(), IdxN,
4015                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4016           } else {
4017             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4018                                             IdxN.getValueType());
4019             IdxN = DAG.getNode(ISD::MUL, dl,
4020                                N.getValueType(), IdxN, Scale);
4021           }
4022         }
4023       }
4024 
4025       N = DAG.getNode(ISD::ADD, dl,
4026                       N.getValueType(), N, IdxN);
4027     }
4028   }
4029 
4030   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4031   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4032   if (IsVectorGEP) {
4033     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4034     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4035   }
4036 
4037   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4038     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4039 
4040   setValue(&I, N);
4041 }
4042 
4043 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4044   // If this is a fixed sized alloca in the entry block of the function,
4045   // allocate it statically on the stack.
4046   if (FuncInfo.StaticAllocaMap.count(&I))
4047     return;   // getValue will auto-populate this.
4048 
4049   SDLoc dl = getCurSDLoc();
4050   Type *Ty = I.getAllocatedType();
4051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4052   auto &DL = DAG.getDataLayout();
4053   TypeSize TySize = DL.getTypeAllocSize(Ty);
4054   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4055 
4056   SDValue AllocSize = getValue(I.getArraySize());
4057 
4058   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4059   if (AllocSize.getValueType() != IntPtr)
4060     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4061 
4062   if (TySize.isScalable())
4063     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4064                             DAG.getVScale(dl, IntPtr,
4065                                           APInt(IntPtr.getScalarSizeInBits(),
4066                                                 TySize.getKnownMinValue())));
4067   else
4068     AllocSize =
4069         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4070                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4071 
4072   // Handle alignment.  If the requested alignment is less than or equal to
4073   // the stack alignment, ignore it.  If the size is greater than or equal to
4074   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4075   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4076   if (*Alignment <= StackAlign)
4077     Alignment = std::nullopt;
4078 
4079   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4080   // Round the size of the allocation up to the stack alignment size
4081   // by add SA-1 to the size. This doesn't overflow because we're computing
4082   // an address inside an alloca.
4083   SDNodeFlags Flags;
4084   Flags.setNoUnsignedWrap(true);
4085   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4086                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4087 
4088   // Mask out the low bits for alignment purposes.
4089   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4090                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4091 
4092   SDValue Ops[] = {
4093       getRoot(), AllocSize,
4094       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4095   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4096   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4097   setValue(&I, DSA);
4098   DAG.setRoot(DSA.getValue(1));
4099 
4100   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4101 }
4102 
4103 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4104   if (I.isAtomic())
4105     return visitAtomicLoad(I);
4106 
4107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4108   const Value *SV = I.getOperand(0);
4109   if (TLI.supportSwiftError()) {
4110     // Swifterror values can come from either a function parameter with
4111     // swifterror attribute or an alloca with swifterror attribute.
4112     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4113       if (Arg->hasSwiftErrorAttr())
4114         return visitLoadFromSwiftError(I);
4115     }
4116 
4117     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4118       if (Alloca->isSwiftError())
4119         return visitLoadFromSwiftError(I);
4120     }
4121   }
4122 
4123   SDValue Ptr = getValue(SV);
4124 
4125   Type *Ty = I.getType();
4126   SmallVector<EVT, 4> ValueVTs, MemVTs;
4127   SmallVector<uint64_t, 4> Offsets;
4128   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4129   unsigned NumValues = ValueVTs.size();
4130   if (NumValues == 0)
4131     return;
4132 
4133   Align Alignment = I.getAlign();
4134   AAMDNodes AAInfo = I.getAAMetadata();
4135   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4136   bool isVolatile = I.isVolatile();
4137   MachineMemOperand::Flags MMOFlags =
4138       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4139 
4140   SDValue Root;
4141   bool ConstantMemory = false;
4142   if (isVolatile)
4143     // Serialize volatile loads with other side effects.
4144     Root = getRoot();
4145   else if (NumValues > MaxParallelChains)
4146     Root = getMemoryRoot();
4147   else if (AA &&
4148            AA->pointsToConstantMemory(MemoryLocation(
4149                SV,
4150                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4151                AAInfo))) {
4152     // Do not serialize (non-volatile) loads of constant memory with anything.
4153     Root = DAG.getEntryNode();
4154     ConstantMemory = true;
4155     MMOFlags |= MachineMemOperand::MOInvariant;
4156   } else {
4157     // Do not serialize non-volatile loads against each other.
4158     Root = DAG.getRoot();
4159   }
4160 
4161   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4162                                          &I, AC, nullptr, LibInfo))
4163     MMOFlags |= MachineMemOperand::MODereferenceable;
4164 
4165   SDLoc dl = getCurSDLoc();
4166 
4167   if (isVolatile)
4168     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4169 
4170   // An aggregate load cannot wrap around the address space, so offsets to its
4171   // parts don't wrap either.
4172   SDNodeFlags Flags;
4173   Flags.setNoUnsignedWrap(true);
4174 
4175   SmallVector<SDValue, 4> Values(NumValues);
4176   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4177   EVT PtrVT = Ptr.getValueType();
4178 
4179   unsigned ChainI = 0;
4180   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4181     // Serializing loads here may result in excessive register pressure, and
4182     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4183     // could recover a bit by hoisting nodes upward in the chain by recognizing
4184     // they are side-effect free or do not alias. The optimizer should really
4185     // avoid this case by converting large object/array copies to llvm.memcpy
4186     // (MaxParallelChains should always remain as failsafe).
4187     if (ChainI == MaxParallelChains) {
4188       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4189       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4190                                   makeArrayRef(Chains.data(), ChainI));
4191       Root = Chain;
4192       ChainI = 0;
4193     }
4194     SDValue A = DAG.getNode(ISD::ADD, dl,
4195                             PtrVT, Ptr,
4196                             DAG.getConstant(Offsets[i], dl, PtrVT),
4197                             Flags);
4198 
4199     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4200                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4201                             MMOFlags, AAInfo, Ranges);
4202     Chains[ChainI] = L.getValue(1);
4203 
4204     if (MemVTs[i] != ValueVTs[i])
4205       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4206 
4207     Values[i] = L;
4208   }
4209 
4210   if (!ConstantMemory) {
4211     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4212                                 makeArrayRef(Chains.data(), ChainI));
4213     if (isVolatile)
4214       DAG.setRoot(Chain);
4215     else
4216       PendingLoads.push_back(Chain);
4217   }
4218 
4219   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4220                            DAG.getVTList(ValueVTs), Values));
4221 }
4222 
4223 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4224   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4225          "call visitStoreToSwiftError when backend supports swifterror");
4226 
4227   SmallVector<EVT, 4> ValueVTs;
4228   SmallVector<uint64_t, 4> Offsets;
4229   const Value *SrcV = I.getOperand(0);
4230   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4231                   SrcV->getType(), ValueVTs, &Offsets);
4232   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4233          "expect a single EVT for swifterror");
4234 
4235   SDValue Src = getValue(SrcV);
4236   // Create a virtual register, then update the virtual register.
4237   Register VReg =
4238       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4239   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4240   // Chain can be getRoot or getControlRoot.
4241   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4242                                       SDValue(Src.getNode(), Src.getResNo()));
4243   DAG.setRoot(CopyNode);
4244 }
4245 
4246 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4247   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4248          "call visitLoadFromSwiftError when backend supports swifterror");
4249 
4250   assert(!I.isVolatile() &&
4251          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4252          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4253          "Support volatile, non temporal, invariant for load_from_swift_error");
4254 
4255   const Value *SV = I.getOperand(0);
4256   Type *Ty = I.getType();
4257   assert(
4258       (!AA ||
4259        !AA->pointsToConstantMemory(MemoryLocation(
4260            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4261            I.getAAMetadata()))) &&
4262       "load_from_swift_error should not be constant memory");
4263 
4264   SmallVector<EVT, 4> ValueVTs;
4265   SmallVector<uint64_t, 4> Offsets;
4266   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4267                   ValueVTs, &Offsets);
4268   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4269          "expect a single EVT for swifterror");
4270 
4271   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4272   SDValue L = DAG.getCopyFromReg(
4273       getRoot(), getCurSDLoc(),
4274       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4275 
4276   setValue(&I, L);
4277 }
4278 
4279 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4280   if (I.isAtomic())
4281     return visitAtomicStore(I);
4282 
4283   const Value *SrcV = I.getOperand(0);
4284   const Value *PtrV = I.getOperand(1);
4285 
4286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4287   if (TLI.supportSwiftError()) {
4288     // Swifterror values can come from either a function parameter with
4289     // swifterror attribute or an alloca with swifterror attribute.
4290     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4291       if (Arg->hasSwiftErrorAttr())
4292         return visitStoreToSwiftError(I);
4293     }
4294 
4295     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4296       if (Alloca->isSwiftError())
4297         return visitStoreToSwiftError(I);
4298     }
4299   }
4300 
4301   SmallVector<EVT, 4> ValueVTs, MemVTs;
4302   SmallVector<uint64_t, 4> Offsets;
4303   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4304                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4305   unsigned NumValues = ValueVTs.size();
4306   if (NumValues == 0)
4307     return;
4308 
4309   // Get the lowered operands. Note that we do this after
4310   // checking if NumResults is zero, because with zero results
4311   // the operands won't have values in the map.
4312   SDValue Src = getValue(SrcV);
4313   SDValue Ptr = getValue(PtrV);
4314 
4315   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4316   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4317   SDLoc dl = getCurSDLoc();
4318   Align Alignment = I.getAlign();
4319   AAMDNodes AAInfo = I.getAAMetadata();
4320 
4321   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4322 
4323   // An aggregate load cannot wrap around the address space, so offsets to its
4324   // parts don't wrap either.
4325   SDNodeFlags Flags;
4326   Flags.setNoUnsignedWrap(true);
4327 
4328   unsigned ChainI = 0;
4329   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4330     // See visitLoad comments.
4331     if (ChainI == MaxParallelChains) {
4332       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4333                                   makeArrayRef(Chains.data(), ChainI));
4334       Root = Chain;
4335       ChainI = 0;
4336     }
4337     SDValue Add =
4338         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4339     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4340     if (MemVTs[i] != ValueVTs[i])
4341       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4342     SDValue St =
4343         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4344                      Alignment, MMOFlags, AAInfo);
4345     Chains[ChainI] = St;
4346   }
4347 
4348   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4349                                   makeArrayRef(Chains.data(), ChainI));
4350   setValue(&I, StoreNode);
4351   DAG.setRoot(StoreNode);
4352 }
4353 
4354 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4355                                            bool IsCompressing) {
4356   SDLoc sdl = getCurSDLoc();
4357 
4358   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4359                                MaybeAlign &Alignment) {
4360     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4361     Src0 = I.getArgOperand(0);
4362     Ptr = I.getArgOperand(1);
4363     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4364     Mask = I.getArgOperand(3);
4365   };
4366   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4367                                     MaybeAlign &Alignment) {
4368     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4369     Src0 = I.getArgOperand(0);
4370     Ptr = I.getArgOperand(1);
4371     Mask = I.getArgOperand(2);
4372     Alignment = std::nullopt;
4373   };
4374 
4375   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4376   MaybeAlign Alignment;
4377   if (IsCompressing)
4378     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4379   else
4380     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4381 
4382   SDValue Ptr = getValue(PtrOperand);
4383   SDValue Src0 = getValue(Src0Operand);
4384   SDValue Mask = getValue(MaskOperand);
4385   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4386 
4387   EVT VT = Src0.getValueType();
4388   if (!Alignment)
4389     Alignment = DAG.getEVTAlign(VT);
4390 
4391   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4392       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4393       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4394   SDValue StoreNode =
4395       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4396                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4397   DAG.setRoot(StoreNode);
4398   setValue(&I, StoreNode);
4399 }
4400 
4401 // Get a uniform base for the Gather/Scatter intrinsic.
4402 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4403 // We try to represent it as a base pointer + vector of indices.
4404 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4405 // The first operand of the GEP may be a single pointer or a vector of pointers
4406 // Example:
4407 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4408 //  or
4409 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4410 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4411 //
4412 // When the first GEP operand is a single pointer - it is the uniform base we
4413 // are looking for. If first operand of the GEP is a splat vector - we
4414 // extract the splat value and use it as a uniform base.
4415 // In all other cases the function returns 'false'.
4416 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4417                            ISD::MemIndexType &IndexType, SDValue &Scale,
4418                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4419                            uint64_t ElemSize) {
4420   SelectionDAG& DAG = SDB->DAG;
4421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4422   const DataLayout &DL = DAG.getDataLayout();
4423 
4424   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4425 
4426   // Handle splat constant pointer.
4427   if (auto *C = dyn_cast<Constant>(Ptr)) {
4428     C = C->getSplatValue();
4429     if (!C)
4430       return false;
4431 
4432     Base = SDB->getValue(C);
4433 
4434     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4435     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4436     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4437     IndexType = ISD::SIGNED_SCALED;
4438     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4439     return true;
4440   }
4441 
4442   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4443   if (!GEP || GEP->getParent() != CurBB)
4444     return false;
4445 
4446   if (GEP->getNumOperands() != 2)
4447     return false;
4448 
4449   const Value *BasePtr = GEP->getPointerOperand();
4450   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4451 
4452   // Make sure the base is scalar and the index is a vector.
4453   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4454     return false;
4455 
4456   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4457 
4458   // Target may not support the required addressing mode.
4459   if (ScaleVal != 1 &&
4460       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4461     return false;
4462 
4463   Base = SDB->getValue(BasePtr);
4464   Index = SDB->getValue(IndexVal);
4465   IndexType = ISD::SIGNED_SCALED;
4466 
4467   Scale =
4468       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4469   return true;
4470 }
4471 
4472 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4473   SDLoc sdl = getCurSDLoc();
4474 
4475   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4476   const Value *Ptr = I.getArgOperand(1);
4477   SDValue Src0 = getValue(I.getArgOperand(0));
4478   SDValue Mask = getValue(I.getArgOperand(3));
4479   EVT VT = Src0.getValueType();
4480   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4481                         ->getMaybeAlignValue()
4482                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4484 
4485   SDValue Base;
4486   SDValue Index;
4487   ISD::MemIndexType IndexType;
4488   SDValue Scale;
4489   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4490                                     I.getParent(), VT.getScalarStoreSize());
4491 
4492   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4493   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4494       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4495       // TODO: Make MachineMemOperands aware of scalable
4496       // vectors.
4497       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4498   if (!UniformBase) {
4499     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4500     Index = getValue(Ptr);
4501     IndexType = ISD::SIGNED_SCALED;
4502     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4503   }
4504 
4505   EVT IdxVT = Index.getValueType();
4506   EVT EltTy = IdxVT.getVectorElementType();
4507   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4508     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4509     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4510   }
4511 
4512   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4513   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4514                                          Ops, MMO, IndexType, false);
4515   DAG.setRoot(Scatter);
4516   setValue(&I, Scatter);
4517 }
4518 
4519 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4520   SDLoc sdl = getCurSDLoc();
4521 
4522   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4523                               MaybeAlign &Alignment) {
4524     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4525     Ptr = I.getArgOperand(0);
4526     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4527     Mask = I.getArgOperand(2);
4528     Src0 = I.getArgOperand(3);
4529   };
4530   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4531                                  MaybeAlign &Alignment) {
4532     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4533     Ptr = I.getArgOperand(0);
4534     Alignment = std::nullopt;
4535     Mask = I.getArgOperand(1);
4536     Src0 = I.getArgOperand(2);
4537   };
4538 
4539   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4540   MaybeAlign Alignment;
4541   if (IsExpanding)
4542     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4543   else
4544     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4545 
4546   SDValue Ptr = getValue(PtrOperand);
4547   SDValue Src0 = getValue(Src0Operand);
4548   SDValue Mask = getValue(MaskOperand);
4549   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4550 
4551   EVT VT = Src0.getValueType();
4552   if (!Alignment)
4553     Alignment = DAG.getEVTAlign(VT);
4554 
4555   AAMDNodes AAInfo = I.getAAMetadata();
4556   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4557 
4558   // Do not serialize masked loads of constant memory with anything.
4559   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4560   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4561 
4562   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4563 
4564   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4565       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4566       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4567 
4568   SDValue Load =
4569       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4570                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4571   if (AddToChain)
4572     PendingLoads.push_back(Load.getValue(1));
4573   setValue(&I, Load);
4574 }
4575 
4576 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4577   SDLoc sdl = getCurSDLoc();
4578 
4579   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4580   const Value *Ptr = I.getArgOperand(0);
4581   SDValue Src0 = getValue(I.getArgOperand(3));
4582   SDValue Mask = getValue(I.getArgOperand(2));
4583 
4584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4585   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4586   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4587                         ->getMaybeAlignValue()
4588                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4589 
4590   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4591 
4592   SDValue Root = DAG.getRoot();
4593   SDValue Base;
4594   SDValue Index;
4595   ISD::MemIndexType IndexType;
4596   SDValue Scale;
4597   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4598                                     I.getParent(), VT.getScalarStoreSize());
4599   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4600   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4601       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4602       // TODO: Make MachineMemOperands aware of scalable
4603       // vectors.
4604       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4605 
4606   if (!UniformBase) {
4607     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4608     Index = getValue(Ptr);
4609     IndexType = ISD::SIGNED_SCALED;
4610     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4611   }
4612 
4613   EVT IdxVT = Index.getValueType();
4614   EVT EltTy = IdxVT.getVectorElementType();
4615   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4616     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4617     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4618   }
4619 
4620   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4621   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4622                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4623 
4624   PendingLoads.push_back(Gather.getValue(1));
4625   setValue(&I, Gather);
4626 }
4627 
4628 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4629   SDLoc dl = getCurSDLoc();
4630   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4631   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4632   SyncScope::ID SSID = I.getSyncScopeID();
4633 
4634   SDValue InChain = getRoot();
4635 
4636   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4637   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4638 
4639   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4640   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4641 
4642   MachineFunction &MF = DAG.getMachineFunction();
4643   MachineMemOperand *MMO = MF.getMachineMemOperand(
4644       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4645       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4646       FailureOrdering);
4647 
4648   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4649                                    dl, MemVT, VTs, InChain,
4650                                    getValue(I.getPointerOperand()),
4651                                    getValue(I.getCompareOperand()),
4652                                    getValue(I.getNewValOperand()), MMO);
4653 
4654   SDValue OutChain = L.getValue(2);
4655 
4656   setValue(&I, L);
4657   DAG.setRoot(OutChain);
4658 }
4659 
4660 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4661   SDLoc dl = getCurSDLoc();
4662   ISD::NodeType NT;
4663   switch (I.getOperation()) {
4664   default: llvm_unreachable("Unknown atomicrmw operation");
4665   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4666   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4667   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4668   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4669   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4670   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4671   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4672   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4673   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4674   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4675   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4676   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4677   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4678   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4679   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4680   }
4681   AtomicOrdering Ordering = I.getOrdering();
4682   SyncScope::ID SSID = I.getSyncScopeID();
4683 
4684   SDValue InChain = getRoot();
4685 
4686   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4688   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4689 
4690   MachineFunction &MF = DAG.getMachineFunction();
4691   MachineMemOperand *MMO = MF.getMachineMemOperand(
4692       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4693       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4694 
4695   SDValue L =
4696     DAG.getAtomic(NT, dl, MemVT, InChain,
4697                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4698                   MMO);
4699 
4700   SDValue OutChain = L.getValue(1);
4701 
4702   setValue(&I, L);
4703   DAG.setRoot(OutChain);
4704 }
4705 
4706 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4707   SDLoc dl = getCurSDLoc();
4708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4709   SDValue Ops[3];
4710   Ops[0] = getRoot();
4711   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4712                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4713   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4714                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4715   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4716   setValue(&I, N);
4717   DAG.setRoot(N);
4718 }
4719 
4720 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4721   SDLoc dl = getCurSDLoc();
4722   AtomicOrdering Order = I.getOrdering();
4723   SyncScope::ID SSID = I.getSyncScopeID();
4724 
4725   SDValue InChain = getRoot();
4726 
4727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4728   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4729   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4730 
4731   if (!TLI.supportsUnalignedAtomics() &&
4732       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4733     report_fatal_error("Cannot generate unaligned atomic load");
4734 
4735   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4736 
4737   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4738       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4739       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4740 
4741   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4742 
4743   SDValue Ptr = getValue(I.getPointerOperand());
4744 
4745   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4746     // TODO: Once this is better exercised by tests, it should be merged with
4747     // the normal path for loads to prevent future divergence.
4748     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4749     if (MemVT != VT)
4750       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4751 
4752     setValue(&I, L);
4753     SDValue OutChain = L.getValue(1);
4754     if (!I.isUnordered())
4755       DAG.setRoot(OutChain);
4756     else
4757       PendingLoads.push_back(OutChain);
4758     return;
4759   }
4760 
4761   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4762                             Ptr, MMO);
4763 
4764   SDValue OutChain = L.getValue(1);
4765   if (MemVT != VT)
4766     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4767 
4768   setValue(&I, L);
4769   DAG.setRoot(OutChain);
4770 }
4771 
4772 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4773   SDLoc dl = getCurSDLoc();
4774 
4775   AtomicOrdering Ordering = I.getOrdering();
4776   SyncScope::ID SSID = I.getSyncScopeID();
4777 
4778   SDValue InChain = getRoot();
4779 
4780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4781   EVT MemVT =
4782       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4783 
4784   if (!TLI.supportsUnalignedAtomics() &&
4785       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4786     report_fatal_error("Cannot generate unaligned atomic store");
4787 
4788   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4789 
4790   MachineFunction &MF = DAG.getMachineFunction();
4791   MachineMemOperand *MMO = MF.getMachineMemOperand(
4792       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4793       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4794 
4795   SDValue Val = getValue(I.getValueOperand());
4796   if (Val.getValueType() != MemVT)
4797     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4798   SDValue Ptr = getValue(I.getPointerOperand());
4799 
4800   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4801     // TODO: Once this is better exercised by tests, it should be merged with
4802     // the normal path for stores to prevent future divergence.
4803     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4804     setValue(&I, S);
4805     DAG.setRoot(S);
4806     return;
4807   }
4808   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4809                                    Ptr, Val, MMO);
4810 
4811   setValue(&I, OutChain);
4812   DAG.setRoot(OutChain);
4813 }
4814 
4815 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4816 /// node.
4817 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4818                                                unsigned Intrinsic) {
4819   // Ignore the callsite's attributes. A specific call site may be marked with
4820   // readnone, but the lowering code will expect the chain based on the
4821   // definition.
4822   const Function *F = I.getCalledFunction();
4823   bool HasChain = !F->doesNotAccessMemory();
4824   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4825 
4826   // Build the operand list.
4827   SmallVector<SDValue, 8> Ops;
4828   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4829     if (OnlyLoad) {
4830       // We don't need to serialize loads against other loads.
4831       Ops.push_back(DAG.getRoot());
4832     } else {
4833       Ops.push_back(getRoot());
4834     }
4835   }
4836 
4837   // Info is set by getTgtMemIntrinsic
4838   TargetLowering::IntrinsicInfo Info;
4839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4840   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4841                                                DAG.getMachineFunction(),
4842                                                Intrinsic);
4843 
4844   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4845   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4846       Info.opc == ISD::INTRINSIC_W_CHAIN)
4847     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4848                                         TLI.getPointerTy(DAG.getDataLayout())));
4849 
4850   // Add all operands of the call to the operand list.
4851   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4852     const Value *Arg = I.getArgOperand(i);
4853     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4854       Ops.push_back(getValue(Arg));
4855       continue;
4856     }
4857 
4858     // Use TargetConstant instead of a regular constant for immarg.
4859     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4860     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4861       assert(CI->getBitWidth() <= 64 &&
4862              "large intrinsic immediates not handled");
4863       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4864     } else {
4865       Ops.push_back(
4866           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4867     }
4868   }
4869 
4870   SmallVector<EVT, 4> ValueVTs;
4871   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4872 
4873   if (HasChain)
4874     ValueVTs.push_back(MVT::Other);
4875 
4876   SDVTList VTs = DAG.getVTList(ValueVTs);
4877 
4878   // Propagate fast-math-flags from IR to node(s).
4879   SDNodeFlags Flags;
4880   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4881     Flags.copyFMF(*FPMO);
4882   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4883 
4884   // Create the node.
4885   SDValue Result;
4886   // In some cases, custom collection of operands from CallInst I may be needed.
4887   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4888   if (IsTgtIntrinsic) {
4889     // This is target intrinsic that touches memory
4890     //
4891     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4892     //       didn't yield anything useful.
4893     MachinePointerInfo MPI;
4894     if (Info.ptrVal)
4895       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4896     else if (Info.fallbackAddressSpace)
4897       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4898     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4899                                      Info.memVT, MPI, Info.align, Info.flags,
4900                                      Info.size, I.getAAMetadata());
4901   } else if (!HasChain) {
4902     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4903   } else if (!I.getType()->isVoidTy()) {
4904     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4905   } else {
4906     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4907   }
4908 
4909   if (HasChain) {
4910     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4911     if (OnlyLoad)
4912       PendingLoads.push_back(Chain);
4913     else
4914       DAG.setRoot(Chain);
4915   }
4916 
4917   if (!I.getType()->isVoidTy()) {
4918     if (!isa<VectorType>(I.getType()))
4919       Result = lowerRangeToAssertZExt(DAG, I, Result);
4920 
4921     MaybeAlign Alignment = I.getRetAlign();
4922     if (!Alignment)
4923       Alignment = F->getAttributes().getRetAlignment();
4924     // Insert `assertalign` node if there's an alignment.
4925     if (InsertAssertAlign && Alignment) {
4926       Result =
4927           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4928     }
4929 
4930     setValue(&I, Result);
4931   }
4932 }
4933 
4934 /// GetSignificand - Get the significand and build it into a floating-point
4935 /// number with exponent of 1:
4936 ///
4937 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4938 ///
4939 /// where Op is the hexadecimal representation of floating point value.
4940 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4941   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4942                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4943   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4944                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4945   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4946 }
4947 
4948 /// GetExponent - Get the exponent:
4949 ///
4950 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4951 ///
4952 /// where Op is the hexadecimal representation of floating point value.
4953 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4954                            const TargetLowering &TLI, const SDLoc &dl) {
4955   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4956                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4957   SDValue t1 = DAG.getNode(
4958       ISD::SRL, dl, MVT::i32, t0,
4959       DAG.getConstant(23, dl,
4960                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4961   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4962                            DAG.getConstant(127, dl, MVT::i32));
4963   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4964 }
4965 
4966 /// getF32Constant - Get 32-bit floating point constant.
4967 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4968                               const SDLoc &dl) {
4969   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4970                            MVT::f32);
4971 }
4972 
4973 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4974                                        SelectionDAG &DAG) {
4975   // TODO: What fast-math-flags should be set on the floating-point nodes?
4976 
4977   //   IntegerPartOfX = ((int32_t)(t0);
4978   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4979 
4980   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4981   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4982   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4983 
4984   //   IntegerPartOfX <<= 23;
4985   IntegerPartOfX =
4986       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4987                   DAG.getConstant(23, dl,
4988                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4989                                       MVT::i32, DAG.getDataLayout())));
4990 
4991   SDValue TwoToFractionalPartOfX;
4992   if (LimitFloatPrecision <= 6) {
4993     // For floating-point precision of 6:
4994     //
4995     //   TwoToFractionalPartOfX =
4996     //     0.997535578f +
4997     //       (0.735607626f + 0.252464424f * x) * x;
4998     //
4999     // error 0.0144103317, which is 6 bits
5000     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5001                              getF32Constant(DAG, 0x3e814304, dl));
5002     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5003                              getF32Constant(DAG, 0x3f3c50c8, dl));
5004     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5005     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5006                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5007   } else if (LimitFloatPrecision <= 12) {
5008     // For floating-point precision of 12:
5009     //
5010     //   TwoToFractionalPartOfX =
5011     //     0.999892986f +
5012     //       (0.696457318f +
5013     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5014     //
5015     // error 0.000107046256, which is 13 to 14 bits
5016     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5017                              getF32Constant(DAG, 0x3da235e3, dl));
5018     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5019                              getF32Constant(DAG, 0x3e65b8f3, dl));
5020     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5021     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5022                              getF32Constant(DAG, 0x3f324b07, dl));
5023     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5024     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5025                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5026   } else { // LimitFloatPrecision <= 18
5027     // For floating-point precision of 18:
5028     //
5029     //   TwoToFractionalPartOfX =
5030     //     0.999999982f +
5031     //       (0.693148872f +
5032     //         (0.240227044f +
5033     //           (0.554906021e-1f +
5034     //             (0.961591928e-2f +
5035     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5036     // error 2.47208000*10^(-7), which is better than 18 bits
5037     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5038                              getF32Constant(DAG, 0x3924b03e, dl));
5039     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5040                              getF32Constant(DAG, 0x3ab24b87, dl));
5041     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5042     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5043                              getF32Constant(DAG, 0x3c1d8c17, dl));
5044     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5045     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5046                              getF32Constant(DAG, 0x3d634a1d, dl));
5047     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5048     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5049                              getF32Constant(DAG, 0x3e75fe14, dl));
5050     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5051     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5052                               getF32Constant(DAG, 0x3f317234, dl));
5053     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5054     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5055                                          getF32Constant(DAG, 0x3f800000, dl));
5056   }
5057 
5058   // Add the exponent into the result in integer domain.
5059   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5060   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5061                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5062 }
5063 
5064 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5065 /// limited-precision mode.
5066 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5067                          const TargetLowering &TLI, SDNodeFlags Flags) {
5068   if (Op.getValueType() == MVT::f32 &&
5069       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5070 
5071     // Put the exponent in the right bit position for later addition to the
5072     // final result:
5073     //
5074     // t0 = Op * log2(e)
5075 
5076     // TODO: What fast-math-flags should be set here?
5077     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5078                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5079     return getLimitedPrecisionExp2(t0, dl, DAG);
5080   }
5081 
5082   // No special expansion.
5083   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5084 }
5085 
5086 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5087 /// limited-precision mode.
5088 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5089                          const TargetLowering &TLI, SDNodeFlags Flags) {
5090   // TODO: What fast-math-flags should be set on the floating-point nodes?
5091 
5092   if (Op.getValueType() == MVT::f32 &&
5093       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5094     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5095 
5096     // Scale the exponent by log(2).
5097     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5098     SDValue LogOfExponent =
5099         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5100                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5101 
5102     // Get the significand and build it into a floating-point number with
5103     // exponent of 1.
5104     SDValue X = GetSignificand(DAG, Op1, dl);
5105 
5106     SDValue LogOfMantissa;
5107     if (LimitFloatPrecision <= 6) {
5108       // For floating-point precision of 6:
5109       //
5110       //   LogofMantissa =
5111       //     -1.1609546f +
5112       //       (1.4034025f - 0.23903021f * x) * x;
5113       //
5114       // error 0.0034276066, which is better than 8 bits
5115       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5116                                getF32Constant(DAG, 0xbe74c456, dl));
5117       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5118                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5119       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5120       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5121                                   getF32Constant(DAG, 0x3f949a29, dl));
5122     } else if (LimitFloatPrecision <= 12) {
5123       // For floating-point precision of 12:
5124       //
5125       //   LogOfMantissa =
5126       //     -1.7417939f +
5127       //       (2.8212026f +
5128       //         (-1.4699568f +
5129       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5130       //
5131       // error 0.000061011436, which is 14 bits
5132       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5133                                getF32Constant(DAG, 0xbd67b6d6, dl));
5134       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5135                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5136       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5137       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5138                                getF32Constant(DAG, 0x3fbc278b, dl));
5139       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5140       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5141                                getF32Constant(DAG, 0x40348e95, dl));
5142       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5143       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5144                                   getF32Constant(DAG, 0x3fdef31a, dl));
5145     } else { // LimitFloatPrecision <= 18
5146       // For floating-point precision of 18:
5147       //
5148       //   LogOfMantissa =
5149       //     -2.1072184f +
5150       //       (4.2372794f +
5151       //         (-3.7029485f +
5152       //           (2.2781945f +
5153       //             (-0.87823314f +
5154       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5155       //
5156       // error 0.0000023660568, which is better than 18 bits
5157       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5158                                getF32Constant(DAG, 0xbc91e5ac, dl));
5159       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5160                                getF32Constant(DAG, 0x3e4350aa, dl));
5161       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5162       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5163                                getF32Constant(DAG, 0x3f60d3e3, dl));
5164       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5165       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5166                                getF32Constant(DAG, 0x4011cdf0, dl));
5167       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5168       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5169                                getF32Constant(DAG, 0x406cfd1c, dl));
5170       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5171       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5172                                getF32Constant(DAG, 0x408797cb, dl));
5173       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5174       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5175                                   getF32Constant(DAG, 0x4006dcab, dl));
5176     }
5177 
5178     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5179   }
5180 
5181   // No special expansion.
5182   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5183 }
5184 
5185 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5186 /// limited-precision mode.
5187 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5188                           const TargetLowering &TLI, SDNodeFlags Flags) {
5189   // TODO: What fast-math-flags should be set on the floating-point nodes?
5190 
5191   if (Op.getValueType() == MVT::f32 &&
5192       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5193     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5194 
5195     // Get the exponent.
5196     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5197 
5198     // Get the significand and build it into a floating-point number with
5199     // exponent of 1.
5200     SDValue X = GetSignificand(DAG, Op1, dl);
5201 
5202     // Different possible minimax approximations of significand in
5203     // floating-point for various degrees of accuracy over [1,2].
5204     SDValue Log2ofMantissa;
5205     if (LimitFloatPrecision <= 6) {
5206       // For floating-point precision of 6:
5207       //
5208       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5209       //
5210       // error 0.0049451742, which is more than 7 bits
5211       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5212                                getF32Constant(DAG, 0xbeb08fe0, dl));
5213       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5214                                getF32Constant(DAG, 0x40019463, dl));
5215       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5216       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5217                                    getF32Constant(DAG, 0x3fd6633d, dl));
5218     } else if (LimitFloatPrecision <= 12) {
5219       // For floating-point precision of 12:
5220       //
5221       //   Log2ofMantissa =
5222       //     -2.51285454f +
5223       //       (4.07009056f +
5224       //         (-2.12067489f +
5225       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5226       //
5227       // error 0.0000876136000, which is better than 13 bits
5228       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5229                                getF32Constant(DAG, 0xbda7262e, dl));
5230       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5231                                getF32Constant(DAG, 0x3f25280b, dl));
5232       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5233       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5234                                getF32Constant(DAG, 0x4007b923, dl));
5235       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5236       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5237                                getF32Constant(DAG, 0x40823e2f, dl));
5238       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5239       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5240                                    getF32Constant(DAG, 0x4020d29c, dl));
5241     } else { // LimitFloatPrecision <= 18
5242       // For floating-point precision of 18:
5243       //
5244       //   Log2ofMantissa =
5245       //     -3.0400495f +
5246       //       (6.1129976f +
5247       //         (-5.3420409f +
5248       //           (3.2865683f +
5249       //             (-1.2669343f +
5250       //               (0.27515199f -
5251       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5252       //
5253       // error 0.0000018516, which is better than 18 bits
5254       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5255                                getF32Constant(DAG, 0xbcd2769e, dl));
5256       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5257                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5258       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5259       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5260                                getF32Constant(DAG, 0x3fa22ae7, dl));
5261       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5262       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5263                                getF32Constant(DAG, 0x40525723, dl));
5264       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5265       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5266                                getF32Constant(DAG, 0x40aaf200, dl));
5267       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5268       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5269                                getF32Constant(DAG, 0x40c39dad, dl));
5270       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5271       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5272                                    getF32Constant(DAG, 0x4042902c, dl));
5273     }
5274 
5275     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5276   }
5277 
5278   // No special expansion.
5279   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5280 }
5281 
5282 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5283 /// limited-precision mode.
5284 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5285                            const TargetLowering &TLI, SDNodeFlags Flags) {
5286   // TODO: What fast-math-flags should be set on the floating-point nodes?
5287 
5288   if (Op.getValueType() == MVT::f32 &&
5289       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5290     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5291 
5292     // Scale the exponent by log10(2) [0.30102999f].
5293     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5294     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5295                                         getF32Constant(DAG, 0x3e9a209a, dl));
5296 
5297     // Get the significand and build it into a floating-point number with
5298     // exponent of 1.
5299     SDValue X = GetSignificand(DAG, Op1, dl);
5300 
5301     SDValue Log10ofMantissa;
5302     if (LimitFloatPrecision <= 6) {
5303       // For floating-point precision of 6:
5304       //
5305       //   Log10ofMantissa =
5306       //     -0.50419619f +
5307       //       (0.60948995f - 0.10380950f * x) * x;
5308       //
5309       // error 0.0014886165, which is 6 bits
5310       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5311                                getF32Constant(DAG, 0xbdd49a13, dl));
5312       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5313                                getF32Constant(DAG, 0x3f1c0789, dl));
5314       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5315       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5316                                     getF32Constant(DAG, 0x3f011300, dl));
5317     } else if (LimitFloatPrecision <= 12) {
5318       // For floating-point precision of 12:
5319       //
5320       //   Log10ofMantissa =
5321       //     -0.64831180f +
5322       //       (0.91751397f +
5323       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5324       //
5325       // error 0.00019228036, which is better than 12 bits
5326       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5327                                getF32Constant(DAG, 0x3d431f31, dl));
5328       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5329                                getF32Constant(DAG, 0x3ea21fb2, dl));
5330       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5331       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5332                                getF32Constant(DAG, 0x3f6ae232, dl));
5333       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5334       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5335                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5336     } else { // LimitFloatPrecision <= 18
5337       // For floating-point precision of 18:
5338       //
5339       //   Log10ofMantissa =
5340       //     -0.84299375f +
5341       //       (1.5327582f +
5342       //         (-1.0688956f +
5343       //           (0.49102474f +
5344       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5345       //
5346       // error 0.0000037995730, which is better than 18 bits
5347       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5348                                getF32Constant(DAG, 0x3c5d51ce, dl));
5349       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5350                                getF32Constant(DAG, 0x3e00685a, dl));
5351       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5352       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5353                                getF32Constant(DAG, 0x3efb6798, dl));
5354       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5355       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5356                                getF32Constant(DAG, 0x3f88d192, dl));
5357       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5358       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5359                                getF32Constant(DAG, 0x3fc4316c, dl));
5360       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5361       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5362                                     getF32Constant(DAG, 0x3f57ce70, dl));
5363     }
5364 
5365     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5366   }
5367 
5368   // No special expansion.
5369   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5370 }
5371 
5372 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5373 /// limited-precision mode.
5374 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5375                           const TargetLowering &TLI, SDNodeFlags Flags) {
5376   if (Op.getValueType() == MVT::f32 &&
5377       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5378     return getLimitedPrecisionExp2(Op, dl, DAG);
5379 
5380   // No special expansion.
5381   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5382 }
5383 
5384 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5385 /// limited-precision mode with x == 10.0f.
5386 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5387                          SelectionDAG &DAG, const TargetLowering &TLI,
5388                          SDNodeFlags Flags) {
5389   bool IsExp10 = false;
5390   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5391       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5392     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5393       APFloat Ten(10.0f);
5394       IsExp10 = LHSC->isExactlyValue(Ten);
5395     }
5396   }
5397 
5398   // TODO: What fast-math-flags should be set on the FMUL node?
5399   if (IsExp10) {
5400     // Put the exponent in the right bit position for later addition to the
5401     // final result:
5402     //
5403     //   #define LOG2OF10 3.3219281f
5404     //   t0 = Op * LOG2OF10;
5405     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5406                              getF32Constant(DAG, 0x40549a78, dl));
5407     return getLimitedPrecisionExp2(t0, dl, DAG);
5408   }
5409 
5410   // No special expansion.
5411   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5412 }
5413 
5414 /// ExpandPowI - Expand a llvm.powi intrinsic.
5415 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5416                           SelectionDAG &DAG) {
5417   // If RHS is a constant, we can expand this out to a multiplication tree if
5418   // it's beneficial on the target, otherwise we end up lowering to a call to
5419   // __powidf2 (for example).
5420   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5421     unsigned Val = RHSC->getSExtValue();
5422 
5423     // powi(x, 0) -> 1.0
5424     if (Val == 0)
5425       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5426 
5427     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5428             Val, DAG.shouldOptForSize())) {
5429       // Get the exponent as a positive value.
5430       if ((int)Val < 0)
5431         Val = -Val;
5432       // We use the simple binary decomposition method to generate the multiply
5433       // sequence.  There are more optimal ways to do this (for example,
5434       // powi(x,15) generates one more multiply than it should), but this has
5435       // the benefit of being both really simple and much better than a libcall.
5436       SDValue Res; // Logically starts equal to 1.0
5437       SDValue CurSquare = LHS;
5438       // TODO: Intrinsics should have fast-math-flags that propagate to these
5439       // nodes.
5440       while (Val) {
5441         if (Val & 1) {
5442           if (Res.getNode())
5443             Res =
5444                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5445           else
5446             Res = CurSquare; // 1.0*CurSquare.
5447         }
5448 
5449         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5450                                 CurSquare, CurSquare);
5451         Val >>= 1;
5452       }
5453 
5454       // If the original was negative, invert the result, producing 1/(x*x*x).
5455       if (RHSC->getSExtValue() < 0)
5456         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5457                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5458       return Res;
5459     }
5460   }
5461 
5462   // Otherwise, expand to a libcall.
5463   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5464 }
5465 
5466 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5467                             SDValue LHS, SDValue RHS, SDValue Scale,
5468                             SelectionDAG &DAG, const TargetLowering &TLI) {
5469   EVT VT = LHS.getValueType();
5470   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5471   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5472   LLVMContext &Ctx = *DAG.getContext();
5473 
5474   // If the type is legal but the operation isn't, this node might survive all
5475   // the way to operation legalization. If we end up there and we do not have
5476   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5477   // node.
5478 
5479   // Coax the legalizer into expanding the node during type legalization instead
5480   // by bumping the size by one bit. This will force it to Promote, enabling the
5481   // early expansion and avoiding the need to expand later.
5482 
5483   // We don't have to do this if Scale is 0; that can always be expanded, unless
5484   // it's a saturating signed operation. Those can experience true integer
5485   // division overflow, a case which we must avoid.
5486 
5487   // FIXME: We wouldn't have to do this (or any of the early
5488   // expansion/promotion) if it was possible to expand a libcall of an
5489   // illegal type during operation legalization. But it's not, so things
5490   // get a bit hacky.
5491   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5492   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5493       (TLI.isTypeLegal(VT) ||
5494        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5495     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5496         Opcode, VT, ScaleInt);
5497     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5498       EVT PromVT;
5499       if (VT.isScalarInteger())
5500         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5501       else if (VT.isVector()) {
5502         PromVT = VT.getVectorElementType();
5503         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5504         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5505       } else
5506         llvm_unreachable("Wrong VT for DIVFIX?");
5507       if (Signed) {
5508         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5509         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5510       } else {
5511         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5512         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5513       }
5514       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5515       // For saturating operations, we need to shift up the LHS to get the
5516       // proper saturation width, and then shift down again afterwards.
5517       if (Saturating)
5518         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5519                           DAG.getConstant(1, DL, ShiftTy));
5520       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5521       if (Saturating)
5522         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5523                           DAG.getConstant(1, DL, ShiftTy));
5524       return DAG.getZExtOrTrunc(Res, DL, VT);
5525     }
5526   }
5527 
5528   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5529 }
5530 
5531 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5532 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5533 static void
5534 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5535                      const SDValue &N) {
5536   switch (N.getOpcode()) {
5537   case ISD::CopyFromReg: {
5538     SDValue Op = N.getOperand(1);
5539     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5540                       Op.getValueType().getSizeInBits());
5541     return;
5542   }
5543   case ISD::BITCAST:
5544   case ISD::AssertZext:
5545   case ISD::AssertSext:
5546   case ISD::TRUNCATE:
5547     getUnderlyingArgRegs(Regs, N.getOperand(0));
5548     return;
5549   case ISD::BUILD_PAIR:
5550   case ISD::BUILD_VECTOR:
5551   case ISD::CONCAT_VECTORS:
5552     for (SDValue Op : N->op_values())
5553       getUnderlyingArgRegs(Regs, Op);
5554     return;
5555   default:
5556     return;
5557   }
5558 }
5559 
5560 /// If the DbgValueInst is a dbg_value of a function argument, create the
5561 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5562 /// instruction selection, they will be inserted to the entry BB.
5563 /// We don't currently support this for variadic dbg_values, as they shouldn't
5564 /// appear for function arguments or in the prologue.
5565 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5566     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5567     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5568   const Argument *Arg = dyn_cast<Argument>(V);
5569   if (!Arg)
5570     return false;
5571 
5572   MachineFunction &MF = DAG.getMachineFunction();
5573   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5574 
5575   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5576   // we've been asked to pursue.
5577   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5578                               bool Indirect) {
5579     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5580       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5581       // pointing at the VReg, which will be patched up later.
5582       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5583       auto MIB = BuildMI(MF, DL, Inst);
5584       MIB.addReg(Reg);
5585       MIB.addImm(0);
5586       MIB.addMetadata(Variable);
5587       auto *NewDIExpr = FragExpr;
5588       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5589       // the DIExpression.
5590       if (Indirect)
5591         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5592       MIB.addMetadata(NewDIExpr);
5593       return MIB;
5594     } else {
5595       // Create a completely standard DBG_VALUE.
5596       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5597       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5598     }
5599   };
5600 
5601   if (Kind == FuncArgumentDbgValueKind::Value) {
5602     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5603     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5604     // the entry block.
5605     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5606     if (!IsInEntryBlock)
5607       return false;
5608 
5609     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5610     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5611     // variable that also is a param.
5612     //
5613     // Although, if we are at the top of the entry block already, we can still
5614     // emit using ArgDbgValue. This might catch some situations when the
5615     // dbg.value refers to an argument that isn't used in the entry block, so
5616     // any CopyToReg node would be optimized out and the only way to express
5617     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5618     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5619     // we should only emit as ArgDbgValue if the Variable is an argument to the
5620     // current function, and the dbg.value intrinsic is found in the entry
5621     // block.
5622     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5623         !DL->getInlinedAt();
5624     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5625     if (!IsInPrologue && !VariableIsFunctionInputArg)
5626       return false;
5627 
5628     // Here we assume that a function argument on IR level only can be used to
5629     // describe one input parameter on source level. If we for example have
5630     // source code like this
5631     //
5632     //    struct A { long x, y; };
5633     //    void foo(struct A a, long b) {
5634     //      ...
5635     //      b = a.x;
5636     //      ...
5637     //    }
5638     //
5639     // and IR like this
5640     //
5641     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5642     //  entry:
5643     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5644     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5645     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5646     //    ...
5647     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5648     //    ...
5649     //
5650     // then the last dbg.value is describing a parameter "b" using a value that
5651     // is an argument. But since we already has used %a1 to describe a parameter
5652     // we should not handle that last dbg.value here (that would result in an
5653     // incorrect hoisting of the DBG_VALUE to the function entry).
5654     // Notice that we allow one dbg.value per IR level argument, to accommodate
5655     // for the situation with fragments above.
5656     if (VariableIsFunctionInputArg) {
5657       unsigned ArgNo = Arg->getArgNo();
5658       if (ArgNo >= FuncInfo.DescribedArgs.size())
5659         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5660       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5661         return false;
5662       FuncInfo.DescribedArgs.set(ArgNo);
5663     }
5664   }
5665 
5666   bool IsIndirect = false;
5667   std::optional<MachineOperand> Op;
5668   // Some arguments' frame index is recorded during argument lowering.
5669   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5670   if (FI != std::numeric_limits<int>::max())
5671     Op = MachineOperand::CreateFI(FI);
5672 
5673   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5674   if (!Op && N.getNode()) {
5675     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5676     Register Reg;
5677     if (ArgRegsAndSizes.size() == 1)
5678       Reg = ArgRegsAndSizes.front().first;
5679 
5680     if (Reg && Reg.isVirtual()) {
5681       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5682       Register PR = RegInfo.getLiveInPhysReg(Reg);
5683       if (PR)
5684         Reg = PR;
5685     }
5686     if (Reg) {
5687       Op = MachineOperand::CreateReg(Reg, false);
5688       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5689     }
5690   }
5691 
5692   if (!Op && N.getNode()) {
5693     // Check if frame index is available.
5694     SDValue LCandidate = peekThroughBitcasts(N);
5695     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5696       if (FrameIndexSDNode *FINode =
5697           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5698         Op = MachineOperand::CreateFI(FINode->getIndex());
5699   }
5700 
5701   if (!Op) {
5702     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5703     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5704                                          SplitRegs) {
5705       unsigned Offset = 0;
5706       for (const auto &RegAndSize : SplitRegs) {
5707         // If the expression is already a fragment, the current register
5708         // offset+size might extend beyond the fragment. In this case, only
5709         // the register bits that are inside the fragment are relevant.
5710         int RegFragmentSizeInBits = RegAndSize.second;
5711         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5712           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5713           // The register is entirely outside the expression fragment,
5714           // so is irrelevant for debug info.
5715           if (Offset >= ExprFragmentSizeInBits)
5716             break;
5717           // The register is partially outside the expression fragment, only
5718           // the low bits within the fragment are relevant for debug info.
5719           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5720             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5721           }
5722         }
5723 
5724         auto FragmentExpr = DIExpression::createFragmentExpression(
5725             Expr, Offset, RegFragmentSizeInBits);
5726         Offset += RegAndSize.second;
5727         // If a valid fragment expression cannot be created, the variable's
5728         // correct value cannot be determined and so it is set as Undef.
5729         if (!FragmentExpr) {
5730           SDDbgValue *SDV = DAG.getConstantDbgValue(
5731               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5732           DAG.AddDbgValue(SDV, false);
5733           continue;
5734         }
5735         MachineInstr *NewMI =
5736             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5737                              Kind != FuncArgumentDbgValueKind::Value);
5738         FuncInfo.ArgDbgValues.push_back(NewMI);
5739       }
5740     };
5741 
5742     // Check if ValueMap has reg number.
5743     DenseMap<const Value *, Register>::const_iterator
5744       VMI = FuncInfo.ValueMap.find(V);
5745     if (VMI != FuncInfo.ValueMap.end()) {
5746       const auto &TLI = DAG.getTargetLoweringInfo();
5747       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5748                        V->getType(), std::nullopt);
5749       if (RFV.occupiesMultipleRegs()) {
5750         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5751         return true;
5752       }
5753 
5754       Op = MachineOperand::CreateReg(VMI->second, false);
5755       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5756     } else if (ArgRegsAndSizes.size() > 1) {
5757       // This was split due to the calling convention, and no virtual register
5758       // mapping exists for the value.
5759       splitMultiRegDbgValue(ArgRegsAndSizes);
5760       return true;
5761     }
5762   }
5763 
5764   if (!Op)
5765     return false;
5766 
5767   assert(Variable->isValidLocationForIntrinsic(DL) &&
5768          "Expected inlined-at fields to agree");
5769   MachineInstr *NewMI = nullptr;
5770 
5771   if (Op->isReg())
5772     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5773   else
5774     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5775                     Variable, Expr);
5776 
5777   // Otherwise, use ArgDbgValues.
5778   FuncInfo.ArgDbgValues.push_back(NewMI);
5779   return true;
5780 }
5781 
5782 /// Return the appropriate SDDbgValue based on N.
5783 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5784                                              DILocalVariable *Variable,
5785                                              DIExpression *Expr,
5786                                              const DebugLoc &dl,
5787                                              unsigned DbgSDNodeOrder) {
5788   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5789     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5790     // stack slot locations.
5791     //
5792     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5793     // debug values here after optimization:
5794     //
5795     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5796     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5797     //
5798     // Both describe the direct values of their associated variables.
5799     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5800                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5801   }
5802   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5803                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5804 }
5805 
5806 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5807   switch (Intrinsic) {
5808   case Intrinsic::smul_fix:
5809     return ISD::SMULFIX;
5810   case Intrinsic::umul_fix:
5811     return ISD::UMULFIX;
5812   case Intrinsic::smul_fix_sat:
5813     return ISD::SMULFIXSAT;
5814   case Intrinsic::umul_fix_sat:
5815     return ISD::UMULFIXSAT;
5816   case Intrinsic::sdiv_fix:
5817     return ISD::SDIVFIX;
5818   case Intrinsic::udiv_fix:
5819     return ISD::UDIVFIX;
5820   case Intrinsic::sdiv_fix_sat:
5821     return ISD::SDIVFIXSAT;
5822   case Intrinsic::udiv_fix_sat:
5823     return ISD::UDIVFIXSAT;
5824   default:
5825     llvm_unreachable("Unhandled fixed point intrinsic");
5826   }
5827 }
5828 
5829 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5830                                            const char *FunctionName) {
5831   assert(FunctionName && "FunctionName must not be nullptr");
5832   SDValue Callee = DAG.getExternalSymbol(
5833       FunctionName,
5834       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5835   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5836 }
5837 
5838 /// Given a @llvm.call.preallocated.setup, return the corresponding
5839 /// preallocated call.
5840 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5841   assert(cast<CallBase>(PreallocatedSetup)
5842                  ->getCalledFunction()
5843                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5844          "expected call_preallocated_setup Value");
5845   for (const auto *U : PreallocatedSetup->users()) {
5846     auto *UseCall = cast<CallBase>(U);
5847     const Function *Fn = UseCall->getCalledFunction();
5848     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5849       return UseCall;
5850     }
5851   }
5852   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5853 }
5854 
5855 /// Lower the call to the specified intrinsic function.
5856 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5857                                              unsigned Intrinsic) {
5858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5859   SDLoc sdl = getCurSDLoc();
5860   DebugLoc dl = getCurDebugLoc();
5861   SDValue Res;
5862 
5863   SDNodeFlags Flags;
5864   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5865     Flags.copyFMF(*FPOp);
5866 
5867   switch (Intrinsic) {
5868   default:
5869     // By default, turn this into a target intrinsic node.
5870     visitTargetIntrinsic(I, Intrinsic);
5871     return;
5872   case Intrinsic::vscale: {
5873     match(&I, m_VScale(DAG.getDataLayout()));
5874     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5875     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5876     return;
5877   }
5878   case Intrinsic::vastart:  visitVAStart(I); return;
5879   case Intrinsic::vaend:    visitVAEnd(I); return;
5880   case Intrinsic::vacopy:   visitVACopy(I); return;
5881   case Intrinsic::returnaddress:
5882     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5883                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5884                              getValue(I.getArgOperand(0))));
5885     return;
5886   case Intrinsic::addressofreturnaddress:
5887     setValue(&I,
5888              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5889                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5890     return;
5891   case Intrinsic::sponentry:
5892     setValue(&I,
5893              DAG.getNode(ISD::SPONENTRY, sdl,
5894                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5895     return;
5896   case Intrinsic::frameaddress:
5897     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5898                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5899                              getValue(I.getArgOperand(0))));
5900     return;
5901   case Intrinsic::read_volatile_register:
5902   case Intrinsic::read_register: {
5903     Value *Reg = I.getArgOperand(0);
5904     SDValue Chain = getRoot();
5905     SDValue RegName =
5906         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5907     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5908     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5909       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5910     setValue(&I, Res);
5911     DAG.setRoot(Res.getValue(1));
5912     return;
5913   }
5914   case Intrinsic::write_register: {
5915     Value *Reg = I.getArgOperand(0);
5916     Value *RegValue = I.getArgOperand(1);
5917     SDValue Chain = getRoot();
5918     SDValue RegName =
5919         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5920     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5921                             RegName, getValue(RegValue)));
5922     return;
5923   }
5924   case Intrinsic::memcpy: {
5925     const auto &MCI = cast<MemCpyInst>(I);
5926     SDValue Op1 = getValue(I.getArgOperand(0));
5927     SDValue Op2 = getValue(I.getArgOperand(1));
5928     SDValue Op3 = getValue(I.getArgOperand(2));
5929     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5930     Align DstAlign = MCI.getDestAlign().valueOrOne();
5931     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5932     Align Alignment = std::min(DstAlign, SrcAlign);
5933     bool isVol = MCI.isVolatile();
5934     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5935     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5936     // node.
5937     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5938     SDValue MC = DAG.getMemcpy(
5939         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5940         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5941         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5942     updateDAGForMaybeTailCall(MC);
5943     return;
5944   }
5945   case Intrinsic::memcpy_inline: {
5946     const auto &MCI = cast<MemCpyInlineInst>(I);
5947     SDValue Dst = getValue(I.getArgOperand(0));
5948     SDValue Src = getValue(I.getArgOperand(1));
5949     SDValue Size = getValue(I.getArgOperand(2));
5950     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5951     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5952     Align DstAlign = MCI.getDestAlign().valueOrOne();
5953     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5954     Align Alignment = std::min(DstAlign, SrcAlign);
5955     bool isVol = MCI.isVolatile();
5956     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5957     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5958     // node.
5959     SDValue MC = DAG.getMemcpy(
5960         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5961         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5962         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5963     updateDAGForMaybeTailCall(MC);
5964     return;
5965   }
5966   case Intrinsic::memset: {
5967     const auto &MSI = cast<MemSetInst>(I);
5968     SDValue Op1 = getValue(I.getArgOperand(0));
5969     SDValue Op2 = getValue(I.getArgOperand(1));
5970     SDValue Op3 = getValue(I.getArgOperand(2));
5971     // @llvm.memset defines 0 and 1 to both mean no alignment.
5972     Align Alignment = MSI.getDestAlign().valueOrOne();
5973     bool isVol = MSI.isVolatile();
5974     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5975     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5976     SDValue MS = DAG.getMemset(
5977         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5978         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5979     updateDAGForMaybeTailCall(MS);
5980     return;
5981   }
5982   case Intrinsic::memset_inline: {
5983     const auto &MSII = cast<MemSetInlineInst>(I);
5984     SDValue Dst = getValue(I.getArgOperand(0));
5985     SDValue Value = getValue(I.getArgOperand(1));
5986     SDValue Size = getValue(I.getArgOperand(2));
5987     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5988     // @llvm.memset defines 0 and 1 to both mean no alignment.
5989     Align DstAlign = MSII.getDestAlign().valueOrOne();
5990     bool isVol = MSII.isVolatile();
5991     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5992     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5993     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5994                                /* AlwaysInline */ true, isTC,
5995                                MachinePointerInfo(I.getArgOperand(0)),
5996                                I.getAAMetadata());
5997     updateDAGForMaybeTailCall(MC);
5998     return;
5999   }
6000   case Intrinsic::memmove: {
6001     const auto &MMI = cast<MemMoveInst>(I);
6002     SDValue Op1 = getValue(I.getArgOperand(0));
6003     SDValue Op2 = getValue(I.getArgOperand(1));
6004     SDValue Op3 = getValue(I.getArgOperand(2));
6005     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6006     Align DstAlign = MMI.getDestAlign().valueOrOne();
6007     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6008     Align Alignment = std::min(DstAlign, SrcAlign);
6009     bool isVol = MMI.isVolatile();
6010     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6011     // FIXME: Support passing different dest/src alignments to the memmove DAG
6012     // node.
6013     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6014     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6015                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6016                                 MachinePointerInfo(I.getArgOperand(1)),
6017                                 I.getAAMetadata(), AA);
6018     updateDAGForMaybeTailCall(MM);
6019     return;
6020   }
6021   case Intrinsic::memcpy_element_unordered_atomic: {
6022     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6023     SDValue Dst = getValue(MI.getRawDest());
6024     SDValue Src = getValue(MI.getRawSource());
6025     SDValue Length = getValue(MI.getLength());
6026 
6027     Type *LengthTy = MI.getLength()->getType();
6028     unsigned ElemSz = MI.getElementSizeInBytes();
6029     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6030     SDValue MC =
6031         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6032                             isTC, MachinePointerInfo(MI.getRawDest()),
6033                             MachinePointerInfo(MI.getRawSource()));
6034     updateDAGForMaybeTailCall(MC);
6035     return;
6036   }
6037   case Intrinsic::memmove_element_unordered_atomic: {
6038     auto &MI = cast<AtomicMemMoveInst>(I);
6039     SDValue Dst = getValue(MI.getRawDest());
6040     SDValue Src = getValue(MI.getRawSource());
6041     SDValue Length = getValue(MI.getLength());
6042 
6043     Type *LengthTy = MI.getLength()->getType();
6044     unsigned ElemSz = MI.getElementSizeInBytes();
6045     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6046     SDValue MC =
6047         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6048                              isTC, MachinePointerInfo(MI.getRawDest()),
6049                              MachinePointerInfo(MI.getRawSource()));
6050     updateDAGForMaybeTailCall(MC);
6051     return;
6052   }
6053   case Intrinsic::memset_element_unordered_atomic: {
6054     auto &MI = cast<AtomicMemSetInst>(I);
6055     SDValue Dst = getValue(MI.getRawDest());
6056     SDValue Val = getValue(MI.getValue());
6057     SDValue Length = getValue(MI.getLength());
6058 
6059     Type *LengthTy = MI.getLength()->getType();
6060     unsigned ElemSz = MI.getElementSizeInBytes();
6061     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6062     SDValue MC =
6063         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6064                             isTC, MachinePointerInfo(MI.getRawDest()));
6065     updateDAGForMaybeTailCall(MC);
6066     return;
6067   }
6068   case Intrinsic::call_preallocated_setup: {
6069     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6070     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6071     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6072                               getRoot(), SrcValue);
6073     setValue(&I, Res);
6074     DAG.setRoot(Res);
6075     return;
6076   }
6077   case Intrinsic::call_preallocated_arg: {
6078     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6079     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6080     SDValue Ops[3];
6081     Ops[0] = getRoot();
6082     Ops[1] = SrcValue;
6083     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6084                                    MVT::i32); // arg index
6085     SDValue Res = DAG.getNode(
6086         ISD::PREALLOCATED_ARG, sdl,
6087         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6088     setValue(&I, Res);
6089     DAG.setRoot(Res.getValue(1));
6090     return;
6091   }
6092   case Intrinsic::dbg_addr:
6093   case Intrinsic::dbg_declare: {
6094     // Debug intrinsics are handled seperately in assignment tracking mode.
6095     if (getEnableAssignmentTracking())
6096       return;
6097     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6098     // they are non-variadic.
6099     const auto &DI = cast<DbgVariableIntrinsic>(I);
6100     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6101     DILocalVariable *Variable = DI.getVariable();
6102     DIExpression *Expression = DI.getExpression();
6103     dropDanglingDebugInfo(Variable, Expression);
6104     assert(Variable && "Missing variable");
6105     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6106                       << "\n");
6107     // Check if address has undef value.
6108     const Value *Address = DI.getVariableLocationOp(0);
6109     if (!Address || isa<UndefValue>(Address) ||
6110         (Address->use_empty() && !isa<Argument>(Address))) {
6111       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6112                         << " (bad/undef/unused-arg address)\n");
6113       return;
6114     }
6115 
6116     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6117 
6118     // Check if this variable can be described by a frame index, typically
6119     // either as a static alloca or a byval parameter.
6120     int FI = std::numeric_limits<int>::max();
6121     if (const auto *AI =
6122             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6123       if (AI->isStaticAlloca()) {
6124         auto I = FuncInfo.StaticAllocaMap.find(AI);
6125         if (I != FuncInfo.StaticAllocaMap.end())
6126           FI = I->second;
6127       }
6128     } else if (const auto *Arg = dyn_cast<Argument>(
6129                    Address->stripInBoundsConstantOffsets())) {
6130       FI = FuncInfo.getArgumentFrameIndex(Arg);
6131     }
6132 
6133     // llvm.dbg.addr is control dependent and always generates indirect
6134     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6135     // the MachineFunction variable table.
6136     if (FI != std::numeric_limits<int>::max()) {
6137       if (Intrinsic == Intrinsic::dbg_addr) {
6138         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6139             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6140             dl, SDNodeOrder);
6141         DAG.AddDbgValue(SDV, isParameter);
6142       } else {
6143         LLVM_DEBUG(dbgs() << "Skipping " << DI
6144                           << " (variable info stashed in MF side table)\n");
6145       }
6146       return;
6147     }
6148 
6149     SDValue &N = NodeMap[Address];
6150     if (!N.getNode() && isa<Argument>(Address))
6151       // Check unused arguments map.
6152       N = UnusedArgNodeMap[Address];
6153     SDDbgValue *SDV;
6154     if (N.getNode()) {
6155       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6156         Address = BCI->getOperand(0);
6157       // Parameters are handled specially.
6158       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6159       if (isParameter && FINode) {
6160         // Byval parameter. We have a frame index at this point.
6161         SDV =
6162             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6163                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6164       } else if (isa<Argument>(Address)) {
6165         // Address is an argument, so try to emit its dbg value using
6166         // virtual register info from the FuncInfo.ValueMap.
6167         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6168                                  FuncArgumentDbgValueKind::Declare, N);
6169         return;
6170       } else {
6171         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6172                               true, dl, SDNodeOrder);
6173       }
6174       DAG.AddDbgValue(SDV, isParameter);
6175     } else {
6176       // If Address is an argument then try to emit its dbg value using
6177       // virtual register info from the FuncInfo.ValueMap.
6178       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6179                                     FuncArgumentDbgValueKind::Declare, N)) {
6180         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6181                           << " (could not emit func-arg dbg_value)\n");
6182       }
6183     }
6184     return;
6185   }
6186   case Intrinsic::dbg_label: {
6187     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6188     DILabel *Label = DI.getLabel();
6189     assert(Label && "Missing label");
6190 
6191     SDDbgLabel *SDV;
6192     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6193     DAG.AddDbgLabel(SDV);
6194     return;
6195   }
6196   case Intrinsic::dbg_assign: {
6197     // Debug intrinsics are handled seperately in assignment tracking mode.
6198     assert(getEnableAssignmentTracking() &&
6199            "expected assignment tracking to be enabled");
6200     return;
6201   }
6202   case Intrinsic::dbg_value: {
6203     // Debug intrinsics are handled seperately in assignment tracking mode.
6204     if (getEnableAssignmentTracking())
6205       return;
6206     const DbgValueInst &DI = cast<DbgValueInst>(I);
6207     assert(DI.getVariable() && "Missing variable");
6208 
6209     DILocalVariable *Variable = DI.getVariable();
6210     DIExpression *Expression = DI.getExpression();
6211     dropDanglingDebugInfo(Variable, Expression);
6212     SmallVector<Value *, 4> Values(DI.getValues());
6213     if (Values.empty())
6214       return;
6215 
6216     if (llvm::is_contained(Values, nullptr))
6217       return;
6218 
6219     bool IsVariadic = DI.hasArgList();
6220     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6221                           SDNodeOrder, IsVariadic))
6222       addDanglingDebugInfo(&DI, SDNodeOrder);
6223     return;
6224   }
6225 
6226   case Intrinsic::eh_typeid_for: {
6227     // Find the type id for the given typeinfo.
6228     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6229     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6230     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6231     setValue(&I, Res);
6232     return;
6233   }
6234 
6235   case Intrinsic::eh_return_i32:
6236   case Intrinsic::eh_return_i64:
6237     DAG.getMachineFunction().setCallsEHReturn(true);
6238     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6239                             MVT::Other,
6240                             getControlRoot(),
6241                             getValue(I.getArgOperand(0)),
6242                             getValue(I.getArgOperand(1))));
6243     return;
6244   case Intrinsic::eh_unwind_init:
6245     DAG.getMachineFunction().setCallsUnwindInit(true);
6246     return;
6247   case Intrinsic::eh_dwarf_cfa:
6248     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6249                              TLI.getPointerTy(DAG.getDataLayout()),
6250                              getValue(I.getArgOperand(0))));
6251     return;
6252   case Intrinsic::eh_sjlj_callsite: {
6253     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6254     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6255     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6256 
6257     MMI.setCurrentCallSite(CI->getZExtValue());
6258     return;
6259   }
6260   case Intrinsic::eh_sjlj_functioncontext: {
6261     // Get and store the index of the function context.
6262     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6263     AllocaInst *FnCtx =
6264       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6265     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6266     MFI.setFunctionContextIndex(FI);
6267     return;
6268   }
6269   case Intrinsic::eh_sjlj_setjmp: {
6270     SDValue Ops[2];
6271     Ops[0] = getRoot();
6272     Ops[1] = getValue(I.getArgOperand(0));
6273     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6274                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6275     setValue(&I, Op.getValue(0));
6276     DAG.setRoot(Op.getValue(1));
6277     return;
6278   }
6279   case Intrinsic::eh_sjlj_longjmp:
6280     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6281                             getRoot(), getValue(I.getArgOperand(0))));
6282     return;
6283   case Intrinsic::eh_sjlj_setup_dispatch:
6284     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6285                             getRoot()));
6286     return;
6287   case Intrinsic::masked_gather:
6288     visitMaskedGather(I);
6289     return;
6290   case Intrinsic::masked_load:
6291     visitMaskedLoad(I);
6292     return;
6293   case Intrinsic::masked_scatter:
6294     visitMaskedScatter(I);
6295     return;
6296   case Intrinsic::masked_store:
6297     visitMaskedStore(I);
6298     return;
6299   case Intrinsic::masked_expandload:
6300     visitMaskedLoad(I, true /* IsExpanding */);
6301     return;
6302   case Intrinsic::masked_compressstore:
6303     visitMaskedStore(I, true /* IsCompressing */);
6304     return;
6305   case Intrinsic::powi:
6306     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6307                             getValue(I.getArgOperand(1)), DAG));
6308     return;
6309   case Intrinsic::log:
6310     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6311     return;
6312   case Intrinsic::log2:
6313     setValue(&I,
6314              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6315     return;
6316   case Intrinsic::log10:
6317     setValue(&I,
6318              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6319     return;
6320   case Intrinsic::exp:
6321     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6322     return;
6323   case Intrinsic::exp2:
6324     setValue(&I,
6325              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6326     return;
6327   case Intrinsic::pow:
6328     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6329                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6330     return;
6331   case Intrinsic::sqrt:
6332   case Intrinsic::fabs:
6333   case Intrinsic::sin:
6334   case Intrinsic::cos:
6335   case Intrinsic::floor:
6336   case Intrinsic::ceil:
6337   case Intrinsic::trunc:
6338   case Intrinsic::rint:
6339   case Intrinsic::nearbyint:
6340   case Intrinsic::round:
6341   case Intrinsic::roundeven:
6342   case Intrinsic::canonicalize: {
6343     unsigned Opcode;
6344     switch (Intrinsic) {
6345     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6346     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6347     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6348     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6349     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6350     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6351     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6352     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6353     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6354     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6355     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6356     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6357     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6358     }
6359 
6360     setValue(&I, DAG.getNode(Opcode, sdl,
6361                              getValue(I.getArgOperand(0)).getValueType(),
6362                              getValue(I.getArgOperand(0)), Flags));
6363     return;
6364   }
6365   case Intrinsic::lround:
6366   case Intrinsic::llround:
6367   case Intrinsic::lrint:
6368   case Intrinsic::llrint: {
6369     unsigned Opcode;
6370     switch (Intrinsic) {
6371     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6372     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6373     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6374     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6375     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6376     }
6377 
6378     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6379     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6380                              getValue(I.getArgOperand(0))));
6381     return;
6382   }
6383   case Intrinsic::minnum:
6384     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6385                              getValue(I.getArgOperand(0)).getValueType(),
6386                              getValue(I.getArgOperand(0)),
6387                              getValue(I.getArgOperand(1)), Flags));
6388     return;
6389   case Intrinsic::maxnum:
6390     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6391                              getValue(I.getArgOperand(0)).getValueType(),
6392                              getValue(I.getArgOperand(0)),
6393                              getValue(I.getArgOperand(1)), Flags));
6394     return;
6395   case Intrinsic::minimum:
6396     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6397                              getValue(I.getArgOperand(0)).getValueType(),
6398                              getValue(I.getArgOperand(0)),
6399                              getValue(I.getArgOperand(1)), Flags));
6400     return;
6401   case Intrinsic::maximum:
6402     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6403                              getValue(I.getArgOperand(0)).getValueType(),
6404                              getValue(I.getArgOperand(0)),
6405                              getValue(I.getArgOperand(1)), Flags));
6406     return;
6407   case Intrinsic::copysign:
6408     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6409                              getValue(I.getArgOperand(0)).getValueType(),
6410                              getValue(I.getArgOperand(0)),
6411                              getValue(I.getArgOperand(1)), Flags));
6412     return;
6413   case Intrinsic::arithmetic_fence: {
6414     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6415                              getValue(I.getArgOperand(0)).getValueType(),
6416                              getValue(I.getArgOperand(0)), Flags));
6417     return;
6418   }
6419   case Intrinsic::fma:
6420     setValue(&I, DAG.getNode(
6421                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6422                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6423                      getValue(I.getArgOperand(2)), Flags));
6424     return;
6425 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6426   case Intrinsic::INTRINSIC:
6427 #include "llvm/IR/ConstrainedOps.def"
6428     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6429     return;
6430 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6431 #include "llvm/IR/VPIntrinsics.def"
6432     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6433     return;
6434   case Intrinsic::fptrunc_round: {
6435     // Get the last argument, the metadata and convert it to an integer in the
6436     // call
6437     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6438     std::optional<RoundingMode> RoundMode =
6439         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6440 
6441     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6442 
6443     // Propagate fast-math-flags from IR to node(s).
6444     SDNodeFlags Flags;
6445     Flags.copyFMF(*cast<FPMathOperator>(&I));
6446     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6447 
6448     SDValue Result;
6449     Result = DAG.getNode(
6450         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6451         DAG.getTargetConstant((int)*RoundMode, sdl,
6452                               TLI.getPointerTy(DAG.getDataLayout())));
6453     setValue(&I, Result);
6454 
6455     return;
6456   }
6457   case Intrinsic::fmuladd: {
6458     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6459     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6460         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6461       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6462                                getValue(I.getArgOperand(0)).getValueType(),
6463                                getValue(I.getArgOperand(0)),
6464                                getValue(I.getArgOperand(1)),
6465                                getValue(I.getArgOperand(2)), Flags));
6466     } else {
6467       // TODO: Intrinsic calls should have fast-math-flags.
6468       SDValue Mul = DAG.getNode(
6469           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6470           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6471       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6472                                 getValue(I.getArgOperand(0)).getValueType(),
6473                                 Mul, getValue(I.getArgOperand(2)), Flags);
6474       setValue(&I, Add);
6475     }
6476     return;
6477   }
6478   case Intrinsic::convert_to_fp16:
6479     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6480                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6481                                          getValue(I.getArgOperand(0)),
6482                                          DAG.getTargetConstant(0, sdl,
6483                                                                MVT::i32))));
6484     return;
6485   case Intrinsic::convert_from_fp16:
6486     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6487                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6488                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6489                                          getValue(I.getArgOperand(0)))));
6490     return;
6491   case Intrinsic::fptosi_sat: {
6492     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6493     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6494                              getValue(I.getArgOperand(0)),
6495                              DAG.getValueType(VT.getScalarType())));
6496     return;
6497   }
6498   case Intrinsic::fptoui_sat: {
6499     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6500     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6501                              getValue(I.getArgOperand(0)),
6502                              DAG.getValueType(VT.getScalarType())));
6503     return;
6504   }
6505   case Intrinsic::set_rounding:
6506     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6507                       {getRoot(), getValue(I.getArgOperand(0))});
6508     setValue(&I, Res);
6509     DAG.setRoot(Res.getValue(0));
6510     return;
6511   case Intrinsic::is_fpclass: {
6512     const DataLayout DLayout = DAG.getDataLayout();
6513     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6514     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6515     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6516     MachineFunction &MF = DAG.getMachineFunction();
6517     const Function &F = MF.getFunction();
6518     SDValue Op = getValue(I.getArgOperand(0));
6519     SDNodeFlags Flags;
6520     Flags.setNoFPExcept(
6521         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6522     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6523     // expansion can use illegal types. Making expansion early allows
6524     // legalizing these types prior to selection.
6525     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6526       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6527       setValue(&I, Result);
6528       return;
6529     }
6530 
6531     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6532     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6533     setValue(&I, V);
6534     return;
6535   }
6536   case Intrinsic::pcmarker: {
6537     SDValue Tmp = getValue(I.getArgOperand(0));
6538     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6539     return;
6540   }
6541   case Intrinsic::readcyclecounter: {
6542     SDValue Op = getRoot();
6543     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6544                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6545     setValue(&I, Res);
6546     DAG.setRoot(Res.getValue(1));
6547     return;
6548   }
6549   case Intrinsic::bitreverse:
6550     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6551                              getValue(I.getArgOperand(0)).getValueType(),
6552                              getValue(I.getArgOperand(0))));
6553     return;
6554   case Intrinsic::bswap:
6555     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6556                              getValue(I.getArgOperand(0)).getValueType(),
6557                              getValue(I.getArgOperand(0))));
6558     return;
6559   case Intrinsic::cttz: {
6560     SDValue Arg = getValue(I.getArgOperand(0));
6561     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6562     EVT Ty = Arg.getValueType();
6563     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6564                              sdl, Ty, Arg));
6565     return;
6566   }
6567   case Intrinsic::ctlz: {
6568     SDValue Arg = getValue(I.getArgOperand(0));
6569     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6570     EVT Ty = Arg.getValueType();
6571     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6572                              sdl, Ty, Arg));
6573     return;
6574   }
6575   case Intrinsic::ctpop: {
6576     SDValue Arg = getValue(I.getArgOperand(0));
6577     EVT Ty = Arg.getValueType();
6578     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6579     return;
6580   }
6581   case Intrinsic::fshl:
6582   case Intrinsic::fshr: {
6583     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6584     SDValue X = getValue(I.getArgOperand(0));
6585     SDValue Y = getValue(I.getArgOperand(1));
6586     SDValue Z = getValue(I.getArgOperand(2));
6587     EVT VT = X.getValueType();
6588 
6589     if (X == Y) {
6590       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6591       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6592     } else {
6593       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6594       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6595     }
6596     return;
6597   }
6598   case Intrinsic::sadd_sat: {
6599     SDValue Op1 = getValue(I.getArgOperand(0));
6600     SDValue Op2 = getValue(I.getArgOperand(1));
6601     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6602     return;
6603   }
6604   case Intrinsic::uadd_sat: {
6605     SDValue Op1 = getValue(I.getArgOperand(0));
6606     SDValue Op2 = getValue(I.getArgOperand(1));
6607     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6608     return;
6609   }
6610   case Intrinsic::ssub_sat: {
6611     SDValue Op1 = getValue(I.getArgOperand(0));
6612     SDValue Op2 = getValue(I.getArgOperand(1));
6613     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6614     return;
6615   }
6616   case Intrinsic::usub_sat: {
6617     SDValue Op1 = getValue(I.getArgOperand(0));
6618     SDValue Op2 = getValue(I.getArgOperand(1));
6619     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6620     return;
6621   }
6622   case Intrinsic::sshl_sat: {
6623     SDValue Op1 = getValue(I.getArgOperand(0));
6624     SDValue Op2 = getValue(I.getArgOperand(1));
6625     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6626     return;
6627   }
6628   case Intrinsic::ushl_sat: {
6629     SDValue Op1 = getValue(I.getArgOperand(0));
6630     SDValue Op2 = getValue(I.getArgOperand(1));
6631     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6632     return;
6633   }
6634   case Intrinsic::smul_fix:
6635   case Intrinsic::umul_fix:
6636   case Intrinsic::smul_fix_sat:
6637   case Intrinsic::umul_fix_sat: {
6638     SDValue Op1 = getValue(I.getArgOperand(0));
6639     SDValue Op2 = getValue(I.getArgOperand(1));
6640     SDValue Op3 = getValue(I.getArgOperand(2));
6641     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6642                              Op1.getValueType(), Op1, Op2, Op3));
6643     return;
6644   }
6645   case Intrinsic::sdiv_fix:
6646   case Intrinsic::udiv_fix:
6647   case Intrinsic::sdiv_fix_sat:
6648   case Intrinsic::udiv_fix_sat: {
6649     SDValue Op1 = getValue(I.getArgOperand(0));
6650     SDValue Op2 = getValue(I.getArgOperand(1));
6651     SDValue Op3 = getValue(I.getArgOperand(2));
6652     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6653                               Op1, Op2, Op3, DAG, TLI));
6654     return;
6655   }
6656   case Intrinsic::smax: {
6657     SDValue Op1 = getValue(I.getArgOperand(0));
6658     SDValue Op2 = getValue(I.getArgOperand(1));
6659     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6660     return;
6661   }
6662   case Intrinsic::smin: {
6663     SDValue Op1 = getValue(I.getArgOperand(0));
6664     SDValue Op2 = getValue(I.getArgOperand(1));
6665     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6666     return;
6667   }
6668   case Intrinsic::umax: {
6669     SDValue Op1 = getValue(I.getArgOperand(0));
6670     SDValue Op2 = getValue(I.getArgOperand(1));
6671     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6672     return;
6673   }
6674   case Intrinsic::umin: {
6675     SDValue Op1 = getValue(I.getArgOperand(0));
6676     SDValue Op2 = getValue(I.getArgOperand(1));
6677     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6678     return;
6679   }
6680   case Intrinsic::abs: {
6681     // TODO: Preserve "int min is poison" arg in SDAG?
6682     SDValue Op1 = getValue(I.getArgOperand(0));
6683     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6684     return;
6685   }
6686   case Intrinsic::stacksave: {
6687     SDValue Op = getRoot();
6688     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6689     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6690     setValue(&I, Res);
6691     DAG.setRoot(Res.getValue(1));
6692     return;
6693   }
6694   case Intrinsic::stackrestore:
6695     Res = getValue(I.getArgOperand(0));
6696     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6697     return;
6698   case Intrinsic::get_dynamic_area_offset: {
6699     SDValue Op = getRoot();
6700     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6701     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6702     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6703     // target.
6704     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6705       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6706                          " intrinsic!");
6707     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6708                       Op);
6709     DAG.setRoot(Op);
6710     setValue(&I, Res);
6711     return;
6712   }
6713   case Intrinsic::stackguard: {
6714     MachineFunction &MF = DAG.getMachineFunction();
6715     const Module &M = *MF.getFunction().getParent();
6716     SDValue Chain = getRoot();
6717     if (TLI.useLoadStackGuardNode()) {
6718       Res = getLoadStackGuard(DAG, sdl, Chain);
6719     } else {
6720       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6721       const Value *Global = TLI.getSDagStackGuard(M);
6722       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6723       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6724                         MachinePointerInfo(Global, 0), Align,
6725                         MachineMemOperand::MOVolatile);
6726     }
6727     if (TLI.useStackGuardXorFP())
6728       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6729     DAG.setRoot(Chain);
6730     setValue(&I, Res);
6731     return;
6732   }
6733   case Intrinsic::stackprotector: {
6734     // Emit code into the DAG to store the stack guard onto the stack.
6735     MachineFunction &MF = DAG.getMachineFunction();
6736     MachineFrameInfo &MFI = MF.getFrameInfo();
6737     SDValue Src, Chain = getRoot();
6738 
6739     if (TLI.useLoadStackGuardNode())
6740       Src = getLoadStackGuard(DAG, sdl, Chain);
6741     else
6742       Src = getValue(I.getArgOperand(0));   // The guard's value.
6743 
6744     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6745 
6746     int FI = FuncInfo.StaticAllocaMap[Slot];
6747     MFI.setStackProtectorIndex(FI);
6748     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6749 
6750     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6751 
6752     // Store the stack protector onto the stack.
6753     Res = DAG.getStore(
6754         Chain, sdl, Src, FIN,
6755         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6756         MaybeAlign(), MachineMemOperand::MOVolatile);
6757     setValue(&I, Res);
6758     DAG.setRoot(Res);
6759     return;
6760   }
6761   case Intrinsic::objectsize:
6762     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6763 
6764   case Intrinsic::is_constant:
6765     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6766 
6767   case Intrinsic::annotation:
6768   case Intrinsic::ptr_annotation:
6769   case Intrinsic::launder_invariant_group:
6770   case Intrinsic::strip_invariant_group:
6771     // Drop the intrinsic, but forward the value
6772     setValue(&I, getValue(I.getOperand(0)));
6773     return;
6774 
6775   case Intrinsic::assume:
6776   case Intrinsic::experimental_noalias_scope_decl:
6777   case Intrinsic::var_annotation:
6778   case Intrinsic::sideeffect:
6779     // Discard annotate attributes, noalias scope declarations, assumptions, and
6780     // artificial side-effects.
6781     return;
6782 
6783   case Intrinsic::codeview_annotation: {
6784     // Emit a label associated with this metadata.
6785     MachineFunction &MF = DAG.getMachineFunction();
6786     MCSymbol *Label =
6787         MF.getMMI().getContext().createTempSymbol("annotation", true);
6788     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6789     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6790     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6791     DAG.setRoot(Res);
6792     return;
6793   }
6794 
6795   case Intrinsic::init_trampoline: {
6796     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6797 
6798     SDValue Ops[6];
6799     Ops[0] = getRoot();
6800     Ops[1] = getValue(I.getArgOperand(0));
6801     Ops[2] = getValue(I.getArgOperand(1));
6802     Ops[3] = getValue(I.getArgOperand(2));
6803     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6804     Ops[5] = DAG.getSrcValue(F);
6805 
6806     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6807 
6808     DAG.setRoot(Res);
6809     return;
6810   }
6811   case Intrinsic::adjust_trampoline:
6812     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6813                              TLI.getPointerTy(DAG.getDataLayout()),
6814                              getValue(I.getArgOperand(0))));
6815     return;
6816   case Intrinsic::gcroot: {
6817     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6818            "only valid in functions with gc specified, enforced by Verifier");
6819     assert(GFI && "implied by previous");
6820     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6821     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6822 
6823     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6824     GFI->addStackRoot(FI->getIndex(), TypeMap);
6825     return;
6826   }
6827   case Intrinsic::gcread:
6828   case Intrinsic::gcwrite:
6829     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6830   case Intrinsic::flt_rounds:
6831     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6832     setValue(&I, Res);
6833     DAG.setRoot(Res.getValue(1));
6834     return;
6835 
6836   case Intrinsic::expect:
6837     // Just replace __builtin_expect(exp, c) with EXP.
6838     setValue(&I, getValue(I.getArgOperand(0)));
6839     return;
6840 
6841   case Intrinsic::ubsantrap:
6842   case Intrinsic::debugtrap:
6843   case Intrinsic::trap: {
6844     StringRef TrapFuncName =
6845         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6846     if (TrapFuncName.empty()) {
6847       switch (Intrinsic) {
6848       case Intrinsic::trap:
6849         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6850         break;
6851       case Intrinsic::debugtrap:
6852         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6853         break;
6854       case Intrinsic::ubsantrap:
6855         DAG.setRoot(DAG.getNode(
6856             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6857             DAG.getTargetConstant(
6858                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6859                 MVT::i32)));
6860         break;
6861       default: llvm_unreachable("unknown trap intrinsic");
6862       }
6863       return;
6864     }
6865     TargetLowering::ArgListTy Args;
6866     if (Intrinsic == Intrinsic::ubsantrap) {
6867       Args.push_back(TargetLoweringBase::ArgListEntry());
6868       Args[0].Val = I.getArgOperand(0);
6869       Args[0].Node = getValue(Args[0].Val);
6870       Args[0].Ty = Args[0].Val->getType();
6871     }
6872 
6873     TargetLowering::CallLoweringInfo CLI(DAG);
6874     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6875         CallingConv::C, I.getType(),
6876         DAG.getExternalSymbol(TrapFuncName.data(),
6877                               TLI.getPointerTy(DAG.getDataLayout())),
6878         std::move(Args));
6879 
6880     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6881     DAG.setRoot(Result.second);
6882     return;
6883   }
6884 
6885   case Intrinsic::uadd_with_overflow:
6886   case Intrinsic::sadd_with_overflow:
6887   case Intrinsic::usub_with_overflow:
6888   case Intrinsic::ssub_with_overflow:
6889   case Intrinsic::umul_with_overflow:
6890   case Intrinsic::smul_with_overflow: {
6891     ISD::NodeType Op;
6892     switch (Intrinsic) {
6893     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6894     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6895     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6896     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6897     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6898     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6899     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6900     }
6901     SDValue Op1 = getValue(I.getArgOperand(0));
6902     SDValue Op2 = getValue(I.getArgOperand(1));
6903 
6904     EVT ResultVT = Op1.getValueType();
6905     EVT OverflowVT = MVT::i1;
6906     if (ResultVT.isVector())
6907       OverflowVT = EVT::getVectorVT(
6908           *Context, OverflowVT, ResultVT.getVectorElementCount());
6909 
6910     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6911     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6912     return;
6913   }
6914   case Intrinsic::prefetch: {
6915     SDValue Ops[5];
6916     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6917     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6918     Ops[0] = DAG.getRoot();
6919     Ops[1] = getValue(I.getArgOperand(0));
6920     Ops[2] = getValue(I.getArgOperand(1));
6921     Ops[3] = getValue(I.getArgOperand(2));
6922     Ops[4] = getValue(I.getArgOperand(3));
6923     SDValue Result = DAG.getMemIntrinsicNode(
6924         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6925         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6926         /* align */ std::nullopt, Flags);
6927 
6928     // Chain the prefetch in parallell with any pending loads, to stay out of
6929     // the way of later optimizations.
6930     PendingLoads.push_back(Result);
6931     Result = getRoot();
6932     DAG.setRoot(Result);
6933     return;
6934   }
6935   case Intrinsic::lifetime_start:
6936   case Intrinsic::lifetime_end: {
6937     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6938     // Stack coloring is not enabled in O0, discard region information.
6939     if (TM.getOptLevel() == CodeGenOpt::None)
6940       return;
6941 
6942     const int64_t ObjectSize =
6943         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6944     Value *const ObjectPtr = I.getArgOperand(1);
6945     SmallVector<const Value *, 4> Allocas;
6946     getUnderlyingObjects(ObjectPtr, Allocas);
6947 
6948     for (const Value *Alloca : Allocas) {
6949       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6950 
6951       // Could not find an Alloca.
6952       if (!LifetimeObject)
6953         continue;
6954 
6955       // First check that the Alloca is static, otherwise it won't have a
6956       // valid frame index.
6957       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6958       if (SI == FuncInfo.StaticAllocaMap.end())
6959         return;
6960 
6961       const int FrameIndex = SI->second;
6962       int64_t Offset;
6963       if (GetPointerBaseWithConstantOffset(
6964               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6965         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6966       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6967                                 Offset);
6968       DAG.setRoot(Res);
6969     }
6970     return;
6971   }
6972   case Intrinsic::pseudoprobe: {
6973     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6974     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6975     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6976     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6977     DAG.setRoot(Res);
6978     return;
6979   }
6980   case Intrinsic::invariant_start:
6981     // Discard region information.
6982     setValue(&I,
6983              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6984     return;
6985   case Intrinsic::invariant_end:
6986     // Discard region information.
6987     return;
6988   case Intrinsic::clear_cache:
6989     /// FunctionName may be null.
6990     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6991       lowerCallToExternalSymbol(I, FunctionName);
6992     return;
6993   case Intrinsic::donothing:
6994   case Intrinsic::seh_try_begin:
6995   case Intrinsic::seh_scope_begin:
6996   case Intrinsic::seh_try_end:
6997   case Intrinsic::seh_scope_end:
6998     // ignore
6999     return;
7000   case Intrinsic::experimental_stackmap:
7001     visitStackmap(I);
7002     return;
7003   case Intrinsic::experimental_patchpoint_void:
7004   case Intrinsic::experimental_patchpoint_i64:
7005     visitPatchpoint(I);
7006     return;
7007   case Intrinsic::experimental_gc_statepoint:
7008     LowerStatepoint(cast<GCStatepointInst>(I));
7009     return;
7010   case Intrinsic::experimental_gc_result:
7011     visitGCResult(cast<GCResultInst>(I));
7012     return;
7013   case Intrinsic::experimental_gc_relocate:
7014     visitGCRelocate(cast<GCRelocateInst>(I));
7015     return;
7016   case Intrinsic::instrprof_cover:
7017     llvm_unreachable("instrprof failed to lower a cover");
7018   case Intrinsic::instrprof_increment:
7019     llvm_unreachable("instrprof failed to lower an increment");
7020   case Intrinsic::instrprof_value_profile:
7021     llvm_unreachable("instrprof failed to lower a value profiling call");
7022   case Intrinsic::localescape: {
7023     MachineFunction &MF = DAG.getMachineFunction();
7024     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7025 
7026     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7027     // is the same on all targets.
7028     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7029       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7030       if (isa<ConstantPointerNull>(Arg))
7031         continue; // Skip null pointers. They represent a hole in index space.
7032       AllocaInst *Slot = cast<AllocaInst>(Arg);
7033       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7034              "can only escape static allocas");
7035       int FI = FuncInfo.StaticAllocaMap[Slot];
7036       MCSymbol *FrameAllocSym =
7037           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7038               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7039       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7040               TII->get(TargetOpcode::LOCAL_ESCAPE))
7041           .addSym(FrameAllocSym)
7042           .addFrameIndex(FI);
7043     }
7044 
7045     return;
7046   }
7047 
7048   case Intrinsic::localrecover: {
7049     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7050     MachineFunction &MF = DAG.getMachineFunction();
7051 
7052     // Get the symbol that defines the frame offset.
7053     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7054     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7055     unsigned IdxVal =
7056         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7057     MCSymbol *FrameAllocSym =
7058         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7059             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7060 
7061     Value *FP = I.getArgOperand(1);
7062     SDValue FPVal = getValue(FP);
7063     EVT PtrVT = FPVal.getValueType();
7064 
7065     // Create a MCSymbol for the label to avoid any target lowering
7066     // that would make this PC relative.
7067     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7068     SDValue OffsetVal =
7069         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7070 
7071     // Add the offset to the FP.
7072     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7073     setValue(&I, Add);
7074 
7075     return;
7076   }
7077 
7078   case Intrinsic::eh_exceptionpointer:
7079   case Intrinsic::eh_exceptioncode: {
7080     // Get the exception pointer vreg, copy from it, and resize it to fit.
7081     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7082     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7083     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7084     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7085     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7086     if (Intrinsic == Intrinsic::eh_exceptioncode)
7087       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7088     setValue(&I, N);
7089     return;
7090   }
7091   case Intrinsic::xray_customevent: {
7092     // Here we want to make sure that the intrinsic behaves as if it has a
7093     // specific calling convention, and only for x86_64.
7094     // FIXME: Support other platforms later.
7095     const auto &Triple = DAG.getTarget().getTargetTriple();
7096     if (Triple.getArch() != Triple::x86_64)
7097       return;
7098 
7099     SmallVector<SDValue, 8> Ops;
7100 
7101     // We want to say that we always want the arguments in registers.
7102     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7103     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7104     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7105     SDValue Chain = getRoot();
7106     Ops.push_back(LogEntryVal);
7107     Ops.push_back(StrSizeVal);
7108     Ops.push_back(Chain);
7109 
7110     // We need to enforce the calling convention for the callsite, so that
7111     // argument ordering is enforced correctly, and that register allocation can
7112     // see that some registers may be assumed clobbered and have to preserve
7113     // them across calls to the intrinsic.
7114     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7115                                            sdl, NodeTys, Ops);
7116     SDValue patchableNode = SDValue(MN, 0);
7117     DAG.setRoot(patchableNode);
7118     setValue(&I, patchableNode);
7119     return;
7120   }
7121   case Intrinsic::xray_typedevent: {
7122     // Here we want to make sure that the intrinsic behaves as if it has a
7123     // specific calling convention, and only for x86_64.
7124     // FIXME: Support other platforms later.
7125     const auto &Triple = DAG.getTarget().getTargetTriple();
7126     if (Triple.getArch() != Triple::x86_64)
7127       return;
7128 
7129     SmallVector<SDValue, 8> Ops;
7130 
7131     // We want to say that we always want the arguments in registers.
7132     // It's unclear to me how manipulating the selection DAG here forces callers
7133     // to provide arguments in registers instead of on the stack.
7134     SDValue LogTypeId = getValue(I.getArgOperand(0));
7135     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7136     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7137     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7138     SDValue Chain = getRoot();
7139     Ops.push_back(LogTypeId);
7140     Ops.push_back(LogEntryVal);
7141     Ops.push_back(StrSizeVal);
7142     Ops.push_back(Chain);
7143 
7144     // We need to enforce the calling convention for the callsite, so that
7145     // argument ordering is enforced correctly, and that register allocation can
7146     // see that some registers may be assumed clobbered and have to preserve
7147     // them across calls to the intrinsic.
7148     MachineSDNode *MN = DAG.getMachineNode(
7149         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7150     SDValue patchableNode = SDValue(MN, 0);
7151     DAG.setRoot(patchableNode);
7152     setValue(&I, patchableNode);
7153     return;
7154   }
7155   case Intrinsic::experimental_deoptimize:
7156     LowerDeoptimizeCall(&I);
7157     return;
7158   case Intrinsic::experimental_stepvector:
7159     visitStepVector(I);
7160     return;
7161   case Intrinsic::vector_reduce_fadd:
7162   case Intrinsic::vector_reduce_fmul:
7163   case Intrinsic::vector_reduce_add:
7164   case Intrinsic::vector_reduce_mul:
7165   case Intrinsic::vector_reduce_and:
7166   case Intrinsic::vector_reduce_or:
7167   case Intrinsic::vector_reduce_xor:
7168   case Intrinsic::vector_reduce_smax:
7169   case Intrinsic::vector_reduce_smin:
7170   case Intrinsic::vector_reduce_umax:
7171   case Intrinsic::vector_reduce_umin:
7172   case Intrinsic::vector_reduce_fmax:
7173   case Intrinsic::vector_reduce_fmin:
7174     visitVectorReduce(I, Intrinsic);
7175     return;
7176 
7177   case Intrinsic::icall_branch_funnel: {
7178     SmallVector<SDValue, 16> Ops;
7179     Ops.push_back(getValue(I.getArgOperand(0)));
7180 
7181     int64_t Offset;
7182     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7183         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7184     if (!Base)
7185       report_fatal_error(
7186           "llvm.icall.branch.funnel operand must be a GlobalValue");
7187     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7188 
7189     struct BranchFunnelTarget {
7190       int64_t Offset;
7191       SDValue Target;
7192     };
7193     SmallVector<BranchFunnelTarget, 8> Targets;
7194 
7195     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7196       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7197           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7198       if (ElemBase != Base)
7199         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7200                            "to the same GlobalValue");
7201 
7202       SDValue Val = getValue(I.getArgOperand(Op + 1));
7203       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7204       if (!GA)
7205         report_fatal_error(
7206             "llvm.icall.branch.funnel operand must be a GlobalValue");
7207       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7208                                      GA->getGlobal(), sdl, Val.getValueType(),
7209                                      GA->getOffset())});
7210     }
7211     llvm::sort(Targets,
7212                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7213                  return T1.Offset < T2.Offset;
7214                });
7215 
7216     for (auto &T : Targets) {
7217       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7218       Ops.push_back(T.Target);
7219     }
7220 
7221     Ops.push_back(DAG.getRoot()); // Chain
7222     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7223                                  MVT::Other, Ops),
7224               0);
7225     DAG.setRoot(N);
7226     setValue(&I, N);
7227     HasTailCall = true;
7228     return;
7229   }
7230 
7231   case Intrinsic::wasm_landingpad_index:
7232     // Information this intrinsic contained has been transferred to
7233     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7234     // delete it now.
7235     return;
7236 
7237   case Intrinsic::aarch64_settag:
7238   case Intrinsic::aarch64_settag_zero: {
7239     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7240     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7241     SDValue Val = TSI.EmitTargetCodeForSetTag(
7242         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7243         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7244         ZeroMemory);
7245     DAG.setRoot(Val);
7246     setValue(&I, Val);
7247     return;
7248   }
7249   case Intrinsic::ptrmask: {
7250     SDValue Ptr = getValue(I.getOperand(0));
7251     SDValue Const = getValue(I.getOperand(1));
7252 
7253     EVT PtrVT = Ptr.getValueType();
7254     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7255                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7256     return;
7257   }
7258   case Intrinsic::threadlocal_address: {
7259     setValue(&I, getValue(I.getOperand(0)));
7260     return;
7261   }
7262   case Intrinsic::get_active_lane_mask: {
7263     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7264     SDValue Index = getValue(I.getOperand(0));
7265     EVT ElementVT = Index.getValueType();
7266 
7267     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7268       visitTargetIntrinsic(I, Intrinsic);
7269       return;
7270     }
7271 
7272     SDValue TripCount = getValue(I.getOperand(1));
7273     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7274 
7275     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7276     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7277     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7278     SDValue VectorInduction = DAG.getNode(
7279         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7280     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7281                                  VectorTripCount, ISD::CondCode::SETULT);
7282     setValue(&I, SetCC);
7283     return;
7284   }
7285   case Intrinsic::vector_insert: {
7286     SDValue Vec = getValue(I.getOperand(0));
7287     SDValue SubVec = getValue(I.getOperand(1));
7288     SDValue Index = getValue(I.getOperand(2));
7289 
7290     // The intrinsic's index type is i64, but the SDNode requires an index type
7291     // suitable for the target. Convert the index as required.
7292     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7293     if (Index.getValueType() != VectorIdxTy)
7294       Index = DAG.getVectorIdxConstant(
7295           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7296 
7297     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7298     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7299                              Index));
7300     return;
7301   }
7302   case Intrinsic::vector_extract: {
7303     SDValue Vec = getValue(I.getOperand(0));
7304     SDValue Index = getValue(I.getOperand(1));
7305     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7306 
7307     // The intrinsic's index type is i64, but the SDNode requires an index type
7308     // suitable for the target. Convert the index as required.
7309     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7310     if (Index.getValueType() != VectorIdxTy)
7311       Index = DAG.getVectorIdxConstant(
7312           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7313 
7314     setValue(&I,
7315              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7316     return;
7317   }
7318   case Intrinsic::experimental_vector_reverse:
7319     visitVectorReverse(I);
7320     return;
7321   case Intrinsic::experimental_vector_splice:
7322     visitVectorSplice(I);
7323     return;
7324   }
7325 }
7326 
7327 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7328     const ConstrainedFPIntrinsic &FPI) {
7329   SDLoc sdl = getCurSDLoc();
7330 
7331   // We do not need to serialize constrained FP intrinsics against
7332   // each other or against (nonvolatile) loads, so they can be
7333   // chained like loads.
7334   SDValue Chain = DAG.getRoot();
7335   SmallVector<SDValue, 4> Opers;
7336   Opers.push_back(Chain);
7337   if (FPI.isUnaryOp()) {
7338     Opers.push_back(getValue(FPI.getArgOperand(0)));
7339   } else if (FPI.isTernaryOp()) {
7340     Opers.push_back(getValue(FPI.getArgOperand(0)));
7341     Opers.push_back(getValue(FPI.getArgOperand(1)));
7342     Opers.push_back(getValue(FPI.getArgOperand(2)));
7343   } else {
7344     Opers.push_back(getValue(FPI.getArgOperand(0)));
7345     Opers.push_back(getValue(FPI.getArgOperand(1)));
7346   }
7347 
7348   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7349     assert(Result.getNode()->getNumValues() == 2);
7350 
7351     // Push node to the appropriate list so that future instructions can be
7352     // chained up correctly.
7353     SDValue OutChain = Result.getValue(1);
7354     switch (EB) {
7355     case fp::ExceptionBehavior::ebIgnore:
7356       // The only reason why ebIgnore nodes still need to be chained is that
7357       // they might depend on the current rounding mode, and therefore must
7358       // not be moved across instruction that may change that mode.
7359       [[fallthrough]];
7360     case fp::ExceptionBehavior::ebMayTrap:
7361       // These must not be moved across calls or instructions that may change
7362       // floating-point exception masks.
7363       PendingConstrainedFP.push_back(OutChain);
7364       break;
7365     case fp::ExceptionBehavior::ebStrict:
7366       // These must not be moved across calls or instructions that may change
7367       // floating-point exception masks or read floating-point exception flags.
7368       // In addition, they cannot be optimized out even if unused.
7369       PendingConstrainedFPStrict.push_back(OutChain);
7370       break;
7371     }
7372   };
7373 
7374   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7375   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7376   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7377   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7378 
7379   SDNodeFlags Flags;
7380   if (EB == fp::ExceptionBehavior::ebIgnore)
7381     Flags.setNoFPExcept(true);
7382 
7383   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7384     Flags.copyFMF(*FPOp);
7385 
7386   unsigned Opcode;
7387   switch (FPI.getIntrinsicID()) {
7388   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7389 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7390   case Intrinsic::INTRINSIC:                                                   \
7391     Opcode = ISD::STRICT_##DAGN;                                               \
7392     break;
7393 #include "llvm/IR/ConstrainedOps.def"
7394   case Intrinsic::experimental_constrained_fmuladd: {
7395     Opcode = ISD::STRICT_FMA;
7396     // Break fmuladd into fmul and fadd.
7397     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7398         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7399       Opers.pop_back();
7400       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7401       pushOutChain(Mul, EB);
7402       Opcode = ISD::STRICT_FADD;
7403       Opers.clear();
7404       Opers.push_back(Mul.getValue(1));
7405       Opers.push_back(Mul.getValue(0));
7406       Opers.push_back(getValue(FPI.getArgOperand(2)));
7407     }
7408     break;
7409   }
7410   }
7411 
7412   // A few strict DAG nodes carry additional operands that are not
7413   // set up by the default code above.
7414   switch (Opcode) {
7415   default: break;
7416   case ISD::STRICT_FP_ROUND:
7417     Opers.push_back(
7418         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7419     break;
7420   case ISD::STRICT_FSETCC:
7421   case ISD::STRICT_FSETCCS: {
7422     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7423     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7424     if (TM.Options.NoNaNsFPMath)
7425       Condition = getFCmpCodeWithoutNaN(Condition);
7426     Opers.push_back(DAG.getCondCode(Condition));
7427     break;
7428   }
7429   }
7430 
7431   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7432   pushOutChain(Result, EB);
7433 
7434   SDValue FPResult = Result.getValue(0);
7435   setValue(&FPI, FPResult);
7436 }
7437 
7438 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7439   std::optional<unsigned> ResOPC;
7440   switch (VPIntrin.getIntrinsicID()) {
7441 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7442   case Intrinsic::VPID:                                                        \
7443     ResOPC = ISD::VPSD;                                                        \
7444     break;
7445 #include "llvm/IR/VPIntrinsics.def"
7446   }
7447 
7448   if (!ResOPC)
7449     llvm_unreachable(
7450         "Inconsistency: no SDNode available for this VPIntrinsic!");
7451 
7452   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7453       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7454     if (VPIntrin.getFastMathFlags().allowReassoc())
7455       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7456                                                 : ISD::VP_REDUCE_FMUL;
7457   }
7458 
7459   return *ResOPC;
7460 }
7461 
7462 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7463                                       SmallVector<SDValue, 7> &OpValues) {
7464   SDLoc DL = getCurSDLoc();
7465   Value *PtrOperand = VPIntrin.getArgOperand(0);
7466   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7467   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7468   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7469   SDValue LD;
7470   bool AddToChain = true;
7471   // Do not serialize variable-length loads of constant memory with
7472   // anything.
7473   if (!Alignment)
7474     Alignment = DAG.getEVTAlign(VT);
7475   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7476   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7477   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7478   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7479       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7480       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7481   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7482                      MMO, false /*IsExpanding */);
7483   if (AddToChain)
7484     PendingLoads.push_back(LD.getValue(1));
7485   setValue(&VPIntrin, LD);
7486 }
7487 
7488 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7489                                         SmallVector<SDValue, 7> &OpValues) {
7490   SDLoc DL = getCurSDLoc();
7491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7492   Value *PtrOperand = VPIntrin.getArgOperand(0);
7493   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7494   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7495   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7496   SDValue LD;
7497   if (!Alignment)
7498     Alignment = DAG.getEVTAlign(VT.getScalarType());
7499   unsigned AS =
7500     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7501   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7502      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7503      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7504   SDValue Base, Index, Scale;
7505   ISD::MemIndexType IndexType;
7506   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7507                                     this, VPIntrin.getParent(),
7508                                     VT.getScalarStoreSize());
7509   if (!UniformBase) {
7510     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7511     Index = getValue(PtrOperand);
7512     IndexType = ISD::SIGNED_SCALED;
7513     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7514   }
7515   EVT IdxVT = Index.getValueType();
7516   EVT EltTy = IdxVT.getVectorElementType();
7517   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7518     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7519     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7520   }
7521   LD = DAG.getGatherVP(
7522       DAG.getVTList(VT, MVT::Other), VT, DL,
7523       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7524       IndexType);
7525   PendingLoads.push_back(LD.getValue(1));
7526   setValue(&VPIntrin, LD);
7527 }
7528 
7529 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7530                                        SmallVector<SDValue, 7> &OpValues) {
7531   SDLoc DL = getCurSDLoc();
7532   Value *PtrOperand = VPIntrin.getArgOperand(1);
7533   EVT VT = OpValues[0].getValueType();
7534   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7535   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7536   SDValue ST;
7537   if (!Alignment)
7538     Alignment = DAG.getEVTAlign(VT);
7539   SDValue Ptr = OpValues[1];
7540   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7541   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7542       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7543       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7544   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7545                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7546                       /* IsTruncating */ false, /*IsCompressing*/ false);
7547   DAG.setRoot(ST);
7548   setValue(&VPIntrin, ST);
7549 }
7550 
7551 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7552                                               SmallVector<SDValue, 7> &OpValues) {
7553   SDLoc DL = getCurSDLoc();
7554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7555   Value *PtrOperand = VPIntrin.getArgOperand(1);
7556   EVT VT = OpValues[0].getValueType();
7557   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7558   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7559   SDValue ST;
7560   if (!Alignment)
7561     Alignment = DAG.getEVTAlign(VT.getScalarType());
7562   unsigned AS =
7563       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7564   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7565       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7566       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7567   SDValue Base, Index, Scale;
7568   ISD::MemIndexType IndexType;
7569   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7570                                     this, VPIntrin.getParent(),
7571                                     VT.getScalarStoreSize());
7572   if (!UniformBase) {
7573     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7574     Index = getValue(PtrOperand);
7575     IndexType = ISD::SIGNED_SCALED;
7576     Scale =
7577       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7578   }
7579   EVT IdxVT = Index.getValueType();
7580   EVT EltTy = IdxVT.getVectorElementType();
7581   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7582     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7583     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7584   }
7585   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7586                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7587                          OpValues[2], OpValues[3]},
7588                         MMO, IndexType);
7589   DAG.setRoot(ST);
7590   setValue(&VPIntrin, ST);
7591 }
7592 
7593 void SelectionDAGBuilder::visitVPStridedLoad(
7594     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7595   SDLoc DL = getCurSDLoc();
7596   Value *PtrOperand = VPIntrin.getArgOperand(0);
7597   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7598   if (!Alignment)
7599     Alignment = DAG.getEVTAlign(VT.getScalarType());
7600   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7601   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7602   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7603   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7604   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7605   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7606       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7607       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7608 
7609   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7610                                     OpValues[2], OpValues[3], MMO,
7611                                     false /*IsExpanding*/);
7612 
7613   if (AddToChain)
7614     PendingLoads.push_back(LD.getValue(1));
7615   setValue(&VPIntrin, LD);
7616 }
7617 
7618 void SelectionDAGBuilder::visitVPStridedStore(
7619     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7620   SDLoc DL = getCurSDLoc();
7621   Value *PtrOperand = VPIntrin.getArgOperand(1);
7622   EVT VT = OpValues[0].getValueType();
7623   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7624   if (!Alignment)
7625     Alignment = DAG.getEVTAlign(VT.getScalarType());
7626   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7627   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7628       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7629       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7630 
7631   SDValue ST = DAG.getStridedStoreVP(
7632       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7633       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7634       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7635       /*IsCompressing*/ false);
7636 
7637   DAG.setRoot(ST);
7638   setValue(&VPIntrin, ST);
7639 }
7640 
7641 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7643   SDLoc DL = getCurSDLoc();
7644 
7645   ISD::CondCode Condition;
7646   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7647   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7648   if (IsFP) {
7649     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7650     // flags, but calls that don't return floating-point types can't be
7651     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7652     Condition = getFCmpCondCode(CondCode);
7653     if (TM.Options.NoNaNsFPMath)
7654       Condition = getFCmpCodeWithoutNaN(Condition);
7655   } else {
7656     Condition = getICmpCondCode(CondCode);
7657   }
7658 
7659   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7660   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7661   // #2 is the condition code
7662   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7663   SDValue EVL = getValue(VPIntrin.getOperand(4));
7664   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7665   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7666          "Unexpected target EVL type");
7667   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7668 
7669   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7670                                                         VPIntrin.getType());
7671   setValue(&VPIntrin,
7672            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7673 }
7674 
7675 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7676     const VPIntrinsic &VPIntrin) {
7677   SDLoc DL = getCurSDLoc();
7678   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7679 
7680   auto IID = VPIntrin.getIntrinsicID();
7681 
7682   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7683     return visitVPCmp(*CmpI);
7684 
7685   SmallVector<EVT, 4> ValueVTs;
7686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7687   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7688   SDVTList VTs = DAG.getVTList(ValueVTs);
7689 
7690   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7691 
7692   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7693   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7694          "Unexpected target EVL type");
7695 
7696   // Request operands.
7697   SmallVector<SDValue, 7> OpValues;
7698   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7699     auto Op = getValue(VPIntrin.getArgOperand(I));
7700     if (I == EVLParamPos)
7701       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7702     OpValues.push_back(Op);
7703   }
7704 
7705   switch (Opcode) {
7706   default: {
7707     SDNodeFlags SDFlags;
7708     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7709       SDFlags.copyFMF(*FPMO);
7710     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7711     setValue(&VPIntrin, Result);
7712     break;
7713   }
7714   case ISD::VP_LOAD:
7715     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7716     break;
7717   case ISD::VP_GATHER:
7718     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7719     break;
7720   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7721     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7722     break;
7723   case ISD::VP_STORE:
7724     visitVPStore(VPIntrin, OpValues);
7725     break;
7726   case ISD::VP_SCATTER:
7727     visitVPScatter(VPIntrin, OpValues);
7728     break;
7729   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7730     visitVPStridedStore(VPIntrin, OpValues);
7731     break;
7732   case ISD::VP_FMULADD: {
7733     assert(OpValues.size() == 5 && "Unexpected number of operands");
7734     SDNodeFlags SDFlags;
7735     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7736       SDFlags.copyFMF(*FPMO);
7737     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7738         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7739       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7740     } else {
7741       SDValue Mul = DAG.getNode(
7742           ISD::VP_FMUL, DL, VTs,
7743           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7744       SDValue Add =
7745           DAG.getNode(ISD::VP_FADD, DL, VTs,
7746                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7747       setValue(&VPIntrin, Add);
7748     }
7749     break;
7750   }
7751   case ISD::VP_INTTOPTR: {
7752     SDValue N = OpValues[0];
7753     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7754     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7755     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7756                                OpValues[2]);
7757     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7758                              OpValues[2]);
7759     setValue(&VPIntrin, N);
7760     break;
7761   }
7762   case ISD::VP_PTRTOINT: {
7763     SDValue N = OpValues[0];
7764     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7765                                                           VPIntrin.getType());
7766     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7767                                        VPIntrin.getOperand(0)->getType());
7768     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7769                                OpValues[2]);
7770     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7771                              OpValues[2]);
7772     setValue(&VPIntrin, N);
7773     break;
7774   }
7775   }
7776 }
7777 
7778 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7779                                           const BasicBlock *EHPadBB,
7780                                           MCSymbol *&BeginLabel) {
7781   MachineFunction &MF = DAG.getMachineFunction();
7782   MachineModuleInfo &MMI = MF.getMMI();
7783 
7784   // Insert a label before the invoke call to mark the try range.  This can be
7785   // used to detect deletion of the invoke via the MachineModuleInfo.
7786   BeginLabel = MMI.getContext().createTempSymbol();
7787 
7788   // For SjLj, keep track of which landing pads go with which invokes
7789   // so as to maintain the ordering of pads in the LSDA.
7790   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7791   if (CallSiteIndex) {
7792     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7793     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7794 
7795     // Now that the call site is handled, stop tracking it.
7796     MMI.setCurrentCallSite(0);
7797   }
7798 
7799   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7800 }
7801 
7802 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7803                                         const BasicBlock *EHPadBB,
7804                                         MCSymbol *BeginLabel) {
7805   assert(BeginLabel && "BeginLabel should've been set");
7806 
7807   MachineFunction &MF = DAG.getMachineFunction();
7808   MachineModuleInfo &MMI = MF.getMMI();
7809 
7810   // Insert a label at the end of the invoke call to mark the try range.  This
7811   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7812   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7813   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7814 
7815   // Inform MachineModuleInfo of range.
7816   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7817   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7818   // actually use outlined funclets and their LSDA info style.
7819   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7820     assert(II && "II should've been set");
7821     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7822     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7823   } else if (!isScopedEHPersonality(Pers)) {
7824     assert(EHPadBB);
7825     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7826   }
7827 
7828   return Chain;
7829 }
7830 
7831 std::pair<SDValue, SDValue>
7832 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7833                                     const BasicBlock *EHPadBB) {
7834   MCSymbol *BeginLabel = nullptr;
7835 
7836   if (EHPadBB) {
7837     // Both PendingLoads and PendingExports must be flushed here;
7838     // this call might not return.
7839     (void)getRoot();
7840     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7841     CLI.setChain(getRoot());
7842   }
7843 
7844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7845   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7846 
7847   assert((CLI.IsTailCall || Result.second.getNode()) &&
7848          "Non-null chain expected with non-tail call!");
7849   assert((Result.second.getNode() || !Result.first.getNode()) &&
7850          "Null value expected with tail call!");
7851 
7852   if (!Result.second.getNode()) {
7853     // As a special case, a null chain means that a tail call has been emitted
7854     // and the DAG root is already updated.
7855     HasTailCall = true;
7856 
7857     // Since there's no actual continuation from this block, nothing can be
7858     // relying on us setting vregs for them.
7859     PendingExports.clear();
7860   } else {
7861     DAG.setRoot(Result.second);
7862   }
7863 
7864   if (EHPadBB) {
7865     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7866                            BeginLabel));
7867   }
7868 
7869   return Result;
7870 }
7871 
7872 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7873                                       bool isTailCall,
7874                                       bool isMustTailCall,
7875                                       const BasicBlock *EHPadBB) {
7876   auto &DL = DAG.getDataLayout();
7877   FunctionType *FTy = CB.getFunctionType();
7878   Type *RetTy = CB.getType();
7879 
7880   TargetLowering::ArgListTy Args;
7881   Args.reserve(CB.arg_size());
7882 
7883   const Value *SwiftErrorVal = nullptr;
7884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7885 
7886   if (isTailCall) {
7887     // Avoid emitting tail calls in functions with the disable-tail-calls
7888     // attribute.
7889     auto *Caller = CB.getParent()->getParent();
7890     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7891         "true" && !isMustTailCall)
7892       isTailCall = false;
7893 
7894     // We can't tail call inside a function with a swifterror argument. Lowering
7895     // does not support this yet. It would have to move into the swifterror
7896     // register before the call.
7897     if (TLI.supportSwiftError() &&
7898         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7899       isTailCall = false;
7900   }
7901 
7902   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7903     TargetLowering::ArgListEntry Entry;
7904     const Value *V = *I;
7905 
7906     // Skip empty types
7907     if (V->getType()->isEmptyTy())
7908       continue;
7909 
7910     SDValue ArgNode = getValue(V);
7911     Entry.Node = ArgNode; Entry.Ty = V->getType();
7912 
7913     Entry.setAttributes(&CB, I - CB.arg_begin());
7914 
7915     // Use swifterror virtual register as input to the call.
7916     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7917       SwiftErrorVal = V;
7918       // We find the virtual register for the actual swifterror argument.
7919       // Instead of using the Value, we use the virtual register instead.
7920       Entry.Node =
7921           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7922                           EVT(TLI.getPointerTy(DL)));
7923     }
7924 
7925     Args.push_back(Entry);
7926 
7927     // If we have an explicit sret argument that is an Instruction, (i.e., it
7928     // might point to function-local memory), we can't meaningfully tail-call.
7929     if (Entry.IsSRet && isa<Instruction>(V))
7930       isTailCall = false;
7931   }
7932 
7933   // If call site has a cfguardtarget operand bundle, create and add an
7934   // additional ArgListEntry.
7935   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7936     TargetLowering::ArgListEntry Entry;
7937     Value *V = Bundle->Inputs[0];
7938     SDValue ArgNode = getValue(V);
7939     Entry.Node = ArgNode;
7940     Entry.Ty = V->getType();
7941     Entry.IsCFGuardTarget = true;
7942     Args.push_back(Entry);
7943   }
7944 
7945   // Check if target-independent constraints permit a tail call here.
7946   // Target-dependent constraints are checked within TLI->LowerCallTo.
7947   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7948     isTailCall = false;
7949 
7950   // Disable tail calls if there is an swifterror argument. Targets have not
7951   // been updated to support tail calls.
7952   if (TLI.supportSwiftError() && SwiftErrorVal)
7953     isTailCall = false;
7954 
7955   ConstantInt *CFIType = nullptr;
7956   if (CB.isIndirectCall()) {
7957     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7958       if (!TLI.supportKCFIBundles())
7959         report_fatal_error(
7960             "Target doesn't support calls with kcfi operand bundles.");
7961       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7962       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7963     }
7964   }
7965 
7966   TargetLowering::CallLoweringInfo CLI(DAG);
7967   CLI.setDebugLoc(getCurSDLoc())
7968       .setChain(getRoot())
7969       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7970       .setTailCall(isTailCall)
7971       .setConvergent(CB.isConvergent())
7972       .setIsPreallocated(
7973           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7974       .setCFIType(CFIType);
7975   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7976 
7977   if (Result.first.getNode()) {
7978     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7979     setValue(&CB, Result.first);
7980   }
7981 
7982   // The last element of CLI.InVals has the SDValue for swifterror return.
7983   // Here we copy it to a virtual register and update SwiftErrorMap for
7984   // book-keeping.
7985   if (SwiftErrorVal && TLI.supportSwiftError()) {
7986     // Get the last element of InVals.
7987     SDValue Src = CLI.InVals.back();
7988     Register VReg =
7989         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7990     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7991     DAG.setRoot(CopyNode);
7992   }
7993 }
7994 
7995 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7996                              SelectionDAGBuilder &Builder) {
7997   // Check to see if this load can be trivially constant folded, e.g. if the
7998   // input is from a string literal.
7999   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8000     // Cast pointer to the type we really want to load.
8001     Type *LoadTy =
8002         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8003     if (LoadVT.isVector())
8004       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8005 
8006     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8007                                          PointerType::getUnqual(LoadTy));
8008 
8009     if (const Constant *LoadCst =
8010             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8011                                          LoadTy, Builder.DAG.getDataLayout()))
8012       return Builder.getValue(LoadCst);
8013   }
8014 
8015   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8016   // still constant memory, the input chain can be the entry node.
8017   SDValue Root;
8018   bool ConstantMemory = false;
8019 
8020   // Do not serialize (non-volatile) loads of constant memory with anything.
8021   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8022     Root = Builder.DAG.getEntryNode();
8023     ConstantMemory = true;
8024   } else {
8025     // Do not serialize non-volatile loads against each other.
8026     Root = Builder.DAG.getRoot();
8027   }
8028 
8029   SDValue Ptr = Builder.getValue(PtrVal);
8030   SDValue LoadVal =
8031       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8032                           MachinePointerInfo(PtrVal), Align(1));
8033 
8034   if (!ConstantMemory)
8035     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8036   return LoadVal;
8037 }
8038 
8039 /// Record the value for an instruction that produces an integer result,
8040 /// converting the type where necessary.
8041 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8042                                                   SDValue Value,
8043                                                   bool IsSigned) {
8044   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8045                                                     I.getType(), true);
8046   if (IsSigned)
8047     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8048   else
8049     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8050   setValue(&I, Value);
8051 }
8052 
8053 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8054 /// true and lower it. Otherwise return false, and it will be lowered like a
8055 /// normal call.
8056 /// The caller already checked that \p I calls the appropriate LibFunc with a
8057 /// correct prototype.
8058 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8059   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8060   const Value *Size = I.getArgOperand(2);
8061   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8062   if (CSize && CSize->getZExtValue() == 0) {
8063     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8064                                                           I.getType(), true);
8065     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8066     return true;
8067   }
8068 
8069   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8070   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8071       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8072       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8073   if (Res.first.getNode()) {
8074     processIntegerCallValue(I, Res.first, true);
8075     PendingLoads.push_back(Res.second);
8076     return true;
8077   }
8078 
8079   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8080   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8081   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8082     return false;
8083 
8084   // If the target has a fast compare for the given size, it will return a
8085   // preferred load type for that size. Require that the load VT is legal and
8086   // that the target supports unaligned loads of that type. Otherwise, return
8087   // INVALID.
8088   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8089     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8090     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8091     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8092       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8093       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8094       // TODO: Check alignment of src and dest ptrs.
8095       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8096       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8097       if (!TLI.isTypeLegal(LVT) ||
8098           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8099           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8100         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8101     }
8102 
8103     return LVT;
8104   };
8105 
8106   // This turns into unaligned loads. We only do this if the target natively
8107   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8108   // we'll only produce a small number of byte loads.
8109   MVT LoadVT;
8110   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8111   switch (NumBitsToCompare) {
8112   default:
8113     return false;
8114   case 16:
8115     LoadVT = MVT::i16;
8116     break;
8117   case 32:
8118     LoadVT = MVT::i32;
8119     break;
8120   case 64:
8121   case 128:
8122   case 256:
8123     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8124     break;
8125   }
8126 
8127   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8128     return false;
8129 
8130   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8131   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8132 
8133   // Bitcast to a wide integer type if the loads are vectors.
8134   if (LoadVT.isVector()) {
8135     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8136     LoadL = DAG.getBitcast(CmpVT, LoadL);
8137     LoadR = DAG.getBitcast(CmpVT, LoadR);
8138   }
8139 
8140   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8141   processIntegerCallValue(I, Cmp, false);
8142   return true;
8143 }
8144 
8145 /// See if we can lower a memchr call into an optimized form. If so, return
8146 /// true and lower it. Otherwise return false, and it will be lowered like a
8147 /// normal call.
8148 /// The caller already checked that \p I calls the appropriate LibFunc with a
8149 /// correct prototype.
8150 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8151   const Value *Src = I.getArgOperand(0);
8152   const Value *Char = I.getArgOperand(1);
8153   const Value *Length = I.getArgOperand(2);
8154 
8155   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8156   std::pair<SDValue, SDValue> Res =
8157     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8158                                 getValue(Src), getValue(Char), getValue(Length),
8159                                 MachinePointerInfo(Src));
8160   if (Res.first.getNode()) {
8161     setValue(&I, Res.first);
8162     PendingLoads.push_back(Res.second);
8163     return true;
8164   }
8165 
8166   return false;
8167 }
8168 
8169 /// See if we can lower a mempcpy call into an optimized form. If so, return
8170 /// true and lower it. Otherwise return false, and it will be lowered like a
8171 /// normal call.
8172 /// The caller already checked that \p I calls the appropriate LibFunc with a
8173 /// correct prototype.
8174 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8175   SDValue Dst = getValue(I.getArgOperand(0));
8176   SDValue Src = getValue(I.getArgOperand(1));
8177   SDValue Size = getValue(I.getArgOperand(2));
8178 
8179   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8180   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8181   // DAG::getMemcpy needs Alignment to be defined.
8182   Align Alignment = std::min(DstAlign, SrcAlign);
8183 
8184   bool isVol = false;
8185   SDLoc sdl = getCurSDLoc();
8186 
8187   // In the mempcpy context we need to pass in a false value for isTailCall
8188   // because the return pointer needs to be adjusted by the size of
8189   // the copied memory.
8190   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8191   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8192                              /*isTailCall=*/false,
8193                              MachinePointerInfo(I.getArgOperand(0)),
8194                              MachinePointerInfo(I.getArgOperand(1)),
8195                              I.getAAMetadata());
8196   assert(MC.getNode() != nullptr &&
8197          "** memcpy should not be lowered as TailCall in mempcpy context **");
8198   DAG.setRoot(MC);
8199 
8200   // Check if Size needs to be truncated or extended.
8201   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8202 
8203   // Adjust return pointer to point just past the last dst byte.
8204   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8205                                     Dst, Size);
8206   setValue(&I, DstPlusSize);
8207   return true;
8208 }
8209 
8210 /// See if we can lower a strcpy call into an optimized form.  If so, return
8211 /// true and lower it, otherwise return false and it will be lowered like a
8212 /// normal call.
8213 /// The caller already checked that \p I calls the appropriate LibFunc with a
8214 /// correct prototype.
8215 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8216   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8217 
8218   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8219   std::pair<SDValue, SDValue> Res =
8220     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8221                                 getValue(Arg0), getValue(Arg1),
8222                                 MachinePointerInfo(Arg0),
8223                                 MachinePointerInfo(Arg1), isStpcpy);
8224   if (Res.first.getNode()) {
8225     setValue(&I, Res.first);
8226     DAG.setRoot(Res.second);
8227     return true;
8228   }
8229 
8230   return false;
8231 }
8232 
8233 /// See if we can lower a strcmp call into an optimized form.  If so, return
8234 /// true and lower it, otherwise return false and it will be lowered like a
8235 /// normal call.
8236 /// The caller already checked that \p I calls the appropriate LibFunc with a
8237 /// correct prototype.
8238 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8239   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8240 
8241   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8242   std::pair<SDValue, SDValue> Res =
8243     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8244                                 getValue(Arg0), getValue(Arg1),
8245                                 MachinePointerInfo(Arg0),
8246                                 MachinePointerInfo(Arg1));
8247   if (Res.first.getNode()) {
8248     processIntegerCallValue(I, Res.first, true);
8249     PendingLoads.push_back(Res.second);
8250     return true;
8251   }
8252 
8253   return false;
8254 }
8255 
8256 /// See if we can lower a strlen call into an optimized form.  If so, return
8257 /// true and lower it, otherwise return false and it will be lowered like a
8258 /// normal call.
8259 /// The caller already checked that \p I calls the appropriate LibFunc with a
8260 /// correct prototype.
8261 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8262   const Value *Arg0 = I.getArgOperand(0);
8263 
8264   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8265   std::pair<SDValue, SDValue> Res =
8266     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8267                                 getValue(Arg0), MachinePointerInfo(Arg0));
8268   if (Res.first.getNode()) {
8269     processIntegerCallValue(I, Res.first, false);
8270     PendingLoads.push_back(Res.second);
8271     return true;
8272   }
8273 
8274   return false;
8275 }
8276 
8277 /// See if we can lower a strnlen call into an optimized form.  If so, return
8278 /// true and lower it, otherwise return false and it will be lowered like a
8279 /// normal call.
8280 /// The caller already checked that \p I calls the appropriate LibFunc with a
8281 /// correct prototype.
8282 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8283   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8284 
8285   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8286   std::pair<SDValue, SDValue> Res =
8287     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8288                                  getValue(Arg0), getValue(Arg1),
8289                                  MachinePointerInfo(Arg0));
8290   if (Res.first.getNode()) {
8291     processIntegerCallValue(I, Res.first, false);
8292     PendingLoads.push_back(Res.second);
8293     return true;
8294   }
8295 
8296   return false;
8297 }
8298 
8299 /// See if we can lower a unary floating-point operation into an SDNode with
8300 /// the specified Opcode.  If so, return true and lower it, otherwise return
8301 /// false and it will be lowered like a normal call.
8302 /// The caller already checked that \p I calls the appropriate LibFunc with a
8303 /// correct prototype.
8304 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8305                                               unsigned Opcode) {
8306   // We already checked this call's prototype; verify it doesn't modify errno.
8307   if (!I.onlyReadsMemory())
8308     return false;
8309 
8310   SDNodeFlags Flags;
8311   Flags.copyFMF(cast<FPMathOperator>(I));
8312 
8313   SDValue Tmp = getValue(I.getArgOperand(0));
8314   setValue(&I,
8315            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8316   return true;
8317 }
8318 
8319 /// See if we can lower a binary floating-point operation into an SDNode with
8320 /// the specified Opcode. If so, return true and lower it. Otherwise return
8321 /// false, and it will be lowered like a normal call.
8322 /// The caller already checked that \p I calls the appropriate LibFunc with a
8323 /// correct prototype.
8324 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8325                                                unsigned Opcode) {
8326   // We already checked this call's prototype; verify it doesn't modify errno.
8327   if (!I.onlyReadsMemory())
8328     return false;
8329 
8330   SDNodeFlags Flags;
8331   Flags.copyFMF(cast<FPMathOperator>(I));
8332 
8333   SDValue Tmp0 = getValue(I.getArgOperand(0));
8334   SDValue Tmp1 = getValue(I.getArgOperand(1));
8335   EVT VT = Tmp0.getValueType();
8336   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8337   return true;
8338 }
8339 
8340 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8341   // Handle inline assembly differently.
8342   if (I.isInlineAsm()) {
8343     visitInlineAsm(I);
8344     return;
8345   }
8346 
8347   if (Function *F = I.getCalledFunction()) {
8348     diagnoseDontCall(I);
8349 
8350     if (F->isDeclaration()) {
8351       // Is this an LLVM intrinsic or a target-specific intrinsic?
8352       unsigned IID = F->getIntrinsicID();
8353       if (!IID)
8354         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8355           IID = II->getIntrinsicID(F);
8356 
8357       if (IID) {
8358         visitIntrinsicCall(I, IID);
8359         return;
8360       }
8361     }
8362 
8363     // Check for well-known libc/libm calls.  If the function is internal, it
8364     // can't be a library call.  Don't do the check if marked as nobuiltin for
8365     // some reason or the call site requires strict floating point semantics.
8366     LibFunc Func;
8367     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8368         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8369         LibInfo->hasOptimizedCodeGen(Func)) {
8370       switch (Func) {
8371       default: break;
8372       case LibFunc_bcmp:
8373         if (visitMemCmpBCmpCall(I))
8374           return;
8375         break;
8376       case LibFunc_copysign:
8377       case LibFunc_copysignf:
8378       case LibFunc_copysignl:
8379         // We already checked this call's prototype; verify it doesn't modify
8380         // errno.
8381         if (I.onlyReadsMemory()) {
8382           SDValue LHS = getValue(I.getArgOperand(0));
8383           SDValue RHS = getValue(I.getArgOperand(1));
8384           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8385                                    LHS.getValueType(), LHS, RHS));
8386           return;
8387         }
8388         break;
8389       case LibFunc_fabs:
8390       case LibFunc_fabsf:
8391       case LibFunc_fabsl:
8392         if (visitUnaryFloatCall(I, ISD::FABS))
8393           return;
8394         break;
8395       case LibFunc_fmin:
8396       case LibFunc_fminf:
8397       case LibFunc_fminl:
8398         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8399           return;
8400         break;
8401       case LibFunc_fmax:
8402       case LibFunc_fmaxf:
8403       case LibFunc_fmaxl:
8404         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8405           return;
8406         break;
8407       case LibFunc_sin:
8408       case LibFunc_sinf:
8409       case LibFunc_sinl:
8410         if (visitUnaryFloatCall(I, ISD::FSIN))
8411           return;
8412         break;
8413       case LibFunc_cos:
8414       case LibFunc_cosf:
8415       case LibFunc_cosl:
8416         if (visitUnaryFloatCall(I, ISD::FCOS))
8417           return;
8418         break;
8419       case LibFunc_sqrt:
8420       case LibFunc_sqrtf:
8421       case LibFunc_sqrtl:
8422       case LibFunc_sqrt_finite:
8423       case LibFunc_sqrtf_finite:
8424       case LibFunc_sqrtl_finite:
8425         if (visitUnaryFloatCall(I, ISD::FSQRT))
8426           return;
8427         break;
8428       case LibFunc_floor:
8429       case LibFunc_floorf:
8430       case LibFunc_floorl:
8431         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8432           return;
8433         break;
8434       case LibFunc_nearbyint:
8435       case LibFunc_nearbyintf:
8436       case LibFunc_nearbyintl:
8437         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8438           return;
8439         break;
8440       case LibFunc_ceil:
8441       case LibFunc_ceilf:
8442       case LibFunc_ceill:
8443         if (visitUnaryFloatCall(I, ISD::FCEIL))
8444           return;
8445         break;
8446       case LibFunc_rint:
8447       case LibFunc_rintf:
8448       case LibFunc_rintl:
8449         if (visitUnaryFloatCall(I, ISD::FRINT))
8450           return;
8451         break;
8452       case LibFunc_round:
8453       case LibFunc_roundf:
8454       case LibFunc_roundl:
8455         if (visitUnaryFloatCall(I, ISD::FROUND))
8456           return;
8457         break;
8458       case LibFunc_trunc:
8459       case LibFunc_truncf:
8460       case LibFunc_truncl:
8461         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8462           return;
8463         break;
8464       case LibFunc_log2:
8465       case LibFunc_log2f:
8466       case LibFunc_log2l:
8467         if (visitUnaryFloatCall(I, ISD::FLOG2))
8468           return;
8469         break;
8470       case LibFunc_exp2:
8471       case LibFunc_exp2f:
8472       case LibFunc_exp2l:
8473         if (visitUnaryFloatCall(I, ISD::FEXP2))
8474           return;
8475         break;
8476       case LibFunc_memcmp:
8477         if (visitMemCmpBCmpCall(I))
8478           return;
8479         break;
8480       case LibFunc_mempcpy:
8481         if (visitMemPCpyCall(I))
8482           return;
8483         break;
8484       case LibFunc_memchr:
8485         if (visitMemChrCall(I))
8486           return;
8487         break;
8488       case LibFunc_strcpy:
8489         if (visitStrCpyCall(I, false))
8490           return;
8491         break;
8492       case LibFunc_stpcpy:
8493         if (visitStrCpyCall(I, true))
8494           return;
8495         break;
8496       case LibFunc_strcmp:
8497         if (visitStrCmpCall(I))
8498           return;
8499         break;
8500       case LibFunc_strlen:
8501         if (visitStrLenCall(I))
8502           return;
8503         break;
8504       case LibFunc_strnlen:
8505         if (visitStrNLenCall(I))
8506           return;
8507         break;
8508       }
8509     }
8510   }
8511 
8512   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8513   // have to do anything here to lower funclet bundles.
8514   // CFGuardTarget bundles are lowered in LowerCallTo.
8515   assert(!I.hasOperandBundlesOtherThan(
8516              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8517               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8518               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8519          "Cannot lower calls with arbitrary operand bundles!");
8520 
8521   SDValue Callee = getValue(I.getCalledOperand());
8522 
8523   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8524     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8525   else
8526     // Check if we can potentially perform a tail call. More detailed checking
8527     // is be done within LowerCallTo, after more information about the call is
8528     // known.
8529     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8530 }
8531 
8532 namespace {
8533 
8534 /// AsmOperandInfo - This contains information for each constraint that we are
8535 /// lowering.
8536 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8537 public:
8538   /// CallOperand - If this is the result output operand or a clobber
8539   /// this is null, otherwise it is the incoming operand to the CallInst.
8540   /// This gets modified as the asm is processed.
8541   SDValue CallOperand;
8542 
8543   /// AssignedRegs - If this is a register or register class operand, this
8544   /// contains the set of register corresponding to the operand.
8545   RegsForValue AssignedRegs;
8546 
8547   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8548     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8549   }
8550 
8551   /// Whether or not this operand accesses memory
8552   bool hasMemory(const TargetLowering &TLI) const {
8553     // Indirect operand accesses access memory.
8554     if (isIndirect)
8555       return true;
8556 
8557     for (const auto &Code : Codes)
8558       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8559         return true;
8560 
8561     return false;
8562   }
8563 };
8564 
8565 
8566 } // end anonymous namespace
8567 
8568 /// Make sure that the output operand \p OpInfo and its corresponding input
8569 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8570 /// out).
8571 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8572                                SDISelAsmOperandInfo &MatchingOpInfo,
8573                                SelectionDAG &DAG) {
8574   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8575     return;
8576 
8577   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8578   const auto &TLI = DAG.getTargetLoweringInfo();
8579 
8580   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8581       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8582                                        OpInfo.ConstraintVT);
8583   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8584       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8585                                        MatchingOpInfo.ConstraintVT);
8586   if ((OpInfo.ConstraintVT.isInteger() !=
8587        MatchingOpInfo.ConstraintVT.isInteger()) ||
8588       (MatchRC.second != InputRC.second)) {
8589     // FIXME: error out in a more elegant fashion
8590     report_fatal_error("Unsupported asm: input constraint"
8591                        " with a matching output constraint of"
8592                        " incompatible type!");
8593   }
8594   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8595 }
8596 
8597 /// Get a direct memory input to behave well as an indirect operand.
8598 /// This may introduce stores, hence the need for a \p Chain.
8599 /// \return The (possibly updated) chain.
8600 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8601                                         SDISelAsmOperandInfo &OpInfo,
8602                                         SelectionDAG &DAG) {
8603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8604 
8605   // If we don't have an indirect input, put it in the constpool if we can,
8606   // otherwise spill it to a stack slot.
8607   // TODO: This isn't quite right. We need to handle these according to
8608   // the addressing mode that the constraint wants. Also, this may take
8609   // an additional register for the computation and we don't want that
8610   // either.
8611 
8612   // If the operand is a float, integer, or vector constant, spill to a
8613   // constant pool entry to get its address.
8614   const Value *OpVal = OpInfo.CallOperandVal;
8615   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8616       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8617     OpInfo.CallOperand = DAG.getConstantPool(
8618         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8619     return Chain;
8620   }
8621 
8622   // Otherwise, create a stack slot and emit a store to it before the asm.
8623   Type *Ty = OpVal->getType();
8624   auto &DL = DAG.getDataLayout();
8625   uint64_t TySize = DL.getTypeAllocSize(Ty);
8626   MachineFunction &MF = DAG.getMachineFunction();
8627   int SSFI = MF.getFrameInfo().CreateStackObject(
8628       TySize, DL.getPrefTypeAlign(Ty), false);
8629   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8630   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8631                             MachinePointerInfo::getFixedStack(MF, SSFI),
8632                             TLI.getMemValueType(DL, Ty));
8633   OpInfo.CallOperand = StackSlot;
8634 
8635   return Chain;
8636 }
8637 
8638 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8639 /// specified operand.  We prefer to assign virtual registers, to allow the
8640 /// register allocator to handle the assignment process.  However, if the asm
8641 /// uses features that we can't model on machineinstrs, we have SDISel do the
8642 /// allocation.  This produces generally horrible, but correct, code.
8643 ///
8644 ///   OpInfo describes the operand
8645 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8646 static std::optional<unsigned>
8647 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8648                      SDISelAsmOperandInfo &OpInfo,
8649                      SDISelAsmOperandInfo &RefOpInfo) {
8650   LLVMContext &Context = *DAG.getContext();
8651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8652 
8653   MachineFunction &MF = DAG.getMachineFunction();
8654   SmallVector<unsigned, 4> Regs;
8655   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8656 
8657   // No work to do for memory/address operands.
8658   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8659       OpInfo.ConstraintType == TargetLowering::C_Address)
8660     return std::nullopt;
8661 
8662   // If this is a constraint for a single physreg, or a constraint for a
8663   // register class, find it.
8664   unsigned AssignedReg;
8665   const TargetRegisterClass *RC;
8666   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8667       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8668   // RC is unset only on failure. Return immediately.
8669   if (!RC)
8670     return std::nullopt;
8671 
8672   // Get the actual register value type.  This is important, because the user
8673   // may have asked for (e.g.) the AX register in i32 type.  We need to
8674   // remember that AX is actually i16 to get the right extension.
8675   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8676 
8677   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8678     // If this is an FP operand in an integer register (or visa versa), or more
8679     // generally if the operand value disagrees with the register class we plan
8680     // to stick it in, fix the operand type.
8681     //
8682     // If this is an input value, the bitcast to the new type is done now.
8683     // Bitcast for output value is done at the end of visitInlineAsm().
8684     if ((OpInfo.Type == InlineAsm::isOutput ||
8685          OpInfo.Type == InlineAsm::isInput) &&
8686         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8687       // Try to convert to the first EVT that the reg class contains.  If the
8688       // types are identical size, use a bitcast to convert (e.g. two differing
8689       // vector types).  Note: output bitcast is done at the end of
8690       // visitInlineAsm().
8691       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8692         // Exclude indirect inputs while they are unsupported because the code
8693         // to perform the load is missing and thus OpInfo.CallOperand still
8694         // refers to the input address rather than the pointed-to value.
8695         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8696           OpInfo.CallOperand =
8697               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8698         OpInfo.ConstraintVT = RegVT;
8699         // If the operand is an FP value and we want it in integer registers,
8700         // use the corresponding integer type. This turns an f64 value into
8701         // i64, which can be passed with two i32 values on a 32-bit machine.
8702       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8703         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8704         if (OpInfo.Type == InlineAsm::isInput)
8705           OpInfo.CallOperand =
8706               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8707         OpInfo.ConstraintVT = VT;
8708       }
8709     }
8710   }
8711 
8712   // No need to allocate a matching input constraint since the constraint it's
8713   // matching to has already been allocated.
8714   if (OpInfo.isMatchingInputConstraint())
8715     return std::nullopt;
8716 
8717   EVT ValueVT = OpInfo.ConstraintVT;
8718   if (OpInfo.ConstraintVT == MVT::Other)
8719     ValueVT = RegVT;
8720 
8721   // Initialize NumRegs.
8722   unsigned NumRegs = 1;
8723   if (OpInfo.ConstraintVT != MVT::Other)
8724     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8725 
8726   // If this is a constraint for a specific physical register, like {r17},
8727   // assign it now.
8728 
8729   // If this associated to a specific register, initialize iterator to correct
8730   // place. If virtual, make sure we have enough registers
8731 
8732   // Initialize iterator if necessary
8733   TargetRegisterClass::iterator I = RC->begin();
8734   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8735 
8736   // Do not check for single registers.
8737   if (AssignedReg) {
8738     I = std::find(I, RC->end(), AssignedReg);
8739     if (I == RC->end()) {
8740       // RC does not contain the selected register, which indicates a
8741       // mismatch between the register and the required type/bitwidth.
8742       return {AssignedReg};
8743     }
8744   }
8745 
8746   for (; NumRegs; --NumRegs, ++I) {
8747     assert(I != RC->end() && "Ran out of registers to allocate!");
8748     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8749     Regs.push_back(R);
8750   }
8751 
8752   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8753   return std::nullopt;
8754 }
8755 
8756 static unsigned
8757 findMatchingInlineAsmOperand(unsigned OperandNo,
8758                              const std::vector<SDValue> &AsmNodeOperands) {
8759   // Scan until we find the definition we already emitted of this operand.
8760   unsigned CurOp = InlineAsm::Op_FirstOperand;
8761   for (; OperandNo; --OperandNo) {
8762     // Advance to the next operand.
8763     unsigned OpFlag =
8764         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8765     assert((InlineAsm::isRegDefKind(OpFlag) ||
8766             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8767             InlineAsm::isMemKind(OpFlag)) &&
8768            "Skipped past definitions?");
8769     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8770   }
8771   return CurOp;
8772 }
8773 
8774 namespace {
8775 
8776 class ExtraFlags {
8777   unsigned Flags = 0;
8778 
8779 public:
8780   explicit ExtraFlags(const CallBase &Call) {
8781     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8782     if (IA->hasSideEffects())
8783       Flags |= InlineAsm::Extra_HasSideEffects;
8784     if (IA->isAlignStack())
8785       Flags |= InlineAsm::Extra_IsAlignStack;
8786     if (Call.isConvergent())
8787       Flags |= InlineAsm::Extra_IsConvergent;
8788     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8789   }
8790 
8791   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8792     // Ideally, we would only check against memory constraints.  However, the
8793     // meaning of an Other constraint can be target-specific and we can't easily
8794     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8795     // for Other constraints as well.
8796     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8797         OpInfo.ConstraintType == TargetLowering::C_Other) {
8798       if (OpInfo.Type == InlineAsm::isInput)
8799         Flags |= InlineAsm::Extra_MayLoad;
8800       else if (OpInfo.Type == InlineAsm::isOutput)
8801         Flags |= InlineAsm::Extra_MayStore;
8802       else if (OpInfo.Type == InlineAsm::isClobber)
8803         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8804     }
8805   }
8806 
8807   unsigned get() const { return Flags; }
8808 };
8809 
8810 } // end anonymous namespace
8811 
8812 static bool isFunction(SDValue Op) {
8813   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8814     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8815       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8816 
8817       // In normal "call dllimport func" instruction (non-inlineasm) it force
8818       // indirect access by specifing call opcode. And usually specially print
8819       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8820       // not do in this way now. (In fact, this is similar with "Data Access"
8821       // action). So here we ignore dllimport function.
8822       if (Fn && !Fn->hasDLLImportStorageClass())
8823         return true;
8824     }
8825   }
8826   return false;
8827 }
8828 
8829 /// visitInlineAsm - Handle a call to an InlineAsm object.
8830 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8831                                          const BasicBlock *EHPadBB) {
8832   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8833 
8834   /// ConstraintOperands - Information about all of the constraints.
8835   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8836 
8837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8838   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8839       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8840 
8841   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8842   // AsmDialect, MayLoad, MayStore).
8843   bool HasSideEffect = IA->hasSideEffects();
8844   ExtraFlags ExtraInfo(Call);
8845 
8846   for (auto &T : TargetConstraints) {
8847     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8848     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8849 
8850     if (OpInfo.CallOperandVal)
8851       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8852 
8853     if (!HasSideEffect)
8854       HasSideEffect = OpInfo.hasMemory(TLI);
8855 
8856     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8857     // FIXME: Could we compute this on OpInfo rather than T?
8858 
8859     // Compute the constraint code and ConstraintType to use.
8860     TLI.ComputeConstraintToUse(T, SDValue());
8861 
8862     if (T.ConstraintType == TargetLowering::C_Immediate &&
8863         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8864       // We've delayed emitting a diagnostic like the "n" constraint because
8865       // inlining could cause an integer showing up.
8866       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8867                                           "' expects an integer constant "
8868                                           "expression");
8869 
8870     ExtraInfo.update(T);
8871   }
8872 
8873   // We won't need to flush pending loads if this asm doesn't touch
8874   // memory and is nonvolatile.
8875   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8876 
8877   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8878   if (EmitEHLabels) {
8879     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8880   }
8881   bool IsCallBr = isa<CallBrInst>(Call);
8882 
8883   if (IsCallBr || EmitEHLabels) {
8884     // If this is a callbr or invoke we need to flush pending exports since
8885     // inlineasm_br and invoke are terminators.
8886     // We need to do this before nodes are glued to the inlineasm_br node.
8887     Chain = getControlRoot();
8888   }
8889 
8890   MCSymbol *BeginLabel = nullptr;
8891   if (EmitEHLabels) {
8892     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8893   }
8894 
8895   int OpNo = -1;
8896   SmallVector<StringRef> AsmStrs;
8897   IA->collectAsmStrs(AsmStrs);
8898 
8899   // Second pass over the constraints: compute which constraint option to use.
8900   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8901     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8902       OpNo++;
8903 
8904     // If this is an output operand with a matching input operand, look up the
8905     // matching input. If their types mismatch, e.g. one is an integer, the
8906     // other is floating point, or their sizes are different, flag it as an
8907     // error.
8908     if (OpInfo.hasMatchingInput()) {
8909       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8910       patchMatchingInput(OpInfo, Input, DAG);
8911     }
8912 
8913     // Compute the constraint code and ConstraintType to use.
8914     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8915 
8916     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8917          OpInfo.Type == InlineAsm::isClobber) ||
8918         OpInfo.ConstraintType == TargetLowering::C_Address)
8919       continue;
8920 
8921     // In Linux PIC model, there are 4 cases about value/label addressing:
8922     //
8923     // 1: Function call or Label jmp inside the module.
8924     // 2: Data access (such as global variable, static variable) inside module.
8925     // 3: Function call or Label jmp outside the module.
8926     // 4: Data access (such as global variable) outside the module.
8927     //
8928     // Due to current llvm inline asm architecture designed to not "recognize"
8929     // the asm code, there are quite troubles for us to treat mem addressing
8930     // differently for same value/adress used in different instuctions.
8931     // For example, in pic model, call a func may in plt way or direclty
8932     // pc-related, but lea/mov a function adress may use got.
8933     //
8934     // Here we try to "recognize" function call for the case 1 and case 3 in
8935     // inline asm. And try to adjust the constraint for them.
8936     //
8937     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8938     // label, so here we don't handle jmp function label now, but we need to
8939     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8940     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8941         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8942         TM.getCodeModel() != CodeModel::Large) {
8943       OpInfo.isIndirect = false;
8944       OpInfo.ConstraintType = TargetLowering::C_Address;
8945     }
8946 
8947     // If this is a memory input, and if the operand is not indirect, do what we
8948     // need to provide an address for the memory input.
8949     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8950         !OpInfo.isIndirect) {
8951       assert((OpInfo.isMultipleAlternative ||
8952               (OpInfo.Type == InlineAsm::isInput)) &&
8953              "Can only indirectify direct input operands!");
8954 
8955       // Memory operands really want the address of the value.
8956       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8957 
8958       // There is no longer a Value* corresponding to this operand.
8959       OpInfo.CallOperandVal = nullptr;
8960 
8961       // It is now an indirect operand.
8962       OpInfo.isIndirect = true;
8963     }
8964 
8965   }
8966 
8967   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8968   std::vector<SDValue> AsmNodeOperands;
8969   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8970   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8971       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8972 
8973   // If we have a !srcloc metadata node associated with it, we want to attach
8974   // this to the ultimately generated inline asm machineinstr.  To do this, we
8975   // pass in the third operand as this (potentially null) inline asm MDNode.
8976   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8977   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8978 
8979   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8980   // bits as operand 3.
8981   AsmNodeOperands.push_back(DAG.getTargetConstant(
8982       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8983 
8984   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8985   // this, assign virtual and physical registers for inputs and otput.
8986   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8987     // Assign Registers.
8988     SDISelAsmOperandInfo &RefOpInfo =
8989         OpInfo.isMatchingInputConstraint()
8990             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8991             : OpInfo;
8992     const auto RegError =
8993         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8994     if (RegError) {
8995       const MachineFunction &MF = DAG.getMachineFunction();
8996       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8997       const char *RegName = TRI.getName(RegError.value());
8998       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8999                                    "' allocated for constraint '" +
9000                                    Twine(OpInfo.ConstraintCode) +
9001                                    "' does not match required type");
9002       return;
9003     }
9004 
9005     auto DetectWriteToReservedRegister = [&]() {
9006       const MachineFunction &MF = DAG.getMachineFunction();
9007       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9008       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9009         if (Register::isPhysicalRegister(Reg) &&
9010             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9011           const char *RegName = TRI.getName(Reg);
9012           emitInlineAsmError(Call, "write to reserved register '" +
9013                                        Twine(RegName) + "'");
9014           return true;
9015         }
9016       }
9017       return false;
9018     };
9019     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9020             (OpInfo.Type == InlineAsm::isInput &&
9021              !OpInfo.isMatchingInputConstraint())) &&
9022            "Only address as input operand is allowed.");
9023 
9024     switch (OpInfo.Type) {
9025     case InlineAsm::isOutput:
9026       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9027         unsigned ConstraintID =
9028             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9029         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9030                "Failed to convert memory constraint code to constraint id.");
9031 
9032         // Add information to the INLINEASM node to know about this output.
9033         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9034         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9035         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9036                                                         MVT::i32));
9037         AsmNodeOperands.push_back(OpInfo.CallOperand);
9038       } else {
9039         // Otherwise, this outputs to a register (directly for C_Register /
9040         // C_RegisterClass, and a target-defined fashion for
9041         // C_Immediate/C_Other). Find a register that we can use.
9042         if (OpInfo.AssignedRegs.Regs.empty()) {
9043           emitInlineAsmError(
9044               Call, "couldn't allocate output register for constraint '" +
9045                         Twine(OpInfo.ConstraintCode) + "'");
9046           return;
9047         }
9048 
9049         if (DetectWriteToReservedRegister())
9050           return;
9051 
9052         // Add information to the INLINEASM node to know that this register is
9053         // set.
9054         OpInfo.AssignedRegs.AddInlineAsmOperands(
9055             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9056                                   : InlineAsm::Kind_RegDef,
9057             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9058       }
9059       break;
9060 
9061     case InlineAsm::isInput:
9062     case InlineAsm::isLabel: {
9063       SDValue InOperandVal = OpInfo.CallOperand;
9064 
9065       if (OpInfo.isMatchingInputConstraint()) {
9066         // If this is required to match an output register we have already set,
9067         // just use its register.
9068         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9069                                                   AsmNodeOperands);
9070         unsigned OpFlag =
9071           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9072         if (InlineAsm::isRegDefKind(OpFlag) ||
9073             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9074           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9075           if (OpInfo.isIndirect) {
9076             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9077             emitInlineAsmError(Call, "inline asm not supported yet: "
9078                                      "don't know how to handle tied "
9079                                      "indirect register inputs");
9080             return;
9081           }
9082 
9083           SmallVector<unsigned, 4> Regs;
9084           MachineFunction &MF = DAG.getMachineFunction();
9085           MachineRegisterInfo &MRI = MF.getRegInfo();
9086           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9087           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9088           Register TiedReg = R->getReg();
9089           MVT RegVT = R->getSimpleValueType(0);
9090           const TargetRegisterClass *RC =
9091               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9092               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9093                                       : TRI.getMinimalPhysRegClass(TiedReg);
9094           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9095           for (unsigned i = 0; i != NumRegs; ++i)
9096             Regs.push_back(MRI.createVirtualRegister(RC));
9097 
9098           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9099 
9100           SDLoc dl = getCurSDLoc();
9101           // Use the produced MatchedRegs object to
9102           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9103           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9104                                            true, OpInfo.getMatchedOperand(), dl,
9105                                            DAG, AsmNodeOperands);
9106           break;
9107         }
9108 
9109         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9110         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9111                "Unexpected number of operands");
9112         // Add information to the INLINEASM node to know about this input.
9113         // See InlineAsm.h isUseOperandTiedToDef.
9114         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9115         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9116                                                     OpInfo.getMatchedOperand());
9117         AsmNodeOperands.push_back(DAG.getTargetConstant(
9118             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9119         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9120         break;
9121       }
9122 
9123       // Treat indirect 'X' constraint as memory.
9124       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9125           OpInfo.isIndirect)
9126         OpInfo.ConstraintType = TargetLowering::C_Memory;
9127 
9128       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9129           OpInfo.ConstraintType == TargetLowering::C_Other) {
9130         std::vector<SDValue> Ops;
9131         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9132                                           Ops, DAG);
9133         if (Ops.empty()) {
9134           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9135             if (isa<ConstantSDNode>(InOperandVal)) {
9136               emitInlineAsmError(Call, "value out of range for constraint '" +
9137                                            Twine(OpInfo.ConstraintCode) + "'");
9138               return;
9139             }
9140 
9141           emitInlineAsmError(Call,
9142                              "invalid operand for inline asm constraint '" +
9143                                  Twine(OpInfo.ConstraintCode) + "'");
9144           return;
9145         }
9146 
9147         // Add information to the INLINEASM node to know about this input.
9148         unsigned ResOpType =
9149           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9150         AsmNodeOperands.push_back(DAG.getTargetConstant(
9151             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9152         llvm::append_range(AsmNodeOperands, Ops);
9153         break;
9154       }
9155 
9156       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9157         assert((OpInfo.isIndirect ||
9158                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9159                "Operand must be indirect to be a mem!");
9160         assert(InOperandVal.getValueType() ==
9161                    TLI.getPointerTy(DAG.getDataLayout()) &&
9162                "Memory operands expect pointer values");
9163 
9164         unsigned ConstraintID =
9165             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9166         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9167                "Failed to convert memory constraint code to constraint id.");
9168 
9169         // Add information to the INLINEASM node to know about this input.
9170         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9171         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9172         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9173                                                         getCurSDLoc(),
9174                                                         MVT::i32));
9175         AsmNodeOperands.push_back(InOperandVal);
9176         break;
9177       }
9178 
9179       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9180         assert(InOperandVal.getValueType() ==
9181                    TLI.getPointerTy(DAG.getDataLayout()) &&
9182                "Address operands expect pointer values");
9183 
9184         unsigned ConstraintID =
9185             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9186         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9187                "Failed to convert memory constraint code to constraint id.");
9188 
9189         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9190 
9191         SDValue AsmOp = InOperandVal;
9192         if (isFunction(InOperandVal)) {
9193           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9194           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9195           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9196                                              InOperandVal.getValueType(),
9197                                              GA->getOffset());
9198         }
9199 
9200         // Add information to the INLINEASM node to know about this input.
9201         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9202 
9203         AsmNodeOperands.push_back(
9204             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9205 
9206         AsmNodeOperands.push_back(AsmOp);
9207         break;
9208       }
9209 
9210       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9211               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9212              "Unknown constraint type!");
9213 
9214       // TODO: Support this.
9215       if (OpInfo.isIndirect) {
9216         emitInlineAsmError(
9217             Call, "Don't know how to handle indirect register inputs yet "
9218                   "for constraint '" +
9219                       Twine(OpInfo.ConstraintCode) + "'");
9220         return;
9221       }
9222 
9223       // Copy the input into the appropriate registers.
9224       if (OpInfo.AssignedRegs.Regs.empty()) {
9225         emitInlineAsmError(Call,
9226                            "couldn't allocate input reg for constraint '" +
9227                                Twine(OpInfo.ConstraintCode) + "'");
9228         return;
9229       }
9230 
9231       if (DetectWriteToReservedRegister())
9232         return;
9233 
9234       SDLoc dl = getCurSDLoc();
9235 
9236       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9237                                         &Call);
9238 
9239       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9240                                                dl, DAG, AsmNodeOperands);
9241       break;
9242     }
9243     case InlineAsm::isClobber:
9244       // Add the clobbered value to the operand list, so that the register
9245       // allocator is aware that the physreg got clobbered.
9246       if (!OpInfo.AssignedRegs.Regs.empty())
9247         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9248                                                  false, 0, getCurSDLoc(), DAG,
9249                                                  AsmNodeOperands);
9250       break;
9251     }
9252   }
9253 
9254   // Finish up input operands.  Set the input chain and add the flag last.
9255   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9256   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9257 
9258   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9259   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9260                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9261   Flag = Chain.getValue(1);
9262 
9263   // Do additional work to generate outputs.
9264 
9265   SmallVector<EVT, 1> ResultVTs;
9266   SmallVector<SDValue, 1> ResultValues;
9267   SmallVector<SDValue, 8> OutChains;
9268 
9269   llvm::Type *CallResultType = Call.getType();
9270   ArrayRef<Type *> ResultTypes;
9271   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9272     ResultTypes = StructResult->elements();
9273   else if (!CallResultType->isVoidTy())
9274     ResultTypes = makeArrayRef(CallResultType);
9275 
9276   auto CurResultType = ResultTypes.begin();
9277   auto handleRegAssign = [&](SDValue V) {
9278     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9279     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9280     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9281     ++CurResultType;
9282     // If the type of the inline asm call site return value is different but has
9283     // same size as the type of the asm output bitcast it.  One example of this
9284     // is for vectors with different width / number of elements.  This can
9285     // happen for register classes that can contain multiple different value
9286     // types.  The preg or vreg allocated may not have the same VT as was
9287     // expected.
9288     //
9289     // This can also happen for a return value that disagrees with the register
9290     // class it is put in, eg. a double in a general-purpose register on a
9291     // 32-bit machine.
9292     if (ResultVT != V.getValueType() &&
9293         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9294       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9295     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9296              V.getValueType().isInteger()) {
9297       // If a result value was tied to an input value, the computed result
9298       // may have a wider width than the expected result.  Extract the
9299       // relevant portion.
9300       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9301     }
9302     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9303     ResultVTs.push_back(ResultVT);
9304     ResultValues.push_back(V);
9305   };
9306 
9307   // Deal with output operands.
9308   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9309     if (OpInfo.Type == InlineAsm::isOutput) {
9310       SDValue Val;
9311       // Skip trivial output operands.
9312       if (OpInfo.AssignedRegs.Regs.empty())
9313         continue;
9314 
9315       switch (OpInfo.ConstraintType) {
9316       case TargetLowering::C_Register:
9317       case TargetLowering::C_RegisterClass:
9318         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9319                                                   Chain, &Flag, &Call);
9320         break;
9321       case TargetLowering::C_Immediate:
9322       case TargetLowering::C_Other:
9323         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9324                                               OpInfo, DAG);
9325         break;
9326       case TargetLowering::C_Memory:
9327         break; // Already handled.
9328       case TargetLowering::C_Address:
9329         break; // Silence warning.
9330       case TargetLowering::C_Unknown:
9331         assert(false && "Unexpected unknown constraint");
9332       }
9333 
9334       // Indirect output manifest as stores. Record output chains.
9335       if (OpInfo.isIndirect) {
9336         const Value *Ptr = OpInfo.CallOperandVal;
9337         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9338         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9339                                      MachinePointerInfo(Ptr));
9340         OutChains.push_back(Store);
9341       } else {
9342         // generate CopyFromRegs to associated registers.
9343         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9344         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9345           for (const SDValue &V : Val->op_values())
9346             handleRegAssign(V);
9347         } else
9348           handleRegAssign(Val);
9349       }
9350     }
9351   }
9352 
9353   // Set results.
9354   if (!ResultValues.empty()) {
9355     assert(CurResultType == ResultTypes.end() &&
9356            "Mismatch in number of ResultTypes");
9357     assert(ResultValues.size() == ResultTypes.size() &&
9358            "Mismatch in number of output operands in asm result");
9359 
9360     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9361                             DAG.getVTList(ResultVTs), ResultValues);
9362     setValue(&Call, V);
9363   }
9364 
9365   // Collect store chains.
9366   if (!OutChains.empty())
9367     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9368 
9369   if (EmitEHLabels) {
9370     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9371   }
9372 
9373   // Only Update Root if inline assembly has a memory effect.
9374   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9375       EmitEHLabels)
9376     DAG.setRoot(Chain);
9377 }
9378 
9379 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9380                                              const Twine &Message) {
9381   LLVMContext &Ctx = *DAG.getContext();
9382   Ctx.emitError(&Call, Message);
9383 
9384   // Make sure we leave the DAG in a valid state
9385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9386   SmallVector<EVT, 1> ValueVTs;
9387   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9388 
9389   if (ValueVTs.empty())
9390     return;
9391 
9392   SmallVector<SDValue, 1> Ops;
9393   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9394     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9395 
9396   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9397 }
9398 
9399 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9400   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9401                           MVT::Other, getRoot(),
9402                           getValue(I.getArgOperand(0)),
9403                           DAG.getSrcValue(I.getArgOperand(0))));
9404 }
9405 
9406 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9408   const DataLayout &DL = DAG.getDataLayout();
9409   SDValue V = DAG.getVAArg(
9410       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9411       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9412       DL.getABITypeAlign(I.getType()).value());
9413   DAG.setRoot(V.getValue(1));
9414 
9415   if (I.getType()->isPointerTy())
9416     V = DAG.getPtrExtOrTrunc(
9417         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9418   setValue(&I, V);
9419 }
9420 
9421 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9422   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9423                           MVT::Other, getRoot(),
9424                           getValue(I.getArgOperand(0)),
9425                           DAG.getSrcValue(I.getArgOperand(0))));
9426 }
9427 
9428 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9429   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9430                           MVT::Other, getRoot(),
9431                           getValue(I.getArgOperand(0)),
9432                           getValue(I.getArgOperand(1)),
9433                           DAG.getSrcValue(I.getArgOperand(0)),
9434                           DAG.getSrcValue(I.getArgOperand(1))));
9435 }
9436 
9437 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9438                                                     const Instruction &I,
9439                                                     SDValue Op) {
9440   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9441   if (!Range)
9442     return Op;
9443 
9444   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9445   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9446     return Op;
9447 
9448   APInt Lo = CR.getUnsignedMin();
9449   if (!Lo.isMinValue())
9450     return Op;
9451 
9452   APInt Hi = CR.getUnsignedMax();
9453   unsigned Bits = std::max(Hi.getActiveBits(),
9454                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9455 
9456   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9457 
9458   SDLoc SL = getCurSDLoc();
9459 
9460   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9461                              DAG.getValueType(SmallVT));
9462   unsigned NumVals = Op.getNode()->getNumValues();
9463   if (NumVals == 1)
9464     return ZExt;
9465 
9466   SmallVector<SDValue, 4> Ops;
9467 
9468   Ops.push_back(ZExt);
9469   for (unsigned I = 1; I != NumVals; ++I)
9470     Ops.push_back(Op.getValue(I));
9471 
9472   return DAG.getMergeValues(Ops, SL);
9473 }
9474 
9475 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9476 /// the call being lowered.
9477 ///
9478 /// This is a helper for lowering intrinsics that follow a target calling
9479 /// convention or require stack pointer adjustment. Only a subset of the
9480 /// intrinsic's operands need to participate in the calling convention.
9481 void SelectionDAGBuilder::populateCallLoweringInfo(
9482     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9483     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9484     bool IsPatchPoint) {
9485   TargetLowering::ArgListTy Args;
9486   Args.reserve(NumArgs);
9487 
9488   // Populate the argument list.
9489   // Attributes for args start at offset 1, after the return attribute.
9490   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9491        ArgI != ArgE; ++ArgI) {
9492     const Value *V = Call->getOperand(ArgI);
9493 
9494     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9495 
9496     TargetLowering::ArgListEntry Entry;
9497     Entry.Node = getValue(V);
9498     Entry.Ty = V->getType();
9499     Entry.setAttributes(Call, ArgI);
9500     Args.push_back(Entry);
9501   }
9502 
9503   CLI.setDebugLoc(getCurSDLoc())
9504       .setChain(getRoot())
9505       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9506       .setDiscardResult(Call->use_empty())
9507       .setIsPatchPoint(IsPatchPoint)
9508       .setIsPreallocated(
9509           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9510 }
9511 
9512 /// Add a stack map intrinsic call's live variable operands to a stackmap
9513 /// or patchpoint target node's operand list.
9514 ///
9515 /// Constants are converted to TargetConstants purely as an optimization to
9516 /// avoid constant materialization and register allocation.
9517 ///
9518 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9519 /// generate addess computation nodes, and so FinalizeISel can convert the
9520 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9521 /// address materialization and register allocation, but may also be required
9522 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9523 /// alloca in the entry block, then the runtime may assume that the alloca's
9524 /// StackMap location can be read immediately after compilation and that the
9525 /// location is valid at any point during execution (this is similar to the
9526 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9527 /// only available in a register, then the runtime would need to trap when
9528 /// execution reaches the StackMap in order to read the alloca's location.
9529 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9530                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9531                                 SelectionDAGBuilder &Builder) {
9532   SelectionDAG &DAG = Builder.DAG;
9533   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9534     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9535 
9536     // Things on the stack are pointer-typed, meaning that they are already
9537     // legal and can be emitted directly to target nodes.
9538     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9539       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9540     } else {
9541       // Otherwise emit a target independent node to be legalised.
9542       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9543     }
9544   }
9545 }
9546 
9547 /// Lower llvm.experimental.stackmap.
9548 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9549   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9550   //                                  [live variables...])
9551 
9552   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9553 
9554   SDValue Chain, InFlag, Callee;
9555   SmallVector<SDValue, 32> Ops;
9556 
9557   SDLoc DL = getCurSDLoc();
9558   Callee = getValue(CI.getCalledOperand());
9559 
9560   // The stackmap intrinsic only records the live variables (the arguments
9561   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9562   // intrinsic, this won't be lowered to a function call. This means we don't
9563   // have to worry about calling conventions and target specific lowering code.
9564   // Instead we perform the call lowering right here.
9565   //
9566   // chain, flag = CALLSEQ_START(chain, 0, 0)
9567   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9568   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9569   //
9570   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9571   InFlag = Chain.getValue(1);
9572 
9573   // Add the STACKMAP operands, starting with DAG house-keeping.
9574   Ops.push_back(Chain);
9575   Ops.push_back(InFlag);
9576 
9577   // Add the <id>, <numShadowBytes> operands.
9578   //
9579   // These do not require legalisation, and can be emitted directly to target
9580   // constant nodes.
9581   SDValue ID = getValue(CI.getArgOperand(0));
9582   assert(ID.getValueType() == MVT::i64);
9583   SDValue IDConst = DAG.getTargetConstant(
9584       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9585   Ops.push_back(IDConst);
9586 
9587   SDValue Shad = getValue(CI.getArgOperand(1));
9588   assert(Shad.getValueType() == MVT::i32);
9589   SDValue ShadConst = DAG.getTargetConstant(
9590       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9591   Ops.push_back(ShadConst);
9592 
9593   // Add the live variables.
9594   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9595 
9596   // Create the STACKMAP node.
9597   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9598   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9599   InFlag = Chain.getValue(1);
9600 
9601   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9602 
9603   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9604 
9605   // Set the root to the target-lowered call chain.
9606   DAG.setRoot(Chain);
9607 
9608   // Inform the Frame Information that we have a stackmap in this function.
9609   FuncInfo.MF->getFrameInfo().setHasStackMap();
9610 }
9611 
9612 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9613 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9614                                           const BasicBlock *EHPadBB) {
9615   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9616   //                                                 i32 <numBytes>,
9617   //                                                 i8* <target>,
9618   //                                                 i32 <numArgs>,
9619   //                                                 [Args...],
9620   //                                                 [live variables...])
9621 
9622   CallingConv::ID CC = CB.getCallingConv();
9623   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9624   bool HasDef = !CB.getType()->isVoidTy();
9625   SDLoc dl = getCurSDLoc();
9626   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9627 
9628   // Handle immediate and symbolic callees.
9629   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9630     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9631                                    /*isTarget=*/true);
9632   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9633     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9634                                          SDLoc(SymbolicCallee),
9635                                          SymbolicCallee->getValueType(0));
9636 
9637   // Get the real number of arguments participating in the call <numArgs>
9638   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9639   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9640 
9641   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9642   // Intrinsics include all meta-operands up to but not including CC.
9643   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9644   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9645          "Not enough arguments provided to the patchpoint intrinsic");
9646 
9647   // For AnyRegCC the arguments are lowered later on manually.
9648   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9649   Type *ReturnTy =
9650       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9651 
9652   TargetLowering::CallLoweringInfo CLI(DAG);
9653   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9654                            ReturnTy, true);
9655   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9656 
9657   SDNode *CallEnd = Result.second.getNode();
9658   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9659     CallEnd = CallEnd->getOperand(0).getNode();
9660 
9661   /// Get a call instruction from the call sequence chain.
9662   /// Tail calls are not allowed.
9663   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9664          "Expected a callseq node.");
9665   SDNode *Call = CallEnd->getOperand(0).getNode();
9666   bool HasGlue = Call->getGluedNode();
9667 
9668   // Replace the target specific call node with the patchable intrinsic.
9669   SmallVector<SDValue, 8> Ops;
9670 
9671   // Push the chain.
9672   Ops.push_back(*(Call->op_begin()));
9673 
9674   // Optionally, push the glue (if any).
9675   if (HasGlue)
9676     Ops.push_back(*(Call->op_end() - 1));
9677 
9678   // Push the register mask info.
9679   if (HasGlue)
9680     Ops.push_back(*(Call->op_end() - 2));
9681   else
9682     Ops.push_back(*(Call->op_end() - 1));
9683 
9684   // Add the <id> and <numBytes> constants.
9685   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9686   Ops.push_back(DAG.getTargetConstant(
9687                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9688   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9689   Ops.push_back(DAG.getTargetConstant(
9690                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9691                   MVT::i32));
9692 
9693   // Add the callee.
9694   Ops.push_back(Callee);
9695 
9696   // Adjust <numArgs> to account for any arguments that have been passed on the
9697   // stack instead.
9698   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9699   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9700   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9701   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9702 
9703   // Add the calling convention
9704   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9705 
9706   // Add the arguments we omitted previously. The register allocator should
9707   // place these in any free register.
9708   if (IsAnyRegCC)
9709     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9710       Ops.push_back(getValue(CB.getArgOperand(i)));
9711 
9712   // Push the arguments from the call instruction.
9713   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9714   Ops.append(Call->op_begin() + 2, e);
9715 
9716   // Push live variables for the stack map.
9717   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9718 
9719   SDVTList NodeTys;
9720   if (IsAnyRegCC && HasDef) {
9721     // Create the return types based on the intrinsic definition
9722     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9723     SmallVector<EVT, 3> ValueVTs;
9724     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9725     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9726 
9727     // There is always a chain and a glue type at the end
9728     ValueVTs.push_back(MVT::Other);
9729     ValueVTs.push_back(MVT::Glue);
9730     NodeTys = DAG.getVTList(ValueVTs);
9731   } else
9732     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9733 
9734   // Replace the target specific call node with a PATCHPOINT node.
9735   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9736 
9737   // Update the NodeMap.
9738   if (HasDef) {
9739     if (IsAnyRegCC)
9740       setValue(&CB, SDValue(PPV.getNode(), 0));
9741     else
9742       setValue(&CB, Result.first);
9743   }
9744 
9745   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9746   // call sequence. Furthermore the location of the chain and glue can change
9747   // when the AnyReg calling convention is used and the intrinsic returns a
9748   // value.
9749   if (IsAnyRegCC && HasDef) {
9750     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9751     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9752     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9753   } else
9754     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9755   DAG.DeleteNode(Call);
9756 
9757   // Inform the Frame Information that we have a patchpoint in this function.
9758   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9759 }
9760 
9761 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9762                                             unsigned Intrinsic) {
9763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9764   SDValue Op1 = getValue(I.getArgOperand(0));
9765   SDValue Op2;
9766   if (I.arg_size() > 1)
9767     Op2 = getValue(I.getArgOperand(1));
9768   SDLoc dl = getCurSDLoc();
9769   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9770   SDValue Res;
9771   SDNodeFlags SDFlags;
9772   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9773     SDFlags.copyFMF(*FPMO);
9774 
9775   switch (Intrinsic) {
9776   case Intrinsic::vector_reduce_fadd:
9777     if (SDFlags.hasAllowReassociation())
9778       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9779                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9780                         SDFlags);
9781     else
9782       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9783     break;
9784   case Intrinsic::vector_reduce_fmul:
9785     if (SDFlags.hasAllowReassociation())
9786       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9787                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9788                         SDFlags);
9789     else
9790       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9791     break;
9792   case Intrinsic::vector_reduce_add:
9793     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9794     break;
9795   case Intrinsic::vector_reduce_mul:
9796     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9797     break;
9798   case Intrinsic::vector_reduce_and:
9799     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9800     break;
9801   case Intrinsic::vector_reduce_or:
9802     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9803     break;
9804   case Intrinsic::vector_reduce_xor:
9805     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9806     break;
9807   case Intrinsic::vector_reduce_smax:
9808     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9809     break;
9810   case Intrinsic::vector_reduce_smin:
9811     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9812     break;
9813   case Intrinsic::vector_reduce_umax:
9814     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9815     break;
9816   case Intrinsic::vector_reduce_umin:
9817     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9818     break;
9819   case Intrinsic::vector_reduce_fmax:
9820     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9821     break;
9822   case Intrinsic::vector_reduce_fmin:
9823     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9824     break;
9825   default:
9826     llvm_unreachable("Unhandled vector reduce intrinsic");
9827   }
9828   setValue(&I, Res);
9829 }
9830 
9831 /// Returns an AttributeList representing the attributes applied to the return
9832 /// value of the given call.
9833 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9834   SmallVector<Attribute::AttrKind, 2> Attrs;
9835   if (CLI.RetSExt)
9836     Attrs.push_back(Attribute::SExt);
9837   if (CLI.RetZExt)
9838     Attrs.push_back(Attribute::ZExt);
9839   if (CLI.IsInReg)
9840     Attrs.push_back(Attribute::InReg);
9841 
9842   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9843                             Attrs);
9844 }
9845 
9846 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9847 /// implementation, which just calls LowerCall.
9848 /// FIXME: When all targets are
9849 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9850 std::pair<SDValue, SDValue>
9851 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9852   // Handle the incoming return values from the call.
9853   CLI.Ins.clear();
9854   Type *OrigRetTy = CLI.RetTy;
9855   SmallVector<EVT, 4> RetTys;
9856   SmallVector<uint64_t, 4> Offsets;
9857   auto &DL = CLI.DAG.getDataLayout();
9858   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9859 
9860   if (CLI.IsPostTypeLegalization) {
9861     // If we are lowering a libcall after legalization, split the return type.
9862     SmallVector<EVT, 4> OldRetTys;
9863     SmallVector<uint64_t, 4> OldOffsets;
9864     RetTys.swap(OldRetTys);
9865     Offsets.swap(OldOffsets);
9866 
9867     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9868       EVT RetVT = OldRetTys[i];
9869       uint64_t Offset = OldOffsets[i];
9870       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9871       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9872       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9873       RetTys.append(NumRegs, RegisterVT);
9874       for (unsigned j = 0; j != NumRegs; ++j)
9875         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9876     }
9877   }
9878 
9879   SmallVector<ISD::OutputArg, 4> Outs;
9880   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9881 
9882   bool CanLowerReturn =
9883       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9884                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9885 
9886   SDValue DemoteStackSlot;
9887   int DemoteStackIdx = -100;
9888   if (!CanLowerReturn) {
9889     // FIXME: equivalent assert?
9890     // assert(!CS.hasInAllocaArgument() &&
9891     //        "sret demotion is incompatible with inalloca");
9892     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9893     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9894     MachineFunction &MF = CLI.DAG.getMachineFunction();
9895     DemoteStackIdx =
9896         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9897     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9898                                               DL.getAllocaAddrSpace());
9899 
9900     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9901     ArgListEntry Entry;
9902     Entry.Node = DemoteStackSlot;
9903     Entry.Ty = StackSlotPtrType;
9904     Entry.IsSExt = false;
9905     Entry.IsZExt = false;
9906     Entry.IsInReg = false;
9907     Entry.IsSRet = true;
9908     Entry.IsNest = false;
9909     Entry.IsByVal = false;
9910     Entry.IsByRef = false;
9911     Entry.IsReturned = false;
9912     Entry.IsSwiftSelf = false;
9913     Entry.IsSwiftAsync = false;
9914     Entry.IsSwiftError = false;
9915     Entry.IsCFGuardTarget = false;
9916     Entry.Alignment = Alignment;
9917     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9918     CLI.NumFixedArgs += 1;
9919     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9920     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9921 
9922     // sret demotion isn't compatible with tail-calls, since the sret argument
9923     // points into the callers stack frame.
9924     CLI.IsTailCall = false;
9925   } else {
9926     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9927         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9928     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9929       ISD::ArgFlagsTy Flags;
9930       if (NeedsRegBlock) {
9931         Flags.setInConsecutiveRegs();
9932         if (I == RetTys.size() - 1)
9933           Flags.setInConsecutiveRegsLast();
9934       }
9935       EVT VT = RetTys[I];
9936       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9937                                                      CLI.CallConv, VT);
9938       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9939                                                        CLI.CallConv, VT);
9940       for (unsigned i = 0; i != NumRegs; ++i) {
9941         ISD::InputArg MyFlags;
9942         MyFlags.Flags = Flags;
9943         MyFlags.VT = RegisterVT;
9944         MyFlags.ArgVT = VT;
9945         MyFlags.Used = CLI.IsReturnValueUsed;
9946         if (CLI.RetTy->isPointerTy()) {
9947           MyFlags.Flags.setPointer();
9948           MyFlags.Flags.setPointerAddrSpace(
9949               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9950         }
9951         if (CLI.RetSExt)
9952           MyFlags.Flags.setSExt();
9953         if (CLI.RetZExt)
9954           MyFlags.Flags.setZExt();
9955         if (CLI.IsInReg)
9956           MyFlags.Flags.setInReg();
9957         CLI.Ins.push_back(MyFlags);
9958       }
9959     }
9960   }
9961 
9962   // We push in swifterror return as the last element of CLI.Ins.
9963   ArgListTy &Args = CLI.getArgs();
9964   if (supportSwiftError()) {
9965     for (const ArgListEntry &Arg : Args) {
9966       if (Arg.IsSwiftError) {
9967         ISD::InputArg MyFlags;
9968         MyFlags.VT = getPointerTy(DL);
9969         MyFlags.ArgVT = EVT(getPointerTy(DL));
9970         MyFlags.Flags.setSwiftError();
9971         CLI.Ins.push_back(MyFlags);
9972       }
9973     }
9974   }
9975 
9976   // Handle all of the outgoing arguments.
9977   CLI.Outs.clear();
9978   CLI.OutVals.clear();
9979   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9980     SmallVector<EVT, 4> ValueVTs;
9981     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9982     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9983     Type *FinalType = Args[i].Ty;
9984     if (Args[i].IsByVal)
9985       FinalType = Args[i].IndirectType;
9986     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9987         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9988     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9989          ++Value) {
9990       EVT VT = ValueVTs[Value];
9991       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9992       SDValue Op = SDValue(Args[i].Node.getNode(),
9993                            Args[i].Node.getResNo() + Value);
9994       ISD::ArgFlagsTy Flags;
9995 
9996       // Certain targets (such as MIPS), may have a different ABI alignment
9997       // for a type depending on the context. Give the target a chance to
9998       // specify the alignment it wants.
9999       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10000       Flags.setOrigAlign(OriginalAlignment);
10001 
10002       if (Args[i].Ty->isPointerTy()) {
10003         Flags.setPointer();
10004         Flags.setPointerAddrSpace(
10005             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10006       }
10007       if (Args[i].IsZExt)
10008         Flags.setZExt();
10009       if (Args[i].IsSExt)
10010         Flags.setSExt();
10011       if (Args[i].IsInReg) {
10012         // If we are using vectorcall calling convention, a structure that is
10013         // passed InReg - is surely an HVA
10014         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10015             isa<StructType>(FinalType)) {
10016           // The first value of a structure is marked
10017           if (0 == Value)
10018             Flags.setHvaStart();
10019           Flags.setHva();
10020         }
10021         // Set InReg Flag
10022         Flags.setInReg();
10023       }
10024       if (Args[i].IsSRet)
10025         Flags.setSRet();
10026       if (Args[i].IsSwiftSelf)
10027         Flags.setSwiftSelf();
10028       if (Args[i].IsSwiftAsync)
10029         Flags.setSwiftAsync();
10030       if (Args[i].IsSwiftError)
10031         Flags.setSwiftError();
10032       if (Args[i].IsCFGuardTarget)
10033         Flags.setCFGuardTarget();
10034       if (Args[i].IsByVal)
10035         Flags.setByVal();
10036       if (Args[i].IsByRef)
10037         Flags.setByRef();
10038       if (Args[i].IsPreallocated) {
10039         Flags.setPreallocated();
10040         // Set the byval flag for CCAssignFn callbacks that don't know about
10041         // preallocated.  This way we can know how many bytes we should've
10042         // allocated and how many bytes a callee cleanup function will pop.  If
10043         // we port preallocated to more targets, we'll have to add custom
10044         // preallocated handling in the various CC lowering callbacks.
10045         Flags.setByVal();
10046       }
10047       if (Args[i].IsInAlloca) {
10048         Flags.setInAlloca();
10049         // Set the byval flag for CCAssignFn callbacks that don't know about
10050         // inalloca.  This way we can know how many bytes we should've allocated
10051         // and how many bytes a callee cleanup function will pop.  If we port
10052         // inalloca to more targets, we'll have to add custom inalloca handling
10053         // in the various CC lowering callbacks.
10054         Flags.setByVal();
10055       }
10056       Align MemAlign;
10057       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10058         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10059         Flags.setByValSize(FrameSize);
10060 
10061         // info is not there but there are cases it cannot get right.
10062         if (auto MA = Args[i].Alignment)
10063           MemAlign = *MA;
10064         else
10065           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10066       } else if (auto MA = Args[i].Alignment) {
10067         MemAlign = *MA;
10068       } else {
10069         MemAlign = OriginalAlignment;
10070       }
10071       Flags.setMemAlign(MemAlign);
10072       if (Args[i].IsNest)
10073         Flags.setNest();
10074       if (NeedsRegBlock)
10075         Flags.setInConsecutiveRegs();
10076 
10077       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10078                                                  CLI.CallConv, VT);
10079       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10080                                                         CLI.CallConv, VT);
10081       SmallVector<SDValue, 4> Parts(NumParts);
10082       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10083 
10084       if (Args[i].IsSExt)
10085         ExtendKind = ISD::SIGN_EXTEND;
10086       else if (Args[i].IsZExt)
10087         ExtendKind = ISD::ZERO_EXTEND;
10088 
10089       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10090       // for now.
10091       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10092           CanLowerReturn) {
10093         assert((CLI.RetTy == Args[i].Ty ||
10094                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10095                  CLI.RetTy->getPointerAddressSpace() ==
10096                      Args[i].Ty->getPointerAddressSpace())) &&
10097                RetTys.size() == NumValues && "unexpected use of 'returned'");
10098         // Before passing 'returned' to the target lowering code, ensure that
10099         // either the register MVT and the actual EVT are the same size or that
10100         // the return value and argument are extended in the same way; in these
10101         // cases it's safe to pass the argument register value unchanged as the
10102         // return register value (although it's at the target's option whether
10103         // to do so)
10104         // TODO: allow code generation to take advantage of partially preserved
10105         // registers rather than clobbering the entire register when the
10106         // parameter extension method is not compatible with the return
10107         // extension method
10108         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10109             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10110              CLI.RetZExt == Args[i].IsZExt))
10111           Flags.setReturned();
10112       }
10113 
10114       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10115                      CLI.CallConv, ExtendKind);
10116 
10117       for (unsigned j = 0; j != NumParts; ++j) {
10118         // if it isn't first piece, alignment must be 1
10119         // For scalable vectors the scalable part is currently handled
10120         // by individual targets, so we just use the known minimum size here.
10121         ISD::OutputArg MyFlags(
10122             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10123             i < CLI.NumFixedArgs, i,
10124             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
10125         if (NumParts > 1 && j == 0)
10126           MyFlags.Flags.setSplit();
10127         else if (j != 0) {
10128           MyFlags.Flags.setOrigAlign(Align(1));
10129           if (j == NumParts - 1)
10130             MyFlags.Flags.setSplitEnd();
10131         }
10132 
10133         CLI.Outs.push_back(MyFlags);
10134         CLI.OutVals.push_back(Parts[j]);
10135       }
10136 
10137       if (NeedsRegBlock && Value == NumValues - 1)
10138         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10139     }
10140   }
10141 
10142   SmallVector<SDValue, 4> InVals;
10143   CLI.Chain = LowerCall(CLI, InVals);
10144 
10145   // Update CLI.InVals to use outside of this function.
10146   CLI.InVals = InVals;
10147 
10148   // Verify that the target's LowerCall behaved as expected.
10149   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10150          "LowerCall didn't return a valid chain!");
10151   assert((!CLI.IsTailCall || InVals.empty()) &&
10152          "LowerCall emitted a return value for a tail call!");
10153   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10154          "LowerCall didn't emit the correct number of values!");
10155 
10156   // For a tail call, the return value is merely live-out and there aren't
10157   // any nodes in the DAG representing it. Return a special value to
10158   // indicate that a tail call has been emitted and no more Instructions
10159   // should be processed in the current block.
10160   if (CLI.IsTailCall) {
10161     CLI.DAG.setRoot(CLI.Chain);
10162     return std::make_pair(SDValue(), SDValue());
10163   }
10164 
10165 #ifndef NDEBUG
10166   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10167     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10168     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10169            "LowerCall emitted a value with the wrong type!");
10170   }
10171 #endif
10172 
10173   SmallVector<SDValue, 4> ReturnValues;
10174   if (!CanLowerReturn) {
10175     // The instruction result is the result of loading from the
10176     // hidden sret parameter.
10177     SmallVector<EVT, 1> PVTs;
10178     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10179 
10180     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10181     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10182     EVT PtrVT = PVTs[0];
10183 
10184     unsigned NumValues = RetTys.size();
10185     ReturnValues.resize(NumValues);
10186     SmallVector<SDValue, 4> Chains(NumValues);
10187 
10188     // An aggregate return value cannot wrap around the address space, so
10189     // offsets to its parts don't wrap either.
10190     SDNodeFlags Flags;
10191     Flags.setNoUnsignedWrap(true);
10192 
10193     MachineFunction &MF = CLI.DAG.getMachineFunction();
10194     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10195     for (unsigned i = 0; i < NumValues; ++i) {
10196       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10197                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10198                                                         PtrVT), Flags);
10199       SDValue L = CLI.DAG.getLoad(
10200           RetTys[i], CLI.DL, CLI.Chain, Add,
10201           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10202                                             DemoteStackIdx, Offsets[i]),
10203           HiddenSRetAlign);
10204       ReturnValues[i] = L;
10205       Chains[i] = L.getValue(1);
10206     }
10207 
10208     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10209   } else {
10210     // Collect the legal value parts into potentially illegal values
10211     // that correspond to the original function's return values.
10212     std::optional<ISD::NodeType> AssertOp;
10213     if (CLI.RetSExt)
10214       AssertOp = ISD::AssertSext;
10215     else if (CLI.RetZExt)
10216       AssertOp = ISD::AssertZext;
10217     unsigned CurReg = 0;
10218     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10219       EVT VT = RetTys[I];
10220       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10221                                                      CLI.CallConv, VT);
10222       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10223                                                        CLI.CallConv, VT);
10224 
10225       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10226                                               NumRegs, RegisterVT, VT, nullptr,
10227                                               CLI.CallConv, AssertOp));
10228       CurReg += NumRegs;
10229     }
10230 
10231     // For a function returning void, there is no return value. We can't create
10232     // such a node, so we just return a null return value in that case. In
10233     // that case, nothing will actually look at the value.
10234     if (ReturnValues.empty())
10235       return std::make_pair(SDValue(), CLI.Chain);
10236   }
10237 
10238   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10239                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10240   return std::make_pair(Res, CLI.Chain);
10241 }
10242 
10243 /// Places new result values for the node in Results (their number
10244 /// and types must exactly match those of the original return values of
10245 /// the node), or leaves Results empty, which indicates that the node is not
10246 /// to be custom lowered after all.
10247 void TargetLowering::LowerOperationWrapper(SDNode *N,
10248                                            SmallVectorImpl<SDValue> &Results,
10249                                            SelectionDAG &DAG) const {
10250   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10251 
10252   if (!Res.getNode())
10253     return;
10254 
10255   // If the original node has one result, take the return value from
10256   // LowerOperation as is. It might not be result number 0.
10257   if (N->getNumValues() == 1) {
10258     Results.push_back(Res);
10259     return;
10260   }
10261 
10262   // If the original node has multiple results, then the return node should
10263   // have the same number of results.
10264   assert((N->getNumValues() == Res->getNumValues()) &&
10265       "Lowering returned the wrong number of results!");
10266 
10267   // Places new result values base on N result number.
10268   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10269     Results.push_back(Res.getValue(I));
10270 }
10271 
10272 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10273   llvm_unreachable("LowerOperation not implemented for this target!");
10274 }
10275 
10276 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10277                                                      unsigned Reg,
10278                                                      ISD::NodeType ExtendType) {
10279   SDValue Op = getNonRegisterValue(V);
10280   assert((Op.getOpcode() != ISD::CopyFromReg ||
10281           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10282          "Copy from a reg to the same reg!");
10283   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10284 
10285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10286   // If this is an InlineAsm we have to match the registers required, not the
10287   // notional registers required by the type.
10288 
10289   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10290                    std::nullopt); // This is not an ABI copy.
10291   SDValue Chain = DAG.getEntryNode();
10292 
10293   if (ExtendType == ISD::ANY_EXTEND) {
10294     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10295     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10296       ExtendType = PreferredExtendIt->second;
10297   }
10298   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10299   PendingExports.push_back(Chain);
10300 }
10301 
10302 #include "llvm/CodeGen/SelectionDAGISel.h"
10303 
10304 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10305 /// entry block, return true.  This includes arguments used by switches, since
10306 /// the switch may expand into multiple basic blocks.
10307 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10308   // With FastISel active, we may be splitting blocks, so force creation
10309   // of virtual registers for all non-dead arguments.
10310   if (FastISel)
10311     return A->use_empty();
10312 
10313   const BasicBlock &Entry = A->getParent()->front();
10314   for (const User *U : A->users())
10315     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10316       return false;  // Use not in entry block.
10317 
10318   return true;
10319 }
10320 
10321 using ArgCopyElisionMapTy =
10322     DenseMap<const Argument *,
10323              std::pair<const AllocaInst *, const StoreInst *>>;
10324 
10325 /// Scan the entry block of the function in FuncInfo for arguments that look
10326 /// like copies into a local alloca. Record any copied arguments in
10327 /// ArgCopyElisionCandidates.
10328 static void
10329 findArgumentCopyElisionCandidates(const DataLayout &DL,
10330                                   FunctionLoweringInfo *FuncInfo,
10331                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10332   // Record the state of every static alloca used in the entry block. Argument
10333   // allocas are all used in the entry block, so we need approximately as many
10334   // entries as we have arguments.
10335   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10336   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10337   unsigned NumArgs = FuncInfo->Fn->arg_size();
10338   StaticAllocas.reserve(NumArgs * 2);
10339 
10340   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10341     if (!V)
10342       return nullptr;
10343     V = V->stripPointerCasts();
10344     const auto *AI = dyn_cast<AllocaInst>(V);
10345     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10346       return nullptr;
10347     auto Iter = StaticAllocas.insert({AI, Unknown});
10348     return &Iter.first->second;
10349   };
10350 
10351   // Look for stores of arguments to static allocas. Look through bitcasts and
10352   // GEPs to handle type coercions, as long as the alloca is fully initialized
10353   // by the store. Any non-store use of an alloca escapes it and any subsequent
10354   // unanalyzed store might write it.
10355   // FIXME: Handle structs initialized with multiple stores.
10356   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10357     // Look for stores, and handle non-store uses conservatively.
10358     const auto *SI = dyn_cast<StoreInst>(&I);
10359     if (!SI) {
10360       // We will look through cast uses, so ignore them completely.
10361       if (I.isCast())
10362         continue;
10363       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10364       // to allocas.
10365       if (I.isDebugOrPseudoInst())
10366         continue;
10367       // This is an unknown instruction. Assume it escapes or writes to all
10368       // static alloca operands.
10369       for (const Use &U : I.operands()) {
10370         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10371           *Info = StaticAllocaInfo::Clobbered;
10372       }
10373       continue;
10374     }
10375 
10376     // If the stored value is a static alloca, mark it as escaped.
10377     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10378       *Info = StaticAllocaInfo::Clobbered;
10379 
10380     // Check if the destination is a static alloca.
10381     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10382     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10383     if (!Info)
10384       continue;
10385     const AllocaInst *AI = cast<AllocaInst>(Dst);
10386 
10387     // Skip allocas that have been initialized or clobbered.
10388     if (*Info != StaticAllocaInfo::Unknown)
10389       continue;
10390 
10391     // Check if the stored value is an argument, and that this store fully
10392     // initializes the alloca.
10393     // If the argument type has padding bits we can't directly forward a pointer
10394     // as the upper bits may contain garbage.
10395     // Don't elide copies from the same argument twice.
10396     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10397     const auto *Arg = dyn_cast<Argument>(Val);
10398     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10399         Arg->getType()->isEmptyTy() ||
10400         DL.getTypeStoreSize(Arg->getType()) !=
10401             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10402         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10403         ArgCopyElisionCandidates.count(Arg)) {
10404       *Info = StaticAllocaInfo::Clobbered;
10405       continue;
10406     }
10407 
10408     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10409                       << '\n');
10410 
10411     // Mark this alloca and store for argument copy elision.
10412     *Info = StaticAllocaInfo::Elidable;
10413     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10414 
10415     // Stop scanning if we've seen all arguments. This will happen early in -O0
10416     // builds, which is useful, because -O0 builds have large entry blocks and
10417     // many allocas.
10418     if (ArgCopyElisionCandidates.size() == NumArgs)
10419       break;
10420   }
10421 }
10422 
10423 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10424 /// ArgVal is a load from a suitable fixed stack object.
10425 static void tryToElideArgumentCopy(
10426     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10427     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10428     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10429     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10430     SDValue ArgVal, bool &ArgHasUses) {
10431   // Check if this is a load from a fixed stack object.
10432   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10433   if (!LNode)
10434     return;
10435   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10436   if (!FINode)
10437     return;
10438 
10439   // Check that the fixed stack object is the right size and alignment.
10440   // Look at the alignment that the user wrote on the alloca instead of looking
10441   // at the stack object.
10442   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10443   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10444   const AllocaInst *AI = ArgCopyIter->second.first;
10445   int FixedIndex = FINode->getIndex();
10446   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10447   int OldIndex = AllocaIndex;
10448   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10449   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10450     LLVM_DEBUG(
10451         dbgs() << "  argument copy elision failed due to bad fixed stack "
10452                   "object size\n");
10453     return;
10454   }
10455   Align RequiredAlignment = AI->getAlign();
10456   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10457     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10458                          "greater than stack argument alignment ("
10459                       << DebugStr(RequiredAlignment) << " vs "
10460                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10461     return;
10462   }
10463 
10464   // Perform the elision. Delete the old stack object and replace its only use
10465   // in the variable info map. Mark the stack object as mutable.
10466   LLVM_DEBUG({
10467     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10468            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10469            << '\n';
10470   });
10471   MFI.RemoveStackObject(OldIndex);
10472   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10473   AllocaIndex = FixedIndex;
10474   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10475   Chains.push_back(ArgVal.getValue(1));
10476 
10477   // Avoid emitting code for the store implementing the copy.
10478   const StoreInst *SI = ArgCopyIter->second.second;
10479   ElidedArgCopyInstrs.insert(SI);
10480 
10481   // Check for uses of the argument again so that we can avoid exporting ArgVal
10482   // if it is't used by anything other than the store.
10483   for (const Value *U : Arg.users()) {
10484     if (U != SI) {
10485       ArgHasUses = true;
10486       break;
10487     }
10488   }
10489 }
10490 
10491 void SelectionDAGISel::LowerArguments(const Function &F) {
10492   SelectionDAG &DAG = SDB->DAG;
10493   SDLoc dl = SDB->getCurSDLoc();
10494   const DataLayout &DL = DAG.getDataLayout();
10495   SmallVector<ISD::InputArg, 16> Ins;
10496 
10497   // In Naked functions we aren't going to save any registers.
10498   if (F.hasFnAttribute(Attribute::Naked))
10499     return;
10500 
10501   if (!FuncInfo->CanLowerReturn) {
10502     // Put in an sret pointer parameter before all the other parameters.
10503     SmallVector<EVT, 1> ValueVTs;
10504     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10505                     F.getReturnType()->getPointerTo(
10506                         DAG.getDataLayout().getAllocaAddrSpace()),
10507                     ValueVTs);
10508 
10509     // NOTE: Assuming that a pointer will never break down to more than one VT
10510     // or one register.
10511     ISD::ArgFlagsTy Flags;
10512     Flags.setSRet();
10513     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10514     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10515                          ISD::InputArg::NoArgIndex, 0);
10516     Ins.push_back(RetArg);
10517   }
10518 
10519   // Look for stores of arguments to static allocas. Mark such arguments with a
10520   // flag to ask the target to give us the memory location of that argument if
10521   // available.
10522   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10523   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10524                                     ArgCopyElisionCandidates);
10525 
10526   // Set up the incoming argument description vector.
10527   for (const Argument &Arg : F.args()) {
10528     unsigned ArgNo = Arg.getArgNo();
10529     SmallVector<EVT, 4> ValueVTs;
10530     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10531     bool isArgValueUsed = !Arg.use_empty();
10532     unsigned PartBase = 0;
10533     Type *FinalType = Arg.getType();
10534     if (Arg.hasAttribute(Attribute::ByVal))
10535       FinalType = Arg.getParamByValType();
10536     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10537         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10538     for (unsigned Value = 0, NumValues = ValueVTs.size();
10539          Value != NumValues; ++Value) {
10540       EVT VT = ValueVTs[Value];
10541       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10542       ISD::ArgFlagsTy Flags;
10543 
10544 
10545       if (Arg.getType()->isPointerTy()) {
10546         Flags.setPointer();
10547         Flags.setPointerAddrSpace(
10548             cast<PointerType>(Arg.getType())->getAddressSpace());
10549       }
10550       if (Arg.hasAttribute(Attribute::ZExt))
10551         Flags.setZExt();
10552       if (Arg.hasAttribute(Attribute::SExt))
10553         Flags.setSExt();
10554       if (Arg.hasAttribute(Attribute::InReg)) {
10555         // If we are using vectorcall calling convention, a structure that is
10556         // passed InReg - is surely an HVA
10557         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10558             isa<StructType>(Arg.getType())) {
10559           // The first value of a structure is marked
10560           if (0 == Value)
10561             Flags.setHvaStart();
10562           Flags.setHva();
10563         }
10564         // Set InReg Flag
10565         Flags.setInReg();
10566       }
10567       if (Arg.hasAttribute(Attribute::StructRet))
10568         Flags.setSRet();
10569       if (Arg.hasAttribute(Attribute::SwiftSelf))
10570         Flags.setSwiftSelf();
10571       if (Arg.hasAttribute(Attribute::SwiftAsync))
10572         Flags.setSwiftAsync();
10573       if (Arg.hasAttribute(Attribute::SwiftError))
10574         Flags.setSwiftError();
10575       if (Arg.hasAttribute(Attribute::ByVal))
10576         Flags.setByVal();
10577       if (Arg.hasAttribute(Attribute::ByRef))
10578         Flags.setByRef();
10579       if (Arg.hasAttribute(Attribute::InAlloca)) {
10580         Flags.setInAlloca();
10581         // Set the byval flag for CCAssignFn callbacks that don't know about
10582         // inalloca.  This way we can know how many bytes we should've allocated
10583         // and how many bytes a callee cleanup function will pop.  If we port
10584         // inalloca to more targets, we'll have to add custom inalloca handling
10585         // in the various CC lowering callbacks.
10586         Flags.setByVal();
10587       }
10588       if (Arg.hasAttribute(Attribute::Preallocated)) {
10589         Flags.setPreallocated();
10590         // Set the byval flag for CCAssignFn callbacks that don't know about
10591         // preallocated.  This way we can know how many bytes we should've
10592         // allocated and how many bytes a callee cleanup function will pop.  If
10593         // we port preallocated to more targets, we'll have to add custom
10594         // preallocated handling in the various CC lowering callbacks.
10595         Flags.setByVal();
10596       }
10597 
10598       // Certain targets (such as MIPS), may have a different ABI alignment
10599       // for a type depending on the context. Give the target a chance to
10600       // specify the alignment it wants.
10601       const Align OriginalAlignment(
10602           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10603       Flags.setOrigAlign(OriginalAlignment);
10604 
10605       Align MemAlign;
10606       Type *ArgMemTy = nullptr;
10607       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10608           Flags.isByRef()) {
10609         if (!ArgMemTy)
10610           ArgMemTy = Arg.getPointeeInMemoryValueType();
10611 
10612         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10613 
10614         // For in-memory arguments, size and alignment should be passed from FE.
10615         // BE will guess if this info is not there but there are cases it cannot
10616         // get right.
10617         if (auto ParamAlign = Arg.getParamStackAlign())
10618           MemAlign = *ParamAlign;
10619         else if ((ParamAlign = Arg.getParamAlign()))
10620           MemAlign = *ParamAlign;
10621         else
10622           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10623         if (Flags.isByRef())
10624           Flags.setByRefSize(MemSize);
10625         else
10626           Flags.setByValSize(MemSize);
10627       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10628         MemAlign = *ParamAlign;
10629       } else {
10630         MemAlign = OriginalAlignment;
10631       }
10632       Flags.setMemAlign(MemAlign);
10633 
10634       if (Arg.hasAttribute(Attribute::Nest))
10635         Flags.setNest();
10636       if (NeedsRegBlock)
10637         Flags.setInConsecutiveRegs();
10638       if (ArgCopyElisionCandidates.count(&Arg))
10639         Flags.setCopyElisionCandidate();
10640       if (Arg.hasAttribute(Attribute::Returned))
10641         Flags.setReturned();
10642 
10643       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10644           *CurDAG->getContext(), F.getCallingConv(), VT);
10645       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10646           *CurDAG->getContext(), F.getCallingConv(), VT);
10647       for (unsigned i = 0; i != NumRegs; ++i) {
10648         // For scalable vectors, use the minimum size; individual targets
10649         // are responsible for handling scalable vector arguments and
10650         // return values.
10651         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10652                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10653         if (NumRegs > 1 && i == 0)
10654           MyFlags.Flags.setSplit();
10655         // if it isn't first piece, alignment must be 1
10656         else if (i > 0) {
10657           MyFlags.Flags.setOrigAlign(Align(1));
10658           if (i == NumRegs - 1)
10659             MyFlags.Flags.setSplitEnd();
10660         }
10661         Ins.push_back(MyFlags);
10662       }
10663       if (NeedsRegBlock && Value == NumValues - 1)
10664         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10665       PartBase += VT.getStoreSize().getKnownMinSize();
10666     }
10667   }
10668 
10669   // Call the target to set up the argument values.
10670   SmallVector<SDValue, 8> InVals;
10671   SDValue NewRoot = TLI->LowerFormalArguments(
10672       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10673 
10674   // Verify that the target's LowerFormalArguments behaved as expected.
10675   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10676          "LowerFormalArguments didn't return a valid chain!");
10677   assert(InVals.size() == Ins.size() &&
10678          "LowerFormalArguments didn't emit the correct number of values!");
10679   LLVM_DEBUG({
10680     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10681       assert(InVals[i].getNode() &&
10682              "LowerFormalArguments emitted a null value!");
10683       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10684              "LowerFormalArguments emitted a value with the wrong type!");
10685     }
10686   });
10687 
10688   // Update the DAG with the new chain value resulting from argument lowering.
10689   DAG.setRoot(NewRoot);
10690 
10691   // Set up the argument values.
10692   unsigned i = 0;
10693   if (!FuncInfo->CanLowerReturn) {
10694     // Create a virtual register for the sret pointer, and put in a copy
10695     // from the sret argument into it.
10696     SmallVector<EVT, 1> ValueVTs;
10697     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10698                     F.getReturnType()->getPointerTo(
10699                         DAG.getDataLayout().getAllocaAddrSpace()),
10700                     ValueVTs);
10701     MVT VT = ValueVTs[0].getSimpleVT();
10702     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10703     std::optional<ISD::NodeType> AssertOp;
10704     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10705                                         nullptr, F.getCallingConv(), AssertOp);
10706 
10707     MachineFunction& MF = SDB->DAG.getMachineFunction();
10708     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10709     Register SRetReg =
10710         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10711     FuncInfo->DemoteRegister = SRetReg;
10712     NewRoot =
10713         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10714     DAG.setRoot(NewRoot);
10715 
10716     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10717     ++i;
10718   }
10719 
10720   SmallVector<SDValue, 4> Chains;
10721   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10722   for (const Argument &Arg : F.args()) {
10723     SmallVector<SDValue, 4> ArgValues;
10724     SmallVector<EVT, 4> ValueVTs;
10725     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10726     unsigned NumValues = ValueVTs.size();
10727     if (NumValues == 0)
10728       continue;
10729 
10730     bool ArgHasUses = !Arg.use_empty();
10731 
10732     // Elide the copying store if the target loaded this argument from a
10733     // suitable fixed stack object.
10734     if (Ins[i].Flags.isCopyElisionCandidate()) {
10735       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10736                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10737                              InVals[i], ArgHasUses);
10738     }
10739 
10740     // If this argument is unused then remember its value. It is used to generate
10741     // debugging information.
10742     bool isSwiftErrorArg =
10743         TLI->supportSwiftError() &&
10744         Arg.hasAttribute(Attribute::SwiftError);
10745     if (!ArgHasUses && !isSwiftErrorArg) {
10746       SDB->setUnusedArgValue(&Arg, InVals[i]);
10747 
10748       // Also remember any frame index for use in FastISel.
10749       if (FrameIndexSDNode *FI =
10750           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10751         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10752     }
10753 
10754     for (unsigned Val = 0; Val != NumValues; ++Val) {
10755       EVT VT = ValueVTs[Val];
10756       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10757                                                       F.getCallingConv(), VT);
10758       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10759           *CurDAG->getContext(), F.getCallingConv(), VT);
10760 
10761       // Even an apparent 'unused' swifterror argument needs to be returned. So
10762       // we do generate a copy for it that can be used on return from the
10763       // function.
10764       if (ArgHasUses || isSwiftErrorArg) {
10765         std::optional<ISD::NodeType> AssertOp;
10766         if (Arg.hasAttribute(Attribute::SExt))
10767           AssertOp = ISD::AssertSext;
10768         else if (Arg.hasAttribute(Attribute::ZExt))
10769           AssertOp = ISD::AssertZext;
10770 
10771         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10772                                              PartVT, VT, nullptr,
10773                                              F.getCallingConv(), AssertOp));
10774       }
10775 
10776       i += NumParts;
10777     }
10778 
10779     // We don't need to do anything else for unused arguments.
10780     if (ArgValues.empty())
10781       continue;
10782 
10783     // Note down frame index.
10784     if (FrameIndexSDNode *FI =
10785         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10786       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10787 
10788     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10789                                      SDB->getCurSDLoc());
10790 
10791     SDB->setValue(&Arg, Res);
10792     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10793       // We want to associate the argument with the frame index, among
10794       // involved operands, that correspond to the lowest address. The
10795       // getCopyFromParts function, called earlier, is swapping the order of
10796       // the operands to BUILD_PAIR depending on endianness. The result of
10797       // that swapping is that the least significant bits of the argument will
10798       // be in the first operand of the BUILD_PAIR node, and the most
10799       // significant bits will be in the second operand.
10800       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10801       if (LoadSDNode *LNode =
10802           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10803         if (FrameIndexSDNode *FI =
10804             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10805           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10806     }
10807 
10808     // Analyses past this point are naive and don't expect an assertion.
10809     if (Res.getOpcode() == ISD::AssertZext)
10810       Res = Res.getOperand(0);
10811 
10812     // Update the SwiftErrorVRegDefMap.
10813     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10814       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10815       if (Register::isVirtualRegister(Reg))
10816         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10817                                    Reg);
10818     }
10819 
10820     // If this argument is live outside of the entry block, insert a copy from
10821     // wherever we got it to the vreg that other BB's will reference it as.
10822     if (Res.getOpcode() == ISD::CopyFromReg) {
10823       // If we can, though, try to skip creating an unnecessary vreg.
10824       // FIXME: This isn't very clean... it would be nice to make this more
10825       // general.
10826       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10827       if (Register::isVirtualRegister(Reg)) {
10828         FuncInfo->ValueMap[&Arg] = Reg;
10829         continue;
10830       }
10831     }
10832     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10833       FuncInfo->InitializeRegForValue(&Arg);
10834       SDB->CopyToExportRegsIfNeeded(&Arg);
10835     }
10836   }
10837 
10838   if (!Chains.empty()) {
10839     Chains.push_back(NewRoot);
10840     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10841   }
10842 
10843   DAG.setRoot(NewRoot);
10844 
10845   assert(i == InVals.size() && "Argument register count mismatch!");
10846 
10847   // If any argument copy elisions occurred and we have debug info, update the
10848   // stale frame indices used in the dbg.declare variable info table.
10849   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10850   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10851     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10852       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10853       if (I != ArgCopyElisionFrameIndexMap.end())
10854         VI.Slot = I->second;
10855     }
10856   }
10857 
10858   // Finally, if the target has anything special to do, allow it to do so.
10859   emitFunctionEntryCode();
10860 }
10861 
10862 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10863 /// ensure constants are generated when needed.  Remember the virtual registers
10864 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10865 /// directly add them, because expansion might result in multiple MBB's for one
10866 /// BB.  As such, the start of the BB might correspond to a different MBB than
10867 /// the end.
10868 void
10869 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10871 
10872   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10873 
10874   // Check PHI nodes in successors that expect a value to be available from this
10875   // block.
10876   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10877     if (!isa<PHINode>(SuccBB->begin())) continue;
10878     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10879 
10880     // If this terminator has multiple identical successors (common for
10881     // switches), only handle each succ once.
10882     if (!SuccsHandled.insert(SuccMBB).second)
10883       continue;
10884 
10885     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10886 
10887     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10888     // nodes and Machine PHI nodes, but the incoming operands have not been
10889     // emitted yet.
10890     for (const PHINode &PN : SuccBB->phis()) {
10891       // Ignore dead phi's.
10892       if (PN.use_empty())
10893         continue;
10894 
10895       // Skip empty types
10896       if (PN.getType()->isEmptyTy())
10897         continue;
10898 
10899       unsigned Reg;
10900       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10901 
10902       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10903         unsigned &RegOut = ConstantsOut[C];
10904         if (RegOut == 0) {
10905           RegOut = FuncInfo.CreateRegs(C);
10906           // We need to zero/sign extend ConstantInt phi operands to match
10907           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10908           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10909           if (auto *CI = dyn_cast<ConstantInt>(C))
10910             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10911                                                     : ISD::ZERO_EXTEND;
10912           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10913         }
10914         Reg = RegOut;
10915       } else {
10916         DenseMap<const Value *, Register>::iterator I =
10917           FuncInfo.ValueMap.find(PHIOp);
10918         if (I != FuncInfo.ValueMap.end())
10919           Reg = I->second;
10920         else {
10921           assert(isa<AllocaInst>(PHIOp) &&
10922                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10923                  "Didn't codegen value into a register!??");
10924           Reg = FuncInfo.CreateRegs(PHIOp);
10925           CopyValueToVirtualRegister(PHIOp, Reg);
10926         }
10927       }
10928 
10929       // Remember that this register needs to added to the machine PHI node as
10930       // the input for this MBB.
10931       SmallVector<EVT, 4> ValueVTs;
10932       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10933       for (EVT VT : ValueVTs) {
10934         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10935         for (unsigned i = 0; i != NumRegisters; ++i)
10936           FuncInfo.PHINodesToUpdate.push_back(
10937               std::make_pair(&*MBBI++, Reg + i));
10938         Reg += NumRegisters;
10939       }
10940     }
10941   }
10942 
10943   ConstantsOut.clear();
10944 }
10945 
10946 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10947   MachineFunction::iterator I(MBB);
10948   if (++I == FuncInfo.MF->end())
10949     return nullptr;
10950   return &*I;
10951 }
10952 
10953 /// During lowering new call nodes can be created (such as memset, etc.).
10954 /// Those will become new roots of the current DAG, but complications arise
10955 /// when they are tail calls. In such cases, the call lowering will update
10956 /// the root, but the builder still needs to know that a tail call has been
10957 /// lowered in order to avoid generating an additional return.
10958 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10959   // If the node is null, we do have a tail call.
10960   if (MaybeTC.getNode() != nullptr)
10961     DAG.setRoot(MaybeTC);
10962   else
10963     HasTailCall = true;
10964 }
10965 
10966 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10967                                         MachineBasicBlock *SwitchMBB,
10968                                         MachineBasicBlock *DefaultMBB) {
10969   MachineFunction *CurMF = FuncInfo.MF;
10970   MachineBasicBlock *NextMBB = nullptr;
10971   MachineFunction::iterator BBI(W.MBB);
10972   if (++BBI != FuncInfo.MF->end())
10973     NextMBB = &*BBI;
10974 
10975   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10976 
10977   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10978 
10979   if (Size == 2 && W.MBB == SwitchMBB) {
10980     // If any two of the cases has the same destination, and if one value
10981     // is the same as the other, but has one bit unset that the other has set,
10982     // use bit manipulation to do two compares at once.  For example:
10983     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10984     // TODO: This could be extended to merge any 2 cases in switches with 3
10985     // cases.
10986     // TODO: Handle cases where W.CaseBB != SwitchBB.
10987     CaseCluster &Small = *W.FirstCluster;
10988     CaseCluster &Big = *W.LastCluster;
10989 
10990     if (Small.Low == Small.High && Big.Low == Big.High &&
10991         Small.MBB == Big.MBB) {
10992       const APInt &SmallValue = Small.Low->getValue();
10993       const APInt &BigValue = Big.Low->getValue();
10994 
10995       // Check that there is only one bit different.
10996       APInt CommonBit = BigValue ^ SmallValue;
10997       if (CommonBit.isPowerOf2()) {
10998         SDValue CondLHS = getValue(Cond);
10999         EVT VT = CondLHS.getValueType();
11000         SDLoc DL = getCurSDLoc();
11001 
11002         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11003                                  DAG.getConstant(CommonBit, DL, VT));
11004         SDValue Cond = DAG.getSetCC(
11005             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11006             ISD::SETEQ);
11007 
11008         // Update successor info.
11009         // Both Small and Big will jump to Small.BB, so we sum up the
11010         // probabilities.
11011         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11012         if (BPI)
11013           addSuccessorWithProb(
11014               SwitchMBB, DefaultMBB,
11015               // The default destination is the first successor in IR.
11016               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11017         else
11018           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11019 
11020         // Insert the true branch.
11021         SDValue BrCond =
11022             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11023                         DAG.getBasicBlock(Small.MBB));
11024         // Insert the false branch.
11025         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11026                              DAG.getBasicBlock(DefaultMBB));
11027 
11028         DAG.setRoot(BrCond);
11029         return;
11030       }
11031     }
11032   }
11033 
11034   if (TM.getOptLevel() != CodeGenOpt::None) {
11035     // Here, we order cases by probability so the most likely case will be
11036     // checked first. However, two clusters can have the same probability in
11037     // which case their relative ordering is non-deterministic. So we use Low
11038     // as a tie-breaker as clusters are guaranteed to never overlap.
11039     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11040                [](const CaseCluster &a, const CaseCluster &b) {
11041       return a.Prob != b.Prob ?
11042              a.Prob > b.Prob :
11043              a.Low->getValue().slt(b.Low->getValue());
11044     });
11045 
11046     // Rearrange the case blocks so that the last one falls through if possible
11047     // without changing the order of probabilities.
11048     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11049       --I;
11050       if (I->Prob > W.LastCluster->Prob)
11051         break;
11052       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11053         std::swap(*I, *W.LastCluster);
11054         break;
11055       }
11056     }
11057   }
11058 
11059   // Compute total probability.
11060   BranchProbability DefaultProb = W.DefaultProb;
11061   BranchProbability UnhandledProbs = DefaultProb;
11062   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11063     UnhandledProbs += I->Prob;
11064 
11065   MachineBasicBlock *CurMBB = W.MBB;
11066   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11067     bool FallthroughUnreachable = false;
11068     MachineBasicBlock *Fallthrough;
11069     if (I == W.LastCluster) {
11070       // For the last cluster, fall through to the default destination.
11071       Fallthrough = DefaultMBB;
11072       FallthroughUnreachable = isa<UnreachableInst>(
11073           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11074     } else {
11075       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11076       CurMF->insert(BBI, Fallthrough);
11077       // Put Cond in a virtual register to make it available from the new blocks.
11078       ExportFromCurrentBlock(Cond);
11079     }
11080     UnhandledProbs -= I->Prob;
11081 
11082     switch (I->Kind) {
11083       case CC_JumpTable: {
11084         // FIXME: Optimize away range check based on pivot comparisons.
11085         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11086         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11087 
11088         // The jump block hasn't been inserted yet; insert it here.
11089         MachineBasicBlock *JumpMBB = JT->MBB;
11090         CurMF->insert(BBI, JumpMBB);
11091 
11092         auto JumpProb = I->Prob;
11093         auto FallthroughProb = UnhandledProbs;
11094 
11095         // If the default statement is a target of the jump table, we evenly
11096         // distribute the default probability to successors of CurMBB. Also
11097         // update the probability on the edge from JumpMBB to Fallthrough.
11098         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11099                                               SE = JumpMBB->succ_end();
11100              SI != SE; ++SI) {
11101           if (*SI == DefaultMBB) {
11102             JumpProb += DefaultProb / 2;
11103             FallthroughProb -= DefaultProb / 2;
11104             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11105             JumpMBB->normalizeSuccProbs();
11106             break;
11107           }
11108         }
11109 
11110         if (FallthroughUnreachable)
11111           JTH->FallthroughUnreachable = true;
11112 
11113         if (!JTH->FallthroughUnreachable)
11114           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11115         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11116         CurMBB->normalizeSuccProbs();
11117 
11118         // The jump table header will be inserted in our current block, do the
11119         // range check, and fall through to our fallthrough block.
11120         JTH->HeaderBB = CurMBB;
11121         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11122 
11123         // If we're in the right place, emit the jump table header right now.
11124         if (CurMBB == SwitchMBB) {
11125           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11126           JTH->Emitted = true;
11127         }
11128         break;
11129       }
11130       case CC_BitTests: {
11131         // FIXME: Optimize away range check based on pivot comparisons.
11132         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11133 
11134         // The bit test blocks haven't been inserted yet; insert them here.
11135         for (BitTestCase &BTC : BTB->Cases)
11136           CurMF->insert(BBI, BTC.ThisBB);
11137 
11138         // Fill in fields of the BitTestBlock.
11139         BTB->Parent = CurMBB;
11140         BTB->Default = Fallthrough;
11141 
11142         BTB->DefaultProb = UnhandledProbs;
11143         // If the cases in bit test don't form a contiguous range, we evenly
11144         // distribute the probability on the edge to Fallthrough to two
11145         // successors of CurMBB.
11146         if (!BTB->ContiguousRange) {
11147           BTB->Prob += DefaultProb / 2;
11148           BTB->DefaultProb -= DefaultProb / 2;
11149         }
11150 
11151         if (FallthroughUnreachable)
11152           BTB->FallthroughUnreachable = true;
11153 
11154         // If we're in the right place, emit the bit test header right now.
11155         if (CurMBB == SwitchMBB) {
11156           visitBitTestHeader(*BTB, SwitchMBB);
11157           BTB->Emitted = true;
11158         }
11159         break;
11160       }
11161       case CC_Range: {
11162         const Value *RHS, *LHS, *MHS;
11163         ISD::CondCode CC;
11164         if (I->Low == I->High) {
11165           // Check Cond == I->Low.
11166           CC = ISD::SETEQ;
11167           LHS = Cond;
11168           RHS=I->Low;
11169           MHS = nullptr;
11170         } else {
11171           // Check I->Low <= Cond <= I->High.
11172           CC = ISD::SETLE;
11173           LHS = I->Low;
11174           MHS = Cond;
11175           RHS = I->High;
11176         }
11177 
11178         // If Fallthrough is unreachable, fold away the comparison.
11179         if (FallthroughUnreachable)
11180           CC = ISD::SETTRUE;
11181 
11182         // The false probability is the sum of all unhandled cases.
11183         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11184                      getCurSDLoc(), I->Prob, UnhandledProbs);
11185 
11186         if (CurMBB == SwitchMBB)
11187           visitSwitchCase(CB, SwitchMBB);
11188         else
11189           SL->SwitchCases.push_back(CB);
11190 
11191         break;
11192       }
11193     }
11194     CurMBB = Fallthrough;
11195   }
11196 }
11197 
11198 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11199                                               CaseClusterIt First,
11200                                               CaseClusterIt Last) {
11201   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11202     if (X.Prob != CC.Prob)
11203       return X.Prob > CC.Prob;
11204 
11205     // Ties are broken by comparing the case value.
11206     return X.Low->getValue().slt(CC.Low->getValue());
11207   });
11208 }
11209 
11210 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11211                                         const SwitchWorkListItem &W,
11212                                         Value *Cond,
11213                                         MachineBasicBlock *SwitchMBB) {
11214   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11215          "Clusters not sorted?");
11216 
11217   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11218 
11219   // Balance the tree based on branch probabilities to create a near-optimal (in
11220   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11221   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11222   CaseClusterIt LastLeft = W.FirstCluster;
11223   CaseClusterIt FirstRight = W.LastCluster;
11224   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11225   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11226 
11227   // Move LastLeft and FirstRight towards each other from opposite directions to
11228   // find a partitioning of the clusters which balances the probability on both
11229   // sides. If LeftProb and RightProb are equal, alternate which side is
11230   // taken to ensure 0-probability nodes are distributed evenly.
11231   unsigned I = 0;
11232   while (LastLeft + 1 < FirstRight) {
11233     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11234       LeftProb += (++LastLeft)->Prob;
11235     else
11236       RightProb += (--FirstRight)->Prob;
11237     I++;
11238   }
11239 
11240   while (true) {
11241     // Our binary search tree differs from a typical BST in that ours can have up
11242     // to three values in each leaf. The pivot selection above doesn't take that
11243     // into account, which means the tree might require more nodes and be less
11244     // efficient. We compensate for this here.
11245 
11246     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11247     unsigned NumRight = W.LastCluster - FirstRight + 1;
11248 
11249     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11250       // If one side has less than 3 clusters, and the other has more than 3,
11251       // consider taking a cluster from the other side.
11252 
11253       if (NumLeft < NumRight) {
11254         // Consider moving the first cluster on the right to the left side.
11255         CaseCluster &CC = *FirstRight;
11256         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11257         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11258         if (LeftSideRank <= RightSideRank) {
11259           // Moving the cluster to the left does not demote it.
11260           ++LastLeft;
11261           ++FirstRight;
11262           continue;
11263         }
11264       } else {
11265         assert(NumRight < NumLeft);
11266         // Consider moving the last element on the left to the right side.
11267         CaseCluster &CC = *LastLeft;
11268         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11269         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11270         if (RightSideRank <= LeftSideRank) {
11271           // Moving the cluster to the right does not demot it.
11272           --LastLeft;
11273           --FirstRight;
11274           continue;
11275         }
11276       }
11277     }
11278     break;
11279   }
11280 
11281   assert(LastLeft + 1 == FirstRight);
11282   assert(LastLeft >= W.FirstCluster);
11283   assert(FirstRight <= W.LastCluster);
11284 
11285   // Use the first element on the right as pivot since we will make less-than
11286   // comparisons against it.
11287   CaseClusterIt PivotCluster = FirstRight;
11288   assert(PivotCluster > W.FirstCluster);
11289   assert(PivotCluster <= W.LastCluster);
11290 
11291   CaseClusterIt FirstLeft = W.FirstCluster;
11292   CaseClusterIt LastRight = W.LastCluster;
11293 
11294   const ConstantInt *Pivot = PivotCluster->Low;
11295 
11296   // New blocks will be inserted immediately after the current one.
11297   MachineFunction::iterator BBI(W.MBB);
11298   ++BBI;
11299 
11300   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11301   // we can branch to its destination directly if it's squeezed exactly in
11302   // between the known lower bound and Pivot - 1.
11303   MachineBasicBlock *LeftMBB;
11304   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11305       FirstLeft->Low == W.GE &&
11306       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11307     LeftMBB = FirstLeft->MBB;
11308   } else {
11309     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11310     FuncInfo.MF->insert(BBI, LeftMBB);
11311     WorkList.push_back(
11312         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11313     // Put Cond in a virtual register to make it available from the new blocks.
11314     ExportFromCurrentBlock(Cond);
11315   }
11316 
11317   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11318   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11319   // directly if RHS.High equals the current upper bound.
11320   MachineBasicBlock *RightMBB;
11321   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11322       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11323     RightMBB = FirstRight->MBB;
11324   } else {
11325     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11326     FuncInfo.MF->insert(BBI, RightMBB);
11327     WorkList.push_back(
11328         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11329     // Put Cond in a virtual register to make it available from the new blocks.
11330     ExportFromCurrentBlock(Cond);
11331   }
11332 
11333   // Create the CaseBlock record that will be used to lower the branch.
11334   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11335                getCurSDLoc(), LeftProb, RightProb);
11336 
11337   if (W.MBB == SwitchMBB)
11338     visitSwitchCase(CB, SwitchMBB);
11339   else
11340     SL->SwitchCases.push_back(CB);
11341 }
11342 
11343 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11344 // from the swith statement.
11345 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11346                                             BranchProbability PeeledCaseProb) {
11347   if (PeeledCaseProb == BranchProbability::getOne())
11348     return BranchProbability::getZero();
11349   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11350 
11351   uint32_t Numerator = CaseProb.getNumerator();
11352   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11353   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11354 }
11355 
11356 // Try to peel the top probability case if it exceeds the threshold.
11357 // Return current MachineBasicBlock for the switch statement if the peeling
11358 // does not occur.
11359 // If the peeling is performed, return the newly created MachineBasicBlock
11360 // for the peeled switch statement. Also update Clusters to remove the peeled
11361 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11362 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11363     const SwitchInst &SI, CaseClusterVector &Clusters,
11364     BranchProbability &PeeledCaseProb) {
11365   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11366   // Don't perform if there is only one cluster or optimizing for size.
11367   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11368       TM.getOptLevel() == CodeGenOpt::None ||
11369       SwitchMBB->getParent()->getFunction().hasMinSize())
11370     return SwitchMBB;
11371 
11372   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11373   unsigned PeeledCaseIndex = 0;
11374   bool SwitchPeeled = false;
11375   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11376     CaseCluster &CC = Clusters[Index];
11377     if (CC.Prob < TopCaseProb)
11378       continue;
11379     TopCaseProb = CC.Prob;
11380     PeeledCaseIndex = Index;
11381     SwitchPeeled = true;
11382   }
11383   if (!SwitchPeeled)
11384     return SwitchMBB;
11385 
11386   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11387                     << TopCaseProb << "\n");
11388 
11389   // Record the MBB for the peeled switch statement.
11390   MachineFunction::iterator BBI(SwitchMBB);
11391   ++BBI;
11392   MachineBasicBlock *PeeledSwitchMBB =
11393       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11394   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11395 
11396   ExportFromCurrentBlock(SI.getCondition());
11397   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11398   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11399                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11400   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11401 
11402   Clusters.erase(PeeledCaseIt);
11403   for (CaseCluster &CC : Clusters) {
11404     LLVM_DEBUG(
11405         dbgs() << "Scale the probablity for one cluster, before scaling: "
11406                << CC.Prob << "\n");
11407     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11408     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11409   }
11410   PeeledCaseProb = TopCaseProb;
11411   return PeeledSwitchMBB;
11412 }
11413 
11414 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11415   // Extract cases from the switch.
11416   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11417   CaseClusterVector Clusters;
11418   Clusters.reserve(SI.getNumCases());
11419   for (auto I : SI.cases()) {
11420     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11421     const ConstantInt *CaseVal = I.getCaseValue();
11422     BranchProbability Prob =
11423         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11424             : BranchProbability(1, SI.getNumCases() + 1);
11425     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11426   }
11427 
11428   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11429 
11430   // Cluster adjacent cases with the same destination. We do this at all
11431   // optimization levels because it's cheap to do and will make codegen faster
11432   // if there are many clusters.
11433   sortAndRangeify(Clusters);
11434 
11435   // The branch probablity of the peeled case.
11436   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11437   MachineBasicBlock *PeeledSwitchMBB =
11438       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11439 
11440   // If there is only the default destination, jump there directly.
11441   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11442   if (Clusters.empty()) {
11443     assert(PeeledSwitchMBB == SwitchMBB);
11444     SwitchMBB->addSuccessor(DefaultMBB);
11445     if (DefaultMBB != NextBlock(SwitchMBB)) {
11446       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11447                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11448     }
11449     return;
11450   }
11451 
11452   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11453   SL->findBitTestClusters(Clusters, &SI);
11454 
11455   LLVM_DEBUG({
11456     dbgs() << "Case clusters: ";
11457     for (const CaseCluster &C : Clusters) {
11458       if (C.Kind == CC_JumpTable)
11459         dbgs() << "JT:";
11460       if (C.Kind == CC_BitTests)
11461         dbgs() << "BT:";
11462 
11463       C.Low->getValue().print(dbgs(), true);
11464       if (C.Low != C.High) {
11465         dbgs() << '-';
11466         C.High->getValue().print(dbgs(), true);
11467       }
11468       dbgs() << ' ';
11469     }
11470     dbgs() << '\n';
11471   });
11472 
11473   assert(!Clusters.empty());
11474   SwitchWorkList WorkList;
11475   CaseClusterIt First = Clusters.begin();
11476   CaseClusterIt Last = Clusters.end() - 1;
11477   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11478   // Scale the branchprobability for DefaultMBB if the peel occurs and
11479   // DefaultMBB is not replaced.
11480   if (PeeledCaseProb != BranchProbability::getZero() &&
11481       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11482     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11483   WorkList.push_back(
11484       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11485 
11486   while (!WorkList.empty()) {
11487     SwitchWorkListItem W = WorkList.pop_back_val();
11488     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11489 
11490     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11491         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11492       // For optimized builds, lower large range as a balanced binary tree.
11493       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11494       continue;
11495     }
11496 
11497     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11498   }
11499 }
11500 
11501 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11503   auto DL = getCurSDLoc();
11504   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11505   setValue(&I, DAG.getStepVector(DL, ResultVT));
11506 }
11507 
11508 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11510   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11511 
11512   SDLoc DL = getCurSDLoc();
11513   SDValue V = getValue(I.getOperand(0));
11514   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11515 
11516   if (VT.isScalableVector()) {
11517     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11518     return;
11519   }
11520 
11521   // Use VECTOR_SHUFFLE for the fixed-length vector
11522   // to maintain existing behavior.
11523   SmallVector<int, 8> Mask;
11524   unsigned NumElts = VT.getVectorMinNumElements();
11525   for (unsigned i = 0; i != NumElts; ++i)
11526     Mask.push_back(NumElts - 1 - i);
11527 
11528   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11529 }
11530 
11531 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11532   SmallVector<EVT, 4> ValueVTs;
11533   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11534                   ValueVTs);
11535   unsigned NumValues = ValueVTs.size();
11536   if (NumValues == 0) return;
11537 
11538   SmallVector<SDValue, 4> Values(NumValues);
11539   SDValue Op = getValue(I.getOperand(0));
11540 
11541   for (unsigned i = 0; i != NumValues; ++i)
11542     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11543                             SDValue(Op.getNode(), Op.getResNo() + i));
11544 
11545   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11546                            DAG.getVTList(ValueVTs), Values));
11547 }
11548 
11549 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11551   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11552 
11553   SDLoc DL = getCurSDLoc();
11554   SDValue V1 = getValue(I.getOperand(0));
11555   SDValue V2 = getValue(I.getOperand(1));
11556   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11557 
11558   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11559   if (VT.isScalableVector()) {
11560     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11561     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11562                              DAG.getConstant(Imm, DL, IdxVT)));
11563     return;
11564   }
11565 
11566   unsigned NumElts = VT.getVectorNumElements();
11567 
11568   uint64_t Idx = (NumElts + Imm) % NumElts;
11569 
11570   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11571   SmallVector<int, 8> Mask;
11572   for (unsigned i = 0; i < NumElts; ++i)
11573     Mask.push_back(Idx + i);
11574   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11575 }
11576