xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 70b35ec0a81375c49482755f08afc9463210ca87)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
33 #include "llvm/CodeGen/CodeGenCommonISel.h"
34 #include "llvm/CodeGen/FunctionLoweringInfo.h"
35 #include "llvm/CodeGen/GCMetadata.h"
36 #include "llvm/CodeGen/ISDOpcodes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineOperand.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/RuntimeLibcalls.h"
47 #include "llvm/CodeGen/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
49 #include "llvm/CodeGen/StackMaps.h"
50 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
51 #include "llvm/CodeGen/TargetFrameLowering.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetOpcodes.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/WinEHFuncInfo.h"
57 #include "llvm/IR/Argument.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/CFG.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/ConstantRange.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugInfo.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/EHPersonalities.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/TargetParser/Triple.h"
101 #include "llvm/Transforms/Utils/Local.h"
102 #include <cstddef>
103 #include <iterator>
104 #include <limits>
105 #include <optional>
106 #include <tuple>
107 
108 using namespace llvm;
109 using namespace PatternMatch;
110 using namespace SwitchCG;
111 
112 #define DEBUG_TYPE "isel"
113 
114 /// LimitFloatPrecision - Generate low-precision inline sequences for
115 /// some float libcalls (6, 8 or 12 bits).
116 static unsigned LimitFloatPrecision;
117 
118 static cl::opt<bool>
119     InsertAssertAlign("insert-assert-align", cl::init(true),
120                       cl::desc("Insert the experimental `assertalign` node."),
121                       cl::ReallyHidden);
122 
123 static cl::opt<unsigned, true>
124     LimitFPPrecision("limit-float-precision",
125                      cl::desc("Generate low-precision inline sequences "
126                               "for some float libcalls"),
127                      cl::location(LimitFloatPrecision), cl::Hidden,
128                      cl::init(0));
129 
130 static cl::opt<unsigned> SwitchPeelThreshold(
131     "switch-peel-threshold", cl::Hidden, cl::init(66),
132     cl::desc("Set the case probability threshold for peeling the case from a "
133              "switch statement. A value greater than 100 will void this "
134              "optimization"));
135 
136 // Limit the width of DAG chains. This is important in general to prevent
137 // DAG-based analysis from blowing up. For example, alias analysis and
138 // load clustering may not complete in reasonable time. It is difficult to
139 // recognize and avoid this situation within each individual analysis, and
140 // future analyses are likely to have the same behavior. Limiting DAG width is
141 // the safe approach and will be especially important with global DAGs.
142 //
143 // MaxParallelChains default is arbitrarily high to avoid affecting
144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
145 // sequence over this should have been converted to llvm.memcpy by the
146 // frontend. It is easy to induce this behavior with .ll code such as:
147 // %buffer = alloca [4096 x i8]
148 // %data = load [4096 x i8]* %argPtr
149 // store [4096 x i8] %data, [4096 x i8]* %buffer
150 static const unsigned MaxParallelChains = 64;
151 
152 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
153                                       const SDValue *Parts, unsigned NumParts,
154                                       MVT PartVT, EVT ValueVT, const Value *V,
155                                       std::optional<CallingConv::ID> CC);
156 
157 /// getCopyFromParts - Create a value that contains the specified legal parts
158 /// combined into the value they represent.  If the parts combine to a type
159 /// larger than ValueVT then AssertOp can be used to specify whether the extra
160 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
161 /// (ISD::AssertSext).
162 static SDValue
163 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
164                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
165                  std::optional<CallingConv::ID> CC = std::nullopt,
166                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
167   // Let the target assemble the parts if it wants to
168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
169   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
170                                                    PartVT, ValueVT, CC))
171     return Val;
172 
173   if (ValueVT.isVector())
174     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
175                                   CC);
176 
177   assert(NumParts > 0 && "No parts to assemble!");
178   SDValue Val = Parts[0];
179 
180   if (NumParts > 1) {
181     // Assemble the value from multiple parts.
182     if (ValueVT.isInteger()) {
183       unsigned PartBits = PartVT.getSizeInBits();
184       unsigned ValueBits = ValueVT.getSizeInBits();
185 
186       // Assemble the power of 2 part.
187       unsigned RoundParts = llvm::bit_floor(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       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
423       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
424         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
425     }
426 
427     // Promoted vector extract
428     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
429   }
430 
431   // Trivial bitcast if the types are the same size and the destination
432   // vector type is legal.
433   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
434       TLI.isTypeLegal(ValueVT))
435     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
436 
437   if (ValueVT.getVectorNumElements() != 1) {
438      // Certain ABIs require that vectors are passed as integers. For vectors
439      // are the same size, this is an obvious bitcast.
440      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
441        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
442      } else if (ValueVT.bitsLT(PartEVT)) {
443        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
444        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
445        // Drop the extra bits.
446        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
447        return DAG.getBitcast(ValueVT, Val);
448      }
449 
450      diagnosePossiblyInvalidConstraint(
451          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
452      return DAG.getUNDEF(ValueVT);
453   }
454 
455   // Handle cases such as i8 -> <1 x i1>
456   EVT ValueSVT = ValueVT.getVectorElementType();
457   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
458     unsigned ValueSize = ValueSVT.getSizeInBits();
459     if (ValueSize == PartEVT.getSizeInBits()) {
460       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
461     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
462       // It's possible a scalar floating point type gets softened to integer and
463       // then promoted to a larger integer. If PartEVT is the larger integer
464       // we need to truncate it and then bitcast to the FP type.
465       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
466       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
467       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
468       Val = DAG.getBitcast(ValueSVT, Val);
469     } else {
470       Val = ValueVT.isFloatingPoint()
471                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
472                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
473     }
474   }
475 
476   return DAG.getBuildVector(ValueVT, DL, Val);
477 }
478 
479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
480                                  SDValue Val, SDValue *Parts, unsigned NumParts,
481                                  MVT PartVT, const Value *V,
482                                  std::optional<CallingConv::ID> CallConv);
483 
484 /// getCopyToParts - Create a series of nodes that contain the specified value
485 /// split into legal parts.  If the parts contain more bits than Val, then, for
486 /// integers, ExtendKind can be used to specify how to generate the extra bits.
487 static void
488 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
489                unsigned NumParts, MVT PartVT, const Value *V,
490                std::optional<CallingConv::ID> CallConv = std::nullopt,
491                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
492   // Let the target split the parts if it wants to
493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
494   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
495                                       CallConv))
496     return;
497   EVT ValueVT = Val.getValueType();
498 
499   // Handle the vector case separately.
500   if (ValueVT.isVector())
501     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
502                                 CallConv);
503 
504   unsigned OrigNumParts = NumParts;
505   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
506          "Copying to an illegal type!");
507 
508   if (NumParts == 0)
509     return;
510 
511   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
512   EVT PartEVT = PartVT;
513   if (PartEVT == ValueVT) {
514     assert(NumParts == 1 && "No-op copy with multiple parts!");
515     Parts[0] = Val;
516     return;
517   }
518 
519   unsigned PartBits = PartVT.getSizeInBits();
520   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
521     // If the parts cover more bits than the value has, promote the value.
522     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
523       assert(NumParts == 1 && "Do not know what to promote to!");
524       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
525     } else {
526       if (ValueVT.isFloatingPoint()) {
527         // FP values need to be bitcast, then extended if they are being put
528         // into a larger container.
529         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
530         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
531       }
532       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533              ValueVT.isInteger() &&
534              "Unknown mismatch!");
535       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
537       if (PartVT == MVT::x86mmx)
538         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539     }
540   } else if (PartBits == ValueVT.getSizeInBits()) {
541     // Different types of the same size.
542     assert(NumParts == 1 && PartEVT != ValueVT);
543     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
544   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
545     // If the parts cover less bits than value has, truncate the value.
546     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
547            ValueVT.isInteger() &&
548            "Unknown mismatch!");
549     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
550     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
551     if (PartVT == MVT::x86mmx)
552       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
553   }
554 
555   // The value may have changed - recompute ValueVT.
556   ValueVT = Val.getValueType();
557   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
558          "Failed to tile the value with PartVT!");
559 
560   if (NumParts == 1) {
561     if (PartEVT != ValueVT) {
562       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
563                                         "scalar-to-vector conversion failed");
564       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
565     }
566 
567     Parts[0] = Val;
568     return;
569   }
570 
571   // Expand the value into multiple parts.
572   if (NumParts & (NumParts - 1)) {
573     // The number of parts is not a power of 2.  Split off and copy the tail.
574     assert(PartVT.isInteger() && ValueVT.isInteger() &&
575            "Do not know what to expand to!");
576     unsigned RoundParts = llvm::bit_floor(NumParts);
577     unsigned RoundBits = RoundParts * PartBits;
578     unsigned OddParts = NumParts - RoundParts;
579     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
580       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
581 
582     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
583                    CallConv);
584 
585     if (DAG.getDataLayout().isBigEndian())
586       // The odd parts were reversed by getCopyToParts - unreverse them.
587       std::reverse(Parts + RoundParts, Parts + NumParts);
588 
589     NumParts = RoundParts;
590     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
591     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
592   }
593 
594   // The number of parts is a power of 2.  Repeatedly bisect the value using
595   // EXTRACT_ELEMENT.
596   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
597                          EVT::getIntegerVT(*DAG.getContext(),
598                                            ValueVT.getSizeInBits()),
599                          Val);
600 
601   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
602     for (unsigned i = 0; i < NumParts; i += StepSize) {
603       unsigned ThisBits = StepSize * PartBits / 2;
604       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
605       SDValue &Part0 = Parts[i];
606       SDValue &Part1 = Parts[i+StepSize/2];
607 
608       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
609                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
610       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
611                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
612 
613       if (ThisBits == PartBits && ThisVT != PartVT) {
614         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
615         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
616       }
617     }
618   }
619 
620   if (DAG.getDataLayout().isBigEndian())
621     std::reverse(Parts, Parts + OrigNumParts);
622 }
623 
624 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
625                                      const SDLoc &DL, EVT PartVT) {
626   if (!PartVT.isVector())
627     return SDValue();
628 
629   EVT ValueVT = Val.getValueType();
630   EVT PartEVT = PartVT.getVectorElementType();
631   EVT ValueEVT = ValueVT.getVectorElementType();
632   ElementCount PartNumElts = PartVT.getVectorElementCount();
633   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
634 
635   // We only support widening vectors with equivalent element types and
636   // fixed/scalable properties. If a target needs to widen a fixed-length type
637   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
638   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
639       PartNumElts.isScalable() != ValueNumElts.isScalable())
640     return SDValue();
641 
642   // Have a try for bf16 because some targets share its ABI with fp16.
643   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
644     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
645            "Cannot widen to illegal type");
646     Val = DAG.getNode(ISD::BITCAST, DL,
647                       ValueVT.changeVectorElementType(MVT::f16), Val);
648   } else if (PartEVT != ValueEVT) {
649     return SDValue();
650   }
651 
652   // Widening a scalable vector to another scalable vector is done by inserting
653   // the vector into a larger undef one.
654   if (PartNumElts.isScalable())
655     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
656                        Val, DAG.getVectorIdxConstant(0, DL));
657 
658   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
659   // undef elements.
660   SmallVector<SDValue, 16> Ops;
661   DAG.ExtractVectorElements(Val, Ops);
662   SDValue EltUndef = DAG.getUNDEF(PartEVT);
663   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
664 
665   // FIXME: Use CONCAT for 2x -> 4x.
666   return DAG.getBuildVector(PartVT, DL, Ops);
667 }
668 
669 /// getCopyToPartsVector - Create a series of nodes that contain the specified
670 /// value split into legal parts.
671 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
672                                  SDValue Val, SDValue *Parts, unsigned NumParts,
673                                  MVT PartVT, const Value *V,
674                                  std::optional<CallingConv::ID> CallConv) {
675   EVT ValueVT = Val.getValueType();
676   assert(ValueVT.isVector() && "Not a vector");
677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
678   const bool IsABIRegCopy = CallConv.has_value();
679 
680   if (NumParts == 1) {
681     EVT PartEVT = PartVT;
682     if (PartEVT == ValueVT) {
683       // Nothing to do.
684     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
685       // Bitconvert vector->vector case.
686       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
687     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
688       Val = Widened;
689     } else if (PartVT.isVector() &&
690                PartEVT.getVectorElementType().bitsGE(
691                    ValueVT.getVectorElementType()) &&
692                PartEVT.getVectorElementCount() ==
693                    ValueVT.getVectorElementCount()) {
694 
695       // Promoted vector extract
696       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
697     } else if (PartEVT.isVector() &&
698                PartEVT.getVectorElementType() !=
699                    ValueVT.getVectorElementType() &&
700                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
701                    TargetLowering::TypeWidenVector) {
702       // Combination of widening and promotion.
703       EVT WidenVT =
704           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
705                            PartVT.getVectorElementCount());
706       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
707       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
708     } else {
709       // Don't extract an integer from a float vector. This can happen if the
710       // FP type gets softened to integer and then promoted. The promotion
711       // prevents it from being picked up by the earlier bitcast case.
712       if (ValueVT.getVectorElementCount().isScalar() &&
713           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
714         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
715                           DAG.getVectorIdxConstant(0, DL));
716       } else {
717         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
718         assert(PartVT.getFixedSizeInBits() > ValueSize &&
719                "lossy conversion of vector to scalar type");
720         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
721         Val = DAG.getBitcast(IntermediateType, Val);
722         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
723       }
724     }
725 
726     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
727     Parts[0] = Val;
728     return;
729   }
730 
731   // Handle a multi-element vector.
732   EVT IntermediateVT;
733   MVT RegisterVT;
734   unsigned NumIntermediates;
735   unsigned NumRegs;
736   if (IsABIRegCopy) {
737     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
738         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
739         RegisterVT);
740   } else {
741     NumRegs =
742         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
743                                    NumIntermediates, RegisterVT);
744   }
745 
746   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
747   NumParts = NumRegs; // Silence a compiler warning.
748   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
749 
750   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
751          "Mixing scalable and fixed vectors when copying in parts");
752 
753   std::optional<ElementCount> DestEltCnt;
754 
755   if (IntermediateVT.isVector())
756     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
757   else
758     DestEltCnt = ElementCount::getFixed(NumIntermediates);
759 
760   EVT BuiltVectorTy = EVT::getVectorVT(
761       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
762 
763   if (ValueVT == BuiltVectorTy) {
764     // Nothing to do.
765   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
766     // Bitconvert vector->vector case.
767     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
768   } else {
769     if (BuiltVectorTy.getVectorElementType().bitsGT(
770             ValueVT.getVectorElementType())) {
771       // Integer promotion.
772       ValueVT = EVT::getVectorVT(*DAG.getContext(),
773                                  BuiltVectorTy.getVectorElementType(),
774                                  ValueVT.getVectorElementCount());
775       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
776     }
777 
778     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
779       Val = Widened;
780     }
781   }
782 
783   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
784 
785   // Split the vector into intermediate operands.
786   SmallVector<SDValue, 8> Ops(NumIntermediates);
787   for (unsigned i = 0; i != NumIntermediates; ++i) {
788     if (IntermediateVT.isVector()) {
789       // This does something sensible for scalable vectors - see the
790       // definition of EXTRACT_SUBVECTOR for further details.
791       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
792       Ops[i] =
793           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
794                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
795     } else {
796       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
797                            DAG.getVectorIdxConstant(i, DL));
798     }
799   }
800 
801   // Split the intermediate operands into legal parts.
802   if (NumParts == NumIntermediates) {
803     // If the register was not expanded, promote or copy the value,
804     // as appropriate.
805     for (unsigned i = 0; i != NumParts; ++i)
806       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
807   } else if (NumParts > 0) {
808     // If the intermediate type was expanded, split each the value into
809     // legal parts.
810     assert(NumIntermediates != 0 && "division by zero");
811     assert(NumParts % NumIntermediates == 0 &&
812            "Must expand into a divisible number of parts!");
813     unsigned Factor = NumParts / NumIntermediates;
814     for (unsigned i = 0; i != NumIntermediates; ++i)
815       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
816                      CallConv);
817   }
818 }
819 
820 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
821                            EVT valuevt, std::optional<CallingConv::ID> CC)
822     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
823       RegCount(1, regs.size()), CallConv(CC) {}
824 
825 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
826                            const DataLayout &DL, unsigned Reg, Type *Ty,
827                            std::optional<CallingConv::ID> CC) {
828   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
829 
830   CallConv = CC;
831 
832   for (EVT ValueVT : ValueVTs) {
833     unsigned NumRegs =
834         isABIMangled()
835             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
836             : TLI.getNumRegisters(Context, ValueVT);
837     MVT RegisterVT =
838         isABIMangled()
839             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
840             : TLI.getRegisterType(Context, ValueVT);
841     for (unsigned i = 0; i != NumRegs; ++i)
842       Regs.push_back(Reg + i);
843     RegVTs.push_back(RegisterVT);
844     RegCount.push_back(NumRegs);
845     Reg += NumRegs;
846   }
847 }
848 
849 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
850                                       FunctionLoweringInfo &FuncInfo,
851                                       const SDLoc &dl, SDValue &Chain,
852                                       SDValue *Glue, const Value *V) const {
853   // A Value with type {} or [0 x %t] needs no registers.
854   if (ValueVTs.empty())
855     return SDValue();
856 
857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
858 
859   // Assemble the legal parts into the final values.
860   SmallVector<SDValue, 4> Values(ValueVTs.size());
861   SmallVector<SDValue, 8> Parts;
862   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
863     // Copy the legal parts from the registers.
864     EVT ValueVT = ValueVTs[Value];
865     unsigned NumRegs = RegCount[Value];
866     MVT RegisterVT = isABIMangled()
867                          ? TLI.getRegisterTypeForCallingConv(
868                                *DAG.getContext(), *CallConv, RegVTs[Value])
869                          : RegVTs[Value];
870 
871     Parts.resize(NumRegs);
872     for (unsigned i = 0; i != NumRegs; ++i) {
873       SDValue P;
874       if (!Glue) {
875         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
876       } else {
877         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
878         *Glue = P.getValue(2);
879       }
880 
881       Chain = P.getValue(1);
882       Parts[i] = P;
883 
884       // If the source register was virtual and if we know something about it,
885       // add an assert node.
886       if (!Register::isVirtualRegister(Regs[Part + i]) ||
887           !RegisterVT.isInteger())
888         continue;
889 
890       const FunctionLoweringInfo::LiveOutInfo *LOI =
891         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
892       if (!LOI)
893         continue;
894 
895       unsigned RegSize = RegisterVT.getScalarSizeInBits();
896       unsigned NumSignBits = LOI->NumSignBits;
897       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
898 
899       if (NumZeroBits == RegSize) {
900         // The current value is a zero.
901         // Explicitly express that as it would be easier for
902         // optimizations to kick in.
903         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
904         continue;
905       }
906 
907       // FIXME: We capture more information than the dag can represent.  For
908       // now, just use the tightest assertzext/assertsext possible.
909       bool isSExt;
910       EVT FromVT(MVT::Other);
911       if (NumZeroBits) {
912         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
913         isSExt = false;
914       } else if (NumSignBits > 1) {
915         FromVT =
916             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
917         isSExt = true;
918       } else {
919         continue;
920       }
921       // Add an assertion node.
922       assert(FromVT != MVT::Other);
923       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
924                              RegisterVT, P, DAG.getValueType(FromVT));
925     }
926 
927     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
928                                      RegisterVT, ValueVT, V, CallConv);
929     Part += NumRegs;
930     Parts.clear();
931   }
932 
933   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
934 }
935 
936 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
937                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
938                                  const Value *V,
939                                  ISD::NodeType PreferredExtendType) const {
940   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
941   ISD::NodeType ExtendKind = PreferredExtendType;
942 
943   // Get the list of the values's legal parts.
944   unsigned NumRegs = Regs.size();
945   SmallVector<SDValue, 8> Parts(NumRegs);
946   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
947     unsigned NumParts = RegCount[Value];
948 
949     MVT RegisterVT = isABIMangled()
950                          ? TLI.getRegisterTypeForCallingConv(
951                                *DAG.getContext(), *CallConv, RegVTs[Value])
952                          : RegVTs[Value];
953 
954     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
955       ExtendKind = ISD::ZERO_EXTEND;
956 
957     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
958                    NumParts, RegisterVT, V, CallConv, ExtendKind);
959     Part += NumParts;
960   }
961 
962   // Copy the parts into the registers.
963   SmallVector<SDValue, 8> Chains(NumRegs);
964   for (unsigned i = 0; i != NumRegs; ++i) {
965     SDValue Part;
966     if (!Glue) {
967       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
968     } else {
969       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
970       *Glue = Part.getValue(1);
971     }
972 
973     Chains[i] = Part.getValue(0);
974   }
975 
976   if (NumRegs == 1 || Glue)
977     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
978     // flagged to it. That is the CopyToReg nodes and the user are considered
979     // a single scheduling unit. If we create a TokenFactor and return it as
980     // chain, then the TokenFactor is both a predecessor (operand) of the
981     // user as well as a successor (the TF operands are flagged to the user).
982     // c1, f1 = CopyToReg
983     // c2, f2 = CopyToReg
984     // c3     = TokenFactor c1, c2
985     // ...
986     //        = op c3, ..., f2
987     Chain = Chains[NumRegs-1];
988   else
989     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
990 }
991 
992 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
993                                         unsigned MatchingIdx, const SDLoc &dl,
994                                         SelectionDAG &DAG,
995                                         std::vector<SDValue> &Ops) const {
996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
997 
998   InlineAsm::Flag Flag(Code, Regs.size());
999   if (HasMatching)
1000     Flag.setMatchingOp(MatchingIdx);
1001   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1002     // Put the register class of the virtual registers in the flag word.  That
1003     // way, later passes can recompute register class constraints for inline
1004     // assembly as well as normal instructions.
1005     // Don't do this for tied operands that can use the regclass information
1006     // from the def.
1007     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1008     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1009     Flag.setRegClass(RC->getID());
1010   }
1011 
1012   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1013   Ops.push_back(Res);
1014 
1015   if (Code == InlineAsm::Kind::Clobber) {
1016     // Clobbers should always have a 1:1 mapping with registers, and may
1017     // reference registers that have illegal (e.g. vector) types. Hence, we
1018     // shouldn't try to apply any sort of splitting logic to them.
1019     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1020            "No 1:1 mapping from clobbers to regs?");
1021     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1022     (void)SP;
1023     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1024       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1025       assert(
1026           (Regs[I] != SP ||
1027            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1028           "If we clobbered the stack pointer, MFI should know about it.");
1029     }
1030     return;
1031   }
1032 
1033   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1034     MVT RegisterVT = RegVTs[Value];
1035     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1036                                            RegisterVT);
1037     for (unsigned i = 0; i != NumRegs; ++i) {
1038       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1039       unsigned TheReg = Regs[Reg++];
1040       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1041     }
1042   }
1043 }
1044 
1045 SmallVector<std::pair<unsigned, TypeSize>, 4>
1046 RegsForValue::getRegsAndSizes() const {
1047   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1048   unsigned I = 0;
1049   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1050     unsigned RegCount = std::get<0>(CountAndVT);
1051     MVT RegisterVT = std::get<1>(CountAndVT);
1052     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1053     for (unsigned E = I + RegCount; I != E; ++I)
1054       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1055   }
1056   return OutVec;
1057 }
1058 
1059 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1060                                AssumptionCache *ac,
1061                                const TargetLibraryInfo *li) {
1062   AA = aa;
1063   AC = ac;
1064   GFI = gfi;
1065   LibInfo = li;
1066   Context = DAG.getContext();
1067   LPadToCallSiteMap.clear();
1068   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1069   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1070       *DAG.getMachineFunction().getFunction().getParent());
1071 }
1072 
1073 void SelectionDAGBuilder::clear() {
1074   NodeMap.clear();
1075   UnusedArgNodeMap.clear();
1076   PendingLoads.clear();
1077   PendingExports.clear();
1078   PendingConstrainedFP.clear();
1079   PendingConstrainedFPStrict.clear();
1080   CurInst = nullptr;
1081   HasTailCall = false;
1082   SDNodeOrder = LowestSDNodeOrder;
1083   StatepointLowering.clear();
1084 }
1085 
1086 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1087   DanglingDebugInfoMap.clear();
1088 }
1089 
1090 // Update DAG root to include dependencies on Pending chains.
1091 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1092   SDValue Root = DAG.getRoot();
1093 
1094   if (Pending.empty())
1095     return Root;
1096 
1097   // Add current root to PendingChains, unless we already indirectly
1098   // depend on it.
1099   if (Root.getOpcode() != ISD::EntryToken) {
1100     unsigned i = 0, e = Pending.size();
1101     for (; i != e; ++i) {
1102       assert(Pending[i].getNode()->getNumOperands() > 1);
1103       if (Pending[i].getNode()->getOperand(0) == Root)
1104         break;  // Don't add the root if we already indirectly depend on it.
1105     }
1106 
1107     if (i == e)
1108       Pending.push_back(Root);
1109   }
1110 
1111   if (Pending.size() == 1)
1112     Root = Pending[0];
1113   else
1114     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1115 
1116   DAG.setRoot(Root);
1117   Pending.clear();
1118   return Root;
1119 }
1120 
1121 SDValue SelectionDAGBuilder::getMemoryRoot() {
1122   return updateRoot(PendingLoads);
1123 }
1124 
1125 SDValue SelectionDAGBuilder::getRoot() {
1126   // Chain up all pending constrained intrinsics together with all
1127   // pending loads, by simply appending them to PendingLoads and
1128   // then calling getMemoryRoot().
1129   PendingLoads.reserve(PendingLoads.size() +
1130                        PendingConstrainedFP.size() +
1131                        PendingConstrainedFPStrict.size());
1132   PendingLoads.append(PendingConstrainedFP.begin(),
1133                       PendingConstrainedFP.end());
1134   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1135                       PendingConstrainedFPStrict.end());
1136   PendingConstrainedFP.clear();
1137   PendingConstrainedFPStrict.clear();
1138   return getMemoryRoot();
1139 }
1140 
1141 SDValue SelectionDAGBuilder::getControlRoot() {
1142   // We need to emit pending fpexcept.strict constrained intrinsics,
1143   // so append them to the PendingExports list.
1144   PendingExports.append(PendingConstrainedFPStrict.begin(),
1145                         PendingConstrainedFPStrict.end());
1146   PendingConstrainedFPStrict.clear();
1147   return updateRoot(PendingExports);
1148 }
1149 
1150 void SelectionDAGBuilder::visit(const Instruction &I) {
1151   // Set up outgoing PHI node register values before emitting the terminator.
1152   if (I.isTerminator()) {
1153     HandlePHINodesInSuccessorBlocks(I.getParent());
1154   }
1155 
1156   // Add SDDbgValue nodes for any var locs here. Do so before updating
1157   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1158   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1159     // Add SDDbgValue nodes for any var locs here. Do so before updating
1160     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1161     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1162          It != End; ++It) {
1163       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1164       dropDanglingDebugInfo(Var, It->Expr);
1165       if (It->Values.isKillLocation(It->Expr)) {
1166         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1167         continue;
1168       }
1169       SmallVector<Value *> Values(It->Values.location_ops());
1170       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1171                             It->Values.hasArgList()))
1172         addDanglingDebugInfo(It, SDNodeOrder);
1173     }
1174   }
1175 
1176   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1177   if (!isa<DbgInfoIntrinsic>(I))
1178     ++SDNodeOrder;
1179 
1180   CurInst = &I;
1181 
1182   // Set inserted listener only if required.
1183   bool NodeInserted = false;
1184   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1185   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1186   if (PCSectionsMD) {
1187     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1188         DAG, [&](SDNode *) { NodeInserted = true; });
1189   }
1190 
1191   visit(I.getOpcode(), I);
1192 
1193   if (!I.isTerminator() && !HasTailCall &&
1194       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1195     CopyToExportRegsIfNeeded(&I);
1196 
1197   // Handle metadata.
1198   if (PCSectionsMD) {
1199     auto It = NodeMap.find(&I);
1200     if (It != NodeMap.end()) {
1201       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1202     } else if (NodeInserted) {
1203       // This should not happen; if it does, don't let it go unnoticed so we can
1204       // fix it. Relevant visit*() function is probably missing a setValue().
1205       errs() << "warning: loosing !pcsections metadata ["
1206              << I.getModule()->getName() << "]\n";
1207       LLVM_DEBUG(I.dump());
1208       assert(false);
1209     }
1210   }
1211 
1212   CurInst = nullptr;
1213 }
1214 
1215 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1216   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1217 }
1218 
1219 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1220   // Note: this doesn't use InstVisitor, because it has to work with
1221   // ConstantExpr's in addition to instructions.
1222   switch (Opcode) {
1223   default: llvm_unreachable("Unknown instruction type encountered!");
1224     // Build the switch statement using the Instruction.def file.
1225 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1226     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1227 #include "llvm/IR/Instruction.def"
1228   }
1229 }
1230 
1231 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1232                                             DILocalVariable *Variable,
1233                                             DebugLoc DL, unsigned Order,
1234                                             RawLocationWrapper Values,
1235                                             DIExpression *Expression) {
1236   if (!Values.hasArgList())
1237     return false;
1238   // For variadic dbg_values we will now insert an undef.
1239   // FIXME: We can potentially recover these!
1240   SmallVector<SDDbgOperand, 2> Locs;
1241   for (const Value *V : Values.location_ops()) {
1242     auto *Undef = UndefValue::get(V->getType());
1243     Locs.push_back(SDDbgOperand::fromConst(Undef));
1244   }
1245   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1246                                         /*IsIndirect=*/false, DL, Order,
1247                                         /*IsVariadic=*/true);
1248   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1249   return true;
1250 }
1251 
1252 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1253                                                unsigned Order) {
1254   if (!handleDanglingVariadicDebugInfo(
1255           DAG,
1256           const_cast<DILocalVariable *>(DAG.getFunctionVarLocs()
1257                                             ->getVariable(VarLoc->VariableID)
1258                                             .getVariable()),
1259           VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) {
1260     DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back(
1261         VarLoc, Order);
1262   }
1263 }
1264 
1265 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1266                                                unsigned Order) {
1267   // We treat variadic dbg_values differently at this stage.
1268   if (!handleDanglingVariadicDebugInfo(
1269           DAG, DI->getVariable(), DI->getDebugLoc(), Order,
1270           DI->getWrappedLocation(), DI->getExpression())) {
1271     // TODO: Dangling debug info will eventually either be resolved or produce
1272     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1273     // between the original dbg.value location and its resolved DBG_VALUE,
1274     // which we should ideally fill with an extra Undef DBG_VALUE.
1275     assert(DI->getNumVariableLocationOps() == 1 &&
1276            "DbgValueInst without an ArgList should have a single location "
1277            "operand.");
1278     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1279   }
1280 }
1281 
1282 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1283                                                 const DIExpression *Expr) {
1284   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1285     DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1286     DIExpression *DanglingExpr = DDI.getExpression();
1287     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1288       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1289                         << "\n");
1290       return true;
1291     }
1292     return false;
1293   };
1294 
1295   for (auto &DDIMI : DanglingDebugInfoMap) {
1296     DanglingDebugInfoVector &DDIV = DDIMI.second;
1297 
1298     // If debug info is to be dropped, run it through final checks to see
1299     // whether it can be salvaged.
1300     for (auto &DDI : DDIV)
1301       if (isMatchingDbgValue(DDI))
1302         salvageUnresolvedDbgValue(DDI);
1303 
1304     erase_if(DDIV, isMatchingDbgValue);
1305   }
1306 }
1307 
1308 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1309 // generate the debug data structures now that we've seen its definition.
1310 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1311                                                    SDValue Val) {
1312   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1313   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1314     return;
1315 
1316   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1317   for (auto &DDI : DDIV) {
1318     DebugLoc DL = DDI.getDebugLoc();
1319     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1320     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1321     DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1322     DIExpression *Expr = DDI.getExpression();
1323     assert(Variable->isValidLocationForIntrinsic(DL) &&
1324            "Expected inlined-at fields to agree");
1325     SDDbgValue *SDV;
1326     if (Val.getNode()) {
1327       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1328       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1329       // we couldn't resolve it directly when examining the DbgValue intrinsic
1330       // in the first place we should not be more successful here). Unless we
1331       // have some test case that prove this to be correct we should avoid
1332       // calling EmitFuncArgumentDbgValue here.
1333       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1334                                     FuncArgumentDbgValueKind::Value, Val)) {
1335         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1336                           << "\n");
1337         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1338         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1339         // inserted after the definition of Val when emitting the instructions
1340         // after ISel. An alternative could be to teach
1341         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1342         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1343                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1344                    << ValSDNodeOrder << "\n");
1345         SDV = getDbgValue(Val, Variable, Expr, DL,
1346                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1347         DAG.AddDbgValue(SDV, false);
1348       } else
1349         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1350                           << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1351     } else {
1352       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1353       auto Undef = UndefValue::get(V->getType());
1354       auto SDV =
1355           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1356       DAG.AddDbgValue(SDV, false);
1357     }
1358   }
1359   DDIV.clear();
1360 }
1361 
1362 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1363   // TODO: For the variadic implementation, instead of only checking the fail
1364   // state of `handleDebugValue`, we need know specifically which values were
1365   // invalid, so that we attempt to salvage only those values when processing
1366   // a DIArgList.
1367   Value *V = DDI.getVariableLocationOp(0);
1368   Value *OrigV = V;
1369   DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1370   DIExpression *Expr = DDI.getExpression();
1371   DebugLoc DL = DDI.getDebugLoc();
1372   unsigned SDOrder = DDI.getSDNodeOrder();
1373 
1374   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1375   // that DW_OP_stack_value is desired.
1376   bool StackValue = true;
1377 
1378   // Can this Value can be encoded without any further work?
1379   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1380     return;
1381 
1382   // Attempt to salvage back through as many instructions as possible. Bail if
1383   // a non-instruction is seen, such as a constant expression or global
1384   // variable. FIXME: Further work could recover those too.
1385   while (isa<Instruction>(V)) {
1386     Instruction &VAsInst = *cast<Instruction>(V);
1387     // Temporary "0", awaiting real implementation.
1388     SmallVector<uint64_t, 16> Ops;
1389     SmallVector<Value *, 4> AdditionalValues;
1390     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1391                              AdditionalValues);
1392     // If we cannot salvage any further, and haven't yet found a suitable debug
1393     // expression, bail out.
1394     if (!V)
1395       break;
1396 
1397     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1398     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1399     // here for variadic dbg_values, remove that condition.
1400     if (!AdditionalValues.empty())
1401       break;
1402 
1403     // New value and expr now represent this debuginfo.
1404     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1405 
1406     // Some kind of simplification occurred: check whether the operand of the
1407     // salvaged debug expression can be encoded in this DAG.
1408     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1409       LLVM_DEBUG(
1410           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1411                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1412       return;
1413     }
1414   }
1415 
1416   // This was the final opportunity to salvage this debug information, and it
1417   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1418   // any earlier variable location.
1419   assert(OrigV && "V shouldn't be null");
1420   auto *Undef = UndefValue::get(OrigV->getType());
1421   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1422   DAG.AddDbgValue(SDV, false);
1423   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << printDDI(DDI)
1424                     << "\n");
1425 }
1426 
1427 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1428                                                DIExpression *Expr,
1429                                                DebugLoc DbgLoc,
1430                                                unsigned Order) {
1431   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1432   DIExpression *NewExpr =
1433       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1434   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1435                    /*IsVariadic*/ false);
1436 }
1437 
1438 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1439                                            DILocalVariable *Var,
1440                                            DIExpression *Expr, DebugLoc DbgLoc,
1441                                            unsigned Order, bool IsVariadic) {
1442   if (Values.empty())
1443     return true;
1444   SmallVector<SDDbgOperand> LocationOps;
1445   SmallVector<SDNode *> Dependencies;
1446   for (const Value *V : Values) {
1447     // Constant value.
1448     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1449         isa<ConstantPointerNull>(V)) {
1450       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1451       continue;
1452     }
1453 
1454     // Look through IntToPtr constants.
1455     if (auto *CE = dyn_cast<ConstantExpr>(V))
1456       if (CE->getOpcode() == Instruction::IntToPtr) {
1457         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1458         continue;
1459       }
1460 
1461     // If the Value is a frame index, we can create a FrameIndex debug value
1462     // without relying on the DAG at all.
1463     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1464       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1465       if (SI != FuncInfo.StaticAllocaMap.end()) {
1466         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1467         continue;
1468       }
1469     }
1470 
1471     // Do not use getValue() in here; we don't want to generate code at
1472     // this point if it hasn't been done yet.
1473     SDValue N = NodeMap[V];
1474     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1475       N = UnusedArgNodeMap[V];
1476     if (N.getNode()) {
1477       // Only emit func arg dbg value for non-variadic dbg.values for now.
1478       if (!IsVariadic &&
1479           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1480                                    FuncArgumentDbgValueKind::Value, N))
1481         return true;
1482       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1483         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1484         // describe stack slot locations.
1485         //
1486         // Consider "int x = 0; int *px = &x;". There are two kinds of
1487         // interesting debug values here after optimization:
1488         //
1489         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1490         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1491         //
1492         // Both describe the direct values of their associated variables.
1493         Dependencies.push_back(N.getNode());
1494         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1495         continue;
1496       }
1497       LocationOps.emplace_back(
1498           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1499       continue;
1500     }
1501 
1502     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1503     // Special rules apply for the first dbg.values of parameter variables in a
1504     // function. Identify them by the fact they reference Argument Values, that
1505     // they're parameters, and they are parameters of the current function. We
1506     // need to let them dangle until they get an SDNode.
1507     bool IsParamOfFunc =
1508         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1509     if (IsParamOfFunc)
1510       return false;
1511 
1512     // The value is not used in this block yet (or it would have an SDNode).
1513     // We still want the value to appear for the user if possible -- if it has
1514     // an associated VReg, we can refer to that instead.
1515     auto VMI = FuncInfo.ValueMap.find(V);
1516     if (VMI != FuncInfo.ValueMap.end()) {
1517       unsigned Reg = VMI->second;
1518       // If this is a PHI node, it may be split up into several MI PHI nodes
1519       // (in FunctionLoweringInfo::set).
1520       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1521                        V->getType(), std::nullopt);
1522       if (RFV.occupiesMultipleRegs()) {
1523         // FIXME: We could potentially support variadic dbg_values here.
1524         if (IsVariadic)
1525           return false;
1526         unsigned Offset = 0;
1527         unsigned BitsToDescribe = 0;
1528         if (auto VarSize = Var->getSizeInBits())
1529           BitsToDescribe = *VarSize;
1530         if (auto Fragment = Expr->getFragmentInfo())
1531           BitsToDescribe = Fragment->SizeInBits;
1532         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1533           // Bail out if all bits are described already.
1534           if (Offset >= BitsToDescribe)
1535             break;
1536           // TODO: handle scalable vectors.
1537           unsigned RegisterSize = RegAndSize.second;
1538           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1539                                       ? BitsToDescribe - Offset
1540                                       : RegisterSize;
1541           auto FragmentExpr = DIExpression::createFragmentExpression(
1542               Expr, Offset, FragmentSize);
1543           if (!FragmentExpr)
1544             continue;
1545           SDDbgValue *SDV = DAG.getVRegDbgValue(
1546               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1547           DAG.AddDbgValue(SDV, false);
1548           Offset += RegisterSize;
1549         }
1550         return true;
1551       }
1552       // We can use simple vreg locations for variadic dbg_values as well.
1553       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1554       continue;
1555     }
1556     // We failed to create a SDDbgOperand for V.
1557     return false;
1558   }
1559 
1560   // We have created a SDDbgOperand for each Value in Values.
1561   // Should use Order instead of SDNodeOrder?
1562   assert(!LocationOps.empty());
1563   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1564                                         /*IsIndirect=*/false, DbgLoc,
1565                                         SDNodeOrder, IsVariadic);
1566   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1567   return true;
1568 }
1569 
1570 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1571   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1572   for (auto &Pair : DanglingDebugInfoMap)
1573     for (auto &DDI : Pair.second)
1574       salvageUnresolvedDbgValue(DDI);
1575   clearDanglingDebugInfo();
1576 }
1577 
1578 /// getCopyFromRegs - If there was virtual register allocated for the value V
1579 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1580 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1581   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1582   SDValue Result;
1583 
1584   if (It != FuncInfo.ValueMap.end()) {
1585     Register InReg = It->second;
1586 
1587     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1588                      DAG.getDataLayout(), InReg, Ty,
1589                      std::nullopt); // This is not an ABI copy.
1590     SDValue Chain = DAG.getEntryNode();
1591     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1592                                  V);
1593     resolveDanglingDebugInfo(V, Result);
1594   }
1595 
1596   return Result;
1597 }
1598 
1599 /// getValue - Return an SDValue for the given Value.
1600 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1601   // If we already have an SDValue for this value, use it. It's important
1602   // to do this first, so that we don't create a CopyFromReg if we already
1603   // have a regular SDValue.
1604   SDValue &N = NodeMap[V];
1605   if (N.getNode()) return N;
1606 
1607   // If there's a virtual register allocated and initialized for this
1608   // value, use it.
1609   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1610     return copyFromReg;
1611 
1612   // Otherwise create a new SDValue and remember it.
1613   SDValue Val = getValueImpl(V);
1614   NodeMap[V] = Val;
1615   resolveDanglingDebugInfo(V, Val);
1616   return Val;
1617 }
1618 
1619 /// getNonRegisterValue - Return an SDValue for the given Value, but
1620 /// don't look in FuncInfo.ValueMap for a virtual register.
1621 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1622   // If we already have an SDValue for this value, use it.
1623   SDValue &N = NodeMap[V];
1624   if (N.getNode()) {
1625     if (isIntOrFPConstant(N)) {
1626       // Remove the debug location from the node as the node is about to be used
1627       // in a location which may differ from the original debug location.  This
1628       // is relevant to Constant and ConstantFP nodes because they can appear
1629       // as constant expressions inside PHI nodes.
1630       N->setDebugLoc(DebugLoc());
1631     }
1632     return N;
1633   }
1634 
1635   // Otherwise create a new SDValue and remember it.
1636   SDValue Val = getValueImpl(V);
1637   NodeMap[V] = Val;
1638   resolveDanglingDebugInfo(V, Val);
1639   return Val;
1640 }
1641 
1642 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1643 /// Create an SDValue for the given value.
1644 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1646 
1647   if (const Constant *C = dyn_cast<Constant>(V)) {
1648     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1649 
1650     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1651       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1652 
1653     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1654       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1655 
1656     if (isa<ConstantPointerNull>(C)) {
1657       unsigned AS = V->getType()->getPointerAddressSpace();
1658       return DAG.getConstant(0, getCurSDLoc(),
1659                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1660     }
1661 
1662     if (match(C, m_VScale()))
1663       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1664 
1665     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1666       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1667 
1668     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1669       return DAG.getUNDEF(VT);
1670 
1671     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1672       visit(CE->getOpcode(), *CE);
1673       SDValue N1 = NodeMap[V];
1674       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1675       return N1;
1676     }
1677 
1678     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1679       SmallVector<SDValue, 4> Constants;
1680       for (const Use &U : C->operands()) {
1681         SDNode *Val = getValue(U).getNode();
1682         // If the operand is an empty aggregate, there are no values.
1683         if (!Val) continue;
1684         // Add each leaf value from the operand to the Constants list
1685         // to form a flattened list of all the values.
1686         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1687           Constants.push_back(SDValue(Val, i));
1688       }
1689 
1690       return DAG.getMergeValues(Constants, getCurSDLoc());
1691     }
1692 
1693     if (const ConstantDataSequential *CDS =
1694           dyn_cast<ConstantDataSequential>(C)) {
1695       SmallVector<SDValue, 4> Ops;
1696       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1697         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1698         // Add each leaf value from the operand to the Constants list
1699         // to form a flattened list of all the values.
1700         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1701           Ops.push_back(SDValue(Val, i));
1702       }
1703 
1704       if (isa<ArrayType>(CDS->getType()))
1705         return DAG.getMergeValues(Ops, getCurSDLoc());
1706       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1707     }
1708 
1709     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1710       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1711              "Unknown struct or array constant!");
1712 
1713       SmallVector<EVT, 4> ValueVTs;
1714       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1715       unsigned NumElts = ValueVTs.size();
1716       if (NumElts == 0)
1717         return SDValue(); // empty struct
1718       SmallVector<SDValue, 4> Constants(NumElts);
1719       for (unsigned i = 0; i != NumElts; ++i) {
1720         EVT EltVT = ValueVTs[i];
1721         if (isa<UndefValue>(C))
1722           Constants[i] = DAG.getUNDEF(EltVT);
1723         else if (EltVT.isFloatingPoint())
1724           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1725         else
1726           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1727       }
1728 
1729       return DAG.getMergeValues(Constants, getCurSDLoc());
1730     }
1731 
1732     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1733       return DAG.getBlockAddress(BA, VT);
1734 
1735     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1736       return getValue(Equiv->getGlobalValue());
1737 
1738     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1739       return getValue(NC->getGlobalValue());
1740 
1741     if (VT == MVT::aarch64svcount) {
1742       assert(C->isNullValue() && "Can only zero this target type!");
1743       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1744                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1745     }
1746 
1747     VectorType *VecTy = cast<VectorType>(V->getType());
1748 
1749     // Now that we know the number and type of the elements, get that number of
1750     // elements into the Ops array based on what kind of constant it is.
1751     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1752       SmallVector<SDValue, 16> Ops;
1753       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1754       for (unsigned i = 0; i != NumElements; ++i)
1755         Ops.push_back(getValue(CV->getOperand(i)));
1756 
1757       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1758     }
1759 
1760     if (isa<ConstantAggregateZero>(C)) {
1761       EVT EltVT =
1762           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1763 
1764       SDValue Op;
1765       if (EltVT.isFloatingPoint())
1766         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1767       else
1768         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1769 
1770       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1771     }
1772 
1773     llvm_unreachable("Unknown vector constant");
1774   }
1775 
1776   // If this is a static alloca, generate it as the frameindex instead of
1777   // computation.
1778   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1779     DenseMap<const AllocaInst*, int>::iterator SI =
1780       FuncInfo.StaticAllocaMap.find(AI);
1781     if (SI != FuncInfo.StaticAllocaMap.end())
1782       return DAG.getFrameIndex(
1783           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1784   }
1785 
1786   // If this is an instruction which fast-isel has deferred, select it now.
1787   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1788     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1789 
1790     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1791                      Inst->getType(), std::nullopt);
1792     SDValue Chain = DAG.getEntryNode();
1793     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1794   }
1795 
1796   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1797     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1798 
1799   if (const auto *BB = dyn_cast<BasicBlock>(V))
1800     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1801 
1802   llvm_unreachable("Can't get register for value!");
1803 }
1804 
1805 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1806   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1807   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1808   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1809   bool IsSEH = isAsynchronousEHPersonality(Pers);
1810   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1811   if (!IsSEH)
1812     CatchPadMBB->setIsEHScopeEntry();
1813   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1814   if (IsMSVCCXX || IsCoreCLR)
1815     CatchPadMBB->setIsEHFuncletEntry();
1816 }
1817 
1818 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1819   // Update machine-CFG edge.
1820   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1821   FuncInfo.MBB->addSuccessor(TargetMBB);
1822   TargetMBB->setIsEHCatchretTarget(true);
1823   DAG.getMachineFunction().setHasEHCatchret(true);
1824 
1825   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1826   bool IsSEH = isAsynchronousEHPersonality(Pers);
1827   if (IsSEH) {
1828     // If this is not a fall-through branch or optimizations are switched off,
1829     // emit the branch.
1830     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1831         TM.getOptLevel() == CodeGenOptLevel::None)
1832       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1833                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1834     return;
1835   }
1836 
1837   // Figure out the funclet membership for the catchret's successor.
1838   // This will be used by the FuncletLayout pass to determine how to order the
1839   // BB's.
1840   // A 'catchret' returns to the outer scope's color.
1841   Value *ParentPad = I.getCatchSwitchParentPad();
1842   const BasicBlock *SuccessorColor;
1843   if (isa<ConstantTokenNone>(ParentPad))
1844     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1845   else
1846     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1847   assert(SuccessorColor && "No parent funclet for catchret!");
1848   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1849   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1850 
1851   // Create the terminator node.
1852   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1853                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1854                             DAG.getBasicBlock(SuccessorColorMBB));
1855   DAG.setRoot(Ret);
1856 }
1857 
1858 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1859   // Don't emit any special code for the cleanuppad instruction. It just marks
1860   // the start of an EH scope/funclet.
1861   FuncInfo.MBB->setIsEHScopeEntry();
1862   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1863   if (Pers != EHPersonality::Wasm_CXX) {
1864     FuncInfo.MBB->setIsEHFuncletEntry();
1865     FuncInfo.MBB->setIsCleanupFuncletEntry();
1866   }
1867 }
1868 
1869 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1870 // not match, it is OK to add only the first unwind destination catchpad to the
1871 // successors, because there will be at least one invoke instruction within the
1872 // catch scope that points to the next unwind destination, if one exists, so
1873 // CFGSort cannot mess up with BB sorting order.
1874 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1875 // call within them, and catchpads only consisting of 'catch (...)' have a
1876 // '__cxa_end_catch' call within them, both of which generate invokes in case
1877 // the next unwind destination exists, i.e., the next unwind destination is not
1878 // the caller.)
1879 //
1880 // Having at most one EH pad successor is also simpler and helps later
1881 // transformations.
1882 //
1883 // For example,
1884 // current:
1885 //   invoke void @foo to ... unwind label %catch.dispatch
1886 // catch.dispatch:
1887 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1888 // catch.start:
1889 //   ...
1890 //   ... in this BB or some other child BB dominated by this BB there will be an
1891 //   invoke that points to 'next' BB as an unwind destination
1892 //
1893 // next: ; We don't need to add this to 'current' BB's successor
1894 //   ...
1895 static void findWasmUnwindDestinations(
1896     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1897     BranchProbability Prob,
1898     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1899         &UnwindDests) {
1900   while (EHPadBB) {
1901     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1902     if (isa<CleanupPadInst>(Pad)) {
1903       // Stop on cleanup pads.
1904       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1905       UnwindDests.back().first->setIsEHScopeEntry();
1906       break;
1907     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1908       // Add the catchpad handlers to the possible destinations. We don't
1909       // continue to the unwind destination of the catchswitch for wasm.
1910       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1911         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1912         UnwindDests.back().first->setIsEHScopeEntry();
1913       }
1914       break;
1915     } else {
1916       continue;
1917     }
1918   }
1919 }
1920 
1921 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1922 /// many places it could ultimately go. In the IR, we have a single unwind
1923 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1924 /// This function skips over imaginary basic blocks that hold catchswitch
1925 /// instructions, and finds all the "real" machine
1926 /// basic block destinations. As those destinations may not be successors of
1927 /// EHPadBB, here we also calculate the edge probability to those destinations.
1928 /// The passed-in Prob is the edge probability to EHPadBB.
1929 static void findUnwindDestinations(
1930     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1931     BranchProbability Prob,
1932     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1933         &UnwindDests) {
1934   EHPersonality Personality =
1935     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1936   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1937   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1938   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1939   bool IsSEH = isAsynchronousEHPersonality(Personality);
1940 
1941   if (IsWasmCXX) {
1942     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1943     assert(UnwindDests.size() <= 1 &&
1944            "There should be at most one unwind destination for wasm");
1945     return;
1946   }
1947 
1948   while (EHPadBB) {
1949     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1950     BasicBlock *NewEHPadBB = nullptr;
1951     if (isa<LandingPadInst>(Pad)) {
1952       // Stop on landingpads. They are not funclets.
1953       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1954       break;
1955     } else if (isa<CleanupPadInst>(Pad)) {
1956       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1957       // personalities.
1958       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1959       UnwindDests.back().first->setIsEHScopeEntry();
1960       UnwindDests.back().first->setIsEHFuncletEntry();
1961       break;
1962     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1963       // Add the catchpad handlers to the possible destinations.
1964       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1965         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1966         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1967         if (IsMSVCCXX || IsCoreCLR)
1968           UnwindDests.back().first->setIsEHFuncletEntry();
1969         if (!IsSEH)
1970           UnwindDests.back().first->setIsEHScopeEntry();
1971       }
1972       NewEHPadBB = CatchSwitch->getUnwindDest();
1973     } else {
1974       continue;
1975     }
1976 
1977     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1978     if (BPI && NewEHPadBB)
1979       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1980     EHPadBB = NewEHPadBB;
1981   }
1982 }
1983 
1984 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1985   // Update successor info.
1986   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1987   auto UnwindDest = I.getUnwindDest();
1988   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1989   BranchProbability UnwindDestProb =
1990       (BPI && UnwindDest)
1991           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1992           : BranchProbability::getZero();
1993   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1994   for (auto &UnwindDest : UnwindDests) {
1995     UnwindDest.first->setIsEHPad();
1996     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1997   }
1998   FuncInfo.MBB->normalizeSuccProbs();
1999 
2000   // Create the terminator node.
2001   SDValue Ret =
2002       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2003   DAG.setRoot(Ret);
2004 }
2005 
2006 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2007   report_fatal_error("visitCatchSwitch not yet implemented!");
2008 }
2009 
2010 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2012   auto &DL = DAG.getDataLayout();
2013   SDValue Chain = getControlRoot();
2014   SmallVector<ISD::OutputArg, 8> Outs;
2015   SmallVector<SDValue, 8> OutVals;
2016 
2017   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2018   // lower
2019   //
2020   //   %val = call <ty> @llvm.experimental.deoptimize()
2021   //   ret <ty> %val
2022   //
2023   // differently.
2024   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2025     LowerDeoptimizingReturn();
2026     return;
2027   }
2028 
2029   if (!FuncInfo.CanLowerReturn) {
2030     unsigned DemoteReg = FuncInfo.DemoteRegister;
2031     const Function *F = I.getParent()->getParent();
2032 
2033     // Emit a store of the return value through the virtual register.
2034     // Leave Outs empty so that LowerReturn won't try to load return
2035     // registers the usual way.
2036     SmallVector<EVT, 1> PtrValueVTs;
2037     ComputeValueVTs(TLI, DL,
2038                     PointerType::get(F->getContext(),
2039                                      DAG.getDataLayout().getAllocaAddrSpace()),
2040                     PtrValueVTs);
2041 
2042     SDValue RetPtr =
2043         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2044     SDValue RetOp = getValue(I.getOperand(0));
2045 
2046     SmallVector<EVT, 4> ValueVTs, MemVTs;
2047     SmallVector<uint64_t, 4> Offsets;
2048     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2049                     &Offsets, 0);
2050     unsigned NumValues = ValueVTs.size();
2051 
2052     SmallVector<SDValue, 4> Chains(NumValues);
2053     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2054     for (unsigned i = 0; i != NumValues; ++i) {
2055       // An aggregate return value cannot wrap around the address space, so
2056       // offsets to its parts don't wrap either.
2057       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2058                                            TypeSize::Fixed(Offsets[i]));
2059 
2060       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2061       if (MemVTs[i] != ValueVTs[i])
2062         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2063       Chains[i] = DAG.getStore(
2064           Chain, getCurSDLoc(), Val,
2065           // FIXME: better loc info would be nice.
2066           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2067           commonAlignment(BaseAlign, Offsets[i]));
2068     }
2069 
2070     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2071                         MVT::Other, Chains);
2072   } else if (I.getNumOperands() != 0) {
2073     SmallVector<EVT, 4> ValueVTs;
2074     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2075     unsigned NumValues = ValueVTs.size();
2076     if (NumValues) {
2077       SDValue RetOp = getValue(I.getOperand(0));
2078 
2079       const Function *F = I.getParent()->getParent();
2080 
2081       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2082           I.getOperand(0)->getType(), F->getCallingConv(),
2083           /*IsVarArg*/ false, DL);
2084 
2085       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2086       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2087         ExtendKind = ISD::SIGN_EXTEND;
2088       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2089         ExtendKind = ISD::ZERO_EXTEND;
2090 
2091       LLVMContext &Context = F->getContext();
2092       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2093 
2094       for (unsigned j = 0; j != NumValues; ++j) {
2095         EVT VT = ValueVTs[j];
2096 
2097         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2098           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2099 
2100         CallingConv::ID CC = F->getCallingConv();
2101 
2102         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2103         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2104         SmallVector<SDValue, 4> Parts(NumParts);
2105         getCopyToParts(DAG, getCurSDLoc(),
2106                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2107                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2108 
2109         // 'inreg' on function refers to return value
2110         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2111         if (RetInReg)
2112           Flags.setInReg();
2113 
2114         if (I.getOperand(0)->getType()->isPointerTy()) {
2115           Flags.setPointer();
2116           Flags.setPointerAddrSpace(
2117               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2118         }
2119 
2120         if (NeedsRegBlock) {
2121           Flags.setInConsecutiveRegs();
2122           if (j == NumValues - 1)
2123             Flags.setInConsecutiveRegsLast();
2124         }
2125 
2126         // Propagate extension type if any
2127         if (ExtendKind == ISD::SIGN_EXTEND)
2128           Flags.setSExt();
2129         else if (ExtendKind == ISD::ZERO_EXTEND)
2130           Flags.setZExt();
2131 
2132         for (unsigned i = 0; i < NumParts; ++i) {
2133           Outs.push_back(ISD::OutputArg(Flags,
2134                                         Parts[i].getValueType().getSimpleVT(),
2135                                         VT, /*isfixed=*/true, 0, 0));
2136           OutVals.push_back(Parts[i]);
2137         }
2138       }
2139     }
2140   }
2141 
2142   // Push in swifterror virtual register as the last element of Outs. This makes
2143   // sure swifterror virtual register will be returned in the swifterror
2144   // physical register.
2145   const Function *F = I.getParent()->getParent();
2146   if (TLI.supportSwiftError() &&
2147       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2148     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2149     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2150     Flags.setSwiftError();
2151     Outs.push_back(ISD::OutputArg(
2152         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2153         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2154     // Create SDNode for the swifterror virtual register.
2155     OutVals.push_back(
2156         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2157                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2158                         EVT(TLI.getPointerTy(DL))));
2159   }
2160 
2161   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2162   CallingConv::ID CallConv =
2163     DAG.getMachineFunction().getFunction().getCallingConv();
2164   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2165       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2166 
2167   // Verify that the target's LowerReturn behaved as expected.
2168   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2169          "LowerReturn didn't return a valid chain!");
2170 
2171   // Update the DAG with the new chain value resulting from return lowering.
2172   DAG.setRoot(Chain);
2173 }
2174 
2175 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2176 /// created for it, emit nodes to copy the value into the virtual
2177 /// registers.
2178 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2179   // Skip empty types
2180   if (V->getType()->isEmptyTy())
2181     return;
2182 
2183   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2184   if (VMI != FuncInfo.ValueMap.end()) {
2185     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2186            "Unused value assigned virtual registers!");
2187     CopyValueToVirtualRegister(V, VMI->second);
2188   }
2189 }
2190 
2191 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2192 /// the current basic block, add it to ValueMap now so that we'll get a
2193 /// CopyTo/FromReg.
2194 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2195   // No need to export constants.
2196   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2197 
2198   // Already exported?
2199   if (FuncInfo.isExportedInst(V)) return;
2200 
2201   Register Reg = FuncInfo.InitializeRegForValue(V);
2202   CopyValueToVirtualRegister(V, Reg);
2203 }
2204 
2205 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2206                                                      const BasicBlock *FromBB) {
2207   // The operands of the setcc have to be in this block.  We don't know
2208   // how to export them from some other block.
2209   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2210     // Can export from current BB.
2211     if (VI->getParent() == FromBB)
2212       return true;
2213 
2214     // Is already exported, noop.
2215     return FuncInfo.isExportedInst(V);
2216   }
2217 
2218   // If this is an argument, we can export it if the BB is the entry block or
2219   // if it is already exported.
2220   if (isa<Argument>(V)) {
2221     if (FromBB->isEntryBlock())
2222       return true;
2223 
2224     // Otherwise, can only export this if it is already exported.
2225     return FuncInfo.isExportedInst(V);
2226   }
2227 
2228   // Otherwise, constants can always be exported.
2229   return true;
2230 }
2231 
2232 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2233 BranchProbability
2234 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2235                                         const MachineBasicBlock *Dst) const {
2236   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2237   const BasicBlock *SrcBB = Src->getBasicBlock();
2238   const BasicBlock *DstBB = Dst->getBasicBlock();
2239   if (!BPI) {
2240     // If BPI is not available, set the default probability as 1 / N, where N is
2241     // the number of successors.
2242     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2243     return BranchProbability(1, SuccSize);
2244   }
2245   return BPI->getEdgeProbability(SrcBB, DstBB);
2246 }
2247 
2248 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2249                                                MachineBasicBlock *Dst,
2250                                                BranchProbability Prob) {
2251   if (!FuncInfo.BPI)
2252     Src->addSuccessorWithoutProb(Dst);
2253   else {
2254     if (Prob.isUnknown())
2255       Prob = getEdgeProbability(Src, Dst);
2256     Src->addSuccessor(Dst, Prob);
2257   }
2258 }
2259 
2260 static bool InBlock(const Value *V, const BasicBlock *BB) {
2261   if (const Instruction *I = dyn_cast<Instruction>(V))
2262     return I->getParent() == BB;
2263   return true;
2264 }
2265 
2266 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2267 /// This function emits a branch and is used at the leaves of an OR or an
2268 /// AND operator tree.
2269 void
2270 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2271                                                   MachineBasicBlock *TBB,
2272                                                   MachineBasicBlock *FBB,
2273                                                   MachineBasicBlock *CurBB,
2274                                                   MachineBasicBlock *SwitchBB,
2275                                                   BranchProbability TProb,
2276                                                   BranchProbability FProb,
2277                                                   bool InvertCond) {
2278   const BasicBlock *BB = CurBB->getBasicBlock();
2279 
2280   // If the leaf of the tree is a comparison, merge the condition into
2281   // the caseblock.
2282   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2283     // The operands of the cmp have to be in this block.  We don't know
2284     // how to export them from some other block.  If this is the first block
2285     // of the sequence, no exporting is needed.
2286     if (CurBB == SwitchBB ||
2287         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2288          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2289       ISD::CondCode Condition;
2290       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2291         ICmpInst::Predicate Pred =
2292             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2293         Condition = getICmpCondCode(Pred);
2294       } else {
2295         const FCmpInst *FC = cast<FCmpInst>(Cond);
2296         FCmpInst::Predicate Pred =
2297             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2298         Condition = getFCmpCondCode(Pred);
2299         if (TM.Options.NoNaNsFPMath)
2300           Condition = getFCmpCodeWithoutNaN(Condition);
2301       }
2302 
2303       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2304                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2305       SL->SwitchCases.push_back(CB);
2306       return;
2307     }
2308   }
2309 
2310   // Create a CaseBlock record representing this branch.
2311   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2312   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2313                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2314   SL->SwitchCases.push_back(CB);
2315 }
2316 
2317 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2318                                                MachineBasicBlock *TBB,
2319                                                MachineBasicBlock *FBB,
2320                                                MachineBasicBlock *CurBB,
2321                                                MachineBasicBlock *SwitchBB,
2322                                                Instruction::BinaryOps Opc,
2323                                                BranchProbability TProb,
2324                                                BranchProbability FProb,
2325                                                bool InvertCond) {
2326   // Skip over not part of the tree and remember to invert op and operands at
2327   // next level.
2328   Value *NotCond;
2329   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2330       InBlock(NotCond, CurBB->getBasicBlock())) {
2331     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2332                          !InvertCond);
2333     return;
2334   }
2335 
2336   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2337   const Value *BOpOp0, *BOpOp1;
2338   // Compute the effective opcode for Cond, taking into account whether it needs
2339   // to be inverted, e.g.
2340   //   and (not (or A, B)), C
2341   // gets lowered as
2342   //   and (and (not A, not B), C)
2343   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2344   if (BOp) {
2345     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2346                ? Instruction::And
2347                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2348                       ? Instruction::Or
2349                       : (Instruction::BinaryOps)0);
2350     if (InvertCond) {
2351       if (BOpc == Instruction::And)
2352         BOpc = Instruction::Or;
2353       else if (BOpc == Instruction::Or)
2354         BOpc = Instruction::And;
2355     }
2356   }
2357 
2358   // If this node is not part of the or/and tree, emit it as a branch.
2359   // Note that all nodes in the tree should have same opcode.
2360   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2361   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2362       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2363       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2364     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2365                                  TProb, FProb, InvertCond);
2366     return;
2367   }
2368 
2369   //  Create TmpBB after CurBB.
2370   MachineFunction::iterator BBI(CurBB);
2371   MachineFunction &MF = DAG.getMachineFunction();
2372   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2373   CurBB->getParent()->insert(++BBI, TmpBB);
2374 
2375   if (Opc == Instruction::Or) {
2376     // Codegen X | Y as:
2377     // BB1:
2378     //   jmp_if_X TBB
2379     //   jmp TmpBB
2380     // TmpBB:
2381     //   jmp_if_Y TBB
2382     //   jmp FBB
2383     //
2384 
2385     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2386     // The requirement is that
2387     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2388     //     = TrueProb for original BB.
2389     // Assuming the original probabilities are A and B, one choice is to set
2390     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2391     // A/(1+B) and 2B/(1+B). This choice assumes that
2392     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2393     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2394     // TmpBB, but the math is more complicated.
2395 
2396     auto NewTrueProb = TProb / 2;
2397     auto NewFalseProb = TProb / 2 + FProb;
2398     // Emit the LHS condition.
2399     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2400                          NewFalseProb, InvertCond);
2401 
2402     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2403     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2404     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2405     // Emit the RHS condition into TmpBB.
2406     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2407                          Probs[1], InvertCond);
2408   } else {
2409     assert(Opc == Instruction::And && "Unknown merge op!");
2410     // Codegen X & Y as:
2411     // BB1:
2412     //   jmp_if_X TmpBB
2413     //   jmp FBB
2414     // TmpBB:
2415     //   jmp_if_Y TBB
2416     //   jmp FBB
2417     //
2418     //  This requires creation of TmpBB after CurBB.
2419 
2420     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2421     // The requirement is that
2422     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2423     //     = FalseProb for original BB.
2424     // Assuming the original probabilities are A and B, one choice is to set
2425     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2426     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2427     // TrueProb for BB1 * FalseProb for TmpBB.
2428 
2429     auto NewTrueProb = TProb + FProb / 2;
2430     auto NewFalseProb = FProb / 2;
2431     // Emit the LHS condition.
2432     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2433                          NewFalseProb, InvertCond);
2434 
2435     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2436     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2437     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2438     // Emit the RHS condition into TmpBB.
2439     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2440                          Probs[1], InvertCond);
2441   }
2442 }
2443 
2444 /// If the set of cases should be emitted as a series of branches, return true.
2445 /// If we should emit this as a bunch of and/or'd together conditions, return
2446 /// false.
2447 bool
2448 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2449   if (Cases.size() != 2) return true;
2450 
2451   // If this is two comparisons of the same values or'd or and'd together, they
2452   // will get folded into a single comparison, so don't emit two blocks.
2453   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2454        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2455       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2456        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2457     return false;
2458   }
2459 
2460   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2461   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2462   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2463       Cases[0].CC == Cases[1].CC &&
2464       isa<Constant>(Cases[0].CmpRHS) &&
2465       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2466     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2467       return false;
2468     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2469       return false;
2470   }
2471 
2472   return true;
2473 }
2474 
2475 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2476   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2477 
2478   // Update machine-CFG edges.
2479   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2480 
2481   if (I.isUnconditional()) {
2482     // Update machine-CFG edges.
2483     BrMBB->addSuccessor(Succ0MBB);
2484 
2485     // If this is not a fall-through branch or optimizations are switched off,
2486     // emit the branch.
2487     if (Succ0MBB != NextBlock(BrMBB) ||
2488         TM.getOptLevel() == CodeGenOptLevel::None) {
2489       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2490                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2491       setValue(&I, Br);
2492       DAG.setRoot(Br);
2493     }
2494 
2495     return;
2496   }
2497 
2498   // If this condition is one of the special cases we handle, do special stuff
2499   // now.
2500   const Value *CondVal = I.getCondition();
2501   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2502 
2503   // If this is a series of conditions that are or'd or and'd together, emit
2504   // this as a sequence of branches instead of setcc's with and/or operations.
2505   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2506   // unpredictable branches, and vector extracts because those jumps are likely
2507   // expensive for any target), this should improve performance.
2508   // For example, instead of something like:
2509   //     cmp A, B
2510   //     C = seteq
2511   //     cmp D, E
2512   //     F = setle
2513   //     or C, F
2514   //     jnz foo
2515   // Emit:
2516   //     cmp A, B
2517   //     je foo
2518   //     cmp D, E
2519   //     jle foo
2520   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2521   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2522       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2523     Value *Vec;
2524     const Value *BOp0, *BOp1;
2525     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2526     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2527       Opcode = Instruction::And;
2528     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2529       Opcode = Instruction::Or;
2530 
2531     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2532                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2533       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2534                            getEdgeProbability(BrMBB, Succ0MBB),
2535                            getEdgeProbability(BrMBB, Succ1MBB),
2536                            /*InvertCond=*/false);
2537       // If the compares in later blocks need to use values not currently
2538       // exported from this block, export them now.  This block should always
2539       // be the first entry.
2540       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2541 
2542       // Allow some cases to be rejected.
2543       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2544         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2545           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2546           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2547         }
2548 
2549         // Emit the branch for this block.
2550         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2551         SL->SwitchCases.erase(SL->SwitchCases.begin());
2552         return;
2553       }
2554 
2555       // Okay, we decided not to do this, remove any inserted MBB's and clear
2556       // SwitchCases.
2557       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2558         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2559 
2560       SL->SwitchCases.clear();
2561     }
2562   }
2563 
2564   // Create a CaseBlock record representing this branch.
2565   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2566                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2567 
2568   // Use visitSwitchCase to actually insert the fast branch sequence for this
2569   // cond branch.
2570   visitSwitchCase(CB, BrMBB);
2571 }
2572 
2573 /// visitSwitchCase - Emits the necessary code to represent a single node in
2574 /// the binary search tree resulting from lowering a switch instruction.
2575 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2576                                           MachineBasicBlock *SwitchBB) {
2577   SDValue Cond;
2578   SDValue CondLHS = getValue(CB.CmpLHS);
2579   SDLoc dl = CB.DL;
2580 
2581   if (CB.CC == ISD::SETTRUE) {
2582     // Branch or fall through to TrueBB.
2583     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2584     SwitchBB->normalizeSuccProbs();
2585     if (CB.TrueBB != NextBlock(SwitchBB)) {
2586       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2587                               DAG.getBasicBlock(CB.TrueBB)));
2588     }
2589     return;
2590   }
2591 
2592   auto &TLI = DAG.getTargetLoweringInfo();
2593   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2594 
2595   // Build the setcc now.
2596   if (!CB.CmpMHS) {
2597     // Fold "(X == true)" to X and "(X == false)" to !X to
2598     // handle common cases produced by branch lowering.
2599     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2600         CB.CC == ISD::SETEQ)
2601       Cond = CondLHS;
2602     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2603              CB.CC == ISD::SETEQ) {
2604       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2605       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2606     } else {
2607       SDValue CondRHS = getValue(CB.CmpRHS);
2608 
2609       // If a pointer's DAG type is larger than its memory type then the DAG
2610       // values are zero-extended. This breaks signed comparisons so truncate
2611       // back to the underlying type before doing the compare.
2612       if (CondLHS.getValueType() != MemVT) {
2613         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2614         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2615       }
2616       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2617     }
2618   } else {
2619     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2620 
2621     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2622     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2623 
2624     SDValue CmpOp = getValue(CB.CmpMHS);
2625     EVT VT = CmpOp.getValueType();
2626 
2627     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2628       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2629                           ISD::SETLE);
2630     } else {
2631       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2632                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2633       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2634                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2635     }
2636   }
2637 
2638   // Update successor info
2639   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2640   // TrueBB and FalseBB are always different unless the incoming IR is
2641   // degenerate. This only happens when running llc on weird IR.
2642   if (CB.TrueBB != CB.FalseBB)
2643     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2644   SwitchBB->normalizeSuccProbs();
2645 
2646   // If the lhs block is the next block, invert the condition so that we can
2647   // fall through to the lhs instead of the rhs block.
2648   if (CB.TrueBB == NextBlock(SwitchBB)) {
2649     std::swap(CB.TrueBB, CB.FalseBB);
2650     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2651     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2652   }
2653 
2654   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2655                                MVT::Other, getControlRoot(), Cond,
2656                                DAG.getBasicBlock(CB.TrueBB));
2657 
2658   setValue(CurInst, BrCond);
2659 
2660   // Insert the false branch. Do this even if it's a fall through branch,
2661   // this makes it easier to do DAG optimizations which require inverting
2662   // the branch condition.
2663   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2664                        DAG.getBasicBlock(CB.FalseBB));
2665 
2666   DAG.setRoot(BrCond);
2667 }
2668 
2669 /// visitJumpTable - Emit JumpTable node in the current MBB
2670 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2671   // Emit the code for the jump table
2672   assert(JT.Reg != -1U && "Should lower JT Header first!");
2673   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2674   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2675                                      JT.Reg, PTy);
2676   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2677   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2678                                     MVT::Other, Index.getValue(1),
2679                                     Table, Index);
2680   DAG.setRoot(BrJumpTable);
2681 }
2682 
2683 /// visitJumpTableHeader - This function emits necessary code to produce index
2684 /// in the JumpTable from switch case.
2685 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2686                                                JumpTableHeader &JTH,
2687                                                MachineBasicBlock *SwitchBB) {
2688   SDLoc dl = getCurSDLoc();
2689 
2690   // Subtract the lowest switch case value from the value being switched on.
2691   SDValue SwitchOp = getValue(JTH.SValue);
2692   EVT VT = SwitchOp.getValueType();
2693   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2694                             DAG.getConstant(JTH.First, dl, VT));
2695 
2696   // The SDNode we just created, which holds the value being switched on minus
2697   // the smallest case value, needs to be copied to a virtual register so it
2698   // can be used as an index into the jump table in a subsequent basic block.
2699   // This value may be smaller or larger than the target's pointer type, and
2700   // therefore require extension or truncating.
2701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2702   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2703 
2704   unsigned JumpTableReg =
2705       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2706   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2707                                     JumpTableReg, SwitchOp);
2708   JT.Reg = JumpTableReg;
2709 
2710   if (!JTH.FallthroughUnreachable) {
2711     // Emit the range check for the jump table, and branch to the default block
2712     // for the switch statement if the value being switched on exceeds the
2713     // largest case in the switch.
2714     SDValue CMP = DAG.getSetCC(
2715         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2716                                    Sub.getValueType()),
2717         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2718 
2719     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2720                                  MVT::Other, CopyTo, CMP,
2721                                  DAG.getBasicBlock(JT.Default));
2722 
2723     // Avoid emitting unnecessary branches to the next block.
2724     if (JT.MBB != NextBlock(SwitchBB))
2725       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2726                            DAG.getBasicBlock(JT.MBB));
2727 
2728     DAG.setRoot(BrCond);
2729   } else {
2730     // Avoid emitting unnecessary branches to the next block.
2731     if (JT.MBB != NextBlock(SwitchBB))
2732       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2733                               DAG.getBasicBlock(JT.MBB)));
2734     else
2735       DAG.setRoot(CopyTo);
2736   }
2737 }
2738 
2739 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2740 /// variable if there exists one.
2741 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2742                                  SDValue &Chain) {
2743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2744   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2745   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2746   MachineFunction &MF = DAG.getMachineFunction();
2747   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2748   MachineSDNode *Node =
2749       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2750   if (Global) {
2751     MachinePointerInfo MPInfo(Global);
2752     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2753                  MachineMemOperand::MODereferenceable;
2754     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2755         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2756     DAG.setNodeMemRefs(Node, {MemRef});
2757   }
2758   if (PtrTy != PtrMemTy)
2759     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2760   return SDValue(Node, 0);
2761 }
2762 
2763 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2764 /// tail spliced into a stack protector check success bb.
2765 ///
2766 /// For a high level explanation of how this fits into the stack protector
2767 /// generation see the comment on the declaration of class
2768 /// StackProtectorDescriptor.
2769 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2770                                                   MachineBasicBlock *ParentBB) {
2771 
2772   // First create the loads to the guard/stack slot for the comparison.
2773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2775   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2776 
2777   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2778   int FI = MFI.getStackProtectorIndex();
2779 
2780   SDValue Guard;
2781   SDLoc dl = getCurSDLoc();
2782   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2783   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2784   Align Align =
2785       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2786 
2787   // Generate code to load the content of the guard slot.
2788   SDValue GuardVal = DAG.getLoad(
2789       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2790       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2791       MachineMemOperand::MOVolatile);
2792 
2793   if (TLI.useStackGuardXorFP())
2794     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2795 
2796   // Retrieve guard check function, nullptr if instrumentation is inlined.
2797   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2798     // The target provides a guard check function to validate the guard value.
2799     // Generate a call to that function with the content of the guard slot as
2800     // argument.
2801     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2802     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2803 
2804     TargetLowering::ArgListTy Args;
2805     TargetLowering::ArgListEntry Entry;
2806     Entry.Node = GuardVal;
2807     Entry.Ty = FnTy->getParamType(0);
2808     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2809       Entry.IsInReg = true;
2810     Args.push_back(Entry);
2811 
2812     TargetLowering::CallLoweringInfo CLI(DAG);
2813     CLI.setDebugLoc(getCurSDLoc())
2814         .setChain(DAG.getEntryNode())
2815         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2816                    getValue(GuardCheckFn), std::move(Args));
2817 
2818     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2819     DAG.setRoot(Result.second);
2820     return;
2821   }
2822 
2823   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2824   // Otherwise, emit a volatile load to retrieve the stack guard value.
2825   SDValue Chain = DAG.getEntryNode();
2826   if (TLI.useLoadStackGuardNode()) {
2827     Guard = getLoadStackGuard(DAG, dl, Chain);
2828   } else {
2829     const Value *IRGuard = TLI.getSDagStackGuard(M);
2830     SDValue GuardPtr = getValue(IRGuard);
2831 
2832     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2833                         MachinePointerInfo(IRGuard, 0), Align,
2834                         MachineMemOperand::MOVolatile);
2835   }
2836 
2837   // Perform the comparison via a getsetcc.
2838   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2839                                                         *DAG.getContext(),
2840                                                         Guard.getValueType()),
2841                              Guard, GuardVal, ISD::SETNE);
2842 
2843   // If the guard/stackslot do not equal, branch to failure MBB.
2844   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2845                                MVT::Other, GuardVal.getOperand(0),
2846                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2847   // Otherwise branch to success MBB.
2848   SDValue Br = DAG.getNode(ISD::BR, dl,
2849                            MVT::Other, BrCond,
2850                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2851 
2852   DAG.setRoot(Br);
2853 }
2854 
2855 /// Codegen the failure basic block for a stack protector check.
2856 ///
2857 /// A failure stack protector machine basic block consists simply of a call to
2858 /// __stack_chk_fail().
2859 ///
2860 /// For a high level explanation of how this fits into the stack protector
2861 /// generation see the comment on the declaration of class
2862 /// StackProtectorDescriptor.
2863 void
2864 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2866   TargetLowering::MakeLibCallOptions CallOptions;
2867   CallOptions.setDiscardResult(true);
2868   SDValue Chain =
2869       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2870                       std::nullopt, CallOptions, getCurSDLoc())
2871           .second;
2872   // On PS4/PS5, the "return address" must still be within the calling
2873   // function, even if it's at the very end, so emit an explicit TRAP here.
2874   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2875   if (TM.getTargetTriple().isPS())
2876     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2877   // WebAssembly needs an unreachable instruction after a non-returning call,
2878   // because the function return type can be different from __stack_chk_fail's
2879   // return type (void).
2880   if (TM.getTargetTriple().isWasm())
2881     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2882 
2883   DAG.setRoot(Chain);
2884 }
2885 
2886 /// visitBitTestHeader - This function emits necessary code to produce value
2887 /// suitable for "bit tests"
2888 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2889                                              MachineBasicBlock *SwitchBB) {
2890   SDLoc dl = getCurSDLoc();
2891 
2892   // Subtract the minimum value.
2893   SDValue SwitchOp = getValue(B.SValue);
2894   EVT VT = SwitchOp.getValueType();
2895   SDValue RangeSub =
2896       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2897 
2898   // Determine the type of the test operands.
2899   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2900   bool UsePtrType = false;
2901   if (!TLI.isTypeLegal(VT)) {
2902     UsePtrType = true;
2903   } else {
2904     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2905       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2906         // Switch table case range are encoded into series of masks.
2907         // Just use pointer type, it's guaranteed to fit.
2908         UsePtrType = true;
2909         break;
2910       }
2911   }
2912   SDValue Sub = RangeSub;
2913   if (UsePtrType) {
2914     VT = TLI.getPointerTy(DAG.getDataLayout());
2915     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2916   }
2917 
2918   B.RegVT = VT.getSimpleVT();
2919   B.Reg = FuncInfo.CreateReg(B.RegVT);
2920   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2921 
2922   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2923 
2924   if (!B.FallthroughUnreachable)
2925     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2926   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2927   SwitchBB->normalizeSuccProbs();
2928 
2929   SDValue Root = CopyTo;
2930   if (!B.FallthroughUnreachable) {
2931     // Conditional branch to the default block.
2932     SDValue RangeCmp = DAG.getSetCC(dl,
2933         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2934                                RangeSub.getValueType()),
2935         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2936         ISD::SETUGT);
2937 
2938     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2939                        DAG.getBasicBlock(B.Default));
2940   }
2941 
2942   // Avoid emitting unnecessary branches to the next block.
2943   if (MBB != NextBlock(SwitchBB))
2944     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2945 
2946   DAG.setRoot(Root);
2947 }
2948 
2949 /// visitBitTestCase - this function produces one "bit test"
2950 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2951                                            MachineBasicBlock* NextMBB,
2952                                            BranchProbability BranchProbToNext,
2953                                            unsigned Reg,
2954                                            BitTestCase &B,
2955                                            MachineBasicBlock *SwitchBB) {
2956   SDLoc dl = getCurSDLoc();
2957   MVT VT = BB.RegVT;
2958   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2959   SDValue Cmp;
2960   unsigned PopCount = llvm::popcount(B.Mask);
2961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2962   if (PopCount == 1) {
2963     // Testing for a single bit; just compare the shift count with what it
2964     // would need to be to shift a 1 bit in that position.
2965     Cmp = DAG.getSetCC(
2966         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2967         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2968         ISD::SETEQ);
2969   } else if (PopCount == BB.Range) {
2970     // There is only one zero bit in the range, test for it directly.
2971     Cmp = DAG.getSetCC(
2972         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2973         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2974   } else {
2975     // Make desired shift
2976     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2977                                     DAG.getConstant(1, dl, VT), ShiftOp);
2978 
2979     // Emit bit tests and jumps
2980     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2981                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2982     Cmp = DAG.getSetCC(
2983         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2984         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2985   }
2986 
2987   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2988   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2989   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2990   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2991   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2992   // one as they are relative probabilities (and thus work more like weights),
2993   // and hence we need to normalize them to let the sum of them become one.
2994   SwitchBB->normalizeSuccProbs();
2995 
2996   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2997                               MVT::Other, getControlRoot(),
2998                               Cmp, DAG.getBasicBlock(B.TargetBB));
2999 
3000   // Avoid emitting unnecessary branches to the next block.
3001   if (NextMBB != NextBlock(SwitchBB))
3002     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3003                         DAG.getBasicBlock(NextMBB));
3004 
3005   DAG.setRoot(BrAnd);
3006 }
3007 
3008 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3009   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3010 
3011   // Retrieve successors. Look through artificial IR level blocks like
3012   // catchswitch for successors.
3013   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3014   const BasicBlock *EHPadBB = I.getSuccessor(1);
3015   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3016 
3017   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3018   // have to do anything here to lower funclet bundles.
3019   assert(!I.hasOperandBundlesOtherThan(
3020              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3021               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3022               LLVMContext::OB_cfguardtarget,
3023               LLVMContext::OB_clang_arc_attachedcall}) &&
3024          "Cannot lower invokes with arbitrary operand bundles yet!");
3025 
3026   const Value *Callee(I.getCalledOperand());
3027   const Function *Fn = dyn_cast<Function>(Callee);
3028   if (isa<InlineAsm>(Callee))
3029     visitInlineAsm(I, EHPadBB);
3030   else if (Fn && Fn->isIntrinsic()) {
3031     switch (Fn->getIntrinsicID()) {
3032     default:
3033       llvm_unreachable("Cannot invoke this intrinsic");
3034     case Intrinsic::donothing:
3035       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3036     case Intrinsic::seh_try_begin:
3037     case Intrinsic::seh_scope_begin:
3038     case Intrinsic::seh_try_end:
3039     case Intrinsic::seh_scope_end:
3040       if (EHPadMBB)
3041           // a block referenced by EH table
3042           // so dtor-funclet not removed by opts
3043           EHPadMBB->setMachineBlockAddressTaken();
3044       break;
3045     case Intrinsic::experimental_patchpoint_void:
3046     case Intrinsic::experimental_patchpoint_i64:
3047       visitPatchpoint(I, EHPadBB);
3048       break;
3049     case Intrinsic::experimental_gc_statepoint:
3050       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3051       break;
3052     case Intrinsic::wasm_rethrow: {
3053       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3054       // special because it can be invoked, so we manually lower it to a DAG
3055       // node here.
3056       SmallVector<SDValue, 8> Ops;
3057       Ops.push_back(getRoot()); // inchain
3058       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3059       Ops.push_back(
3060           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3061                                 TLI.getPointerTy(DAG.getDataLayout())));
3062       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3063       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3064       break;
3065     }
3066     }
3067   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3068     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3069     // Eventually we will support lowering the @llvm.experimental.deoptimize
3070     // intrinsic, and right now there are no plans to support other intrinsics
3071     // with deopt state.
3072     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3073   } else {
3074     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3075   }
3076 
3077   // If the value of the invoke is used outside of its defining block, make it
3078   // available as a virtual register.
3079   // We already took care of the exported value for the statepoint instruction
3080   // during call to the LowerStatepoint.
3081   if (!isa<GCStatepointInst>(I)) {
3082     CopyToExportRegsIfNeeded(&I);
3083   }
3084 
3085   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3086   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3087   BranchProbability EHPadBBProb =
3088       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3089           : BranchProbability::getZero();
3090   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3091 
3092   // Update successor info.
3093   addSuccessorWithProb(InvokeMBB, Return);
3094   for (auto &UnwindDest : UnwindDests) {
3095     UnwindDest.first->setIsEHPad();
3096     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3097   }
3098   InvokeMBB->normalizeSuccProbs();
3099 
3100   // Drop into normal successor.
3101   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3102                           DAG.getBasicBlock(Return)));
3103 }
3104 
3105 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3106   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3107 
3108   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3109   // have to do anything here to lower funclet bundles.
3110   assert(!I.hasOperandBundlesOtherThan(
3111              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3112          "Cannot lower callbrs with arbitrary operand bundles yet!");
3113 
3114   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3115   visitInlineAsm(I);
3116   CopyToExportRegsIfNeeded(&I);
3117 
3118   // Retrieve successors.
3119   SmallPtrSet<BasicBlock *, 8> Dests;
3120   Dests.insert(I.getDefaultDest());
3121   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3122 
3123   // Update successor info.
3124   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3125   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3126     BasicBlock *Dest = I.getIndirectDest(i);
3127     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3128     Target->setIsInlineAsmBrIndirectTarget();
3129     Target->setMachineBlockAddressTaken();
3130     Target->setLabelMustBeEmitted();
3131     // Don't add duplicate machine successors.
3132     if (Dests.insert(Dest).second)
3133       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3134   }
3135   CallBrMBB->normalizeSuccProbs();
3136 
3137   // Drop into default successor.
3138   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3139                           MVT::Other, getControlRoot(),
3140                           DAG.getBasicBlock(Return)));
3141 }
3142 
3143 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3144   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3145 }
3146 
3147 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3148   assert(FuncInfo.MBB->isEHPad() &&
3149          "Call to landingpad not in landing pad!");
3150 
3151   // If there aren't registers to copy the values into (e.g., during SjLj
3152   // exceptions), then don't bother to create these DAG nodes.
3153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3154   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3155   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3156       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3157     return;
3158 
3159   // If landingpad's return type is token type, we don't create DAG nodes
3160   // for its exception pointer and selector value. The extraction of exception
3161   // pointer or selector value from token type landingpads is not currently
3162   // supported.
3163   if (LP.getType()->isTokenTy())
3164     return;
3165 
3166   SmallVector<EVT, 2> ValueVTs;
3167   SDLoc dl = getCurSDLoc();
3168   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3169   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3170 
3171   // Get the two live-in registers as SDValues. The physregs have already been
3172   // copied into virtual registers.
3173   SDValue Ops[2];
3174   if (FuncInfo.ExceptionPointerVirtReg) {
3175     Ops[0] = DAG.getZExtOrTrunc(
3176         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3177                            FuncInfo.ExceptionPointerVirtReg,
3178                            TLI.getPointerTy(DAG.getDataLayout())),
3179         dl, ValueVTs[0]);
3180   } else {
3181     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3182   }
3183   Ops[1] = DAG.getZExtOrTrunc(
3184       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3185                          FuncInfo.ExceptionSelectorVirtReg,
3186                          TLI.getPointerTy(DAG.getDataLayout())),
3187       dl, ValueVTs[1]);
3188 
3189   // Merge into one.
3190   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3191                             DAG.getVTList(ValueVTs), Ops);
3192   setValue(&LP, Res);
3193 }
3194 
3195 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3196                                            MachineBasicBlock *Last) {
3197   // Update JTCases.
3198   for (JumpTableBlock &JTB : SL->JTCases)
3199     if (JTB.first.HeaderBB == First)
3200       JTB.first.HeaderBB = Last;
3201 
3202   // Update BitTestCases.
3203   for (BitTestBlock &BTB : SL->BitTestCases)
3204     if (BTB.Parent == First)
3205       BTB.Parent = Last;
3206 }
3207 
3208 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3209   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3210 
3211   // Update machine-CFG edges with unique successors.
3212   SmallSet<BasicBlock*, 32> Done;
3213   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3214     BasicBlock *BB = I.getSuccessor(i);
3215     bool Inserted = Done.insert(BB).second;
3216     if (!Inserted)
3217         continue;
3218 
3219     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3220     addSuccessorWithProb(IndirectBrMBB, Succ);
3221   }
3222   IndirectBrMBB->normalizeSuccProbs();
3223 
3224   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3225                           MVT::Other, getControlRoot(),
3226                           getValue(I.getAddress())));
3227 }
3228 
3229 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3230   if (!DAG.getTarget().Options.TrapUnreachable)
3231     return;
3232 
3233   // We may be able to ignore unreachable behind a noreturn call.
3234   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3235     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3236       if (Call->doesNotReturn())
3237         return;
3238     }
3239   }
3240 
3241   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3242 }
3243 
3244 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3245   SDNodeFlags Flags;
3246   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3247     Flags.copyFMF(*FPOp);
3248 
3249   SDValue Op = getValue(I.getOperand(0));
3250   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3251                                     Op, Flags);
3252   setValue(&I, UnNodeValue);
3253 }
3254 
3255 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3256   SDNodeFlags Flags;
3257   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3258     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3259     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3260   }
3261   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3262     Flags.setExact(ExactOp->isExact());
3263   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3264     Flags.copyFMF(*FPOp);
3265 
3266   SDValue Op1 = getValue(I.getOperand(0));
3267   SDValue Op2 = getValue(I.getOperand(1));
3268   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3269                                      Op1, Op2, Flags);
3270   setValue(&I, BinNodeValue);
3271 }
3272 
3273 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3274   SDValue Op1 = getValue(I.getOperand(0));
3275   SDValue Op2 = getValue(I.getOperand(1));
3276 
3277   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3278       Op1.getValueType(), DAG.getDataLayout());
3279 
3280   // Coerce the shift amount to the right type if we can. This exposes the
3281   // truncate or zext to optimization early.
3282   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3283     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3284            "Unexpected shift type");
3285     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3286   }
3287 
3288   bool nuw = false;
3289   bool nsw = false;
3290   bool exact = false;
3291 
3292   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3293 
3294     if (const OverflowingBinaryOperator *OFBinOp =
3295             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3296       nuw = OFBinOp->hasNoUnsignedWrap();
3297       nsw = OFBinOp->hasNoSignedWrap();
3298     }
3299     if (const PossiblyExactOperator *ExactOp =
3300             dyn_cast<const PossiblyExactOperator>(&I))
3301       exact = ExactOp->isExact();
3302   }
3303   SDNodeFlags Flags;
3304   Flags.setExact(exact);
3305   Flags.setNoSignedWrap(nsw);
3306   Flags.setNoUnsignedWrap(nuw);
3307   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3308                             Flags);
3309   setValue(&I, Res);
3310 }
3311 
3312 void SelectionDAGBuilder::visitSDiv(const User &I) {
3313   SDValue Op1 = getValue(I.getOperand(0));
3314   SDValue Op2 = getValue(I.getOperand(1));
3315 
3316   SDNodeFlags Flags;
3317   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3318                  cast<PossiblyExactOperator>(&I)->isExact());
3319   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3320                            Op2, Flags));
3321 }
3322 
3323 void SelectionDAGBuilder::visitICmp(const User &I) {
3324   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3325   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3326     predicate = IC->getPredicate();
3327   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3328     predicate = ICmpInst::Predicate(IC->getPredicate());
3329   SDValue Op1 = getValue(I.getOperand(0));
3330   SDValue Op2 = getValue(I.getOperand(1));
3331   ISD::CondCode Opcode = getICmpCondCode(predicate);
3332 
3333   auto &TLI = DAG.getTargetLoweringInfo();
3334   EVT MemVT =
3335       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3336 
3337   // If a pointer's DAG type is larger than its memory type then the DAG values
3338   // are zero-extended. This breaks signed comparisons so truncate back to the
3339   // underlying type before doing the compare.
3340   if (Op1.getValueType() != MemVT) {
3341     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3342     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3343   }
3344 
3345   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3346                                                         I.getType());
3347   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3348 }
3349 
3350 void SelectionDAGBuilder::visitFCmp(const User &I) {
3351   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3352   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3353     predicate = FC->getPredicate();
3354   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3355     predicate = FCmpInst::Predicate(FC->getPredicate());
3356   SDValue Op1 = getValue(I.getOperand(0));
3357   SDValue Op2 = getValue(I.getOperand(1));
3358 
3359   ISD::CondCode Condition = getFCmpCondCode(predicate);
3360   auto *FPMO = cast<FPMathOperator>(&I);
3361   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3362     Condition = getFCmpCodeWithoutNaN(Condition);
3363 
3364   SDNodeFlags Flags;
3365   Flags.copyFMF(*FPMO);
3366   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3367 
3368   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3369                                                         I.getType());
3370   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3371 }
3372 
3373 // Check if the condition of the select has one use or two users that are both
3374 // selects with the same condition.
3375 static bool hasOnlySelectUsers(const Value *Cond) {
3376   return llvm::all_of(Cond->users(), [](const Value *V) {
3377     return isa<SelectInst>(V);
3378   });
3379 }
3380 
3381 void SelectionDAGBuilder::visitSelect(const User &I) {
3382   SmallVector<EVT, 4> ValueVTs;
3383   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3384                   ValueVTs);
3385   unsigned NumValues = ValueVTs.size();
3386   if (NumValues == 0) return;
3387 
3388   SmallVector<SDValue, 4> Values(NumValues);
3389   SDValue Cond     = getValue(I.getOperand(0));
3390   SDValue LHSVal   = getValue(I.getOperand(1));
3391   SDValue RHSVal   = getValue(I.getOperand(2));
3392   SmallVector<SDValue, 1> BaseOps(1, Cond);
3393   ISD::NodeType OpCode =
3394       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3395 
3396   bool IsUnaryAbs = false;
3397   bool Negate = false;
3398 
3399   SDNodeFlags Flags;
3400   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3401     Flags.copyFMF(*FPOp);
3402 
3403   Flags.setUnpredictable(
3404       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3405 
3406   // Min/max matching is only viable if all output VTs are the same.
3407   if (all_equal(ValueVTs)) {
3408     EVT VT = ValueVTs[0];
3409     LLVMContext &Ctx = *DAG.getContext();
3410     auto &TLI = DAG.getTargetLoweringInfo();
3411 
3412     // We care about the legality of the operation after it has been type
3413     // legalized.
3414     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3415       VT = TLI.getTypeToTransformTo(Ctx, VT);
3416 
3417     // If the vselect is legal, assume we want to leave this as a vector setcc +
3418     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3419     // min/max is legal on the scalar type.
3420     bool UseScalarMinMax = VT.isVector() &&
3421       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3422 
3423     // ValueTracking's select pattern matching does not account for -0.0,
3424     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3425     // -0.0 is less than +0.0.
3426     Value *LHS, *RHS;
3427     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3428     ISD::NodeType Opc = ISD::DELETED_NODE;
3429     switch (SPR.Flavor) {
3430     case SPF_UMAX:    Opc = ISD::UMAX; break;
3431     case SPF_UMIN:    Opc = ISD::UMIN; break;
3432     case SPF_SMAX:    Opc = ISD::SMAX; break;
3433     case SPF_SMIN:    Opc = ISD::SMIN; break;
3434     case SPF_FMINNUM:
3435       switch (SPR.NaNBehavior) {
3436       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3437       case SPNB_RETURNS_NAN: break;
3438       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3439       case SPNB_RETURNS_ANY:
3440         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3441             (UseScalarMinMax &&
3442              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3443           Opc = ISD::FMINNUM;
3444         break;
3445       }
3446       break;
3447     case SPF_FMAXNUM:
3448       switch (SPR.NaNBehavior) {
3449       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3450       case SPNB_RETURNS_NAN: break;
3451       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3452       case SPNB_RETURNS_ANY:
3453         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3454             (UseScalarMinMax &&
3455              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3456           Opc = ISD::FMAXNUM;
3457         break;
3458       }
3459       break;
3460     case SPF_NABS:
3461       Negate = true;
3462       [[fallthrough]];
3463     case SPF_ABS:
3464       IsUnaryAbs = true;
3465       Opc = ISD::ABS;
3466       break;
3467     default: break;
3468     }
3469 
3470     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3471         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3472          (UseScalarMinMax &&
3473           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3474         // If the underlying comparison instruction is used by any other
3475         // instruction, the consumed instructions won't be destroyed, so it is
3476         // not profitable to convert to a min/max.
3477         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3478       OpCode = Opc;
3479       LHSVal = getValue(LHS);
3480       RHSVal = getValue(RHS);
3481       BaseOps.clear();
3482     }
3483 
3484     if (IsUnaryAbs) {
3485       OpCode = Opc;
3486       LHSVal = getValue(LHS);
3487       BaseOps.clear();
3488     }
3489   }
3490 
3491   if (IsUnaryAbs) {
3492     for (unsigned i = 0; i != NumValues; ++i) {
3493       SDLoc dl = getCurSDLoc();
3494       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3495       Values[i] =
3496           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3497       if (Negate)
3498         Values[i] = DAG.getNegative(Values[i], dl, VT);
3499     }
3500   } else {
3501     for (unsigned i = 0; i != NumValues; ++i) {
3502       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3503       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3504       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3505       Values[i] = DAG.getNode(
3506           OpCode, getCurSDLoc(),
3507           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3508     }
3509   }
3510 
3511   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3512                            DAG.getVTList(ValueVTs), Values));
3513 }
3514 
3515 void SelectionDAGBuilder::visitTrunc(const User &I) {
3516   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3517   SDValue N = getValue(I.getOperand(0));
3518   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3519                                                         I.getType());
3520   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3521 }
3522 
3523 void SelectionDAGBuilder::visitZExt(const User &I) {
3524   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3525   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3526   SDValue N = getValue(I.getOperand(0));
3527   auto &TLI = DAG.getTargetLoweringInfo();
3528   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3529 
3530   SDNodeFlags Flags;
3531   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3532     Flags.setNonNeg(PNI->hasNonNeg());
3533 
3534   // Eagerly use nonneg information to canonicalize towards sign_extend if
3535   // that is the target's preference.
3536   // TODO: Let the target do this later.
3537   if (Flags.hasNonNeg() &&
3538       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3539     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3540     return;
3541   }
3542 
3543   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3544 }
3545 
3546 void SelectionDAGBuilder::visitSExt(const User &I) {
3547   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3548   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3549   SDValue N = getValue(I.getOperand(0));
3550   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3551                                                         I.getType());
3552   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3553 }
3554 
3555 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3556   // FPTrunc is never a no-op cast, no need to check
3557   SDValue N = getValue(I.getOperand(0));
3558   SDLoc dl = getCurSDLoc();
3559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3560   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3561   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3562                            DAG.getTargetConstant(
3563                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3564 }
3565 
3566 void SelectionDAGBuilder::visitFPExt(const User &I) {
3567   // FPExt is never a no-op cast, no need to check
3568   SDValue N = getValue(I.getOperand(0));
3569   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3570                                                         I.getType());
3571   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3572 }
3573 
3574 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3575   // FPToUI is never a no-op cast, no need to check
3576   SDValue N = getValue(I.getOperand(0));
3577   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3578                                                         I.getType());
3579   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3580 }
3581 
3582 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3583   // FPToSI is never a no-op cast, no need to check
3584   SDValue N = getValue(I.getOperand(0));
3585   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3586                                                         I.getType());
3587   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3588 }
3589 
3590 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3591   // UIToFP is never a no-op cast, no need to check
3592   SDValue N = getValue(I.getOperand(0));
3593   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3594                                                         I.getType());
3595   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3596 }
3597 
3598 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3599   // SIToFP is never a no-op cast, no need to check
3600   SDValue N = getValue(I.getOperand(0));
3601   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3602                                                         I.getType());
3603   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3604 }
3605 
3606 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3607   // What to do depends on the size of the integer and the size of the pointer.
3608   // We can either truncate, zero extend, or no-op, accordingly.
3609   SDValue N = getValue(I.getOperand(0));
3610   auto &TLI = DAG.getTargetLoweringInfo();
3611   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3612                                                         I.getType());
3613   EVT PtrMemVT =
3614       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3615   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3616   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3617   setValue(&I, N);
3618 }
3619 
3620 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3621   // What to do depends on the size of the integer and the size of the pointer.
3622   // We can either truncate, zero extend, or no-op, accordingly.
3623   SDValue N = getValue(I.getOperand(0));
3624   auto &TLI = DAG.getTargetLoweringInfo();
3625   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3626   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3627   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3628   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3629   setValue(&I, N);
3630 }
3631 
3632 void SelectionDAGBuilder::visitBitCast(const User &I) {
3633   SDValue N = getValue(I.getOperand(0));
3634   SDLoc dl = getCurSDLoc();
3635   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3636                                                         I.getType());
3637 
3638   // BitCast assures us that source and destination are the same size so this is
3639   // either a BITCAST or a no-op.
3640   if (DestVT != N.getValueType())
3641     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3642                              DestVT, N)); // convert types.
3643   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3644   // might fold any kind of constant expression to an integer constant and that
3645   // is not what we are looking for. Only recognize a bitcast of a genuine
3646   // constant integer as an opaque constant.
3647   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3648     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3649                                  /*isOpaque*/true));
3650   else
3651     setValue(&I, N);            // noop cast.
3652 }
3653 
3654 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3656   const Value *SV = I.getOperand(0);
3657   SDValue N = getValue(SV);
3658   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3659 
3660   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3661   unsigned DestAS = I.getType()->getPointerAddressSpace();
3662 
3663   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3664     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3665 
3666   setValue(&I, N);
3667 }
3668 
3669 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3670   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3671   SDValue InVec = getValue(I.getOperand(0));
3672   SDValue InVal = getValue(I.getOperand(1));
3673   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3674                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3675   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3676                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3677                            InVec, InVal, InIdx));
3678 }
3679 
3680 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3682   SDValue InVec = getValue(I.getOperand(0));
3683   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3684                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3685   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3686                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3687                            InVec, InIdx));
3688 }
3689 
3690 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3691   SDValue Src1 = getValue(I.getOperand(0));
3692   SDValue Src2 = getValue(I.getOperand(1));
3693   ArrayRef<int> Mask;
3694   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3695     Mask = SVI->getShuffleMask();
3696   else
3697     Mask = cast<ConstantExpr>(I).getShuffleMask();
3698   SDLoc DL = getCurSDLoc();
3699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3700   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3701   EVT SrcVT = Src1.getValueType();
3702 
3703   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3704       VT.isScalableVector()) {
3705     // Canonical splat form of first element of first input vector.
3706     SDValue FirstElt =
3707         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3708                     DAG.getVectorIdxConstant(0, DL));
3709     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3710     return;
3711   }
3712 
3713   // For now, we only handle splats for scalable vectors.
3714   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3715   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3716   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3717 
3718   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3719   unsigned MaskNumElts = Mask.size();
3720 
3721   if (SrcNumElts == MaskNumElts) {
3722     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3723     return;
3724   }
3725 
3726   // Normalize the shuffle vector since mask and vector length don't match.
3727   if (SrcNumElts < MaskNumElts) {
3728     // Mask is longer than the source vectors. We can use concatenate vector to
3729     // make the mask and vectors lengths match.
3730 
3731     if (MaskNumElts % SrcNumElts == 0) {
3732       // Mask length is a multiple of the source vector length.
3733       // Check if the shuffle is some kind of concatenation of the input
3734       // vectors.
3735       unsigned NumConcat = MaskNumElts / SrcNumElts;
3736       bool IsConcat = true;
3737       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3738       for (unsigned i = 0; i != MaskNumElts; ++i) {
3739         int Idx = Mask[i];
3740         if (Idx < 0)
3741           continue;
3742         // Ensure the indices in each SrcVT sized piece are sequential and that
3743         // the same source is used for the whole piece.
3744         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3745             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3746              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3747           IsConcat = false;
3748           break;
3749         }
3750         // Remember which source this index came from.
3751         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3752       }
3753 
3754       // The shuffle is concatenating multiple vectors together. Just emit
3755       // a CONCAT_VECTORS operation.
3756       if (IsConcat) {
3757         SmallVector<SDValue, 8> ConcatOps;
3758         for (auto Src : ConcatSrcs) {
3759           if (Src < 0)
3760             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3761           else if (Src == 0)
3762             ConcatOps.push_back(Src1);
3763           else
3764             ConcatOps.push_back(Src2);
3765         }
3766         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3767         return;
3768       }
3769     }
3770 
3771     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3772     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3773     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3774                                     PaddedMaskNumElts);
3775 
3776     // Pad both vectors with undefs to make them the same length as the mask.
3777     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3778 
3779     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3780     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3781     MOps1[0] = Src1;
3782     MOps2[0] = Src2;
3783 
3784     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3785     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3786 
3787     // Readjust mask for new input vector length.
3788     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3789     for (unsigned i = 0; i != MaskNumElts; ++i) {
3790       int Idx = Mask[i];
3791       if (Idx >= (int)SrcNumElts)
3792         Idx -= SrcNumElts - PaddedMaskNumElts;
3793       MappedOps[i] = Idx;
3794     }
3795 
3796     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3797 
3798     // If the concatenated vector was padded, extract a subvector with the
3799     // correct number of elements.
3800     if (MaskNumElts != PaddedMaskNumElts)
3801       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3802                            DAG.getVectorIdxConstant(0, DL));
3803 
3804     setValue(&I, Result);
3805     return;
3806   }
3807 
3808   if (SrcNumElts > MaskNumElts) {
3809     // Analyze the access pattern of the vector to see if we can extract
3810     // two subvectors and do the shuffle.
3811     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3812     bool CanExtract = true;
3813     for (int Idx : Mask) {
3814       unsigned Input = 0;
3815       if (Idx < 0)
3816         continue;
3817 
3818       if (Idx >= (int)SrcNumElts) {
3819         Input = 1;
3820         Idx -= SrcNumElts;
3821       }
3822 
3823       // If all the indices come from the same MaskNumElts sized portion of
3824       // the sources we can use extract. Also make sure the extract wouldn't
3825       // extract past the end of the source.
3826       int NewStartIdx = alignDown(Idx, MaskNumElts);
3827       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3828           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3829         CanExtract = false;
3830       // Make sure we always update StartIdx as we use it to track if all
3831       // elements are undef.
3832       StartIdx[Input] = NewStartIdx;
3833     }
3834 
3835     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3836       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3837       return;
3838     }
3839     if (CanExtract) {
3840       // Extract appropriate subvector and generate a vector shuffle
3841       for (unsigned Input = 0; Input < 2; ++Input) {
3842         SDValue &Src = Input == 0 ? Src1 : Src2;
3843         if (StartIdx[Input] < 0)
3844           Src = DAG.getUNDEF(VT);
3845         else {
3846           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3847                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3848         }
3849       }
3850 
3851       // Calculate new mask.
3852       SmallVector<int, 8> MappedOps(Mask);
3853       for (int &Idx : MappedOps) {
3854         if (Idx >= (int)SrcNumElts)
3855           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3856         else if (Idx >= 0)
3857           Idx -= StartIdx[0];
3858       }
3859 
3860       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3861       return;
3862     }
3863   }
3864 
3865   // We can't use either concat vectors or extract subvectors so fall back to
3866   // replacing the shuffle with extract and build vector.
3867   // to insert and build vector.
3868   EVT EltVT = VT.getVectorElementType();
3869   SmallVector<SDValue,8> Ops;
3870   for (int Idx : Mask) {
3871     SDValue Res;
3872 
3873     if (Idx < 0) {
3874       Res = DAG.getUNDEF(EltVT);
3875     } else {
3876       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3877       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3878 
3879       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3880                         DAG.getVectorIdxConstant(Idx, DL));
3881     }
3882 
3883     Ops.push_back(Res);
3884   }
3885 
3886   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3887 }
3888 
3889 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3890   ArrayRef<unsigned> Indices = I.getIndices();
3891   const Value *Op0 = I.getOperand(0);
3892   const Value *Op1 = I.getOperand(1);
3893   Type *AggTy = I.getType();
3894   Type *ValTy = Op1->getType();
3895   bool IntoUndef = isa<UndefValue>(Op0);
3896   bool FromUndef = isa<UndefValue>(Op1);
3897 
3898   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3899 
3900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3901   SmallVector<EVT, 4> AggValueVTs;
3902   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3903   SmallVector<EVT, 4> ValValueVTs;
3904   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3905 
3906   unsigned NumAggValues = AggValueVTs.size();
3907   unsigned NumValValues = ValValueVTs.size();
3908   SmallVector<SDValue, 4> Values(NumAggValues);
3909 
3910   // Ignore an insertvalue that produces an empty object
3911   if (!NumAggValues) {
3912     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3913     return;
3914   }
3915 
3916   SDValue Agg = getValue(Op0);
3917   unsigned i = 0;
3918   // Copy the beginning value(s) from the original aggregate.
3919   for (; i != LinearIndex; ++i)
3920     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3921                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3922   // Copy values from the inserted value(s).
3923   if (NumValValues) {
3924     SDValue Val = getValue(Op1);
3925     for (; i != LinearIndex + NumValValues; ++i)
3926       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3927                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3928   }
3929   // Copy remaining value(s) from the original aggregate.
3930   for (; i != NumAggValues; ++i)
3931     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3932                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3933 
3934   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3935                            DAG.getVTList(AggValueVTs), Values));
3936 }
3937 
3938 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3939   ArrayRef<unsigned> Indices = I.getIndices();
3940   const Value *Op0 = I.getOperand(0);
3941   Type *AggTy = Op0->getType();
3942   Type *ValTy = I.getType();
3943   bool OutOfUndef = isa<UndefValue>(Op0);
3944 
3945   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3946 
3947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3948   SmallVector<EVT, 4> ValValueVTs;
3949   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3950 
3951   unsigned NumValValues = ValValueVTs.size();
3952 
3953   // Ignore a extractvalue that produces an empty object
3954   if (!NumValValues) {
3955     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3956     return;
3957   }
3958 
3959   SmallVector<SDValue, 4> Values(NumValValues);
3960 
3961   SDValue Agg = getValue(Op0);
3962   // Copy out the selected value(s).
3963   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3964     Values[i - LinearIndex] =
3965       OutOfUndef ?
3966         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3967         SDValue(Agg.getNode(), Agg.getResNo() + i);
3968 
3969   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3970                            DAG.getVTList(ValValueVTs), Values));
3971 }
3972 
3973 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3974   Value *Op0 = I.getOperand(0);
3975   // Note that the pointer operand may be a vector of pointers. Take the scalar
3976   // element which holds a pointer.
3977   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3978   SDValue N = getValue(Op0);
3979   SDLoc dl = getCurSDLoc();
3980   auto &TLI = DAG.getTargetLoweringInfo();
3981 
3982   // Normalize Vector GEP - all scalar operands should be converted to the
3983   // splat vector.
3984   bool IsVectorGEP = I.getType()->isVectorTy();
3985   ElementCount VectorElementCount =
3986       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3987                   : ElementCount::getFixed(0);
3988 
3989   if (IsVectorGEP && !N.getValueType().isVector()) {
3990     LLVMContext &Context = *DAG.getContext();
3991     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3992     N = DAG.getSplat(VT, dl, N);
3993   }
3994 
3995   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3996        GTI != E; ++GTI) {
3997     const Value *Idx = GTI.getOperand();
3998     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3999       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4000       if (Field) {
4001         // N = N + Offset
4002         uint64_t Offset =
4003             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4004 
4005         // In an inbounds GEP with an offset that is nonnegative even when
4006         // interpreted as signed, assume there is no unsigned overflow.
4007         SDNodeFlags Flags;
4008         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4009           Flags.setNoUnsignedWrap(true);
4010 
4011         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4012                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4013       }
4014     } else {
4015       // IdxSize is the width of the arithmetic according to IR semantics.
4016       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4017       // (and fix up the result later).
4018       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4019       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4020       TypeSize ElementSize =
4021           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
4022       // We intentionally mask away the high bits here; ElementSize may not
4023       // fit in IdxTy.
4024       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4025       bool ElementScalable = ElementSize.isScalable();
4026 
4027       // If this is a scalar constant or a splat vector of constants,
4028       // handle it quickly.
4029       const auto *C = dyn_cast<Constant>(Idx);
4030       if (C && isa<VectorType>(C->getType()))
4031         C = C->getSplatValue();
4032 
4033       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4034       if (CI && CI->isZero())
4035         continue;
4036       if (CI && !ElementScalable) {
4037         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4038         LLVMContext &Context = *DAG.getContext();
4039         SDValue OffsVal;
4040         if (IsVectorGEP)
4041           OffsVal = DAG.getConstant(
4042               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4043         else
4044           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4045 
4046         // In an inbounds GEP with an offset that is nonnegative even when
4047         // interpreted as signed, assume there is no unsigned overflow.
4048         SDNodeFlags Flags;
4049         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4050           Flags.setNoUnsignedWrap(true);
4051 
4052         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4053 
4054         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4055         continue;
4056       }
4057 
4058       // N = N + Idx * ElementMul;
4059       SDValue IdxN = getValue(Idx);
4060 
4061       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4062         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4063                                   VectorElementCount);
4064         IdxN = DAG.getSplat(VT, dl, IdxN);
4065       }
4066 
4067       // If the index is smaller or larger than intptr_t, truncate or extend
4068       // it.
4069       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4070 
4071       if (ElementScalable) {
4072         EVT VScaleTy = N.getValueType().getScalarType();
4073         SDValue VScale = DAG.getNode(
4074             ISD::VSCALE, dl, VScaleTy,
4075             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4076         if (IsVectorGEP)
4077           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4078         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4079       } else {
4080         // If this is a multiply by a power of two, turn it into a shl
4081         // immediately.  This is a very common case.
4082         if (ElementMul != 1) {
4083           if (ElementMul.isPowerOf2()) {
4084             unsigned Amt = ElementMul.logBase2();
4085             IdxN = DAG.getNode(ISD::SHL, dl,
4086                                N.getValueType(), IdxN,
4087                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4088           } else {
4089             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4090                                             IdxN.getValueType());
4091             IdxN = DAG.getNode(ISD::MUL, dl,
4092                                N.getValueType(), IdxN, Scale);
4093           }
4094         }
4095       }
4096 
4097       N = DAG.getNode(ISD::ADD, dl,
4098                       N.getValueType(), N, IdxN);
4099     }
4100   }
4101 
4102   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4103   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4104   if (IsVectorGEP) {
4105     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4106     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4107   }
4108 
4109   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4110     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4111 
4112   setValue(&I, N);
4113 }
4114 
4115 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4116   // If this is a fixed sized alloca in the entry block of the function,
4117   // allocate it statically on the stack.
4118   if (FuncInfo.StaticAllocaMap.count(&I))
4119     return;   // getValue will auto-populate this.
4120 
4121   SDLoc dl = getCurSDLoc();
4122   Type *Ty = I.getAllocatedType();
4123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4124   auto &DL = DAG.getDataLayout();
4125   TypeSize TySize = DL.getTypeAllocSize(Ty);
4126   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4127 
4128   SDValue AllocSize = getValue(I.getArraySize());
4129 
4130   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4131   if (AllocSize.getValueType() != IntPtr)
4132     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4133 
4134   if (TySize.isScalable())
4135     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4136                             DAG.getVScale(dl, IntPtr,
4137                                           APInt(IntPtr.getScalarSizeInBits(),
4138                                                 TySize.getKnownMinValue())));
4139   else
4140     AllocSize =
4141         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4142                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4143 
4144   // Handle alignment.  If the requested alignment is less than or equal to
4145   // the stack alignment, ignore it.  If the size is greater than or equal to
4146   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4147   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4148   if (*Alignment <= StackAlign)
4149     Alignment = std::nullopt;
4150 
4151   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4152   // Round the size of the allocation up to the stack alignment size
4153   // by add SA-1 to the size. This doesn't overflow because we're computing
4154   // an address inside an alloca.
4155   SDNodeFlags Flags;
4156   Flags.setNoUnsignedWrap(true);
4157   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4158                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4159 
4160   // Mask out the low bits for alignment purposes.
4161   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4162                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4163 
4164   SDValue Ops[] = {
4165       getRoot(), AllocSize,
4166       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4167   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4168   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4169   setValue(&I, DSA);
4170   DAG.setRoot(DSA.getValue(1));
4171 
4172   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4173 }
4174 
4175 static const MDNode *getRangeMetadata(const Instruction &I) {
4176   // If !noundef is not present, then !range violation results in a poison
4177   // value rather than immediate undefined behavior. In theory, transferring
4178   // these annotations to SDAG is fine, but in practice there are key SDAG
4179   // transforms that are known not to be poison-safe, such as folding logical
4180   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4181   // also present.
4182   if (!I.hasMetadata(LLVMContext::MD_noundef))
4183     return nullptr;
4184   return I.getMetadata(LLVMContext::MD_range);
4185 }
4186 
4187 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4188   if (I.isAtomic())
4189     return visitAtomicLoad(I);
4190 
4191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4192   const Value *SV = I.getOperand(0);
4193   if (TLI.supportSwiftError()) {
4194     // Swifterror values can come from either a function parameter with
4195     // swifterror attribute or an alloca with swifterror attribute.
4196     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4197       if (Arg->hasSwiftErrorAttr())
4198         return visitLoadFromSwiftError(I);
4199     }
4200 
4201     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4202       if (Alloca->isSwiftError())
4203         return visitLoadFromSwiftError(I);
4204     }
4205   }
4206 
4207   SDValue Ptr = getValue(SV);
4208 
4209   Type *Ty = I.getType();
4210   SmallVector<EVT, 4> ValueVTs, MemVTs;
4211   SmallVector<TypeSize, 4> Offsets;
4212   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4213   unsigned NumValues = ValueVTs.size();
4214   if (NumValues == 0)
4215     return;
4216 
4217   Align Alignment = I.getAlign();
4218   AAMDNodes AAInfo = I.getAAMetadata();
4219   const MDNode *Ranges = getRangeMetadata(I);
4220   bool isVolatile = I.isVolatile();
4221   MachineMemOperand::Flags MMOFlags =
4222       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4223 
4224   SDValue Root;
4225   bool ConstantMemory = false;
4226   if (isVolatile)
4227     // Serialize volatile loads with other side effects.
4228     Root = getRoot();
4229   else if (NumValues > MaxParallelChains)
4230     Root = getMemoryRoot();
4231   else if (AA &&
4232            AA->pointsToConstantMemory(MemoryLocation(
4233                SV,
4234                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4235                AAInfo))) {
4236     // Do not serialize (non-volatile) loads of constant memory with anything.
4237     Root = DAG.getEntryNode();
4238     ConstantMemory = true;
4239     MMOFlags |= MachineMemOperand::MOInvariant;
4240   } else {
4241     // Do not serialize non-volatile loads against each other.
4242     Root = DAG.getRoot();
4243   }
4244 
4245   SDLoc dl = getCurSDLoc();
4246 
4247   if (isVolatile)
4248     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4249 
4250   SmallVector<SDValue, 4> Values(NumValues);
4251   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4252 
4253   unsigned ChainI = 0;
4254   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4255     // Serializing loads here may result in excessive register pressure, and
4256     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4257     // could recover a bit by hoisting nodes upward in the chain by recognizing
4258     // they are side-effect free or do not alias. The optimizer should really
4259     // avoid this case by converting large object/array copies to llvm.memcpy
4260     // (MaxParallelChains should always remain as failsafe).
4261     if (ChainI == MaxParallelChains) {
4262       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4263       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4264                                   ArrayRef(Chains.data(), ChainI));
4265       Root = Chain;
4266       ChainI = 0;
4267     }
4268 
4269     // TODO: MachinePointerInfo only supports a fixed length offset.
4270     MachinePointerInfo PtrInfo =
4271         !Offsets[i].isScalable() || Offsets[i].isZero()
4272             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4273             : MachinePointerInfo();
4274 
4275     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4276     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4277                             MMOFlags, AAInfo, Ranges);
4278     Chains[ChainI] = L.getValue(1);
4279 
4280     if (MemVTs[i] != ValueVTs[i])
4281       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4282 
4283     Values[i] = L;
4284   }
4285 
4286   if (!ConstantMemory) {
4287     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4288                                 ArrayRef(Chains.data(), ChainI));
4289     if (isVolatile)
4290       DAG.setRoot(Chain);
4291     else
4292       PendingLoads.push_back(Chain);
4293   }
4294 
4295   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4296                            DAG.getVTList(ValueVTs), Values));
4297 }
4298 
4299 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4300   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4301          "call visitStoreToSwiftError when backend supports swifterror");
4302 
4303   SmallVector<EVT, 4> ValueVTs;
4304   SmallVector<uint64_t, 4> Offsets;
4305   const Value *SrcV = I.getOperand(0);
4306   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4307                   SrcV->getType(), ValueVTs, &Offsets, 0);
4308   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4309          "expect a single EVT for swifterror");
4310 
4311   SDValue Src = getValue(SrcV);
4312   // Create a virtual register, then update the virtual register.
4313   Register VReg =
4314       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4315   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4316   // Chain can be getRoot or getControlRoot.
4317   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4318                                       SDValue(Src.getNode(), Src.getResNo()));
4319   DAG.setRoot(CopyNode);
4320 }
4321 
4322 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4323   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4324          "call visitLoadFromSwiftError when backend supports swifterror");
4325 
4326   assert(!I.isVolatile() &&
4327          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4328          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4329          "Support volatile, non temporal, invariant for load_from_swift_error");
4330 
4331   const Value *SV = I.getOperand(0);
4332   Type *Ty = I.getType();
4333   assert(
4334       (!AA ||
4335        !AA->pointsToConstantMemory(MemoryLocation(
4336            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4337            I.getAAMetadata()))) &&
4338       "load_from_swift_error should not be constant memory");
4339 
4340   SmallVector<EVT, 4> ValueVTs;
4341   SmallVector<uint64_t, 4> Offsets;
4342   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4343                   ValueVTs, &Offsets, 0);
4344   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4345          "expect a single EVT for swifterror");
4346 
4347   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4348   SDValue L = DAG.getCopyFromReg(
4349       getRoot(), getCurSDLoc(),
4350       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4351 
4352   setValue(&I, L);
4353 }
4354 
4355 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4356   if (I.isAtomic())
4357     return visitAtomicStore(I);
4358 
4359   const Value *SrcV = I.getOperand(0);
4360   const Value *PtrV = I.getOperand(1);
4361 
4362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4363   if (TLI.supportSwiftError()) {
4364     // Swifterror values can come from either a function parameter with
4365     // swifterror attribute or an alloca with swifterror attribute.
4366     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4367       if (Arg->hasSwiftErrorAttr())
4368         return visitStoreToSwiftError(I);
4369     }
4370 
4371     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4372       if (Alloca->isSwiftError())
4373         return visitStoreToSwiftError(I);
4374     }
4375   }
4376 
4377   SmallVector<EVT, 4> ValueVTs, MemVTs;
4378   SmallVector<TypeSize, 4> Offsets;
4379   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4380                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4381   unsigned NumValues = ValueVTs.size();
4382   if (NumValues == 0)
4383     return;
4384 
4385   // Get the lowered operands. Note that we do this after
4386   // checking if NumResults is zero, because with zero results
4387   // the operands won't have values in the map.
4388   SDValue Src = getValue(SrcV);
4389   SDValue Ptr = getValue(PtrV);
4390 
4391   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4392   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4393   SDLoc dl = getCurSDLoc();
4394   Align Alignment = I.getAlign();
4395   AAMDNodes AAInfo = I.getAAMetadata();
4396 
4397   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4398 
4399   unsigned ChainI = 0;
4400   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4401     // See visitLoad comments.
4402     if (ChainI == MaxParallelChains) {
4403       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4404                                   ArrayRef(Chains.data(), ChainI));
4405       Root = Chain;
4406       ChainI = 0;
4407     }
4408 
4409     // TODO: MachinePointerInfo only supports a fixed length offset.
4410     MachinePointerInfo PtrInfo =
4411         !Offsets[i].isScalable() || Offsets[i].isZero()
4412             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4413             : MachinePointerInfo();
4414 
4415     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4416     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4417     if (MemVTs[i] != ValueVTs[i])
4418       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4419     SDValue St =
4420         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4421     Chains[ChainI] = St;
4422   }
4423 
4424   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4425                                   ArrayRef(Chains.data(), ChainI));
4426   setValue(&I, StoreNode);
4427   DAG.setRoot(StoreNode);
4428 }
4429 
4430 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4431                                            bool IsCompressing) {
4432   SDLoc sdl = getCurSDLoc();
4433 
4434   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4435                                MaybeAlign &Alignment) {
4436     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4437     Src0 = I.getArgOperand(0);
4438     Ptr = I.getArgOperand(1);
4439     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4440     Mask = I.getArgOperand(3);
4441   };
4442   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4443                                     MaybeAlign &Alignment) {
4444     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4445     Src0 = I.getArgOperand(0);
4446     Ptr = I.getArgOperand(1);
4447     Mask = I.getArgOperand(2);
4448     Alignment = std::nullopt;
4449   };
4450 
4451   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4452   MaybeAlign Alignment;
4453   if (IsCompressing)
4454     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4455   else
4456     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4457 
4458   SDValue Ptr = getValue(PtrOperand);
4459   SDValue Src0 = getValue(Src0Operand);
4460   SDValue Mask = getValue(MaskOperand);
4461   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4462 
4463   EVT VT = Src0.getValueType();
4464   if (!Alignment)
4465     Alignment = DAG.getEVTAlign(VT);
4466 
4467   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4468       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4469       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4470   SDValue StoreNode =
4471       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4472                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4473   DAG.setRoot(StoreNode);
4474   setValue(&I, StoreNode);
4475 }
4476 
4477 // Get a uniform base for the Gather/Scatter intrinsic.
4478 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4479 // We try to represent it as a base pointer + vector of indices.
4480 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4481 // The first operand of the GEP may be a single pointer or a vector of pointers
4482 // Example:
4483 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4484 //  or
4485 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4486 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4487 //
4488 // When the first GEP operand is a single pointer - it is the uniform base we
4489 // are looking for. If first operand of the GEP is a splat vector - we
4490 // extract the splat value and use it as a uniform base.
4491 // In all other cases the function returns 'false'.
4492 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4493                            ISD::MemIndexType &IndexType, SDValue &Scale,
4494                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4495                            uint64_t ElemSize) {
4496   SelectionDAG& DAG = SDB->DAG;
4497   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4498   const DataLayout &DL = DAG.getDataLayout();
4499 
4500   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4501 
4502   // Handle splat constant pointer.
4503   if (auto *C = dyn_cast<Constant>(Ptr)) {
4504     C = C->getSplatValue();
4505     if (!C)
4506       return false;
4507 
4508     Base = SDB->getValue(C);
4509 
4510     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4511     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4512     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4513     IndexType = ISD::SIGNED_SCALED;
4514     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4515     return true;
4516   }
4517 
4518   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4519   if (!GEP || GEP->getParent() != CurBB)
4520     return false;
4521 
4522   if (GEP->getNumOperands() != 2)
4523     return false;
4524 
4525   const Value *BasePtr = GEP->getPointerOperand();
4526   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4527 
4528   // Make sure the base is scalar and the index is a vector.
4529   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4530     return false;
4531 
4532   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4533   if (ScaleVal.isScalable())
4534     return false;
4535 
4536   // Target may not support the required addressing mode.
4537   if (ScaleVal != 1 &&
4538       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4539     return false;
4540 
4541   Base = SDB->getValue(BasePtr);
4542   Index = SDB->getValue(IndexVal);
4543   IndexType = ISD::SIGNED_SCALED;
4544 
4545   Scale =
4546       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4547   return true;
4548 }
4549 
4550 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4551   SDLoc sdl = getCurSDLoc();
4552 
4553   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4554   const Value *Ptr = I.getArgOperand(1);
4555   SDValue Src0 = getValue(I.getArgOperand(0));
4556   SDValue Mask = getValue(I.getArgOperand(3));
4557   EVT VT = Src0.getValueType();
4558   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4559                         ->getMaybeAlignValue()
4560                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4562 
4563   SDValue Base;
4564   SDValue Index;
4565   ISD::MemIndexType IndexType;
4566   SDValue Scale;
4567   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4568                                     I.getParent(), VT.getScalarStoreSize());
4569 
4570   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4571   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4572       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4573       // TODO: Make MachineMemOperands aware of scalable
4574       // vectors.
4575       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4576   if (!UniformBase) {
4577     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4578     Index = getValue(Ptr);
4579     IndexType = ISD::SIGNED_SCALED;
4580     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4581   }
4582 
4583   EVT IdxVT = Index.getValueType();
4584   EVT EltTy = IdxVT.getVectorElementType();
4585   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4586     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4587     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4588   }
4589 
4590   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4591   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4592                                          Ops, MMO, IndexType, false);
4593   DAG.setRoot(Scatter);
4594   setValue(&I, Scatter);
4595 }
4596 
4597 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4598   SDLoc sdl = getCurSDLoc();
4599 
4600   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4601                               MaybeAlign &Alignment) {
4602     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4603     Ptr = I.getArgOperand(0);
4604     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4605     Mask = I.getArgOperand(2);
4606     Src0 = I.getArgOperand(3);
4607   };
4608   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4609                                  MaybeAlign &Alignment) {
4610     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4611     Ptr = I.getArgOperand(0);
4612     Alignment = std::nullopt;
4613     Mask = I.getArgOperand(1);
4614     Src0 = I.getArgOperand(2);
4615   };
4616 
4617   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4618   MaybeAlign Alignment;
4619   if (IsExpanding)
4620     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4621   else
4622     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4623 
4624   SDValue Ptr = getValue(PtrOperand);
4625   SDValue Src0 = getValue(Src0Operand);
4626   SDValue Mask = getValue(MaskOperand);
4627   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4628 
4629   EVT VT = Src0.getValueType();
4630   if (!Alignment)
4631     Alignment = DAG.getEVTAlign(VT);
4632 
4633   AAMDNodes AAInfo = I.getAAMetadata();
4634   const MDNode *Ranges = getRangeMetadata(I);
4635 
4636   // Do not serialize masked loads of constant memory with anything.
4637   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4638   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4639 
4640   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4641 
4642   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4643       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4644       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4645 
4646   SDValue Load =
4647       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4648                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4649   if (AddToChain)
4650     PendingLoads.push_back(Load.getValue(1));
4651   setValue(&I, Load);
4652 }
4653 
4654 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4655   SDLoc sdl = getCurSDLoc();
4656 
4657   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4658   const Value *Ptr = I.getArgOperand(0);
4659   SDValue Src0 = getValue(I.getArgOperand(3));
4660   SDValue Mask = getValue(I.getArgOperand(2));
4661 
4662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4663   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4664   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4665                         ->getMaybeAlignValue()
4666                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4667 
4668   const MDNode *Ranges = getRangeMetadata(I);
4669 
4670   SDValue Root = DAG.getRoot();
4671   SDValue Base;
4672   SDValue Index;
4673   ISD::MemIndexType IndexType;
4674   SDValue Scale;
4675   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4676                                     I.getParent(), VT.getScalarStoreSize());
4677   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4678   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4679       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4680       // TODO: Make MachineMemOperands aware of scalable
4681       // vectors.
4682       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4683 
4684   if (!UniformBase) {
4685     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4686     Index = getValue(Ptr);
4687     IndexType = ISD::SIGNED_SCALED;
4688     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4689   }
4690 
4691   EVT IdxVT = Index.getValueType();
4692   EVT EltTy = IdxVT.getVectorElementType();
4693   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4694     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4695     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4696   }
4697 
4698   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4699   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4700                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4701 
4702   PendingLoads.push_back(Gather.getValue(1));
4703   setValue(&I, Gather);
4704 }
4705 
4706 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4707   SDLoc dl = getCurSDLoc();
4708   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4709   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4710   SyncScope::ID SSID = I.getSyncScopeID();
4711 
4712   SDValue InChain = getRoot();
4713 
4714   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4715   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4716 
4717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4718   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4719 
4720   MachineFunction &MF = DAG.getMachineFunction();
4721   MachineMemOperand *MMO = MF.getMachineMemOperand(
4722       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4723       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4724       FailureOrdering);
4725 
4726   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4727                                    dl, MemVT, VTs, InChain,
4728                                    getValue(I.getPointerOperand()),
4729                                    getValue(I.getCompareOperand()),
4730                                    getValue(I.getNewValOperand()), MMO);
4731 
4732   SDValue OutChain = L.getValue(2);
4733 
4734   setValue(&I, L);
4735   DAG.setRoot(OutChain);
4736 }
4737 
4738 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4739   SDLoc dl = getCurSDLoc();
4740   ISD::NodeType NT;
4741   switch (I.getOperation()) {
4742   default: llvm_unreachable("Unknown atomicrmw operation");
4743   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4744   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4745   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4746   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4747   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4748   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4749   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4750   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4751   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4752   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4753   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4754   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4755   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4756   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4757   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4758   case AtomicRMWInst::UIncWrap:
4759     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4760     break;
4761   case AtomicRMWInst::UDecWrap:
4762     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4763     break;
4764   }
4765   AtomicOrdering Ordering = I.getOrdering();
4766   SyncScope::ID SSID = I.getSyncScopeID();
4767 
4768   SDValue InChain = getRoot();
4769 
4770   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4772   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4773 
4774   MachineFunction &MF = DAG.getMachineFunction();
4775   MachineMemOperand *MMO = MF.getMachineMemOperand(
4776       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4777       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4778 
4779   SDValue L =
4780     DAG.getAtomic(NT, dl, MemVT, InChain,
4781                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4782                   MMO);
4783 
4784   SDValue OutChain = L.getValue(1);
4785 
4786   setValue(&I, L);
4787   DAG.setRoot(OutChain);
4788 }
4789 
4790 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4791   SDLoc dl = getCurSDLoc();
4792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4793   SDValue Ops[3];
4794   Ops[0] = getRoot();
4795   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4796                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4797   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4798                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4799   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4800   setValue(&I, N);
4801   DAG.setRoot(N);
4802 }
4803 
4804 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4805   SDLoc dl = getCurSDLoc();
4806   AtomicOrdering Order = I.getOrdering();
4807   SyncScope::ID SSID = I.getSyncScopeID();
4808 
4809   SDValue InChain = getRoot();
4810 
4811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4812   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4813   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4814 
4815   if (!TLI.supportsUnalignedAtomics() &&
4816       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4817     report_fatal_error("Cannot generate unaligned atomic load");
4818 
4819   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4820 
4821   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4822       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4823       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4824 
4825   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4826 
4827   SDValue Ptr = getValue(I.getPointerOperand());
4828 
4829   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4830     // TODO: Once this is better exercised by tests, it should be merged with
4831     // the normal path for loads to prevent future divergence.
4832     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4833     if (MemVT != VT)
4834       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4835 
4836     setValue(&I, L);
4837     SDValue OutChain = L.getValue(1);
4838     if (!I.isUnordered())
4839       DAG.setRoot(OutChain);
4840     else
4841       PendingLoads.push_back(OutChain);
4842     return;
4843   }
4844 
4845   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4846                             Ptr, MMO);
4847 
4848   SDValue OutChain = L.getValue(1);
4849   if (MemVT != VT)
4850     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4851 
4852   setValue(&I, L);
4853   DAG.setRoot(OutChain);
4854 }
4855 
4856 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4857   SDLoc dl = getCurSDLoc();
4858 
4859   AtomicOrdering Ordering = I.getOrdering();
4860   SyncScope::ID SSID = I.getSyncScopeID();
4861 
4862   SDValue InChain = getRoot();
4863 
4864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4865   EVT MemVT =
4866       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4867 
4868   if (!TLI.supportsUnalignedAtomics() &&
4869       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4870     report_fatal_error("Cannot generate unaligned atomic store");
4871 
4872   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4873 
4874   MachineFunction &MF = DAG.getMachineFunction();
4875   MachineMemOperand *MMO = MF.getMachineMemOperand(
4876       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4877       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4878 
4879   SDValue Val = getValue(I.getValueOperand());
4880   if (Val.getValueType() != MemVT)
4881     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4882   SDValue Ptr = getValue(I.getPointerOperand());
4883 
4884   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4885     // TODO: Once this is better exercised by tests, it should be merged with
4886     // the normal path for stores to prevent future divergence.
4887     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4888     setValue(&I, S);
4889     DAG.setRoot(S);
4890     return;
4891   }
4892   SDValue OutChain =
4893       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4894 
4895   setValue(&I, OutChain);
4896   DAG.setRoot(OutChain);
4897 }
4898 
4899 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4900 /// node.
4901 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4902                                                unsigned Intrinsic) {
4903   // Ignore the callsite's attributes. A specific call site may be marked with
4904   // readnone, but the lowering code will expect the chain based on the
4905   // definition.
4906   const Function *F = I.getCalledFunction();
4907   bool HasChain = !F->doesNotAccessMemory();
4908   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4909 
4910   // Build the operand list.
4911   SmallVector<SDValue, 8> Ops;
4912   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4913     if (OnlyLoad) {
4914       // We don't need to serialize loads against other loads.
4915       Ops.push_back(DAG.getRoot());
4916     } else {
4917       Ops.push_back(getRoot());
4918     }
4919   }
4920 
4921   // Info is set by getTgtMemIntrinsic
4922   TargetLowering::IntrinsicInfo Info;
4923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4924   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4925                                                DAG.getMachineFunction(),
4926                                                Intrinsic);
4927 
4928   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4929   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4930       Info.opc == ISD::INTRINSIC_W_CHAIN)
4931     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4932                                         TLI.getPointerTy(DAG.getDataLayout())));
4933 
4934   // Add all operands of the call to the operand list.
4935   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4936     const Value *Arg = I.getArgOperand(i);
4937     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4938       Ops.push_back(getValue(Arg));
4939       continue;
4940     }
4941 
4942     // Use TargetConstant instead of a regular constant for immarg.
4943     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4944     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4945       assert(CI->getBitWidth() <= 64 &&
4946              "large intrinsic immediates not handled");
4947       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4948     } else {
4949       Ops.push_back(
4950           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4951     }
4952   }
4953 
4954   SmallVector<EVT, 4> ValueVTs;
4955   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4956 
4957   if (HasChain)
4958     ValueVTs.push_back(MVT::Other);
4959 
4960   SDVTList VTs = DAG.getVTList(ValueVTs);
4961 
4962   // Propagate fast-math-flags from IR to node(s).
4963   SDNodeFlags Flags;
4964   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4965     Flags.copyFMF(*FPMO);
4966   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4967 
4968   // Create the node.
4969   SDValue Result;
4970   // In some cases, custom collection of operands from CallInst I may be needed.
4971   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4972   if (IsTgtIntrinsic) {
4973     // This is target intrinsic that touches memory
4974     //
4975     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4976     //       didn't yield anything useful.
4977     MachinePointerInfo MPI;
4978     if (Info.ptrVal)
4979       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4980     else if (Info.fallbackAddressSpace)
4981       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4982     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4983                                      Info.memVT, MPI, Info.align, Info.flags,
4984                                      Info.size, I.getAAMetadata());
4985   } else if (!HasChain) {
4986     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4987   } else if (!I.getType()->isVoidTy()) {
4988     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4989   } else {
4990     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4991   }
4992 
4993   if (HasChain) {
4994     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4995     if (OnlyLoad)
4996       PendingLoads.push_back(Chain);
4997     else
4998       DAG.setRoot(Chain);
4999   }
5000 
5001   if (!I.getType()->isVoidTy()) {
5002     if (!isa<VectorType>(I.getType()))
5003       Result = lowerRangeToAssertZExt(DAG, I, Result);
5004 
5005     MaybeAlign Alignment = I.getRetAlign();
5006 
5007     // Insert `assertalign` node if there's an alignment.
5008     if (InsertAssertAlign && Alignment) {
5009       Result =
5010           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5011     }
5012 
5013     setValue(&I, Result);
5014   }
5015 }
5016 
5017 /// GetSignificand - Get the significand and build it into a floating-point
5018 /// number with exponent of 1:
5019 ///
5020 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5021 ///
5022 /// where Op is the hexadecimal representation of floating point value.
5023 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5024   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5025                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5026   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5027                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5028   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5029 }
5030 
5031 /// GetExponent - Get the exponent:
5032 ///
5033 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5034 ///
5035 /// where Op is the hexadecimal representation of floating point value.
5036 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5037                            const TargetLowering &TLI, const SDLoc &dl) {
5038   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5039                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5040   SDValue t1 = DAG.getNode(
5041       ISD::SRL, dl, MVT::i32, t0,
5042       DAG.getConstant(23, dl,
5043                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5044   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5045                            DAG.getConstant(127, dl, MVT::i32));
5046   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5047 }
5048 
5049 /// getF32Constant - Get 32-bit floating point constant.
5050 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5051                               const SDLoc &dl) {
5052   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5053                            MVT::f32);
5054 }
5055 
5056 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5057                                        SelectionDAG &DAG) {
5058   // TODO: What fast-math-flags should be set on the floating-point nodes?
5059 
5060   //   IntegerPartOfX = ((int32_t)(t0);
5061   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5062 
5063   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5064   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5065   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5066 
5067   //   IntegerPartOfX <<= 23;
5068   IntegerPartOfX =
5069       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5070                   DAG.getConstant(23, dl,
5071                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5072                                       MVT::i32, DAG.getDataLayout())));
5073 
5074   SDValue TwoToFractionalPartOfX;
5075   if (LimitFloatPrecision <= 6) {
5076     // For floating-point precision of 6:
5077     //
5078     //   TwoToFractionalPartOfX =
5079     //     0.997535578f +
5080     //       (0.735607626f + 0.252464424f * x) * x;
5081     //
5082     // error 0.0144103317, which is 6 bits
5083     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5084                              getF32Constant(DAG, 0x3e814304, dl));
5085     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5086                              getF32Constant(DAG, 0x3f3c50c8, dl));
5087     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5088     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5089                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5090   } else if (LimitFloatPrecision <= 12) {
5091     // For floating-point precision of 12:
5092     //
5093     //   TwoToFractionalPartOfX =
5094     //     0.999892986f +
5095     //       (0.696457318f +
5096     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5097     //
5098     // error 0.000107046256, which is 13 to 14 bits
5099     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5100                              getF32Constant(DAG, 0x3da235e3, dl));
5101     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5102                              getF32Constant(DAG, 0x3e65b8f3, dl));
5103     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5104     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5105                              getF32Constant(DAG, 0x3f324b07, dl));
5106     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5107     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5108                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5109   } else { // LimitFloatPrecision <= 18
5110     // For floating-point precision of 18:
5111     //
5112     //   TwoToFractionalPartOfX =
5113     //     0.999999982f +
5114     //       (0.693148872f +
5115     //         (0.240227044f +
5116     //           (0.554906021e-1f +
5117     //             (0.961591928e-2f +
5118     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5119     // error 2.47208000*10^(-7), which is better than 18 bits
5120     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5121                              getF32Constant(DAG, 0x3924b03e, dl));
5122     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5123                              getF32Constant(DAG, 0x3ab24b87, dl));
5124     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5125     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5126                              getF32Constant(DAG, 0x3c1d8c17, dl));
5127     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5128     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5129                              getF32Constant(DAG, 0x3d634a1d, dl));
5130     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5131     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5132                              getF32Constant(DAG, 0x3e75fe14, dl));
5133     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5134     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5135                               getF32Constant(DAG, 0x3f317234, dl));
5136     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5137     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5138                                          getF32Constant(DAG, 0x3f800000, dl));
5139   }
5140 
5141   // Add the exponent into the result in integer domain.
5142   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5143   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5144                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5145 }
5146 
5147 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5148 /// limited-precision mode.
5149 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5150                          const TargetLowering &TLI, SDNodeFlags Flags) {
5151   if (Op.getValueType() == MVT::f32 &&
5152       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5153 
5154     // Put the exponent in the right bit position for later addition to the
5155     // final result:
5156     //
5157     // t0 = Op * log2(e)
5158 
5159     // TODO: What fast-math-flags should be set here?
5160     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5161                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5162     return getLimitedPrecisionExp2(t0, dl, DAG);
5163   }
5164 
5165   // No special expansion.
5166   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5167 }
5168 
5169 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5170 /// limited-precision mode.
5171 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5172                          const TargetLowering &TLI, SDNodeFlags Flags) {
5173   // TODO: What fast-math-flags should be set on the floating-point nodes?
5174 
5175   if (Op.getValueType() == MVT::f32 &&
5176       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5177     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5178 
5179     // Scale the exponent by log(2).
5180     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5181     SDValue LogOfExponent =
5182         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5183                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5184 
5185     // Get the significand and build it into a floating-point number with
5186     // exponent of 1.
5187     SDValue X = GetSignificand(DAG, Op1, dl);
5188 
5189     SDValue LogOfMantissa;
5190     if (LimitFloatPrecision <= 6) {
5191       // For floating-point precision of 6:
5192       //
5193       //   LogofMantissa =
5194       //     -1.1609546f +
5195       //       (1.4034025f - 0.23903021f * x) * x;
5196       //
5197       // error 0.0034276066, which is better than 8 bits
5198       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5199                                getF32Constant(DAG, 0xbe74c456, dl));
5200       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5201                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5202       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5203       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5204                                   getF32Constant(DAG, 0x3f949a29, dl));
5205     } else if (LimitFloatPrecision <= 12) {
5206       // For floating-point precision of 12:
5207       //
5208       //   LogOfMantissa =
5209       //     -1.7417939f +
5210       //       (2.8212026f +
5211       //         (-1.4699568f +
5212       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5213       //
5214       // error 0.000061011436, which is 14 bits
5215       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5216                                getF32Constant(DAG, 0xbd67b6d6, dl));
5217       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5218                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5219       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5220       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5221                                getF32Constant(DAG, 0x3fbc278b, dl));
5222       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5223       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5224                                getF32Constant(DAG, 0x40348e95, dl));
5225       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5226       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5227                                   getF32Constant(DAG, 0x3fdef31a, dl));
5228     } else { // LimitFloatPrecision <= 18
5229       // For floating-point precision of 18:
5230       //
5231       //   LogOfMantissa =
5232       //     -2.1072184f +
5233       //       (4.2372794f +
5234       //         (-3.7029485f +
5235       //           (2.2781945f +
5236       //             (-0.87823314f +
5237       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5238       //
5239       // error 0.0000023660568, which is better than 18 bits
5240       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5241                                getF32Constant(DAG, 0xbc91e5ac, dl));
5242       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5243                                getF32Constant(DAG, 0x3e4350aa, dl));
5244       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5245       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5246                                getF32Constant(DAG, 0x3f60d3e3, dl));
5247       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5248       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5249                                getF32Constant(DAG, 0x4011cdf0, dl));
5250       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5251       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5252                                getF32Constant(DAG, 0x406cfd1c, dl));
5253       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5254       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5255                                getF32Constant(DAG, 0x408797cb, dl));
5256       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5257       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5258                                   getF32Constant(DAG, 0x4006dcab, dl));
5259     }
5260 
5261     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5262   }
5263 
5264   // No special expansion.
5265   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5266 }
5267 
5268 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5269 /// limited-precision mode.
5270 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5271                           const TargetLowering &TLI, SDNodeFlags Flags) {
5272   // TODO: What fast-math-flags should be set on the floating-point nodes?
5273 
5274   if (Op.getValueType() == MVT::f32 &&
5275       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5276     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5277 
5278     // Get the exponent.
5279     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5280 
5281     // Get the significand and build it into a floating-point number with
5282     // exponent of 1.
5283     SDValue X = GetSignificand(DAG, Op1, dl);
5284 
5285     // Different possible minimax approximations of significand in
5286     // floating-point for various degrees of accuracy over [1,2].
5287     SDValue Log2ofMantissa;
5288     if (LimitFloatPrecision <= 6) {
5289       // For floating-point precision of 6:
5290       //
5291       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5292       //
5293       // error 0.0049451742, which is more than 7 bits
5294       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5295                                getF32Constant(DAG, 0xbeb08fe0, dl));
5296       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5297                                getF32Constant(DAG, 0x40019463, dl));
5298       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5299       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5300                                    getF32Constant(DAG, 0x3fd6633d, dl));
5301     } else if (LimitFloatPrecision <= 12) {
5302       // For floating-point precision of 12:
5303       //
5304       //   Log2ofMantissa =
5305       //     -2.51285454f +
5306       //       (4.07009056f +
5307       //         (-2.12067489f +
5308       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5309       //
5310       // error 0.0000876136000, which is better than 13 bits
5311       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5312                                getF32Constant(DAG, 0xbda7262e, dl));
5313       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5314                                getF32Constant(DAG, 0x3f25280b, dl));
5315       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5316       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5317                                getF32Constant(DAG, 0x4007b923, dl));
5318       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5319       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5320                                getF32Constant(DAG, 0x40823e2f, dl));
5321       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5322       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5323                                    getF32Constant(DAG, 0x4020d29c, dl));
5324     } else { // LimitFloatPrecision <= 18
5325       // For floating-point precision of 18:
5326       //
5327       //   Log2ofMantissa =
5328       //     -3.0400495f +
5329       //       (6.1129976f +
5330       //         (-5.3420409f +
5331       //           (3.2865683f +
5332       //             (-1.2669343f +
5333       //               (0.27515199f -
5334       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5335       //
5336       // error 0.0000018516, which is better than 18 bits
5337       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5338                                getF32Constant(DAG, 0xbcd2769e, dl));
5339       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5340                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5341       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5342       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5343                                getF32Constant(DAG, 0x3fa22ae7, dl));
5344       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5345       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5346                                getF32Constant(DAG, 0x40525723, dl));
5347       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5348       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5349                                getF32Constant(DAG, 0x40aaf200, dl));
5350       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5351       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5352                                getF32Constant(DAG, 0x40c39dad, dl));
5353       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5354       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5355                                    getF32Constant(DAG, 0x4042902c, dl));
5356     }
5357 
5358     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5359   }
5360 
5361   // No special expansion.
5362   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5363 }
5364 
5365 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5366 /// limited-precision mode.
5367 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5368                            const TargetLowering &TLI, SDNodeFlags Flags) {
5369   // TODO: What fast-math-flags should be set on the floating-point nodes?
5370 
5371   if (Op.getValueType() == MVT::f32 &&
5372       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5373     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5374 
5375     // Scale the exponent by log10(2) [0.30102999f].
5376     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5377     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5378                                         getF32Constant(DAG, 0x3e9a209a, dl));
5379 
5380     // Get the significand and build it into a floating-point number with
5381     // exponent of 1.
5382     SDValue X = GetSignificand(DAG, Op1, dl);
5383 
5384     SDValue Log10ofMantissa;
5385     if (LimitFloatPrecision <= 6) {
5386       // For floating-point precision of 6:
5387       //
5388       //   Log10ofMantissa =
5389       //     -0.50419619f +
5390       //       (0.60948995f - 0.10380950f * x) * x;
5391       //
5392       // error 0.0014886165, which is 6 bits
5393       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5394                                getF32Constant(DAG, 0xbdd49a13, dl));
5395       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5396                                getF32Constant(DAG, 0x3f1c0789, dl));
5397       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5398       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5399                                     getF32Constant(DAG, 0x3f011300, dl));
5400     } else if (LimitFloatPrecision <= 12) {
5401       // For floating-point precision of 12:
5402       //
5403       //   Log10ofMantissa =
5404       //     -0.64831180f +
5405       //       (0.91751397f +
5406       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5407       //
5408       // error 0.00019228036, which is better than 12 bits
5409       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5410                                getF32Constant(DAG, 0x3d431f31, dl));
5411       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5412                                getF32Constant(DAG, 0x3ea21fb2, dl));
5413       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5414       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5415                                getF32Constant(DAG, 0x3f6ae232, dl));
5416       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5417       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5418                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5419     } else { // LimitFloatPrecision <= 18
5420       // For floating-point precision of 18:
5421       //
5422       //   Log10ofMantissa =
5423       //     -0.84299375f +
5424       //       (1.5327582f +
5425       //         (-1.0688956f +
5426       //           (0.49102474f +
5427       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5428       //
5429       // error 0.0000037995730, which is better than 18 bits
5430       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5431                                getF32Constant(DAG, 0x3c5d51ce, dl));
5432       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5433                                getF32Constant(DAG, 0x3e00685a, dl));
5434       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5435       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5436                                getF32Constant(DAG, 0x3efb6798, dl));
5437       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5438       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5439                                getF32Constant(DAG, 0x3f88d192, dl));
5440       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5441       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5442                                getF32Constant(DAG, 0x3fc4316c, dl));
5443       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5444       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5445                                     getF32Constant(DAG, 0x3f57ce70, dl));
5446     }
5447 
5448     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5449   }
5450 
5451   // No special expansion.
5452   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5453 }
5454 
5455 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5456 /// limited-precision mode.
5457 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5458                           const TargetLowering &TLI, SDNodeFlags Flags) {
5459   if (Op.getValueType() == MVT::f32 &&
5460       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5461     return getLimitedPrecisionExp2(Op, dl, DAG);
5462 
5463   // No special expansion.
5464   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5465 }
5466 
5467 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5468 /// limited-precision mode with x == 10.0f.
5469 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5470                          SelectionDAG &DAG, const TargetLowering &TLI,
5471                          SDNodeFlags Flags) {
5472   bool IsExp10 = false;
5473   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5474       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5475     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5476       APFloat Ten(10.0f);
5477       IsExp10 = LHSC->isExactlyValue(Ten);
5478     }
5479   }
5480 
5481   // TODO: What fast-math-flags should be set on the FMUL node?
5482   if (IsExp10) {
5483     // Put the exponent in the right bit position for later addition to the
5484     // final result:
5485     //
5486     //   #define LOG2OF10 3.3219281f
5487     //   t0 = Op * LOG2OF10;
5488     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5489                              getF32Constant(DAG, 0x40549a78, dl));
5490     return getLimitedPrecisionExp2(t0, dl, DAG);
5491   }
5492 
5493   // No special expansion.
5494   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5495 }
5496 
5497 /// ExpandPowI - Expand a llvm.powi intrinsic.
5498 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5499                           SelectionDAG &DAG) {
5500   // If RHS is a constant, we can expand this out to a multiplication tree if
5501   // it's beneficial on the target, otherwise we end up lowering to a call to
5502   // __powidf2 (for example).
5503   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5504     unsigned Val = RHSC->getSExtValue();
5505 
5506     // powi(x, 0) -> 1.0
5507     if (Val == 0)
5508       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5509 
5510     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5511             Val, DAG.shouldOptForSize())) {
5512       // Get the exponent as a positive value.
5513       if ((int)Val < 0)
5514         Val = -Val;
5515       // We use the simple binary decomposition method to generate the multiply
5516       // sequence.  There are more optimal ways to do this (for example,
5517       // powi(x,15) generates one more multiply than it should), but this has
5518       // the benefit of being both really simple and much better than a libcall.
5519       SDValue Res; // Logically starts equal to 1.0
5520       SDValue CurSquare = LHS;
5521       // TODO: Intrinsics should have fast-math-flags that propagate to these
5522       // nodes.
5523       while (Val) {
5524         if (Val & 1) {
5525           if (Res.getNode())
5526             Res =
5527                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5528           else
5529             Res = CurSquare; // 1.0*CurSquare.
5530         }
5531 
5532         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5533                                 CurSquare, CurSquare);
5534         Val >>= 1;
5535       }
5536 
5537       // If the original was negative, invert the result, producing 1/(x*x*x).
5538       if (RHSC->getSExtValue() < 0)
5539         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5540                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5541       return Res;
5542     }
5543   }
5544 
5545   // Otherwise, expand to a libcall.
5546   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5547 }
5548 
5549 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5550                             SDValue LHS, SDValue RHS, SDValue Scale,
5551                             SelectionDAG &DAG, const TargetLowering &TLI) {
5552   EVT VT = LHS.getValueType();
5553   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5554   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5555   LLVMContext &Ctx = *DAG.getContext();
5556 
5557   // If the type is legal but the operation isn't, this node might survive all
5558   // the way to operation legalization. If we end up there and we do not have
5559   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5560   // node.
5561 
5562   // Coax the legalizer into expanding the node during type legalization instead
5563   // by bumping the size by one bit. This will force it to Promote, enabling the
5564   // early expansion and avoiding the need to expand later.
5565 
5566   // We don't have to do this if Scale is 0; that can always be expanded, unless
5567   // it's a saturating signed operation. Those can experience true integer
5568   // division overflow, a case which we must avoid.
5569 
5570   // FIXME: We wouldn't have to do this (or any of the early
5571   // expansion/promotion) if it was possible to expand a libcall of an
5572   // illegal type during operation legalization. But it's not, so things
5573   // get a bit hacky.
5574   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5575   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5576       (TLI.isTypeLegal(VT) ||
5577        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5578     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5579         Opcode, VT, ScaleInt);
5580     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5581       EVT PromVT;
5582       if (VT.isScalarInteger())
5583         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5584       else if (VT.isVector()) {
5585         PromVT = VT.getVectorElementType();
5586         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5587         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5588       } else
5589         llvm_unreachable("Wrong VT for DIVFIX?");
5590       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5591       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5592       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5593       // For saturating operations, we need to shift up the LHS to get the
5594       // proper saturation width, and then shift down again afterwards.
5595       if (Saturating)
5596         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5597                           DAG.getConstant(1, DL, ShiftTy));
5598       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5599       if (Saturating)
5600         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5601                           DAG.getConstant(1, DL, ShiftTy));
5602       return DAG.getZExtOrTrunc(Res, DL, VT);
5603     }
5604   }
5605 
5606   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5607 }
5608 
5609 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5610 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5611 static void
5612 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5613                      const SDValue &N) {
5614   switch (N.getOpcode()) {
5615   case ISD::CopyFromReg: {
5616     SDValue Op = N.getOperand(1);
5617     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5618                       Op.getValueType().getSizeInBits());
5619     return;
5620   }
5621   case ISD::BITCAST:
5622   case ISD::AssertZext:
5623   case ISD::AssertSext:
5624   case ISD::TRUNCATE:
5625     getUnderlyingArgRegs(Regs, N.getOperand(0));
5626     return;
5627   case ISD::BUILD_PAIR:
5628   case ISD::BUILD_VECTOR:
5629   case ISD::CONCAT_VECTORS:
5630     for (SDValue Op : N->op_values())
5631       getUnderlyingArgRegs(Regs, Op);
5632     return;
5633   default:
5634     return;
5635   }
5636 }
5637 
5638 /// If the DbgValueInst is a dbg_value of a function argument, create the
5639 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5640 /// instruction selection, they will be inserted to the entry BB.
5641 /// We don't currently support this for variadic dbg_values, as they shouldn't
5642 /// appear for function arguments or in the prologue.
5643 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5644     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5645     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5646   const Argument *Arg = dyn_cast<Argument>(V);
5647   if (!Arg)
5648     return false;
5649 
5650   MachineFunction &MF = DAG.getMachineFunction();
5651   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5652 
5653   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5654   // we've been asked to pursue.
5655   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5656                               bool Indirect) {
5657     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5658       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5659       // pointing at the VReg, which will be patched up later.
5660       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5661       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5662           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5663           /* isKill */ false, /* isDead */ false,
5664           /* isUndef */ false, /* isEarlyClobber */ false,
5665           /* SubReg */ 0, /* isDebug */ true)});
5666 
5667       auto *NewDIExpr = FragExpr;
5668       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5669       // the DIExpression.
5670       if (Indirect)
5671         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5672       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5673       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5674       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5675     } else {
5676       // Create a completely standard DBG_VALUE.
5677       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5678       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5679     }
5680   };
5681 
5682   if (Kind == FuncArgumentDbgValueKind::Value) {
5683     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5684     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5685     // the entry block.
5686     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5687     if (!IsInEntryBlock)
5688       return false;
5689 
5690     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5691     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5692     // variable that also is a param.
5693     //
5694     // Although, if we are at the top of the entry block already, we can still
5695     // emit using ArgDbgValue. This might catch some situations when the
5696     // dbg.value refers to an argument that isn't used in the entry block, so
5697     // any CopyToReg node would be optimized out and the only way to express
5698     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5699     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5700     // we should only emit as ArgDbgValue if the Variable is an argument to the
5701     // current function, and the dbg.value intrinsic is found in the entry
5702     // block.
5703     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5704         !DL->getInlinedAt();
5705     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5706     if (!IsInPrologue && !VariableIsFunctionInputArg)
5707       return false;
5708 
5709     // Here we assume that a function argument on IR level only can be used to
5710     // describe one input parameter on source level. If we for example have
5711     // source code like this
5712     //
5713     //    struct A { long x, y; };
5714     //    void foo(struct A a, long b) {
5715     //      ...
5716     //      b = a.x;
5717     //      ...
5718     //    }
5719     //
5720     // and IR like this
5721     //
5722     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5723     //  entry:
5724     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5725     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5726     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5727     //    ...
5728     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5729     //    ...
5730     //
5731     // then the last dbg.value is describing a parameter "b" using a value that
5732     // is an argument. But since we already has used %a1 to describe a parameter
5733     // we should not handle that last dbg.value here (that would result in an
5734     // incorrect hoisting of the DBG_VALUE to the function entry).
5735     // Notice that we allow one dbg.value per IR level argument, to accommodate
5736     // for the situation with fragments above.
5737     if (VariableIsFunctionInputArg) {
5738       unsigned ArgNo = Arg->getArgNo();
5739       if (ArgNo >= FuncInfo.DescribedArgs.size())
5740         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5741       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5742         return false;
5743       FuncInfo.DescribedArgs.set(ArgNo);
5744     }
5745   }
5746 
5747   bool IsIndirect = false;
5748   std::optional<MachineOperand> Op;
5749   // Some arguments' frame index is recorded during argument lowering.
5750   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5751   if (FI != std::numeric_limits<int>::max())
5752     Op = MachineOperand::CreateFI(FI);
5753 
5754   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5755   if (!Op && N.getNode()) {
5756     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5757     Register Reg;
5758     if (ArgRegsAndSizes.size() == 1)
5759       Reg = ArgRegsAndSizes.front().first;
5760 
5761     if (Reg && Reg.isVirtual()) {
5762       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5763       Register PR = RegInfo.getLiveInPhysReg(Reg);
5764       if (PR)
5765         Reg = PR;
5766     }
5767     if (Reg) {
5768       Op = MachineOperand::CreateReg(Reg, false);
5769       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5770     }
5771   }
5772 
5773   if (!Op && N.getNode()) {
5774     // Check if frame index is available.
5775     SDValue LCandidate = peekThroughBitcasts(N);
5776     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5777       if (FrameIndexSDNode *FINode =
5778           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5779         Op = MachineOperand::CreateFI(FINode->getIndex());
5780   }
5781 
5782   if (!Op) {
5783     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5784     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5785                                          SplitRegs) {
5786       unsigned Offset = 0;
5787       for (const auto &RegAndSize : SplitRegs) {
5788         // If the expression is already a fragment, the current register
5789         // offset+size might extend beyond the fragment. In this case, only
5790         // the register bits that are inside the fragment are relevant.
5791         int RegFragmentSizeInBits = RegAndSize.second;
5792         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5793           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5794           // The register is entirely outside the expression fragment,
5795           // so is irrelevant for debug info.
5796           if (Offset >= ExprFragmentSizeInBits)
5797             break;
5798           // The register is partially outside the expression fragment, only
5799           // the low bits within the fragment are relevant for debug info.
5800           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5801             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5802           }
5803         }
5804 
5805         auto FragmentExpr = DIExpression::createFragmentExpression(
5806             Expr, Offset, RegFragmentSizeInBits);
5807         Offset += RegAndSize.second;
5808         // If a valid fragment expression cannot be created, the variable's
5809         // correct value cannot be determined and so it is set as Undef.
5810         if (!FragmentExpr) {
5811           SDDbgValue *SDV = DAG.getConstantDbgValue(
5812               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5813           DAG.AddDbgValue(SDV, false);
5814           continue;
5815         }
5816         MachineInstr *NewMI =
5817             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5818                              Kind != FuncArgumentDbgValueKind::Value);
5819         FuncInfo.ArgDbgValues.push_back(NewMI);
5820       }
5821     };
5822 
5823     // Check if ValueMap has reg number.
5824     DenseMap<const Value *, Register>::const_iterator
5825       VMI = FuncInfo.ValueMap.find(V);
5826     if (VMI != FuncInfo.ValueMap.end()) {
5827       const auto &TLI = DAG.getTargetLoweringInfo();
5828       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5829                        V->getType(), std::nullopt);
5830       if (RFV.occupiesMultipleRegs()) {
5831         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5832         return true;
5833       }
5834 
5835       Op = MachineOperand::CreateReg(VMI->second, false);
5836       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5837     } else if (ArgRegsAndSizes.size() > 1) {
5838       // This was split due to the calling convention, and no virtual register
5839       // mapping exists for the value.
5840       splitMultiRegDbgValue(ArgRegsAndSizes);
5841       return true;
5842     }
5843   }
5844 
5845   if (!Op)
5846     return false;
5847 
5848   assert(Variable->isValidLocationForIntrinsic(DL) &&
5849          "Expected inlined-at fields to agree");
5850   MachineInstr *NewMI = nullptr;
5851 
5852   if (Op->isReg())
5853     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5854   else
5855     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5856                     Variable, Expr);
5857 
5858   // Otherwise, use ArgDbgValues.
5859   FuncInfo.ArgDbgValues.push_back(NewMI);
5860   return true;
5861 }
5862 
5863 /// Return the appropriate SDDbgValue based on N.
5864 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5865                                              DILocalVariable *Variable,
5866                                              DIExpression *Expr,
5867                                              const DebugLoc &dl,
5868                                              unsigned DbgSDNodeOrder) {
5869   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5870     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5871     // stack slot locations.
5872     //
5873     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5874     // debug values here after optimization:
5875     //
5876     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5877     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5878     //
5879     // Both describe the direct values of their associated variables.
5880     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5881                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5882   }
5883   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5884                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5885 }
5886 
5887 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5888   switch (Intrinsic) {
5889   case Intrinsic::smul_fix:
5890     return ISD::SMULFIX;
5891   case Intrinsic::umul_fix:
5892     return ISD::UMULFIX;
5893   case Intrinsic::smul_fix_sat:
5894     return ISD::SMULFIXSAT;
5895   case Intrinsic::umul_fix_sat:
5896     return ISD::UMULFIXSAT;
5897   case Intrinsic::sdiv_fix:
5898     return ISD::SDIVFIX;
5899   case Intrinsic::udiv_fix:
5900     return ISD::UDIVFIX;
5901   case Intrinsic::sdiv_fix_sat:
5902     return ISD::SDIVFIXSAT;
5903   case Intrinsic::udiv_fix_sat:
5904     return ISD::UDIVFIXSAT;
5905   default:
5906     llvm_unreachable("Unhandled fixed point intrinsic");
5907   }
5908 }
5909 
5910 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5911                                            const char *FunctionName) {
5912   assert(FunctionName && "FunctionName must not be nullptr");
5913   SDValue Callee = DAG.getExternalSymbol(
5914       FunctionName,
5915       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5916   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5917 }
5918 
5919 /// Given a @llvm.call.preallocated.setup, return the corresponding
5920 /// preallocated call.
5921 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5922   assert(cast<CallBase>(PreallocatedSetup)
5923                  ->getCalledFunction()
5924                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5925          "expected call_preallocated_setup Value");
5926   for (const auto *U : PreallocatedSetup->users()) {
5927     auto *UseCall = cast<CallBase>(U);
5928     const Function *Fn = UseCall->getCalledFunction();
5929     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5930       return UseCall;
5931     }
5932   }
5933   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5934 }
5935 
5936 /// If DI is a debug value with an EntryValue expression, lower it using the
5937 /// corresponding physical register of the associated Argument value
5938 /// (guaranteed to exist by the verifier).
5939 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) {
5940   DILocalVariable *Variable = DI.getVariable();
5941   DIExpression *Expr = DI.getExpression();
5942   if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues()))
5943     return false;
5944 
5945   // These properties are guaranteed by the verifier.
5946   Argument *Arg = cast<Argument>(DI.getValue(0));
5947   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5948 
5949   auto ArgIt = FuncInfo.ValueMap.find(Arg);
5950   if (ArgIt == FuncInfo.ValueMap.end()) {
5951     LLVM_DEBUG(
5952         dbgs() << "Dropping dbg.value: expression is entry_value but "
5953                   "couldn't find an associated register for the Argument\n");
5954     return true;
5955   }
5956   Register ArgVReg = ArgIt->getSecond();
5957 
5958   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5959     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
5960       SDDbgValue *SDV =
5961           DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/,
5962                               DI.getDebugLoc(), SDNodeOrder);
5963       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5964       return true;
5965     }
5966   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5967                        "couldn't find a physical register\n");
5968   return true;
5969 }
5970 
5971 /// Lower the call to the specified intrinsic function.
5972 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5973                                              unsigned Intrinsic) {
5974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5975   SDLoc sdl = getCurSDLoc();
5976   DebugLoc dl = getCurDebugLoc();
5977   SDValue Res;
5978 
5979   SDNodeFlags Flags;
5980   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5981     Flags.copyFMF(*FPOp);
5982 
5983   switch (Intrinsic) {
5984   default:
5985     // By default, turn this into a target intrinsic node.
5986     visitTargetIntrinsic(I, Intrinsic);
5987     return;
5988   case Intrinsic::vscale: {
5989     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5990     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5991     return;
5992   }
5993   case Intrinsic::vastart:  visitVAStart(I); return;
5994   case Intrinsic::vaend:    visitVAEnd(I); return;
5995   case Intrinsic::vacopy:   visitVACopy(I); return;
5996   case Intrinsic::returnaddress:
5997     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5998                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5999                              getValue(I.getArgOperand(0))));
6000     return;
6001   case Intrinsic::addressofreturnaddress:
6002     setValue(&I,
6003              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6004                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6005     return;
6006   case Intrinsic::sponentry:
6007     setValue(&I,
6008              DAG.getNode(ISD::SPONENTRY, sdl,
6009                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6010     return;
6011   case Intrinsic::frameaddress:
6012     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6013                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6014                              getValue(I.getArgOperand(0))));
6015     return;
6016   case Intrinsic::read_volatile_register:
6017   case Intrinsic::read_register: {
6018     Value *Reg = I.getArgOperand(0);
6019     SDValue Chain = getRoot();
6020     SDValue RegName =
6021         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6022     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6023     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6024       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6025     setValue(&I, Res);
6026     DAG.setRoot(Res.getValue(1));
6027     return;
6028   }
6029   case Intrinsic::write_register: {
6030     Value *Reg = I.getArgOperand(0);
6031     Value *RegValue = I.getArgOperand(1);
6032     SDValue Chain = getRoot();
6033     SDValue RegName =
6034         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6035     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6036                             RegName, getValue(RegValue)));
6037     return;
6038   }
6039   case Intrinsic::memcpy: {
6040     const auto &MCI = cast<MemCpyInst>(I);
6041     SDValue Op1 = getValue(I.getArgOperand(0));
6042     SDValue Op2 = getValue(I.getArgOperand(1));
6043     SDValue Op3 = getValue(I.getArgOperand(2));
6044     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6045     Align DstAlign = MCI.getDestAlign().valueOrOne();
6046     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6047     Align Alignment = std::min(DstAlign, SrcAlign);
6048     bool isVol = MCI.isVolatile();
6049     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6050     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6051     // node.
6052     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6053     SDValue MC = DAG.getMemcpy(
6054         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6055         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6056         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6057     updateDAGForMaybeTailCall(MC);
6058     return;
6059   }
6060   case Intrinsic::memcpy_inline: {
6061     const auto &MCI = cast<MemCpyInlineInst>(I);
6062     SDValue Dst = getValue(I.getArgOperand(0));
6063     SDValue Src = getValue(I.getArgOperand(1));
6064     SDValue Size = getValue(I.getArgOperand(2));
6065     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6066     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6067     Align DstAlign = MCI.getDestAlign().valueOrOne();
6068     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6069     Align Alignment = std::min(DstAlign, SrcAlign);
6070     bool isVol = MCI.isVolatile();
6071     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6072     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6073     // node.
6074     SDValue MC = DAG.getMemcpy(
6075         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6076         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6077         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6078     updateDAGForMaybeTailCall(MC);
6079     return;
6080   }
6081   case Intrinsic::memset: {
6082     const auto &MSI = cast<MemSetInst>(I);
6083     SDValue Op1 = getValue(I.getArgOperand(0));
6084     SDValue Op2 = getValue(I.getArgOperand(1));
6085     SDValue Op3 = getValue(I.getArgOperand(2));
6086     // @llvm.memset defines 0 and 1 to both mean no alignment.
6087     Align Alignment = MSI.getDestAlign().valueOrOne();
6088     bool isVol = MSI.isVolatile();
6089     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6090     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6091     SDValue MS = DAG.getMemset(
6092         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6093         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6094     updateDAGForMaybeTailCall(MS);
6095     return;
6096   }
6097   case Intrinsic::memset_inline: {
6098     const auto &MSII = cast<MemSetInlineInst>(I);
6099     SDValue Dst = getValue(I.getArgOperand(0));
6100     SDValue Value = getValue(I.getArgOperand(1));
6101     SDValue Size = getValue(I.getArgOperand(2));
6102     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6103     // @llvm.memset defines 0 and 1 to both mean no alignment.
6104     Align DstAlign = MSII.getDestAlign().valueOrOne();
6105     bool isVol = MSII.isVolatile();
6106     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6107     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6108     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6109                                /* AlwaysInline */ true, isTC,
6110                                MachinePointerInfo(I.getArgOperand(0)),
6111                                I.getAAMetadata());
6112     updateDAGForMaybeTailCall(MC);
6113     return;
6114   }
6115   case Intrinsic::memmove: {
6116     const auto &MMI = cast<MemMoveInst>(I);
6117     SDValue Op1 = getValue(I.getArgOperand(0));
6118     SDValue Op2 = getValue(I.getArgOperand(1));
6119     SDValue Op3 = getValue(I.getArgOperand(2));
6120     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6121     Align DstAlign = MMI.getDestAlign().valueOrOne();
6122     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6123     Align Alignment = std::min(DstAlign, SrcAlign);
6124     bool isVol = MMI.isVolatile();
6125     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6126     // FIXME: Support passing different dest/src alignments to the memmove DAG
6127     // node.
6128     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6129     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6130                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6131                                 MachinePointerInfo(I.getArgOperand(1)),
6132                                 I.getAAMetadata(), AA);
6133     updateDAGForMaybeTailCall(MM);
6134     return;
6135   }
6136   case Intrinsic::memcpy_element_unordered_atomic: {
6137     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6138     SDValue Dst = getValue(MI.getRawDest());
6139     SDValue Src = getValue(MI.getRawSource());
6140     SDValue Length = getValue(MI.getLength());
6141 
6142     Type *LengthTy = MI.getLength()->getType();
6143     unsigned ElemSz = MI.getElementSizeInBytes();
6144     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6145     SDValue MC =
6146         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6147                             isTC, MachinePointerInfo(MI.getRawDest()),
6148                             MachinePointerInfo(MI.getRawSource()));
6149     updateDAGForMaybeTailCall(MC);
6150     return;
6151   }
6152   case Intrinsic::memmove_element_unordered_atomic: {
6153     auto &MI = cast<AtomicMemMoveInst>(I);
6154     SDValue Dst = getValue(MI.getRawDest());
6155     SDValue Src = getValue(MI.getRawSource());
6156     SDValue Length = getValue(MI.getLength());
6157 
6158     Type *LengthTy = MI.getLength()->getType();
6159     unsigned ElemSz = MI.getElementSizeInBytes();
6160     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6161     SDValue MC =
6162         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6163                              isTC, MachinePointerInfo(MI.getRawDest()),
6164                              MachinePointerInfo(MI.getRawSource()));
6165     updateDAGForMaybeTailCall(MC);
6166     return;
6167   }
6168   case Intrinsic::memset_element_unordered_atomic: {
6169     auto &MI = cast<AtomicMemSetInst>(I);
6170     SDValue Dst = getValue(MI.getRawDest());
6171     SDValue Val = getValue(MI.getValue());
6172     SDValue Length = getValue(MI.getLength());
6173 
6174     Type *LengthTy = MI.getLength()->getType();
6175     unsigned ElemSz = MI.getElementSizeInBytes();
6176     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6177     SDValue MC =
6178         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6179                             isTC, MachinePointerInfo(MI.getRawDest()));
6180     updateDAGForMaybeTailCall(MC);
6181     return;
6182   }
6183   case Intrinsic::call_preallocated_setup: {
6184     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6185     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6186     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6187                               getRoot(), SrcValue);
6188     setValue(&I, Res);
6189     DAG.setRoot(Res);
6190     return;
6191   }
6192   case Intrinsic::call_preallocated_arg: {
6193     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6194     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6195     SDValue Ops[3];
6196     Ops[0] = getRoot();
6197     Ops[1] = SrcValue;
6198     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6199                                    MVT::i32); // arg index
6200     SDValue Res = DAG.getNode(
6201         ISD::PREALLOCATED_ARG, sdl,
6202         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6203     setValue(&I, Res);
6204     DAG.setRoot(Res.getValue(1));
6205     return;
6206   }
6207   case Intrinsic::dbg_declare: {
6208     const auto &DI = cast<DbgDeclareInst>(I);
6209     // Debug intrinsics are handled separately in assignment tracking mode.
6210     // Some intrinsics are handled right after Argument lowering.
6211     if (AssignmentTrackingEnabled ||
6212         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6213       return;
6214     // Assume dbg.declare can not currently use DIArgList, i.e.
6215     // it is non-variadic.
6216     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6217     DILocalVariable *Variable = DI.getVariable();
6218     DIExpression *Expression = DI.getExpression();
6219     dropDanglingDebugInfo(Variable, Expression);
6220     assert(Variable && "Missing variable");
6221     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6222                       << "\n");
6223     // Check if address has undef value.
6224     const Value *Address = DI.getVariableLocationOp(0);
6225     if (!Address || isa<UndefValue>(Address) ||
6226         (Address->use_empty() && !isa<Argument>(Address))) {
6227       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6228                         << " (bad/undef/unused-arg address)\n");
6229       return;
6230     }
6231 
6232     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6233 
6234     SDValue &N = NodeMap[Address];
6235     if (!N.getNode() && isa<Argument>(Address))
6236       // Check unused arguments map.
6237       N = UnusedArgNodeMap[Address];
6238     SDDbgValue *SDV;
6239     if (N.getNode()) {
6240       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6241         Address = BCI->getOperand(0);
6242       // Parameters are handled specially.
6243       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6244       if (isParameter && FINode) {
6245         // Byval parameter. We have a frame index at this point.
6246         SDV =
6247             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6248                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6249       } else if (isa<Argument>(Address)) {
6250         // Address is an argument, so try to emit its dbg value using
6251         // virtual register info from the FuncInfo.ValueMap.
6252         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6253                                  FuncArgumentDbgValueKind::Declare, N);
6254         return;
6255       } else {
6256         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6257                               true, dl, SDNodeOrder);
6258       }
6259       DAG.AddDbgValue(SDV, isParameter);
6260     } else {
6261       // If Address is an argument then try to emit its dbg value using
6262       // virtual register info from the FuncInfo.ValueMap.
6263       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6264                                     FuncArgumentDbgValueKind::Declare, N)) {
6265         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6266                           << " (could not emit func-arg dbg_value)\n");
6267       }
6268     }
6269     return;
6270   }
6271   case Intrinsic::dbg_label: {
6272     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6273     DILabel *Label = DI.getLabel();
6274     assert(Label && "Missing label");
6275 
6276     SDDbgLabel *SDV;
6277     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6278     DAG.AddDbgLabel(SDV);
6279     return;
6280   }
6281   case Intrinsic::dbg_assign: {
6282     // Debug intrinsics are handled seperately in assignment tracking mode.
6283     if (AssignmentTrackingEnabled)
6284       return;
6285     // If assignment tracking hasn't been enabled then fall through and treat
6286     // the dbg.assign as a dbg.value.
6287     [[fallthrough]];
6288   }
6289   case Intrinsic::dbg_value: {
6290     // Debug intrinsics are handled seperately in assignment tracking mode.
6291     if (AssignmentTrackingEnabled)
6292       return;
6293     const DbgValueInst &DI = cast<DbgValueInst>(I);
6294     assert(DI.getVariable() && "Missing variable");
6295 
6296     DILocalVariable *Variable = DI.getVariable();
6297     DIExpression *Expression = DI.getExpression();
6298     dropDanglingDebugInfo(Variable, Expression);
6299 
6300     if (visitEntryValueDbgValue(DI))
6301       return;
6302 
6303     if (DI.isKillLocation()) {
6304       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6305       return;
6306     }
6307 
6308     SmallVector<Value *, 4> Values(DI.getValues());
6309     if (Values.empty())
6310       return;
6311 
6312     bool IsVariadic = DI.hasArgList();
6313     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6314                           SDNodeOrder, IsVariadic))
6315       addDanglingDebugInfo(&DI, SDNodeOrder);
6316     return;
6317   }
6318 
6319   case Intrinsic::eh_typeid_for: {
6320     // Find the type id for the given typeinfo.
6321     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6322     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6323     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6324     setValue(&I, Res);
6325     return;
6326   }
6327 
6328   case Intrinsic::eh_return_i32:
6329   case Intrinsic::eh_return_i64:
6330     DAG.getMachineFunction().setCallsEHReturn(true);
6331     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6332                             MVT::Other,
6333                             getControlRoot(),
6334                             getValue(I.getArgOperand(0)),
6335                             getValue(I.getArgOperand(1))));
6336     return;
6337   case Intrinsic::eh_unwind_init:
6338     DAG.getMachineFunction().setCallsUnwindInit(true);
6339     return;
6340   case Intrinsic::eh_dwarf_cfa:
6341     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6342                              TLI.getPointerTy(DAG.getDataLayout()),
6343                              getValue(I.getArgOperand(0))));
6344     return;
6345   case Intrinsic::eh_sjlj_callsite: {
6346     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6347     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6348     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6349 
6350     MMI.setCurrentCallSite(CI->getZExtValue());
6351     return;
6352   }
6353   case Intrinsic::eh_sjlj_functioncontext: {
6354     // Get and store the index of the function context.
6355     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6356     AllocaInst *FnCtx =
6357       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6358     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6359     MFI.setFunctionContextIndex(FI);
6360     return;
6361   }
6362   case Intrinsic::eh_sjlj_setjmp: {
6363     SDValue Ops[2];
6364     Ops[0] = getRoot();
6365     Ops[1] = getValue(I.getArgOperand(0));
6366     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6367                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6368     setValue(&I, Op.getValue(0));
6369     DAG.setRoot(Op.getValue(1));
6370     return;
6371   }
6372   case Intrinsic::eh_sjlj_longjmp:
6373     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6374                             getRoot(), getValue(I.getArgOperand(0))));
6375     return;
6376   case Intrinsic::eh_sjlj_setup_dispatch:
6377     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6378                             getRoot()));
6379     return;
6380   case Intrinsic::masked_gather:
6381     visitMaskedGather(I);
6382     return;
6383   case Intrinsic::masked_load:
6384     visitMaskedLoad(I);
6385     return;
6386   case Intrinsic::masked_scatter:
6387     visitMaskedScatter(I);
6388     return;
6389   case Intrinsic::masked_store:
6390     visitMaskedStore(I);
6391     return;
6392   case Intrinsic::masked_expandload:
6393     visitMaskedLoad(I, true /* IsExpanding */);
6394     return;
6395   case Intrinsic::masked_compressstore:
6396     visitMaskedStore(I, true /* IsCompressing */);
6397     return;
6398   case Intrinsic::powi:
6399     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6400                             getValue(I.getArgOperand(1)), DAG));
6401     return;
6402   case Intrinsic::log:
6403     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6404     return;
6405   case Intrinsic::log2:
6406     setValue(&I,
6407              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6408     return;
6409   case Intrinsic::log10:
6410     setValue(&I,
6411              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6412     return;
6413   case Intrinsic::exp:
6414     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6415     return;
6416   case Intrinsic::exp2:
6417     setValue(&I,
6418              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6419     return;
6420   case Intrinsic::pow:
6421     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6422                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6423     return;
6424   case Intrinsic::sqrt:
6425   case Intrinsic::fabs:
6426   case Intrinsic::sin:
6427   case Intrinsic::cos:
6428   case Intrinsic::exp10:
6429   case Intrinsic::floor:
6430   case Intrinsic::ceil:
6431   case Intrinsic::trunc:
6432   case Intrinsic::rint:
6433   case Intrinsic::nearbyint:
6434   case Intrinsic::round:
6435   case Intrinsic::roundeven:
6436   case Intrinsic::canonicalize: {
6437     unsigned Opcode;
6438     switch (Intrinsic) {
6439     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6440     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6441     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6442     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6443     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6444     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6445     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6446     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6447     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6448     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6449     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6450     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6451     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6452     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6453     }
6454 
6455     setValue(&I, DAG.getNode(Opcode, sdl,
6456                              getValue(I.getArgOperand(0)).getValueType(),
6457                              getValue(I.getArgOperand(0)), Flags));
6458     return;
6459   }
6460   case Intrinsic::lround:
6461   case Intrinsic::llround:
6462   case Intrinsic::lrint:
6463   case Intrinsic::llrint: {
6464     unsigned Opcode;
6465     switch (Intrinsic) {
6466     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6467     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6468     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6469     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6470     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6471     }
6472 
6473     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6474     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6475                              getValue(I.getArgOperand(0))));
6476     return;
6477   }
6478   case Intrinsic::minnum:
6479     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6480                              getValue(I.getArgOperand(0)).getValueType(),
6481                              getValue(I.getArgOperand(0)),
6482                              getValue(I.getArgOperand(1)), Flags));
6483     return;
6484   case Intrinsic::maxnum:
6485     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6486                              getValue(I.getArgOperand(0)).getValueType(),
6487                              getValue(I.getArgOperand(0)),
6488                              getValue(I.getArgOperand(1)), Flags));
6489     return;
6490   case Intrinsic::minimum:
6491     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6492                              getValue(I.getArgOperand(0)).getValueType(),
6493                              getValue(I.getArgOperand(0)),
6494                              getValue(I.getArgOperand(1)), Flags));
6495     return;
6496   case Intrinsic::maximum:
6497     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6498                              getValue(I.getArgOperand(0)).getValueType(),
6499                              getValue(I.getArgOperand(0)),
6500                              getValue(I.getArgOperand(1)), Flags));
6501     return;
6502   case Intrinsic::copysign:
6503     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6504                              getValue(I.getArgOperand(0)).getValueType(),
6505                              getValue(I.getArgOperand(0)),
6506                              getValue(I.getArgOperand(1)), Flags));
6507     return;
6508   case Intrinsic::ldexp:
6509     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6510                              getValue(I.getArgOperand(0)).getValueType(),
6511                              getValue(I.getArgOperand(0)),
6512                              getValue(I.getArgOperand(1)), Flags));
6513     return;
6514   case Intrinsic::frexp: {
6515     SmallVector<EVT, 2> ValueVTs;
6516     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6517     SDVTList VTs = DAG.getVTList(ValueVTs);
6518     setValue(&I,
6519              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6520     return;
6521   }
6522   case Intrinsic::arithmetic_fence: {
6523     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6524                              getValue(I.getArgOperand(0)).getValueType(),
6525                              getValue(I.getArgOperand(0)), Flags));
6526     return;
6527   }
6528   case Intrinsic::fma:
6529     setValue(&I, DAG.getNode(
6530                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6531                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6532                      getValue(I.getArgOperand(2)), Flags));
6533     return;
6534 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6535   case Intrinsic::INTRINSIC:
6536 #include "llvm/IR/ConstrainedOps.def"
6537     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6538     return;
6539 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6540 #include "llvm/IR/VPIntrinsics.def"
6541     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6542     return;
6543   case Intrinsic::fptrunc_round: {
6544     // Get the last argument, the metadata and convert it to an integer in the
6545     // call
6546     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6547     std::optional<RoundingMode> RoundMode =
6548         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6549 
6550     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6551 
6552     // Propagate fast-math-flags from IR to node(s).
6553     SDNodeFlags Flags;
6554     Flags.copyFMF(*cast<FPMathOperator>(&I));
6555     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6556 
6557     SDValue Result;
6558     Result = DAG.getNode(
6559         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6560         DAG.getTargetConstant((int)*RoundMode, sdl,
6561                               TLI.getPointerTy(DAG.getDataLayout())));
6562     setValue(&I, Result);
6563 
6564     return;
6565   }
6566   case Intrinsic::fmuladd: {
6567     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6568     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6569         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6570       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6571                                getValue(I.getArgOperand(0)).getValueType(),
6572                                getValue(I.getArgOperand(0)),
6573                                getValue(I.getArgOperand(1)),
6574                                getValue(I.getArgOperand(2)), Flags));
6575     } else {
6576       // TODO: Intrinsic calls should have fast-math-flags.
6577       SDValue Mul = DAG.getNode(
6578           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6579           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6580       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6581                                 getValue(I.getArgOperand(0)).getValueType(),
6582                                 Mul, getValue(I.getArgOperand(2)), Flags);
6583       setValue(&I, Add);
6584     }
6585     return;
6586   }
6587   case Intrinsic::convert_to_fp16:
6588     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6589                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6590                                          getValue(I.getArgOperand(0)),
6591                                          DAG.getTargetConstant(0, sdl,
6592                                                                MVT::i32))));
6593     return;
6594   case Intrinsic::convert_from_fp16:
6595     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6596                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6597                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6598                                          getValue(I.getArgOperand(0)))));
6599     return;
6600   case Intrinsic::fptosi_sat: {
6601     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6602     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6603                              getValue(I.getArgOperand(0)),
6604                              DAG.getValueType(VT.getScalarType())));
6605     return;
6606   }
6607   case Intrinsic::fptoui_sat: {
6608     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6609     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6610                              getValue(I.getArgOperand(0)),
6611                              DAG.getValueType(VT.getScalarType())));
6612     return;
6613   }
6614   case Intrinsic::set_rounding:
6615     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6616                       {getRoot(), getValue(I.getArgOperand(0))});
6617     setValue(&I, Res);
6618     DAG.setRoot(Res.getValue(0));
6619     return;
6620   case Intrinsic::is_fpclass: {
6621     const DataLayout DLayout = DAG.getDataLayout();
6622     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6623     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6624     FPClassTest Test = static_cast<FPClassTest>(
6625         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6626     MachineFunction &MF = DAG.getMachineFunction();
6627     const Function &F = MF.getFunction();
6628     SDValue Op = getValue(I.getArgOperand(0));
6629     SDNodeFlags Flags;
6630     Flags.setNoFPExcept(
6631         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6632     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6633     // expansion can use illegal types. Making expansion early allows
6634     // legalizing these types prior to selection.
6635     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6636       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6637       setValue(&I, Result);
6638       return;
6639     }
6640 
6641     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6642     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6643     setValue(&I, V);
6644     return;
6645   }
6646   case Intrinsic::get_fpenv: {
6647     const DataLayout DLayout = DAG.getDataLayout();
6648     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6649     Align TempAlign = DAG.getEVTAlign(EnvVT);
6650     SDValue Chain = getRoot();
6651     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6652     // and temporary storage in stack.
6653     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6654       Res = DAG.getNode(
6655           ISD::GET_FPENV, sdl,
6656           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6657                         MVT::Other),
6658           Chain);
6659     } else {
6660       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6661       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6662       auto MPI =
6663           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6664       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6665           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6666           TempAlign);
6667       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6668       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6669     }
6670     setValue(&I, Res);
6671     DAG.setRoot(Res.getValue(1));
6672     return;
6673   }
6674   case Intrinsic::set_fpenv: {
6675     const DataLayout DLayout = DAG.getDataLayout();
6676     SDValue Env = getValue(I.getArgOperand(0));
6677     EVT EnvVT = Env.getValueType();
6678     Align TempAlign = DAG.getEVTAlign(EnvVT);
6679     SDValue Chain = getRoot();
6680     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6681     // environment from memory.
6682     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6683       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6684     } else {
6685       // Allocate space in stack, copy environment bits into it and use this
6686       // memory in SET_FPENV_MEM.
6687       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6688       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6689       auto MPI =
6690           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6691       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6692                            MachineMemOperand::MOStore);
6693       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6694           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6695           TempAlign);
6696       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6697     }
6698     DAG.setRoot(Chain);
6699     return;
6700   }
6701   case Intrinsic::reset_fpenv:
6702     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6703     return;
6704   case Intrinsic::get_fpmode:
6705     Res = DAG.getNode(
6706         ISD::GET_FPMODE, sdl,
6707         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6708                       MVT::Other),
6709         DAG.getRoot());
6710     setValue(&I, Res);
6711     DAG.setRoot(Res.getValue(1));
6712     return;
6713   case Intrinsic::set_fpmode:
6714     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6715                       getValue(I.getArgOperand(0)));
6716     DAG.setRoot(Res);
6717     return;
6718   case Intrinsic::reset_fpmode: {
6719     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6720     DAG.setRoot(Res);
6721     return;
6722   }
6723   case Intrinsic::pcmarker: {
6724     SDValue Tmp = getValue(I.getArgOperand(0));
6725     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6726     return;
6727   }
6728   case Intrinsic::readcyclecounter: {
6729     SDValue Op = getRoot();
6730     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6731                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6732     setValue(&I, Res);
6733     DAG.setRoot(Res.getValue(1));
6734     return;
6735   }
6736   case Intrinsic::bitreverse:
6737     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6738                              getValue(I.getArgOperand(0)).getValueType(),
6739                              getValue(I.getArgOperand(0))));
6740     return;
6741   case Intrinsic::bswap:
6742     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6743                              getValue(I.getArgOperand(0)).getValueType(),
6744                              getValue(I.getArgOperand(0))));
6745     return;
6746   case Intrinsic::cttz: {
6747     SDValue Arg = getValue(I.getArgOperand(0));
6748     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6749     EVT Ty = Arg.getValueType();
6750     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6751                              sdl, Ty, Arg));
6752     return;
6753   }
6754   case Intrinsic::ctlz: {
6755     SDValue Arg = getValue(I.getArgOperand(0));
6756     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6757     EVT Ty = Arg.getValueType();
6758     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6759                              sdl, Ty, Arg));
6760     return;
6761   }
6762   case Intrinsic::ctpop: {
6763     SDValue Arg = getValue(I.getArgOperand(0));
6764     EVT Ty = Arg.getValueType();
6765     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6766     return;
6767   }
6768   case Intrinsic::fshl:
6769   case Intrinsic::fshr: {
6770     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6771     SDValue X = getValue(I.getArgOperand(0));
6772     SDValue Y = getValue(I.getArgOperand(1));
6773     SDValue Z = getValue(I.getArgOperand(2));
6774     EVT VT = X.getValueType();
6775 
6776     if (X == Y) {
6777       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6778       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6779     } else {
6780       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6781       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6782     }
6783     return;
6784   }
6785   case Intrinsic::sadd_sat: {
6786     SDValue Op1 = getValue(I.getArgOperand(0));
6787     SDValue Op2 = getValue(I.getArgOperand(1));
6788     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6789     return;
6790   }
6791   case Intrinsic::uadd_sat: {
6792     SDValue Op1 = getValue(I.getArgOperand(0));
6793     SDValue Op2 = getValue(I.getArgOperand(1));
6794     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6795     return;
6796   }
6797   case Intrinsic::ssub_sat: {
6798     SDValue Op1 = getValue(I.getArgOperand(0));
6799     SDValue Op2 = getValue(I.getArgOperand(1));
6800     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6801     return;
6802   }
6803   case Intrinsic::usub_sat: {
6804     SDValue Op1 = getValue(I.getArgOperand(0));
6805     SDValue Op2 = getValue(I.getArgOperand(1));
6806     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6807     return;
6808   }
6809   case Intrinsic::sshl_sat: {
6810     SDValue Op1 = getValue(I.getArgOperand(0));
6811     SDValue Op2 = getValue(I.getArgOperand(1));
6812     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6813     return;
6814   }
6815   case Intrinsic::ushl_sat: {
6816     SDValue Op1 = getValue(I.getArgOperand(0));
6817     SDValue Op2 = getValue(I.getArgOperand(1));
6818     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6819     return;
6820   }
6821   case Intrinsic::smul_fix:
6822   case Intrinsic::umul_fix:
6823   case Intrinsic::smul_fix_sat:
6824   case Intrinsic::umul_fix_sat: {
6825     SDValue Op1 = getValue(I.getArgOperand(0));
6826     SDValue Op2 = getValue(I.getArgOperand(1));
6827     SDValue Op3 = getValue(I.getArgOperand(2));
6828     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6829                              Op1.getValueType(), Op1, Op2, Op3));
6830     return;
6831   }
6832   case Intrinsic::sdiv_fix:
6833   case Intrinsic::udiv_fix:
6834   case Intrinsic::sdiv_fix_sat:
6835   case Intrinsic::udiv_fix_sat: {
6836     SDValue Op1 = getValue(I.getArgOperand(0));
6837     SDValue Op2 = getValue(I.getArgOperand(1));
6838     SDValue Op3 = getValue(I.getArgOperand(2));
6839     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6840                               Op1, Op2, Op3, DAG, TLI));
6841     return;
6842   }
6843   case Intrinsic::smax: {
6844     SDValue Op1 = getValue(I.getArgOperand(0));
6845     SDValue Op2 = getValue(I.getArgOperand(1));
6846     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6847     return;
6848   }
6849   case Intrinsic::smin: {
6850     SDValue Op1 = getValue(I.getArgOperand(0));
6851     SDValue Op2 = getValue(I.getArgOperand(1));
6852     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6853     return;
6854   }
6855   case Intrinsic::umax: {
6856     SDValue Op1 = getValue(I.getArgOperand(0));
6857     SDValue Op2 = getValue(I.getArgOperand(1));
6858     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6859     return;
6860   }
6861   case Intrinsic::umin: {
6862     SDValue Op1 = getValue(I.getArgOperand(0));
6863     SDValue Op2 = getValue(I.getArgOperand(1));
6864     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6865     return;
6866   }
6867   case Intrinsic::abs: {
6868     // TODO: Preserve "int min is poison" arg in SDAG?
6869     SDValue Op1 = getValue(I.getArgOperand(0));
6870     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6871     return;
6872   }
6873   case Intrinsic::stacksave: {
6874     SDValue Op = getRoot();
6875     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6876     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6877     setValue(&I, Res);
6878     DAG.setRoot(Res.getValue(1));
6879     return;
6880   }
6881   case Intrinsic::stackrestore:
6882     Res = getValue(I.getArgOperand(0));
6883     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6884     return;
6885   case Intrinsic::get_dynamic_area_offset: {
6886     SDValue Op = getRoot();
6887     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6888     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6889     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6890     // target.
6891     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6892       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6893                          " intrinsic!");
6894     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6895                       Op);
6896     DAG.setRoot(Op);
6897     setValue(&I, Res);
6898     return;
6899   }
6900   case Intrinsic::stackguard: {
6901     MachineFunction &MF = DAG.getMachineFunction();
6902     const Module &M = *MF.getFunction().getParent();
6903     SDValue Chain = getRoot();
6904     if (TLI.useLoadStackGuardNode()) {
6905       Res = getLoadStackGuard(DAG, sdl, Chain);
6906     } else {
6907       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6908       const Value *Global = TLI.getSDagStackGuard(M);
6909       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6910       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6911                         MachinePointerInfo(Global, 0), Align,
6912                         MachineMemOperand::MOVolatile);
6913     }
6914     if (TLI.useStackGuardXorFP())
6915       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6916     DAG.setRoot(Chain);
6917     setValue(&I, Res);
6918     return;
6919   }
6920   case Intrinsic::stackprotector: {
6921     // Emit code into the DAG to store the stack guard onto the stack.
6922     MachineFunction &MF = DAG.getMachineFunction();
6923     MachineFrameInfo &MFI = MF.getFrameInfo();
6924     SDValue Src, Chain = getRoot();
6925 
6926     if (TLI.useLoadStackGuardNode())
6927       Src = getLoadStackGuard(DAG, sdl, Chain);
6928     else
6929       Src = getValue(I.getArgOperand(0));   // The guard's value.
6930 
6931     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6932 
6933     int FI = FuncInfo.StaticAllocaMap[Slot];
6934     MFI.setStackProtectorIndex(FI);
6935     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6936 
6937     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6938 
6939     // Store the stack protector onto the stack.
6940     Res = DAG.getStore(
6941         Chain, sdl, Src, FIN,
6942         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6943         MaybeAlign(), MachineMemOperand::MOVolatile);
6944     setValue(&I, Res);
6945     DAG.setRoot(Res);
6946     return;
6947   }
6948   case Intrinsic::objectsize:
6949     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6950 
6951   case Intrinsic::is_constant:
6952     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6953 
6954   case Intrinsic::annotation:
6955   case Intrinsic::ptr_annotation:
6956   case Intrinsic::launder_invariant_group:
6957   case Intrinsic::strip_invariant_group:
6958     // Drop the intrinsic, but forward the value
6959     setValue(&I, getValue(I.getOperand(0)));
6960     return;
6961 
6962   case Intrinsic::assume:
6963   case Intrinsic::experimental_noalias_scope_decl:
6964   case Intrinsic::var_annotation:
6965   case Intrinsic::sideeffect:
6966     // Discard annotate attributes, noalias scope declarations, assumptions, and
6967     // artificial side-effects.
6968     return;
6969 
6970   case Intrinsic::codeview_annotation: {
6971     // Emit a label associated with this metadata.
6972     MachineFunction &MF = DAG.getMachineFunction();
6973     MCSymbol *Label =
6974         MF.getMMI().getContext().createTempSymbol("annotation", true);
6975     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6976     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6977     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6978     DAG.setRoot(Res);
6979     return;
6980   }
6981 
6982   case Intrinsic::init_trampoline: {
6983     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6984 
6985     SDValue Ops[6];
6986     Ops[0] = getRoot();
6987     Ops[1] = getValue(I.getArgOperand(0));
6988     Ops[2] = getValue(I.getArgOperand(1));
6989     Ops[3] = getValue(I.getArgOperand(2));
6990     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6991     Ops[5] = DAG.getSrcValue(F);
6992 
6993     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6994 
6995     DAG.setRoot(Res);
6996     return;
6997   }
6998   case Intrinsic::adjust_trampoline:
6999     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7000                              TLI.getPointerTy(DAG.getDataLayout()),
7001                              getValue(I.getArgOperand(0))));
7002     return;
7003   case Intrinsic::gcroot: {
7004     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7005            "only valid in functions with gc specified, enforced by Verifier");
7006     assert(GFI && "implied by previous");
7007     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7008     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7009 
7010     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7011     GFI->addStackRoot(FI->getIndex(), TypeMap);
7012     return;
7013   }
7014   case Intrinsic::gcread:
7015   case Intrinsic::gcwrite:
7016     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7017   case Intrinsic::get_rounding:
7018     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7019     setValue(&I, Res);
7020     DAG.setRoot(Res.getValue(1));
7021     return;
7022 
7023   case Intrinsic::expect:
7024     // Just replace __builtin_expect(exp, c) with EXP.
7025     setValue(&I, getValue(I.getArgOperand(0)));
7026     return;
7027 
7028   case Intrinsic::ubsantrap:
7029   case Intrinsic::debugtrap:
7030   case Intrinsic::trap: {
7031     StringRef TrapFuncName =
7032         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7033     if (TrapFuncName.empty()) {
7034       switch (Intrinsic) {
7035       case Intrinsic::trap:
7036         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7037         break;
7038       case Intrinsic::debugtrap:
7039         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7040         break;
7041       case Intrinsic::ubsantrap:
7042         DAG.setRoot(DAG.getNode(
7043             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7044             DAG.getTargetConstant(
7045                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7046                 MVT::i32)));
7047         break;
7048       default: llvm_unreachable("unknown trap intrinsic");
7049       }
7050       return;
7051     }
7052     TargetLowering::ArgListTy Args;
7053     if (Intrinsic == Intrinsic::ubsantrap) {
7054       Args.push_back(TargetLoweringBase::ArgListEntry());
7055       Args[0].Val = I.getArgOperand(0);
7056       Args[0].Node = getValue(Args[0].Val);
7057       Args[0].Ty = Args[0].Val->getType();
7058     }
7059 
7060     TargetLowering::CallLoweringInfo CLI(DAG);
7061     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7062         CallingConv::C, I.getType(),
7063         DAG.getExternalSymbol(TrapFuncName.data(),
7064                               TLI.getPointerTy(DAG.getDataLayout())),
7065         std::move(Args));
7066 
7067     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7068     DAG.setRoot(Result.second);
7069     return;
7070   }
7071 
7072   case Intrinsic::uadd_with_overflow:
7073   case Intrinsic::sadd_with_overflow:
7074   case Intrinsic::usub_with_overflow:
7075   case Intrinsic::ssub_with_overflow:
7076   case Intrinsic::umul_with_overflow:
7077   case Intrinsic::smul_with_overflow: {
7078     ISD::NodeType Op;
7079     switch (Intrinsic) {
7080     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7081     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7082     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7083     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7084     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7085     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7086     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7087     }
7088     SDValue Op1 = getValue(I.getArgOperand(0));
7089     SDValue Op2 = getValue(I.getArgOperand(1));
7090 
7091     EVT ResultVT = Op1.getValueType();
7092     EVT OverflowVT = MVT::i1;
7093     if (ResultVT.isVector())
7094       OverflowVT = EVT::getVectorVT(
7095           *Context, OverflowVT, ResultVT.getVectorElementCount());
7096 
7097     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7098     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7099     return;
7100   }
7101   case Intrinsic::prefetch: {
7102     SDValue Ops[5];
7103     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7104     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7105     Ops[0] = DAG.getRoot();
7106     Ops[1] = getValue(I.getArgOperand(0));
7107     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7108                                    MVT::i32);
7109     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7110                                    MVT::i32);
7111     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7112                                    MVT::i32);
7113     SDValue Result = DAG.getMemIntrinsicNode(
7114         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7115         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7116         /* align */ std::nullopt, Flags);
7117 
7118     // Chain the prefetch in parallell with any pending loads, to stay out of
7119     // the way of later optimizations.
7120     PendingLoads.push_back(Result);
7121     Result = getRoot();
7122     DAG.setRoot(Result);
7123     return;
7124   }
7125   case Intrinsic::lifetime_start:
7126   case Intrinsic::lifetime_end: {
7127     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7128     // Stack coloring is not enabled in O0, discard region information.
7129     if (TM.getOptLevel() == CodeGenOptLevel::None)
7130       return;
7131 
7132     const int64_t ObjectSize =
7133         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7134     Value *const ObjectPtr = I.getArgOperand(1);
7135     SmallVector<const Value *, 4> Allocas;
7136     getUnderlyingObjects(ObjectPtr, Allocas);
7137 
7138     for (const Value *Alloca : Allocas) {
7139       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7140 
7141       // Could not find an Alloca.
7142       if (!LifetimeObject)
7143         continue;
7144 
7145       // First check that the Alloca is static, otherwise it won't have a
7146       // valid frame index.
7147       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7148       if (SI == FuncInfo.StaticAllocaMap.end())
7149         return;
7150 
7151       const int FrameIndex = SI->second;
7152       int64_t Offset;
7153       if (GetPointerBaseWithConstantOffset(
7154               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7155         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7156       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7157                                 Offset);
7158       DAG.setRoot(Res);
7159     }
7160     return;
7161   }
7162   case Intrinsic::pseudoprobe: {
7163     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7164     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7165     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7166     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7167     DAG.setRoot(Res);
7168     return;
7169   }
7170   case Intrinsic::invariant_start:
7171     // Discard region information.
7172     setValue(&I,
7173              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7174     return;
7175   case Intrinsic::invariant_end:
7176     // Discard region information.
7177     return;
7178   case Intrinsic::clear_cache:
7179     /// FunctionName may be null.
7180     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7181       lowerCallToExternalSymbol(I, FunctionName);
7182     return;
7183   case Intrinsic::donothing:
7184   case Intrinsic::seh_try_begin:
7185   case Intrinsic::seh_scope_begin:
7186   case Intrinsic::seh_try_end:
7187   case Intrinsic::seh_scope_end:
7188     // ignore
7189     return;
7190   case Intrinsic::experimental_stackmap:
7191     visitStackmap(I);
7192     return;
7193   case Intrinsic::experimental_patchpoint_void:
7194   case Intrinsic::experimental_patchpoint_i64:
7195     visitPatchpoint(I);
7196     return;
7197   case Intrinsic::experimental_gc_statepoint:
7198     LowerStatepoint(cast<GCStatepointInst>(I));
7199     return;
7200   case Intrinsic::experimental_gc_result:
7201     visitGCResult(cast<GCResultInst>(I));
7202     return;
7203   case Intrinsic::experimental_gc_relocate:
7204     visitGCRelocate(cast<GCRelocateInst>(I));
7205     return;
7206   case Intrinsic::instrprof_cover:
7207     llvm_unreachable("instrprof failed to lower a cover");
7208   case Intrinsic::instrprof_increment:
7209     llvm_unreachable("instrprof failed to lower an increment");
7210   case Intrinsic::instrprof_timestamp:
7211     llvm_unreachable("instrprof failed to lower a timestamp");
7212   case Intrinsic::instrprof_value_profile:
7213     llvm_unreachable("instrprof failed to lower a value profiling call");
7214   case Intrinsic::instrprof_mcdc_parameters:
7215     llvm_unreachable("instrprof failed to lower mcdc parameters");
7216   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7217     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7218   case Intrinsic::instrprof_mcdc_condbitmap_update:
7219     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7220   case Intrinsic::localescape: {
7221     MachineFunction &MF = DAG.getMachineFunction();
7222     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7223 
7224     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7225     // is the same on all targets.
7226     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7227       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7228       if (isa<ConstantPointerNull>(Arg))
7229         continue; // Skip null pointers. They represent a hole in index space.
7230       AllocaInst *Slot = cast<AllocaInst>(Arg);
7231       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7232              "can only escape static allocas");
7233       int FI = FuncInfo.StaticAllocaMap[Slot];
7234       MCSymbol *FrameAllocSym =
7235           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7236               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7237       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7238               TII->get(TargetOpcode::LOCAL_ESCAPE))
7239           .addSym(FrameAllocSym)
7240           .addFrameIndex(FI);
7241     }
7242 
7243     return;
7244   }
7245 
7246   case Intrinsic::localrecover: {
7247     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7248     MachineFunction &MF = DAG.getMachineFunction();
7249 
7250     // Get the symbol that defines the frame offset.
7251     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7252     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7253     unsigned IdxVal =
7254         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7255     MCSymbol *FrameAllocSym =
7256         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7257             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7258 
7259     Value *FP = I.getArgOperand(1);
7260     SDValue FPVal = getValue(FP);
7261     EVT PtrVT = FPVal.getValueType();
7262 
7263     // Create a MCSymbol for the label to avoid any target lowering
7264     // that would make this PC relative.
7265     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7266     SDValue OffsetVal =
7267         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7268 
7269     // Add the offset to the FP.
7270     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7271     setValue(&I, Add);
7272 
7273     return;
7274   }
7275 
7276   case Intrinsic::eh_exceptionpointer:
7277   case Intrinsic::eh_exceptioncode: {
7278     // Get the exception pointer vreg, copy from it, and resize it to fit.
7279     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7280     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7281     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7282     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7283     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7284     if (Intrinsic == Intrinsic::eh_exceptioncode)
7285       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7286     setValue(&I, N);
7287     return;
7288   }
7289   case Intrinsic::xray_customevent: {
7290     // Here we want to make sure that the intrinsic behaves as if it has a
7291     // specific calling convention.
7292     const auto &Triple = DAG.getTarget().getTargetTriple();
7293     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7294       return;
7295 
7296     SmallVector<SDValue, 8> Ops;
7297 
7298     // We want to say that we always want the arguments in registers.
7299     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7300     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7301     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7302     SDValue Chain = getRoot();
7303     Ops.push_back(LogEntryVal);
7304     Ops.push_back(StrSizeVal);
7305     Ops.push_back(Chain);
7306 
7307     // We need to enforce the calling convention for the callsite, so that
7308     // argument ordering is enforced correctly, and that register allocation can
7309     // see that some registers may be assumed clobbered and have to preserve
7310     // them across calls to the intrinsic.
7311     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7312                                            sdl, NodeTys, Ops);
7313     SDValue patchableNode = SDValue(MN, 0);
7314     DAG.setRoot(patchableNode);
7315     setValue(&I, patchableNode);
7316     return;
7317   }
7318   case Intrinsic::xray_typedevent: {
7319     // Here we want to make sure that the intrinsic behaves as if it has a
7320     // specific calling convention.
7321     const auto &Triple = DAG.getTarget().getTargetTriple();
7322     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7323       return;
7324 
7325     SmallVector<SDValue, 8> Ops;
7326 
7327     // We want to say that we always want the arguments in registers.
7328     // It's unclear to me how manipulating the selection DAG here forces callers
7329     // to provide arguments in registers instead of on the stack.
7330     SDValue LogTypeId = getValue(I.getArgOperand(0));
7331     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7332     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7333     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7334     SDValue Chain = getRoot();
7335     Ops.push_back(LogTypeId);
7336     Ops.push_back(LogEntryVal);
7337     Ops.push_back(StrSizeVal);
7338     Ops.push_back(Chain);
7339 
7340     // We need to enforce the calling convention for the callsite, so that
7341     // argument ordering is enforced correctly, and that register allocation can
7342     // see that some registers may be assumed clobbered and have to preserve
7343     // them across calls to the intrinsic.
7344     MachineSDNode *MN = DAG.getMachineNode(
7345         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7346     SDValue patchableNode = SDValue(MN, 0);
7347     DAG.setRoot(patchableNode);
7348     setValue(&I, patchableNode);
7349     return;
7350   }
7351   case Intrinsic::experimental_deoptimize:
7352     LowerDeoptimizeCall(&I);
7353     return;
7354   case Intrinsic::experimental_stepvector:
7355     visitStepVector(I);
7356     return;
7357   case Intrinsic::vector_reduce_fadd:
7358   case Intrinsic::vector_reduce_fmul:
7359   case Intrinsic::vector_reduce_add:
7360   case Intrinsic::vector_reduce_mul:
7361   case Intrinsic::vector_reduce_and:
7362   case Intrinsic::vector_reduce_or:
7363   case Intrinsic::vector_reduce_xor:
7364   case Intrinsic::vector_reduce_smax:
7365   case Intrinsic::vector_reduce_smin:
7366   case Intrinsic::vector_reduce_umax:
7367   case Intrinsic::vector_reduce_umin:
7368   case Intrinsic::vector_reduce_fmax:
7369   case Intrinsic::vector_reduce_fmin:
7370   case Intrinsic::vector_reduce_fmaximum:
7371   case Intrinsic::vector_reduce_fminimum:
7372     visitVectorReduce(I, Intrinsic);
7373     return;
7374 
7375   case Intrinsic::icall_branch_funnel: {
7376     SmallVector<SDValue, 16> Ops;
7377     Ops.push_back(getValue(I.getArgOperand(0)));
7378 
7379     int64_t Offset;
7380     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7381         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7382     if (!Base)
7383       report_fatal_error(
7384           "llvm.icall.branch.funnel operand must be a GlobalValue");
7385     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7386 
7387     struct BranchFunnelTarget {
7388       int64_t Offset;
7389       SDValue Target;
7390     };
7391     SmallVector<BranchFunnelTarget, 8> Targets;
7392 
7393     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7394       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7395           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7396       if (ElemBase != Base)
7397         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7398                            "to the same GlobalValue");
7399 
7400       SDValue Val = getValue(I.getArgOperand(Op + 1));
7401       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7402       if (!GA)
7403         report_fatal_error(
7404             "llvm.icall.branch.funnel operand must be a GlobalValue");
7405       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7406                                      GA->getGlobal(), sdl, Val.getValueType(),
7407                                      GA->getOffset())});
7408     }
7409     llvm::sort(Targets,
7410                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7411                  return T1.Offset < T2.Offset;
7412                });
7413 
7414     for (auto &T : Targets) {
7415       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7416       Ops.push_back(T.Target);
7417     }
7418 
7419     Ops.push_back(DAG.getRoot()); // Chain
7420     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7421                                  MVT::Other, Ops),
7422               0);
7423     DAG.setRoot(N);
7424     setValue(&I, N);
7425     HasTailCall = true;
7426     return;
7427   }
7428 
7429   case Intrinsic::wasm_landingpad_index:
7430     // Information this intrinsic contained has been transferred to
7431     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7432     // delete it now.
7433     return;
7434 
7435   case Intrinsic::aarch64_settag:
7436   case Intrinsic::aarch64_settag_zero: {
7437     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7438     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7439     SDValue Val = TSI.EmitTargetCodeForSetTag(
7440         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7441         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7442         ZeroMemory);
7443     DAG.setRoot(Val);
7444     setValue(&I, Val);
7445     return;
7446   }
7447   case Intrinsic::ptrmask: {
7448     SDValue Ptr = getValue(I.getOperand(0));
7449     SDValue Mask = getValue(I.getOperand(1));
7450 
7451     EVT PtrVT = Ptr.getValueType();
7452     assert(PtrVT == Mask.getValueType() &&
7453            "Pointers with different index type are not supported by SDAG");
7454     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7455     return;
7456   }
7457   case Intrinsic::threadlocal_address: {
7458     setValue(&I, getValue(I.getOperand(0)));
7459     return;
7460   }
7461   case Intrinsic::get_active_lane_mask: {
7462     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7463     SDValue Index = getValue(I.getOperand(0));
7464     EVT ElementVT = Index.getValueType();
7465 
7466     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7467       visitTargetIntrinsic(I, Intrinsic);
7468       return;
7469     }
7470 
7471     SDValue TripCount = getValue(I.getOperand(1));
7472     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7473                                  CCVT.getVectorElementCount());
7474 
7475     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7476     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7477     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7478     SDValue VectorInduction = DAG.getNode(
7479         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7480     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7481                                  VectorTripCount, ISD::CondCode::SETULT);
7482     setValue(&I, SetCC);
7483     return;
7484   }
7485   case Intrinsic::experimental_get_vector_length: {
7486     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7487            "Expected positive VF");
7488     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7489     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7490 
7491     SDValue Count = getValue(I.getOperand(0));
7492     EVT CountVT = Count.getValueType();
7493 
7494     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7495       visitTargetIntrinsic(I, Intrinsic);
7496       return;
7497     }
7498 
7499     // Expand to a umin between the trip count and the maximum elements the type
7500     // can hold.
7501     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7502 
7503     // Extend the trip count to at least the result VT.
7504     if (CountVT.bitsLT(VT)) {
7505       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7506       CountVT = VT;
7507     }
7508 
7509     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7510                                          ElementCount::get(VF, IsScalable));
7511 
7512     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7513     // Clip to the result type if needed.
7514     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7515 
7516     setValue(&I, Trunc);
7517     return;
7518   }
7519   case Intrinsic::experimental_cttz_elts: {
7520     auto DL = getCurSDLoc();
7521     SDValue Op = getValue(I.getOperand(0));
7522     EVT OpVT = Op.getValueType();
7523 
7524     if (!TLI.shouldExpandCttzElements(OpVT)) {
7525       visitTargetIntrinsic(I, Intrinsic);
7526       return;
7527     }
7528 
7529     if (OpVT.getScalarType() != MVT::i1) {
7530       // Compare the input vector elements to zero & use to count trailing zeros
7531       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7532       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7533                               OpVT.getVectorElementCount());
7534       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7535     }
7536 
7537     // Find the smallest "sensible" element type to use for the expansion.
7538     ConstantRange CR(
7539         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7540     if (OpVT.isScalableVT())
7541       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7542 
7543     // If the zero-is-poison flag is set, we can assume the upper limit
7544     // of the result is VF-1.
7545     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7546       CR = CR.subtract(APInt(64, 1));
7547 
7548     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7549     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7550     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7551 
7552     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7553 
7554     // Create the new vector type & get the vector length
7555     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7556                                  OpVT.getVectorElementCount());
7557 
7558     SDValue VL =
7559         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7560 
7561     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7562     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7563     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7564     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7565     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7566     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7567     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7568 
7569     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7570     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7571 
7572     setValue(&I, Ret);
7573     return;
7574   }
7575   case Intrinsic::vector_insert: {
7576     SDValue Vec = getValue(I.getOperand(0));
7577     SDValue SubVec = getValue(I.getOperand(1));
7578     SDValue Index = getValue(I.getOperand(2));
7579 
7580     // The intrinsic's index type is i64, but the SDNode requires an index type
7581     // suitable for the target. Convert the index as required.
7582     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7583     if (Index.getValueType() != VectorIdxTy)
7584       Index = DAG.getVectorIdxConstant(
7585           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7586 
7587     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7588     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7589                              Index));
7590     return;
7591   }
7592   case Intrinsic::vector_extract: {
7593     SDValue Vec = getValue(I.getOperand(0));
7594     SDValue Index = getValue(I.getOperand(1));
7595     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7596 
7597     // The intrinsic's index type is i64, but the SDNode requires an index type
7598     // suitable for the target. Convert the index as required.
7599     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7600     if (Index.getValueType() != VectorIdxTy)
7601       Index = DAG.getVectorIdxConstant(
7602           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7603 
7604     setValue(&I,
7605              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7606     return;
7607   }
7608   case Intrinsic::experimental_vector_reverse:
7609     visitVectorReverse(I);
7610     return;
7611   case Intrinsic::experimental_vector_splice:
7612     visitVectorSplice(I);
7613     return;
7614   case Intrinsic::callbr_landingpad:
7615     visitCallBrLandingPad(I);
7616     return;
7617   case Intrinsic::experimental_vector_interleave2:
7618     visitVectorInterleave(I);
7619     return;
7620   case Intrinsic::experimental_vector_deinterleave2:
7621     visitVectorDeinterleave(I);
7622     return;
7623   }
7624 }
7625 
7626 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7627     const ConstrainedFPIntrinsic &FPI) {
7628   SDLoc sdl = getCurSDLoc();
7629 
7630   // We do not need to serialize constrained FP intrinsics against
7631   // each other or against (nonvolatile) loads, so they can be
7632   // chained like loads.
7633   SDValue Chain = DAG.getRoot();
7634   SmallVector<SDValue, 4> Opers;
7635   Opers.push_back(Chain);
7636   if (FPI.isUnaryOp()) {
7637     Opers.push_back(getValue(FPI.getArgOperand(0)));
7638   } else if (FPI.isTernaryOp()) {
7639     Opers.push_back(getValue(FPI.getArgOperand(0)));
7640     Opers.push_back(getValue(FPI.getArgOperand(1)));
7641     Opers.push_back(getValue(FPI.getArgOperand(2)));
7642   } else {
7643     Opers.push_back(getValue(FPI.getArgOperand(0)));
7644     Opers.push_back(getValue(FPI.getArgOperand(1)));
7645   }
7646 
7647   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7648     assert(Result.getNode()->getNumValues() == 2);
7649 
7650     // Push node to the appropriate list so that future instructions can be
7651     // chained up correctly.
7652     SDValue OutChain = Result.getValue(1);
7653     switch (EB) {
7654     case fp::ExceptionBehavior::ebIgnore:
7655       // The only reason why ebIgnore nodes still need to be chained is that
7656       // they might depend on the current rounding mode, and therefore must
7657       // not be moved across instruction that may change that mode.
7658       [[fallthrough]];
7659     case fp::ExceptionBehavior::ebMayTrap:
7660       // These must not be moved across calls or instructions that may change
7661       // floating-point exception masks.
7662       PendingConstrainedFP.push_back(OutChain);
7663       break;
7664     case fp::ExceptionBehavior::ebStrict:
7665       // These must not be moved across calls or instructions that may change
7666       // floating-point exception masks or read floating-point exception flags.
7667       // In addition, they cannot be optimized out even if unused.
7668       PendingConstrainedFPStrict.push_back(OutChain);
7669       break;
7670     }
7671   };
7672 
7673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7674   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7675   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7676   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7677 
7678   SDNodeFlags Flags;
7679   if (EB == fp::ExceptionBehavior::ebIgnore)
7680     Flags.setNoFPExcept(true);
7681 
7682   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7683     Flags.copyFMF(*FPOp);
7684 
7685   unsigned Opcode;
7686   switch (FPI.getIntrinsicID()) {
7687   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7688 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7689   case Intrinsic::INTRINSIC:                                                   \
7690     Opcode = ISD::STRICT_##DAGN;                                               \
7691     break;
7692 #include "llvm/IR/ConstrainedOps.def"
7693   case Intrinsic::experimental_constrained_fmuladd: {
7694     Opcode = ISD::STRICT_FMA;
7695     // Break fmuladd into fmul and fadd.
7696     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7697         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7698       Opers.pop_back();
7699       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7700       pushOutChain(Mul, EB);
7701       Opcode = ISD::STRICT_FADD;
7702       Opers.clear();
7703       Opers.push_back(Mul.getValue(1));
7704       Opers.push_back(Mul.getValue(0));
7705       Opers.push_back(getValue(FPI.getArgOperand(2)));
7706     }
7707     break;
7708   }
7709   }
7710 
7711   // A few strict DAG nodes carry additional operands that are not
7712   // set up by the default code above.
7713   switch (Opcode) {
7714   default: break;
7715   case ISD::STRICT_FP_ROUND:
7716     Opers.push_back(
7717         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7718     break;
7719   case ISD::STRICT_FSETCC:
7720   case ISD::STRICT_FSETCCS: {
7721     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7722     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7723     if (TM.Options.NoNaNsFPMath)
7724       Condition = getFCmpCodeWithoutNaN(Condition);
7725     Opers.push_back(DAG.getCondCode(Condition));
7726     break;
7727   }
7728   }
7729 
7730   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7731   pushOutChain(Result, EB);
7732 
7733   SDValue FPResult = Result.getValue(0);
7734   setValue(&FPI, FPResult);
7735 }
7736 
7737 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7738   std::optional<unsigned> ResOPC;
7739   switch (VPIntrin.getIntrinsicID()) {
7740   case Intrinsic::vp_ctlz: {
7741     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7742     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7743     break;
7744   }
7745   case Intrinsic::vp_cttz: {
7746     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7747     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7748     break;
7749   }
7750 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7751   case Intrinsic::VPID:                                                        \
7752     ResOPC = ISD::VPSD;                                                        \
7753     break;
7754 #include "llvm/IR/VPIntrinsics.def"
7755   }
7756 
7757   if (!ResOPC)
7758     llvm_unreachable(
7759         "Inconsistency: no SDNode available for this VPIntrinsic!");
7760 
7761   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7762       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7763     if (VPIntrin.getFastMathFlags().allowReassoc())
7764       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7765                                                 : ISD::VP_REDUCE_FMUL;
7766   }
7767 
7768   return *ResOPC;
7769 }
7770 
7771 void SelectionDAGBuilder::visitVPLoad(
7772     const VPIntrinsic &VPIntrin, EVT VT,
7773     const SmallVectorImpl<SDValue> &OpValues) {
7774   SDLoc DL = getCurSDLoc();
7775   Value *PtrOperand = VPIntrin.getArgOperand(0);
7776   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7777   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7778   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7779   SDValue LD;
7780   // Do not serialize variable-length loads of constant memory with
7781   // anything.
7782   if (!Alignment)
7783     Alignment = DAG.getEVTAlign(VT);
7784   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7785   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7786   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7787   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7788       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7789       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7790   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7791                      MMO, false /*IsExpanding */);
7792   if (AddToChain)
7793     PendingLoads.push_back(LD.getValue(1));
7794   setValue(&VPIntrin, LD);
7795 }
7796 
7797 void SelectionDAGBuilder::visitVPGather(
7798     const VPIntrinsic &VPIntrin, EVT VT,
7799     const SmallVectorImpl<SDValue> &OpValues) {
7800   SDLoc DL = getCurSDLoc();
7801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7802   Value *PtrOperand = VPIntrin.getArgOperand(0);
7803   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7804   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7805   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7806   SDValue LD;
7807   if (!Alignment)
7808     Alignment = DAG.getEVTAlign(VT.getScalarType());
7809   unsigned AS =
7810     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7811   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7812      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7813      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7814   SDValue Base, Index, Scale;
7815   ISD::MemIndexType IndexType;
7816   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7817                                     this, VPIntrin.getParent(),
7818                                     VT.getScalarStoreSize());
7819   if (!UniformBase) {
7820     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7821     Index = getValue(PtrOperand);
7822     IndexType = ISD::SIGNED_SCALED;
7823     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7824   }
7825   EVT IdxVT = Index.getValueType();
7826   EVT EltTy = IdxVT.getVectorElementType();
7827   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7828     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7829     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7830   }
7831   LD = DAG.getGatherVP(
7832       DAG.getVTList(VT, MVT::Other), VT, DL,
7833       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7834       IndexType);
7835   PendingLoads.push_back(LD.getValue(1));
7836   setValue(&VPIntrin, LD);
7837 }
7838 
7839 void SelectionDAGBuilder::visitVPStore(
7840     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7841   SDLoc DL = getCurSDLoc();
7842   Value *PtrOperand = VPIntrin.getArgOperand(1);
7843   EVT VT = OpValues[0].getValueType();
7844   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7845   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7846   SDValue ST;
7847   if (!Alignment)
7848     Alignment = DAG.getEVTAlign(VT);
7849   SDValue Ptr = OpValues[1];
7850   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7851   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7852       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7853       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7854   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7855                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7856                       /* IsTruncating */ false, /*IsCompressing*/ false);
7857   DAG.setRoot(ST);
7858   setValue(&VPIntrin, ST);
7859 }
7860 
7861 void SelectionDAGBuilder::visitVPScatter(
7862     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7863   SDLoc DL = getCurSDLoc();
7864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7865   Value *PtrOperand = VPIntrin.getArgOperand(1);
7866   EVT VT = OpValues[0].getValueType();
7867   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7868   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7869   SDValue ST;
7870   if (!Alignment)
7871     Alignment = DAG.getEVTAlign(VT.getScalarType());
7872   unsigned AS =
7873       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7874   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7875       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7876       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7877   SDValue Base, Index, Scale;
7878   ISD::MemIndexType IndexType;
7879   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7880                                     this, VPIntrin.getParent(),
7881                                     VT.getScalarStoreSize());
7882   if (!UniformBase) {
7883     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7884     Index = getValue(PtrOperand);
7885     IndexType = ISD::SIGNED_SCALED;
7886     Scale =
7887       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7888   }
7889   EVT IdxVT = Index.getValueType();
7890   EVT EltTy = IdxVT.getVectorElementType();
7891   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7892     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7893     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7894   }
7895   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7896                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7897                          OpValues[2], OpValues[3]},
7898                         MMO, IndexType);
7899   DAG.setRoot(ST);
7900   setValue(&VPIntrin, ST);
7901 }
7902 
7903 void SelectionDAGBuilder::visitVPStridedLoad(
7904     const VPIntrinsic &VPIntrin, EVT VT,
7905     const SmallVectorImpl<SDValue> &OpValues) {
7906   SDLoc DL = getCurSDLoc();
7907   Value *PtrOperand = VPIntrin.getArgOperand(0);
7908   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7909   if (!Alignment)
7910     Alignment = DAG.getEVTAlign(VT.getScalarType());
7911   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7912   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7913   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7914   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7915   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7916   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7917       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7918       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7919 
7920   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7921                                     OpValues[2], OpValues[3], MMO,
7922                                     false /*IsExpanding*/);
7923 
7924   if (AddToChain)
7925     PendingLoads.push_back(LD.getValue(1));
7926   setValue(&VPIntrin, LD);
7927 }
7928 
7929 void SelectionDAGBuilder::visitVPStridedStore(
7930     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7931   SDLoc DL = getCurSDLoc();
7932   Value *PtrOperand = VPIntrin.getArgOperand(1);
7933   EVT VT = OpValues[0].getValueType();
7934   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7935   if (!Alignment)
7936     Alignment = DAG.getEVTAlign(VT.getScalarType());
7937   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7938   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7939       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7940       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7941 
7942   SDValue ST = DAG.getStridedStoreVP(
7943       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7944       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7945       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7946       /*IsCompressing*/ false);
7947 
7948   DAG.setRoot(ST);
7949   setValue(&VPIntrin, ST);
7950 }
7951 
7952 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7954   SDLoc DL = getCurSDLoc();
7955 
7956   ISD::CondCode Condition;
7957   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7958   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7959   if (IsFP) {
7960     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7961     // flags, but calls that don't return floating-point types can't be
7962     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7963     Condition = getFCmpCondCode(CondCode);
7964     if (TM.Options.NoNaNsFPMath)
7965       Condition = getFCmpCodeWithoutNaN(Condition);
7966   } else {
7967     Condition = getICmpCondCode(CondCode);
7968   }
7969 
7970   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7971   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7972   // #2 is the condition code
7973   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7974   SDValue EVL = getValue(VPIntrin.getOperand(4));
7975   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7976   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7977          "Unexpected target EVL type");
7978   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7979 
7980   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7981                                                         VPIntrin.getType());
7982   setValue(&VPIntrin,
7983            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7984 }
7985 
7986 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7987     const VPIntrinsic &VPIntrin) {
7988   SDLoc DL = getCurSDLoc();
7989   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7990 
7991   auto IID = VPIntrin.getIntrinsicID();
7992 
7993   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7994     return visitVPCmp(*CmpI);
7995 
7996   SmallVector<EVT, 4> ValueVTs;
7997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7998   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7999   SDVTList VTs = DAG.getVTList(ValueVTs);
8000 
8001   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8002 
8003   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8004   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8005          "Unexpected target EVL type");
8006 
8007   // Request operands.
8008   SmallVector<SDValue, 7> OpValues;
8009   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8010     auto Op = getValue(VPIntrin.getArgOperand(I));
8011     if (I == EVLParamPos)
8012       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8013     OpValues.push_back(Op);
8014   }
8015 
8016   switch (Opcode) {
8017   default: {
8018     SDNodeFlags SDFlags;
8019     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8020       SDFlags.copyFMF(*FPMO);
8021     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8022     setValue(&VPIntrin, Result);
8023     break;
8024   }
8025   case ISD::VP_LOAD:
8026     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8027     break;
8028   case ISD::VP_GATHER:
8029     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8030     break;
8031   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8032     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8033     break;
8034   case ISD::VP_STORE:
8035     visitVPStore(VPIntrin, OpValues);
8036     break;
8037   case ISD::VP_SCATTER:
8038     visitVPScatter(VPIntrin, OpValues);
8039     break;
8040   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8041     visitVPStridedStore(VPIntrin, OpValues);
8042     break;
8043   case ISD::VP_FMULADD: {
8044     assert(OpValues.size() == 5 && "Unexpected number of operands");
8045     SDNodeFlags SDFlags;
8046     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8047       SDFlags.copyFMF(*FPMO);
8048     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8049         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8050       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8051     } else {
8052       SDValue Mul = DAG.getNode(
8053           ISD::VP_FMUL, DL, VTs,
8054           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8055       SDValue Add =
8056           DAG.getNode(ISD::VP_FADD, DL, VTs,
8057                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8058       setValue(&VPIntrin, Add);
8059     }
8060     break;
8061   }
8062   case ISD::VP_IS_FPCLASS: {
8063     const DataLayout DLayout = DAG.getDataLayout();
8064     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8065     auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue();
8066     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8067     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8068                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8069     setValue(&VPIntrin, V);
8070     return;
8071   }
8072   case ISD::VP_INTTOPTR: {
8073     SDValue N = OpValues[0];
8074     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8075     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8076     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8077                                OpValues[2]);
8078     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8079                              OpValues[2]);
8080     setValue(&VPIntrin, N);
8081     break;
8082   }
8083   case ISD::VP_PTRTOINT: {
8084     SDValue N = OpValues[0];
8085     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8086                                                           VPIntrin.getType());
8087     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8088                                        VPIntrin.getOperand(0)->getType());
8089     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8090                                OpValues[2]);
8091     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8092                              OpValues[2]);
8093     setValue(&VPIntrin, N);
8094     break;
8095   }
8096   case ISD::VP_ABS:
8097   case ISD::VP_CTLZ:
8098   case ISD::VP_CTLZ_ZERO_UNDEF:
8099   case ISD::VP_CTTZ:
8100   case ISD::VP_CTTZ_ZERO_UNDEF: {
8101     SDValue Result =
8102         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8103     setValue(&VPIntrin, Result);
8104     break;
8105   }
8106   }
8107 }
8108 
8109 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8110                                           const BasicBlock *EHPadBB,
8111                                           MCSymbol *&BeginLabel) {
8112   MachineFunction &MF = DAG.getMachineFunction();
8113   MachineModuleInfo &MMI = MF.getMMI();
8114 
8115   // Insert a label before the invoke call to mark the try range.  This can be
8116   // used to detect deletion of the invoke via the MachineModuleInfo.
8117   BeginLabel = MMI.getContext().createTempSymbol();
8118 
8119   // For SjLj, keep track of which landing pads go with which invokes
8120   // so as to maintain the ordering of pads in the LSDA.
8121   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8122   if (CallSiteIndex) {
8123     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8124     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8125 
8126     // Now that the call site is handled, stop tracking it.
8127     MMI.setCurrentCallSite(0);
8128   }
8129 
8130   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8131 }
8132 
8133 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8134                                         const BasicBlock *EHPadBB,
8135                                         MCSymbol *BeginLabel) {
8136   assert(BeginLabel && "BeginLabel should've been set");
8137 
8138   MachineFunction &MF = DAG.getMachineFunction();
8139   MachineModuleInfo &MMI = MF.getMMI();
8140 
8141   // Insert a label at the end of the invoke call to mark the try range.  This
8142   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8143   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8144   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8145 
8146   // Inform MachineModuleInfo of range.
8147   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8148   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8149   // actually use outlined funclets and their LSDA info style.
8150   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8151     assert(II && "II should've been set");
8152     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8153     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8154   } else if (!isScopedEHPersonality(Pers)) {
8155     assert(EHPadBB);
8156     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8157   }
8158 
8159   return Chain;
8160 }
8161 
8162 std::pair<SDValue, SDValue>
8163 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8164                                     const BasicBlock *EHPadBB) {
8165   MCSymbol *BeginLabel = nullptr;
8166 
8167   if (EHPadBB) {
8168     // Both PendingLoads and PendingExports must be flushed here;
8169     // this call might not return.
8170     (void)getRoot();
8171     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8172     CLI.setChain(getRoot());
8173   }
8174 
8175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8176   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8177 
8178   assert((CLI.IsTailCall || Result.second.getNode()) &&
8179          "Non-null chain expected with non-tail call!");
8180   assert((Result.second.getNode() || !Result.first.getNode()) &&
8181          "Null value expected with tail call!");
8182 
8183   if (!Result.second.getNode()) {
8184     // As a special case, a null chain means that a tail call has been emitted
8185     // and the DAG root is already updated.
8186     HasTailCall = true;
8187 
8188     // Since there's no actual continuation from this block, nothing can be
8189     // relying on us setting vregs for them.
8190     PendingExports.clear();
8191   } else {
8192     DAG.setRoot(Result.second);
8193   }
8194 
8195   if (EHPadBB) {
8196     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8197                            BeginLabel));
8198   }
8199 
8200   return Result;
8201 }
8202 
8203 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8204                                       bool isTailCall,
8205                                       bool isMustTailCall,
8206                                       const BasicBlock *EHPadBB) {
8207   auto &DL = DAG.getDataLayout();
8208   FunctionType *FTy = CB.getFunctionType();
8209   Type *RetTy = CB.getType();
8210 
8211   TargetLowering::ArgListTy Args;
8212   Args.reserve(CB.arg_size());
8213 
8214   const Value *SwiftErrorVal = nullptr;
8215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8216 
8217   if (isTailCall) {
8218     // Avoid emitting tail calls in functions with the disable-tail-calls
8219     // attribute.
8220     auto *Caller = CB.getParent()->getParent();
8221     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8222         "true" && !isMustTailCall)
8223       isTailCall = false;
8224 
8225     // We can't tail call inside a function with a swifterror argument. Lowering
8226     // does not support this yet. It would have to move into the swifterror
8227     // register before the call.
8228     if (TLI.supportSwiftError() &&
8229         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8230       isTailCall = false;
8231   }
8232 
8233   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8234     TargetLowering::ArgListEntry Entry;
8235     const Value *V = *I;
8236 
8237     // Skip empty types
8238     if (V->getType()->isEmptyTy())
8239       continue;
8240 
8241     SDValue ArgNode = getValue(V);
8242     Entry.Node = ArgNode; Entry.Ty = V->getType();
8243 
8244     Entry.setAttributes(&CB, I - CB.arg_begin());
8245 
8246     // Use swifterror virtual register as input to the call.
8247     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8248       SwiftErrorVal = V;
8249       // We find the virtual register for the actual swifterror argument.
8250       // Instead of using the Value, we use the virtual register instead.
8251       Entry.Node =
8252           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8253                           EVT(TLI.getPointerTy(DL)));
8254     }
8255 
8256     Args.push_back(Entry);
8257 
8258     // If we have an explicit sret argument that is an Instruction, (i.e., it
8259     // might point to function-local memory), we can't meaningfully tail-call.
8260     if (Entry.IsSRet && isa<Instruction>(V))
8261       isTailCall = false;
8262   }
8263 
8264   // If call site has a cfguardtarget operand bundle, create and add an
8265   // additional ArgListEntry.
8266   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8267     TargetLowering::ArgListEntry Entry;
8268     Value *V = Bundle->Inputs[0];
8269     SDValue ArgNode = getValue(V);
8270     Entry.Node = ArgNode;
8271     Entry.Ty = V->getType();
8272     Entry.IsCFGuardTarget = true;
8273     Args.push_back(Entry);
8274   }
8275 
8276   // Check if target-independent constraints permit a tail call here.
8277   // Target-dependent constraints are checked within TLI->LowerCallTo.
8278   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8279     isTailCall = false;
8280 
8281   // Disable tail calls if there is an swifterror argument. Targets have not
8282   // been updated to support tail calls.
8283   if (TLI.supportSwiftError() && SwiftErrorVal)
8284     isTailCall = false;
8285 
8286   ConstantInt *CFIType = nullptr;
8287   if (CB.isIndirectCall()) {
8288     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8289       if (!TLI.supportKCFIBundles())
8290         report_fatal_error(
8291             "Target doesn't support calls with kcfi operand bundles.");
8292       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8293       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8294     }
8295   }
8296 
8297   TargetLowering::CallLoweringInfo CLI(DAG);
8298   CLI.setDebugLoc(getCurSDLoc())
8299       .setChain(getRoot())
8300       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8301       .setTailCall(isTailCall)
8302       .setConvergent(CB.isConvergent())
8303       .setIsPreallocated(
8304           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8305       .setCFIType(CFIType);
8306   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8307 
8308   if (Result.first.getNode()) {
8309     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8310     setValue(&CB, Result.first);
8311   }
8312 
8313   // The last element of CLI.InVals has the SDValue for swifterror return.
8314   // Here we copy it to a virtual register and update SwiftErrorMap for
8315   // book-keeping.
8316   if (SwiftErrorVal && TLI.supportSwiftError()) {
8317     // Get the last element of InVals.
8318     SDValue Src = CLI.InVals.back();
8319     Register VReg =
8320         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8321     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8322     DAG.setRoot(CopyNode);
8323   }
8324 }
8325 
8326 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8327                              SelectionDAGBuilder &Builder) {
8328   // Check to see if this load can be trivially constant folded, e.g. if the
8329   // input is from a string literal.
8330   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8331     // Cast pointer to the type we really want to load.
8332     Type *LoadTy =
8333         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8334     if (LoadVT.isVector())
8335       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8336 
8337     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8338                                          PointerType::getUnqual(LoadTy));
8339 
8340     if (const Constant *LoadCst =
8341             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8342                                          LoadTy, Builder.DAG.getDataLayout()))
8343       return Builder.getValue(LoadCst);
8344   }
8345 
8346   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8347   // still constant memory, the input chain can be the entry node.
8348   SDValue Root;
8349   bool ConstantMemory = false;
8350 
8351   // Do not serialize (non-volatile) loads of constant memory with anything.
8352   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8353     Root = Builder.DAG.getEntryNode();
8354     ConstantMemory = true;
8355   } else {
8356     // Do not serialize non-volatile loads against each other.
8357     Root = Builder.DAG.getRoot();
8358   }
8359 
8360   SDValue Ptr = Builder.getValue(PtrVal);
8361   SDValue LoadVal =
8362       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8363                           MachinePointerInfo(PtrVal), Align(1));
8364 
8365   if (!ConstantMemory)
8366     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8367   return LoadVal;
8368 }
8369 
8370 /// Record the value for an instruction that produces an integer result,
8371 /// converting the type where necessary.
8372 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8373                                                   SDValue Value,
8374                                                   bool IsSigned) {
8375   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8376                                                     I.getType(), true);
8377   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8378   setValue(&I, Value);
8379 }
8380 
8381 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8382 /// true and lower it. Otherwise return false, and it will be lowered like a
8383 /// normal call.
8384 /// The caller already checked that \p I calls the appropriate LibFunc with a
8385 /// correct prototype.
8386 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8387   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8388   const Value *Size = I.getArgOperand(2);
8389   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8390   if (CSize && CSize->getZExtValue() == 0) {
8391     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8392                                                           I.getType(), true);
8393     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8394     return true;
8395   }
8396 
8397   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8398   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8399       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8400       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8401   if (Res.first.getNode()) {
8402     processIntegerCallValue(I, Res.first, true);
8403     PendingLoads.push_back(Res.second);
8404     return true;
8405   }
8406 
8407   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8408   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8409   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8410     return false;
8411 
8412   // If the target has a fast compare for the given size, it will return a
8413   // preferred load type for that size. Require that the load VT is legal and
8414   // that the target supports unaligned loads of that type. Otherwise, return
8415   // INVALID.
8416   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8417     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8418     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8419     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8420       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8421       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8422       // TODO: Check alignment of src and dest ptrs.
8423       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8424       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8425       if (!TLI.isTypeLegal(LVT) ||
8426           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8427           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8428         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8429     }
8430 
8431     return LVT;
8432   };
8433 
8434   // This turns into unaligned loads. We only do this if the target natively
8435   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8436   // we'll only produce a small number of byte loads.
8437   MVT LoadVT;
8438   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8439   switch (NumBitsToCompare) {
8440   default:
8441     return false;
8442   case 16:
8443     LoadVT = MVT::i16;
8444     break;
8445   case 32:
8446     LoadVT = MVT::i32;
8447     break;
8448   case 64:
8449   case 128:
8450   case 256:
8451     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8452     break;
8453   }
8454 
8455   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8456     return false;
8457 
8458   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8459   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8460 
8461   // Bitcast to a wide integer type if the loads are vectors.
8462   if (LoadVT.isVector()) {
8463     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8464     LoadL = DAG.getBitcast(CmpVT, LoadL);
8465     LoadR = DAG.getBitcast(CmpVT, LoadR);
8466   }
8467 
8468   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8469   processIntegerCallValue(I, Cmp, false);
8470   return true;
8471 }
8472 
8473 /// See if we can lower a memchr call into an optimized form. If so, return
8474 /// true and lower it. Otherwise return false, and it will be lowered like a
8475 /// normal call.
8476 /// The caller already checked that \p I calls the appropriate LibFunc with a
8477 /// correct prototype.
8478 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8479   const Value *Src = I.getArgOperand(0);
8480   const Value *Char = I.getArgOperand(1);
8481   const Value *Length = I.getArgOperand(2);
8482 
8483   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8484   std::pair<SDValue, SDValue> Res =
8485     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8486                                 getValue(Src), getValue(Char), getValue(Length),
8487                                 MachinePointerInfo(Src));
8488   if (Res.first.getNode()) {
8489     setValue(&I, Res.first);
8490     PendingLoads.push_back(Res.second);
8491     return true;
8492   }
8493 
8494   return false;
8495 }
8496 
8497 /// See if we can lower a mempcpy call into an optimized form. If so, return
8498 /// true and lower it. Otherwise return false, and it will be lowered like a
8499 /// normal call.
8500 /// The caller already checked that \p I calls the appropriate LibFunc with a
8501 /// correct prototype.
8502 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8503   SDValue Dst = getValue(I.getArgOperand(0));
8504   SDValue Src = getValue(I.getArgOperand(1));
8505   SDValue Size = getValue(I.getArgOperand(2));
8506 
8507   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8508   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8509   // DAG::getMemcpy needs Alignment to be defined.
8510   Align Alignment = std::min(DstAlign, SrcAlign);
8511 
8512   SDLoc sdl = getCurSDLoc();
8513 
8514   // In the mempcpy context we need to pass in a false value for isTailCall
8515   // because the return pointer needs to be adjusted by the size of
8516   // the copied memory.
8517   SDValue Root = getMemoryRoot();
8518   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8519                              /*isTailCall=*/false,
8520                              MachinePointerInfo(I.getArgOperand(0)),
8521                              MachinePointerInfo(I.getArgOperand(1)),
8522                              I.getAAMetadata());
8523   assert(MC.getNode() != nullptr &&
8524          "** memcpy should not be lowered as TailCall in mempcpy context **");
8525   DAG.setRoot(MC);
8526 
8527   // Check if Size needs to be truncated or extended.
8528   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8529 
8530   // Adjust return pointer to point just past the last dst byte.
8531   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8532                                     Dst, Size);
8533   setValue(&I, DstPlusSize);
8534   return true;
8535 }
8536 
8537 /// See if we can lower a strcpy call into an optimized form.  If so, return
8538 /// true and lower it, otherwise return false and it will be lowered like a
8539 /// normal call.
8540 /// The caller already checked that \p I calls the appropriate LibFunc with a
8541 /// correct prototype.
8542 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8543   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8544 
8545   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8546   std::pair<SDValue, SDValue> Res =
8547     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8548                                 getValue(Arg0), getValue(Arg1),
8549                                 MachinePointerInfo(Arg0),
8550                                 MachinePointerInfo(Arg1), isStpcpy);
8551   if (Res.first.getNode()) {
8552     setValue(&I, Res.first);
8553     DAG.setRoot(Res.second);
8554     return true;
8555   }
8556 
8557   return false;
8558 }
8559 
8560 /// See if we can lower a strcmp call into an optimized form.  If so, return
8561 /// true and lower it, otherwise return false and it will be lowered like a
8562 /// normal call.
8563 /// The caller already checked that \p I calls the appropriate LibFunc with a
8564 /// correct prototype.
8565 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8566   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8567 
8568   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8569   std::pair<SDValue, SDValue> Res =
8570     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8571                                 getValue(Arg0), getValue(Arg1),
8572                                 MachinePointerInfo(Arg0),
8573                                 MachinePointerInfo(Arg1));
8574   if (Res.first.getNode()) {
8575     processIntegerCallValue(I, Res.first, true);
8576     PendingLoads.push_back(Res.second);
8577     return true;
8578   }
8579 
8580   return false;
8581 }
8582 
8583 /// See if we can lower a strlen call into an optimized form.  If so, return
8584 /// true and lower it, otherwise return false and it will be lowered like a
8585 /// normal call.
8586 /// The caller already checked that \p I calls the appropriate LibFunc with a
8587 /// correct prototype.
8588 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8589   const Value *Arg0 = I.getArgOperand(0);
8590 
8591   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8592   std::pair<SDValue, SDValue> Res =
8593     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8594                                 getValue(Arg0), MachinePointerInfo(Arg0));
8595   if (Res.first.getNode()) {
8596     processIntegerCallValue(I, Res.first, false);
8597     PendingLoads.push_back(Res.second);
8598     return true;
8599   }
8600 
8601   return false;
8602 }
8603 
8604 /// See if we can lower a strnlen call into an optimized form.  If so, return
8605 /// true and lower it, otherwise return false and it will be lowered like a
8606 /// normal call.
8607 /// The caller already checked that \p I calls the appropriate LibFunc with a
8608 /// correct prototype.
8609 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8610   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8611 
8612   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8613   std::pair<SDValue, SDValue> Res =
8614     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8615                                  getValue(Arg0), getValue(Arg1),
8616                                  MachinePointerInfo(Arg0));
8617   if (Res.first.getNode()) {
8618     processIntegerCallValue(I, Res.first, false);
8619     PendingLoads.push_back(Res.second);
8620     return true;
8621   }
8622 
8623   return false;
8624 }
8625 
8626 /// See if we can lower a unary floating-point operation into an SDNode with
8627 /// the specified Opcode.  If so, return true and lower it, otherwise return
8628 /// false and it will be lowered like a normal call.
8629 /// The caller already checked that \p I calls the appropriate LibFunc with a
8630 /// correct prototype.
8631 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8632                                               unsigned Opcode) {
8633   // We already checked this call's prototype; verify it doesn't modify errno.
8634   if (!I.onlyReadsMemory())
8635     return false;
8636 
8637   SDNodeFlags Flags;
8638   Flags.copyFMF(cast<FPMathOperator>(I));
8639 
8640   SDValue Tmp = getValue(I.getArgOperand(0));
8641   setValue(&I,
8642            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8643   return true;
8644 }
8645 
8646 /// See if we can lower a binary floating-point operation into an SDNode with
8647 /// the specified Opcode. If so, return true and lower it. Otherwise return
8648 /// false, and it will be lowered like a normal call.
8649 /// The caller already checked that \p I calls the appropriate LibFunc with a
8650 /// correct prototype.
8651 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8652                                                unsigned Opcode) {
8653   // We already checked this call's prototype; verify it doesn't modify errno.
8654   if (!I.onlyReadsMemory())
8655     return false;
8656 
8657   SDNodeFlags Flags;
8658   Flags.copyFMF(cast<FPMathOperator>(I));
8659 
8660   SDValue Tmp0 = getValue(I.getArgOperand(0));
8661   SDValue Tmp1 = getValue(I.getArgOperand(1));
8662   EVT VT = Tmp0.getValueType();
8663   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8664   return true;
8665 }
8666 
8667 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8668   // Handle inline assembly differently.
8669   if (I.isInlineAsm()) {
8670     visitInlineAsm(I);
8671     return;
8672   }
8673 
8674   diagnoseDontCall(I);
8675 
8676   if (Function *F = I.getCalledFunction()) {
8677     if (F->isDeclaration()) {
8678       // Is this an LLVM intrinsic or a target-specific intrinsic?
8679       unsigned IID = F->getIntrinsicID();
8680       if (!IID)
8681         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8682           IID = II->getIntrinsicID(F);
8683 
8684       if (IID) {
8685         visitIntrinsicCall(I, IID);
8686         return;
8687       }
8688     }
8689 
8690     // Check for well-known libc/libm calls.  If the function is internal, it
8691     // can't be a library call.  Don't do the check if marked as nobuiltin for
8692     // some reason or the call site requires strict floating point semantics.
8693     LibFunc Func;
8694     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8695         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8696         LibInfo->hasOptimizedCodeGen(Func)) {
8697       switch (Func) {
8698       default: break;
8699       case LibFunc_bcmp:
8700         if (visitMemCmpBCmpCall(I))
8701           return;
8702         break;
8703       case LibFunc_copysign:
8704       case LibFunc_copysignf:
8705       case LibFunc_copysignl:
8706         // We already checked this call's prototype; verify it doesn't modify
8707         // errno.
8708         if (I.onlyReadsMemory()) {
8709           SDValue LHS = getValue(I.getArgOperand(0));
8710           SDValue RHS = getValue(I.getArgOperand(1));
8711           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8712                                    LHS.getValueType(), LHS, RHS));
8713           return;
8714         }
8715         break;
8716       case LibFunc_fabs:
8717       case LibFunc_fabsf:
8718       case LibFunc_fabsl:
8719         if (visitUnaryFloatCall(I, ISD::FABS))
8720           return;
8721         break;
8722       case LibFunc_fmin:
8723       case LibFunc_fminf:
8724       case LibFunc_fminl:
8725         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8726           return;
8727         break;
8728       case LibFunc_fmax:
8729       case LibFunc_fmaxf:
8730       case LibFunc_fmaxl:
8731         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8732           return;
8733         break;
8734       case LibFunc_sin:
8735       case LibFunc_sinf:
8736       case LibFunc_sinl:
8737         if (visitUnaryFloatCall(I, ISD::FSIN))
8738           return;
8739         break;
8740       case LibFunc_cos:
8741       case LibFunc_cosf:
8742       case LibFunc_cosl:
8743         if (visitUnaryFloatCall(I, ISD::FCOS))
8744           return;
8745         break;
8746       case LibFunc_sqrt:
8747       case LibFunc_sqrtf:
8748       case LibFunc_sqrtl:
8749       case LibFunc_sqrt_finite:
8750       case LibFunc_sqrtf_finite:
8751       case LibFunc_sqrtl_finite:
8752         if (visitUnaryFloatCall(I, ISD::FSQRT))
8753           return;
8754         break;
8755       case LibFunc_floor:
8756       case LibFunc_floorf:
8757       case LibFunc_floorl:
8758         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8759           return;
8760         break;
8761       case LibFunc_nearbyint:
8762       case LibFunc_nearbyintf:
8763       case LibFunc_nearbyintl:
8764         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8765           return;
8766         break;
8767       case LibFunc_ceil:
8768       case LibFunc_ceilf:
8769       case LibFunc_ceill:
8770         if (visitUnaryFloatCall(I, ISD::FCEIL))
8771           return;
8772         break;
8773       case LibFunc_rint:
8774       case LibFunc_rintf:
8775       case LibFunc_rintl:
8776         if (visitUnaryFloatCall(I, ISD::FRINT))
8777           return;
8778         break;
8779       case LibFunc_round:
8780       case LibFunc_roundf:
8781       case LibFunc_roundl:
8782         if (visitUnaryFloatCall(I, ISD::FROUND))
8783           return;
8784         break;
8785       case LibFunc_trunc:
8786       case LibFunc_truncf:
8787       case LibFunc_truncl:
8788         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8789           return;
8790         break;
8791       case LibFunc_log2:
8792       case LibFunc_log2f:
8793       case LibFunc_log2l:
8794         if (visitUnaryFloatCall(I, ISD::FLOG2))
8795           return;
8796         break;
8797       case LibFunc_exp2:
8798       case LibFunc_exp2f:
8799       case LibFunc_exp2l:
8800         if (visitUnaryFloatCall(I, ISD::FEXP2))
8801           return;
8802         break;
8803       case LibFunc_exp10:
8804       case LibFunc_exp10f:
8805       case LibFunc_exp10l:
8806         if (visitUnaryFloatCall(I, ISD::FEXP10))
8807           return;
8808         break;
8809       case LibFunc_ldexp:
8810       case LibFunc_ldexpf:
8811       case LibFunc_ldexpl:
8812         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8813           return;
8814         break;
8815       case LibFunc_memcmp:
8816         if (visitMemCmpBCmpCall(I))
8817           return;
8818         break;
8819       case LibFunc_mempcpy:
8820         if (visitMemPCpyCall(I))
8821           return;
8822         break;
8823       case LibFunc_memchr:
8824         if (visitMemChrCall(I))
8825           return;
8826         break;
8827       case LibFunc_strcpy:
8828         if (visitStrCpyCall(I, false))
8829           return;
8830         break;
8831       case LibFunc_stpcpy:
8832         if (visitStrCpyCall(I, true))
8833           return;
8834         break;
8835       case LibFunc_strcmp:
8836         if (visitStrCmpCall(I))
8837           return;
8838         break;
8839       case LibFunc_strlen:
8840         if (visitStrLenCall(I))
8841           return;
8842         break;
8843       case LibFunc_strnlen:
8844         if (visitStrNLenCall(I))
8845           return;
8846         break;
8847       }
8848     }
8849   }
8850 
8851   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8852   // have to do anything here to lower funclet bundles.
8853   // CFGuardTarget bundles are lowered in LowerCallTo.
8854   assert(!I.hasOperandBundlesOtherThan(
8855              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8856               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8857               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8858          "Cannot lower calls with arbitrary operand bundles!");
8859 
8860   SDValue Callee = getValue(I.getCalledOperand());
8861 
8862   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8863     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8864   else
8865     // Check if we can potentially perform a tail call. More detailed checking
8866     // is be done within LowerCallTo, after more information about the call is
8867     // known.
8868     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8869 }
8870 
8871 namespace {
8872 
8873 /// AsmOperandInfo - This contains information for each constraint that we are
8874 /// lowering.
8875 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8876 public:
8877   /// CallOperand - If this is the result output operand or a clobber
8878   /// this is null, otherwise it is the incoming operand to the CallInst.
8879   /// This gets modified as the asm is processed.
8880   SDValue CallOperand;
8881 
8882   /// AssignedRegs - If this is a register or register class operand, this
8883   /// contains the set of register corresponding to the operand.
8884   RegsForValue AssignedRegs;
8885 
8886   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8887     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8888   }
8889 
8890   /// Whether or not this operand accesses memory
8891   bool hasMemory(const TargetLowering &TLI) const {
8892     // Indirect operand accesses access memory.
8893     if (isIndirect)
8894       return true;
8895 
8896     for (const auto &Code : Codes)
8897       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8898         return true;
8899 
8900     return false;
8901   }
8902 };
8903 
8904 
8905 } // end anonymous namespace
8906 
8907 /// Make sure that the output operand \p OpInfo and its corresponding input
8908 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8909 /// out).
8910 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8911                                SDISelAsmOperandInfo &MatchingOpInfo,
8912                                SelectionDAG &DAG) {
8913   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8914     return;
8915 
8916   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8917   const auto &TLI = DAG.getTargetLoweringInfo();
8918 
8919   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8920       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8921                                        OpInfo.ConstraintVT);
8922   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8923       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8924                                        MatchingOpInfo.ConstraintVT);
8925   if ((OpInfo.ConstraintVT.isInteger() !=
8926        MatchingOpInfo.ConstraintVT.isInteger()) ||
8927       (MatchRC.second != InputRC.second)) {
8928     // FIXME: error out in a more elegant fashion
8929     report_fatal_error("Unsupported asm: input constraint"
8930                        " with a matching output constraint of"
8931                        " incompatible type!");
8932   }
8933   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8934 }
8935 
8936 /// Get a direct memory input to behave well as an indirect operand.
8937 /// This may introduce stores, hence the need for a \p Chain.
8938 /// \return The (possibly updated) chain.
8939 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8940                                         SDISelAsmOperandInfo &OpInfo,
8941                                         SelectionDAG &DAG) {
8942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8943 
8944   // If we don't have an indirect input, put it in the constpool if we can,
8945   // otherwise spill it to a stack slot.
8946   // TODO: This isn't quite right. We need to handle these according to
8947   // the addressing mode that the constraint wants. Also, this may take
8948   // an additional register for the computation and we don't want that
8949   // either.
8950 
8951   // If the operand is a float, integer, or vector constant, spill to a
8952   // constant pool entry to get its address.
8953   const Value *OpVal = OpInfo.CallOperandVal;
8954   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8955       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8956     OpInfo.CallOperand = DAG.getConstantPool(
8957         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8958     return Chain;
8959   }
8960 
8961   // Otherwise, create a stack slot and emit a store to it before the asm.
8962   Type *Ty = OpVal->getType();
8963   auto &DL = DAG.getDataLayout();
8964   uint64_t TySize = DL.getTypeAllocSize(Ty);
8965   MachineFunction &MF = DAG.getMachineFunction();
8966   int SSFI = MF.getFrameInfo().CreateStackObject(
8967       TySize, DL.getPrefTypeAlign(Ty), false);
8968   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8969   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8970                             MachinePointerInfo::getFixedStack(MF, SSFI),
8971                             TLI.getMemValueType(DL, Ty));
8972   OpInfo.CallOperand = StackSlot;
8973 
8974   return Chain;
8975 }
8976 
8977 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8978 /// specified operand.  We prefer to assign virtual registers, to allow the
8979 /// register allocator to handle the assignment process.  However, if the asm
8980 /// uses features that we can't model on machineinstrs, we have SDISel do the
8981 /// allocation.  This produces generally horrible, but correct, code.
8982 ///
8983 ///   OpInfo describes the operand
8984 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8985 static std::optional<unsigned>
8986 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8987                      SDISelAsmOperandInfo &OpInfo,
8988                      SDISelAsmOperandInfo &RefOpInfo) {
8989   LLVMContext &Context = *DAG.getContext();
8990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8991 
8992   MachineFunction &MF = DAG.getMachineFunction();
8993   SmallVector<unsigned, 4> Regs;
8994   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8995 
8996   // No work to do for memory/address operands.
8997   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8998       OpInfo.ConstraintType == TargetLowering::C_Address)
8999     return std::nullopt;
9000 
9001   // If this is a constraint for a single physreg, or a constraint for a
9002   // register class, find it.
9003   unsigned AssignedReg;
9004   const TargetRegisterClass *RC;
9005   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9006       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9007   // RC is unset only on failure. Return immediately.
9008   if (!RC)
9009     return std::nullopt;
9010 
9011   // Get the actual register value type.  This is important, because the user
9012   // may have asked for (e.g.) the AX register in i32 type.  We need to
9013   // remember that AX is actually i16 to get the right extension.
9014   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9015 
9016   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9017     // If this is an FP operand in an integer register (or visa versa), or more
9018     // generally if the operand value disagrees with the register class we plan
9019     // to stick it in, fix the operand type.
9020     //
9021     // If this is an input value, the bitcast to the new type is done now.
9022     // Bitcast for output value is done at the end of visitInlineAsm().
9023     if ((OpInfo.Type == InlineAsm::isOutput ||
9024          OpInfo.Type == InlineAsm::isInput) &&
9025         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9026       // Try to convert to the first EVT that the reg class contains.  If the
9027       // types are identical size, use a bitcast to convert (e.g. two differing
9028       // vector types).  Note: output bitcast is done at the end of
9029       // visitInlineAsm().
9030       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9031         // Exclude indirect inputs while they are unsupported because the code
9032         // to perform the load is missing and thus OpInfo.CallOperand still
9033         // refers to the input address rather than the pointed-to value.
9034         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9035           OpInfo.CallOperand =
9036               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9037         OpInfo.ConstraintVT = RegVT;
9038         // If the operand is an FP value and we want it in integer registers,
9039         // use the corresponding integer type. This turns an f64 value into
9040         // i64, which can be passed with two i32 values on a 32-bit machine.
9041       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9042         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9043         if (OpInfo.Type == InlineAsm::isInput)
9044           OpInfo.CallOperand =
9045               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9046         OpInfo.ConstraintVT = VT;
9047       }
9048     }
9049   }
9050 
9051   // No need to allocate a matching input constraint since the constraint it's
9052   // matching to has already been allocated.
9053   if (OpInfo.isMatchingInputConstraint())
9054     return std::nullopt;
9055 
9056   EVT ValueVT = OpInfo.ConstraintVT;
9057   if (OpInfo.ConstraintVT == MVT::Other)
9058     ValueVT = RegVT;
9059 
9060   // Initialize NumRegs.
9061   unsigned NumRegs = 1;
9062   if (OpInfo.ConstraintVT != MVT::Other)
9063     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9064 
9065   // If this is a constraint for a specific physical register, like {r17},
9066   // assign it now.
9067 
9068   // If this associated to a specific register, initialize iterator to correct
9069   // place. If virtual, make sure we have enough registers
9070 
9071   // Initialize iterator if necessary
9072   TargetRegisterClass::iterator I = RC->begin();
9073   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9074 
9075   // Do not check for single registers.
9076   if (AssignedReg) {
9077     I = std::find(I, RC->end(), AssignedReg);
9078     if (I == RC->end()) {
9079       // RC does not contain the selected register, which indicates a
9080       // mismatch between the register and the required type/bitwidth.
9081       return {AssignedReg};
9082     }
9083   }
9084 
9085   for (; NumRegs; --NumRegs, ++I) {
9086     assert(I != RC->end() && "Ran out of registers to allocate!");
9087     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9088     Regs.push_back(R);
9089   }
9090 
9091   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9092   return std::nullopt;
9093 }
9094 
9095 static unsigned
9096 findMatchingInlineAsmOperand(unsigned OperandNo,
9097                              const std::vector<SDValue> &AsmNodeOperands) {
9098   // Scan until we find the definition we already emitted of this operand.
9099   unsigned CurOp = InlineAsm::Op_FirstOperand;
9100   for (; OperandNo; --OperandNo) {
9101     // Advance to the next operand.
9102     unsigned OpFlag =
9103         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9104     const InlineAsm::Flag F(OpFlag);
9105     assert(
9106         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9107         "Skipped past definitions?");
9108     CurOp += F.getNumOperandRegisters() + 1;
9109   }
9110   return CurOp;
9111 }
9112 
9113 namespace {
9114 
9115 class ExtraFlags {
9116   unsigned Flags = 0;
9117 
9118 public:
9119   explicit ExtraFlags(const CallBase &Call) {
9120     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9121     if (IA->hasSideEffects())
9122       Flags |= InlineAsm::Extra_HasSideEffects;
9123     if (IA->isAlignStack())
9124       Flags |= InlineAsm::Extra_IsAlignStack;
9125     if (Call.isConvergent())
9126       Flags |= InlineAsm::Extra_IsConvergent;
9127     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9128   }
9129 
9130   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9131     // Ideally, we would only check against memory constraints.  However, the
9132     // meaning of an Other constraint can be target-specific and we can't easily
9133     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9134     // for Other constraints as well.
9135     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9136         OpInfo.ConstraintType == TargetLowering::C_Other) {
9137       if (OpInfo.Type == InlineAsm::isInput)
9138         Flags |= InlineAsm::Extra_MayLoad;
9139       else if (OpInfo.Type == InlineAsm::isOutput)
9140         Flags |= InlineAsm::Extra_MayStore;
9141       else if (OpInfo.Type == InlineAsm::isClobber)
9142         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9143     }
9144   }
9145 
9146   unsigned get() const { return Flags; }
9147 };
9148 
9149 } // end anonymous namespace
9150 
9151 static bool isFunction(SDValue Op) {
9152   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9153     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9154       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9155 
9156       // In normal "call dllimport func" instruction (non-inlineasm) it force
9157       // indirect access by specifing call opcode. And usually specially print
9158       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9159       // not do in this way now. (In fact, this is similar with "Data Access"
9160       // action). So here we ignore dllimport function.
9161       if (Fn && !Fn->hasDLLImportStorageClass())
9162         return true;
9163     }
9164   }
9165   return false;
9166 }
9167 
9168 /// visitInlineAsm - Handle a call to an InlineAsm object.
9169 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9170                                          const BasicBlock *EHPadBB) {
9171   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9172 
9173   /// ConstraintOperands - Information about all of the constraints.
9174   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9175 
9176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9177   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9178       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9179 
9180   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9181   // AsmDialect, MayLoad, MayStore).
9182   bool HasSideEffect = IA->hasSideEffects();
9183   ExtraFlags ExtraInfo(Call);
9184 
9185   for (auto &T : TargetConstraints) {
9186     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9187     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9188 
9189     if (OpInfo.CallOperandVal)
9190       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9191 
9192     if (!HasSideEffect)
9193       HasSideEffect = OpInfo.hasMemory(TLI);
9194 
9195     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9196     // FIXME: Could we compute this on OpInfo rather than T?
9197 
9198     // Compute the constraint code and ConstraintType to use.
9199     TLI.ComputeConstraintToUse(T, SDValue());
9200 
9201     if (T.ConstraintType == TargetLowering::C_Immediate &&
9202         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9203       // We've delayed emitting a diagnostic like the "n" constraint because
9204       // inlining could cause an integer showing up.
9205       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9206                                           "' expects an integer constant "
9207                                           "expression");
9208 
9209     ExtraInfo.update(T);
9210   }
9211 
9212   // We won't need to flush pending loads if this asm doesn't touch
9213   // memory and is nonvolatile.
9214   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9215 
9216   bool EmitEHLabels = isa<InvokeInst>(Call);
9217   if (EmitEHLabels) {
9218     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9219   }
9220   bool IsCallBr = isa<CallBrInst>(Call);
9221 
9222   if (IsCallBr || EmitEHLabels) {
9223     // If this is a callbr or invoke we need to flush pending exports since
9224     // inlineasm_br and invoke are terminators.
9225     // We need to do this before nodes are glued to the inlineasm_br node.
9226     Chain = getControlRoot();
9227   }
9228 
9229   MCSymbol *BeginLabel = nullptr;
9230   if (EmitEHLabels) {
9231     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9232   }
9233 
9234   int OpNo = -1;
9235   SmallVector<StringRef> AsmStrs;
9236   IA->collectAsmStrs(AsmStrs);
9237 
9238   // Second pass over the constraints: compute which constraint option to use.
9239   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9240     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9241       OpNo++;
9242 
9243     // If this is an output operand with a matching input operand, look up the
9244     // matching input. If their types mismatch, e.g. one is an integer, the
9245     // other is floating point, or their sizes are different, flag it as an
9246     // error.
9247     if (OpInfo.hasMatchingInput()) {
9248       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9249       patchMatchingInput(OpInfo, Input, DAG);
9250     }
9251 
9252     // Compute the constraint code and ConstraintType to use.
9253     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9254 
9255     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9256          OpInfo.Type == InlineAsm::isClobber) ||
9257         OpInfo.ConstraintType == TargetLowering::C_Address)
9258       continue;
9259 
9260     // In Linux PIC model, there are 4 cases about value/label addressing:
9261     //
9262     // 1: Function call or Label jmp inside the module.
9263     // 2: Data access (such as global variable, static variable) inside module.
9264     // 3: Function call or Label jmp outside the module.
9265     // 4: Data access (such as global variable) outside the module.
9266     //
9267     // Due to current llvm inline asm architecture designed to not "recognize"
9268     // the asm code, there are quite troubles for us to treat mem addressing
9269     // differently for same value/adress used in different instuctions.
9270     // For example, in pic model, call a func may in plt way or direclty
9271     // pc-related, but lea/mov a function adress may use got.
9272     //
9273     // Here we try to "recognize" function call for the case 1 and case 3 in
9274     // inline asm. And try to adjust the constraint for them.
9275     //
9276     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9277     // label, so here we don't handle jmp function label now, but we need to
9278     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9279     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9280         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9281         TM.getCodeModel() != CodeModel::Large) {
9282       OpInfo.isIndirect = false;
9283       OpInfo.ConstraintType = TargetLowering::C_Address;
9284     }
9285 
9286     // If this is a memory input, and if the operand is not indirect, do what we
9287     // need to provide an address for the memory input.
9288     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9289         !OpInfo.isIndirect) {
9290       assert((OpInfo.isMultipleAlternative ||
9291               (OpInfo.Type == InlineAsm::isInput)) &&
9292              "Can only indirectify direct input operands!");
9293 
9294       // Memory operands really want the address of the value.
9295       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9296 
9297       // There is no longer a Value* corresponding to this operand.
9298       OpInfo.CallOperandVal = nullptr;
9299 
9300       // It is now an indirect operand.
9301       OpInfo.isIndirect = true;
9302     }
9303 
9304   }
9305 
9306   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9307   std::vector<SDValue> AsmNodeOperands;
9308   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9309   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9310       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9311 
9312   // If we have a !srcloc metadata node associated with it, we want to attach
9313   // this to the ultimately generated inline asm machineinstr.  To do this, we
9314   // pass in the third operand as this (potentially null) inline asm MDNode.
9315   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9316   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9317 
9318   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9319   // bits as operand 3.
9320   AsmNodeOperands.push_back(DAG.getTargetConstant(
9321       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9322 
9323   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9324   // this, assign virtual and physical registers for inputs and otput.
9325   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9326     // Assign Registers.
9327     SDISelAsmOperandInfo &RefOpInfo =
9328         OpInfo.isMatchingInputConstraint()
9329             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9330             : OpInfo;
9331     const auto RegError =
9332         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9333     if (RegError) {
9334       const MachineFunction &MF = DAG.getMachineFunction();
9335       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9336       const char *RegName = TRI.getName(*RegError);
9337       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9338                                    "' allocated for constraint '" +
9339                                    Twine(OpInfo.ConstraintCode) +
9340                                    "' does not match required type");
9341       return;
9342     }
9343 
9344     auto DetectWriteToReservedRegister = [&]() {
9345       const MachineFunction &MF = DAG.getMachineFunction();
9346       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9347       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9348         if (Register::isPhysicalRegister(Reg) &&
9349             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9350           const char *RegName = TRI.getName(Reg);
9351           emitInlineAsmError(Call, "write to reserved register '" +
9352                                        Twine(RegName) + "'");
9353           return true;
9354         }
9355       }
9356       return false;
9357     };
9358     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9359             (OpInfo.Type == InlineAsm::isInput &&
9360              !OpInfo.isMatchingInputConstraint())) &&
9361            "Only address as input operand is allowed.");
9362 
9363     switch (OpInfo.Type) {
9364     case InlineAsm::isOutput:
9365       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9366         const InlineAsm::ConstraintCode ConstraintID =
9367             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9368         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9369                "Failed to convert memory constraint code to constraint id.");
9370 
9371         // Add information to the INLINEASM node to know about this output.
9372         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9373         OpFlags.setMemConstraint(ConstraintID);
9374         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9375                                                         MVT::i32));
9376         AsmNodeOperands.push_back(OpInfo.CallOperand);
9377       } else {
9378         // Otherwise, this outputs to a register (directly for C_Register /
9379         // C_RegisterClass, and a target-defined fashion for
9380         // C_Immediate/C_Other). Find a register that we can use.
9381         if (OpInfo.AssignedRegs.Regs.empty()) {
9382           emitInlineAsmError(
9383               Call, "couldn't allocate output register for constraint '" +
9384                         Twine(OpInfo.ConstraintCode) + "'");
9385           return;
9386         }
9387 
9388         if (DetectWriteToReservedRegister())
9389           return;
9390 
9391         // Add information to the INLINEASM node to know that this register is
9392         // set.
9393         OpInfo.AssignedRegs.AddInlineAsmOperands(
9394             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9395                                   : InlineAsm::Kind::RegDef,
9396             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9397       }
9398       break;
9399 
9400     case InlineAsm::isInput:
9401     case InlineAsm::isLabel: {
9402       SDValue InOperandVal = OpInfo.CallOperand;
9403 
9404       if (OpInfo.isMatchingInputConstraint()) {
9405         // If this is required to match an output register we have already set,
9406         // just use its register.
9407         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9408                                                   AsmNodeOperands);
9409         InlineAsm::Flag Flag(
9410             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue());
9411         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9412           if (OpInfo.isIndirect) {
9413             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9414             emitInlineAsmError(Call, "inline asm not supported yet: "
9415                                      "don't know how to handle tied "
9416                                      "indirect register inputs");
9417             return;
9418           }
9419 
9420           SmallVector<unsigned, 4> Regs;
9421           MachineFunction &MF = DAG.getMachineFunction();
9422           MachineRegisterInfo &MRI = MF.getRegInfo();
9423           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9424           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9425           Register TiedReg = R->getReg();
9426           MVT RegVT = R->getSimpleValueType(0);
9427           const TargetRegisterClass *RC =
9428               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9429               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9430                                       : TRI.getMinimalPhysRegClass(TiedReg);
9431           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9432             Regs.push_back(MRI.createVirtualRegister(RC));
9433 
9434           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9435 
9436           SDLoc dl = getCurSDLoc();
9437           // Use the produced MatchedRegs object to
9438           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9439           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9440                                            OpInfo.getMatchedOperand(), dl, DAG,
9441                                            AsmNodeOperands);
9442           break;
9443         }
9444 
9445         assert(Flag.isMemKind() && "Unknown matching constraint!");
9446         assert(Flag.getNumOperandRegisters() == 1 &&
9447                "Unexpected number of operands");
9448         // Add information to the INLINEASM node to know about this input.
9449         // See InlineAsm.h isUseOperandTiedToDef.
9450         Flag.clearMemConstraint();
9451         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9452         AsmNodeOperands.push_back(DAG.getTargetConstant(
9453             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9454         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9455         break;
9456       }
9457 
9458       // Treat indirect 'X' constraint as memory.
9459       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9460           OpInfo.isIndirect)
9461         OpInfo.ConstraintType = TargetLowering::C_Memory;
9462 
9463       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9464           OpInfo.ConstraintType == TargetLowering::C_Other) {
9465         std::vector<SDValue> Ops;
9466         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9467                                           Ops, DAG);
9468         if (Ops.empty()) {
9469           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9470             if (isa<ConstantSDNode>(InOperandVal)) {
9471               emitInlineAsmError(Call, "value out of range for constraint '" +
9472                                            Twine(OpInfo.ConstraintCode) + "'");
9473               return;
9474             }
9475 
9476           emitInlineAsmError(Call,
9477                              "invalid operand for inline asm constraint '" +
9478                                  Twine(OpInfo.ConstraintCode) + "'");
9479           return;
9480         }
9481 
9482         // Add information to the INLINEASM node to know about this input.
9483         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9484         AsmNodeOperands.push_back(DAG.getTargetConstant(
9485             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9486         llvm::append_range(AsmNodeOperands, Ops);
9487         break;
9488       }
9489 
9490       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9491         assert((OpInfo.isIndirect ||
9492                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9493                "Operand must be indirect to be a mem!");
9494         assert(InOperandVal.getValueType() ==
9495                    TLI.getPointerTy(DAG.getDataLayout()) &&
9496                "Memory operands expect pointer values");
9497 
9498         const InlineAsm::ConstraintCode ConstraintID =
9499             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9500         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9501                "Failed to convert memory constraint code to constraint id.");
9502 
9503         // Add information to the INLINEASM node to know about this input.
9504         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9505         ResOpType.setMemConstraint(ConstraintID);
9506         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9507                                                         getCurSDLoc(),
9508                                                         MVT::i32));
9509         AsmNodeOperands.push_back(InOperandVal);
9510         break;
9511       }
9512 
9513       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9514         const InlineAsm::ConstraintCode ConstraintID =
9515             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9516         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9517                "Failed to convert memory constraint code to constraint id.");
9518 
9519         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9520 
9521         SDValue AsmOp = InOperandVal;
9522         if (isFunction(InOperandVal)) {
9523           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9524           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9525           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9526                                              InOperandVal.getValueType(),
9527                                              GA->getOffset());
9528         }
9529 
9530         // Add information to the INLINEASM node to know about this input.
9531         ResOpType.setMemConstraint(ConstraintID);
9532 
9533         AsmNodeOperands.push_back(
9534             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9535 
9536         AsmNodeOperands.push_back(AsmOp);
9537         break;
9538       }
9539 
9540       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9541               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9542              "Unknown constraint type!");
9543 
9544       // TODO: Support this.
9545       if (OpInfo.isIndirect) {
9546         emitInlineAsmError(
9547             Call, "Don't know how to handle indirect register inputs yet "
9548                   "for constraint '" +
9549                       Twine(OpInfo.ConstraintCode) + "'");
9550         return;
9551       }
9552 
9553       // Copy the input into the appropriate registers.
9554       if (OpInfo.AssignedRegs.Regs.empty()) {
9555         emitInlineAsmError(Call,
9556                            "couldn't allocate input reg for constraint '" +
9557                                Twine(OpInfo.ConstraintCode) + "'");
9558         return;
9559       }
9560 
9561       if (DetectWriteToReservedRegister())
9562         return;
9563 
9564       SDLoc dl = getCurSDLoc();
9565 
9566       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9567                                         &Call);
9568 
9569       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9570                                                0, dl, DAG, AsmNodeOperands);
9571       break;
9572     }
9573     case InlineAsm::isClobber:
9574       // Add the clobbered value to the operand list, so that the register
9575       // allocator is aware that the physreg got clobbered.
9576       if (!OpInfo.AssignedRegs.Regs.empty())
9577         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9578                                                  false, 0, getCurSDLoc(), DAG,
9579                                                  AsmNodeOperands);
9580       break;
9581     }
9582   }
9583 
9584   // Finish up input operands.  Set the input chain and add the flag last.
9585   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9586   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9587 
9588   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9589   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9590                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9591   Glue = Chain.getValue(1);
9592 
9593   // Do additional work to generate outputs.
9594 
9595   SmallVector<EVT, 1> ResultVTs;
9596   SmallVector<SDValue, 1> ResultValues;
9597   SmallVector<SDValue, 8> OutChains;
9598 
9599   llvm::Type *CallResultType = Call.getType();
9600   ArrayRef<Type *> ResultTypes;
9601   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9602     ResultTypes = StructResult->elements();
9603   else if (!CallResultType->isVoidTy())
9604     ResultTypes = ArrayRef(CallResultType);
9605 
9606   auto CurResultType = ResultTypes.begin();
9607   auto handleRegAssign = [&](SDValue V) {
9608     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9609     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9610     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9611     ++CurResultType;
9612     // If the type of the inline asm call site return value is different but has
9613     // same size as the type of the asm output bitcast it.  One example of this
9614     // is for vectors with different width / number of elements.  This can
9615     // happen for register classes that can contain multiple different value
9616     // types.  The preg or vreg allocated may not have the same VT as was
9617     // expected.
9618     //
9619     // This can also happen for a return value that disagrees with the register
9620     // class it is put in, eg. a double in a general-purpose register on a
9621     // 32-bit machine.
9622     if (ResultVT != V.getValueType() &&
9623         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9624       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9625     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9626              V.getValueType().isInteger()) {
9627       // If a result value was tied to an input value, the computed result
9628       // may have a wider width than the expected result.  Extract the
9629       // relevant portion.
9630       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9631     }
9632     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9633     ResultVTs.push_back(ResultVT);
9634     ResultValues.push_back(V);
9635   };
9636 
9637   // Deal with output operands.
9638   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9639     if (OpInfo.Type == InlineAsm::isOutput) {
9640       SDValue Val;
9641       // Skip trivial output operands.
9642       if (OpInfo.AssignedRegs.Regs.empty())
9643         continue;
9644 
9645       switch (OpInfo.ConstraintType) {
9646       case TargetLowering::C_Register:
9647       case TargetLowering::C_RegisterClass:
9648         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9649                                                   Chain, &Glue, &Call);
9650         break;
9651       case TargetLowering::C_Immediate:
9652       case TargetLowering::C_Other:
9653         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9654                                               OpInfo, DAG);
9655         break;
9656       case TargetLowering::C_Memory:
9657         break; // Already handled.
9658       case TargetLowering::C_Address:
9659         break; // Silence warning.
9660       case TargetLowering::C_Unknown:
9661         assert(false && "Unexpected unknown constraint");
9662       }
9663 
9664       // Indirect output manifest as stores. Record output chains.
9665       if (OpInfo.isIndirect) {
9666         const Value *Ptr = OpInfo.CallOperandVal;
9667         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9668         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9669                                      MachinePointerInfo(Ptr));
9670         OutChains.push_back(Store);
9671       } else {
9672         // generate CopyFromRegs to associated registers.
9673         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9674         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9675           for (const SDValue &V : Val->op_values())
9676             handleRegAssign(V);
9677         } else
9678           handleRegAssign(Val);
9679       }
9680     }
9681   }
9682 
9683   // Set results.
9684   if (!ResultValues.empty()) {
9685     assert(CurResultType == ResultTypes.end() &&
9686            "Mismatch in number of ResultTypes");
9687     assert(ResultValues.size() == ResultTypes.size() &&
9688            "Mismatch in number of output operands in asm result");
9689 
9690     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9691                             DAG.getVTList(ResultVTs), ResultValues);
9692     setValue(&Call, V);
9693   }
9694 
9695   // Collect store chains.
9696   if (!OutChains.empty())
9697     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9698 
9699   if (EmitEHLabels) {
9700     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9701   }
9702 
9703   // Only Update Root if inline assembly has a memory effect.
9704   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9705       EmitEHLabels)
9706     DAG.setRoot(Chain);
9707 }
9708 
9709 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9710                                              const Twine &Message) {
9711   LLVMContext &Ctx = *DAG.getContext();
9712   Ctx.emitError(&Call, Message);
9713 
9714   // Make sure we leave the DAG in a valid state
9715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9716   SmallVector<EVT, 1> ValueVTs;
9717   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9718 
9719   if (ValueVTs.empty())
9720     return;
9721 
9722   SmallVector<SDValue, 1> Ops;
9723   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9724     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9725 
9726   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9727 }
9728 
9729 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9730   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9731                           MVT::Other, getRoot(),
9732                           getValue(I.getArgOperand(0)),
9733                           DAG.getSrcValue(I.getArgOperand(0))));
9734 }
9735 
9736 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9738   const DataLayout &DL = DAG.getDataLayout();
9739   SDValue V = DAG.getVAArg(
9740       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9741       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9742       DL.getABITypeAlign(I.getType()).value());
9743   DAG.setRoot(V.getValue(1));
9744 
9745   if (I.getType()->isPointerTy())
9746     V = DAG.getPtrExtOrTrunc(
9747         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9748   setValue(&I, V);
9749 }
9750 
9751 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9752   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9753                           MVT::Other, getRoot(),
9754                           getValue(I.getArgOperand(0)),
9755                           DAG.getSrcValue(I.getArgOperand(0))));
9756 }
9757 
9758 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9759   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9760                           MVT::Other, getRoot(),
9761                           getValue(I.getArgOperand(0)),
9762                           getValue(I.getArgOperand(1)),
9763                           DAG.getSrcValue(I.getArgOperand(0)),
9764                           DAG.getSrcValue(I.getArgOperand(1))));
9765 }
9766 
9767 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9768                                                     const Instruction &I,
9769                                                     SDValue Op) {
9770   const MDNode *Range = getRangeMetadata(I);
9771   if (!Range)
9772     return Op;
9773 
9774   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9775   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9776     return Op;
9777 
9778   APInt Lo = CR.getUnsignedMin();
9779   if (!Lo.isMinValue())
9780     return Op;
9781 
9782   APInt Hi = CR.getUnsignedMax();
9783   unsigned Bits = std::max(Hi.getActiveBits(),
9784                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9785 
9786   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9787 
9788   SDLoc SL = getCurSDLoc();
9789 
9790   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9791                              DAG.getValueType(SmallVT));
9792   unsigned NumVals = Op.getNode()->getNumValues();
9793   if (NumVals == 1)
9794     return ZExt;
9795 
9796   SmallVector<SDValue, 4> Ops;
9797 
9798   Ops.push_back(ZExt);
9799   for (unsigned I = 1; I != NumVals; ++I)
9800     Ops.push_back(Op.getValue(I));
9801 
9802   return DAG.getMergeValues(Ops, SL);
9803 }
9804 
9805 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9806 /// the call being lowered.
9807 ///
9808 /// This is a helper for lowering intrinsics that follow a target calling
9809 /// convention or require stack pointer adjustment. Only a subset of the
9810 /// intrinsic's operands need to participate in the calling convention.
9811 void SelectionDAGBuilder::populateCallLoweringInfo(
9812     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9813     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9814     AttributeSet RetAttrs, bool IsPatchPoint) {
9815   TargetLowering::ArgListTy Args;
9816   Args.reserve(NumArgs);
9817 
9818   // Populate the argument list.
9819   // Attributes for args start at offset 1, after the return attribute.
9820   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9821        ArgI != ArgE; ++ArgI) {
9822     const Value *V = Call->getOperand(ArgI);
9823 
9824     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9825 
9826     TargetLowering::ArgListEntry Entry;
9827     Entry.Node = getValue(V);
9828     Entry.Ty = V->getType();
9829     Entry.setAttributes(Call, ArgI);
9830     Args.push_back(Entry);
9831   }
9832 
9833   CLI.setDebugLoc(getCurSDLoc())
9834       .setChain(getRoot())
9835       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9836                  RetAttrs)
9837       .setDiscardResult(Call->use_empty())
9838       .setIsPatchPoint(IsPatchPoint)
9839       .setIsPreallocated(
9840           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9841 }
9842 
9843 /// Add a stack map intrinsic call's live variable operands to a stackmap
9844 /// or patchpoint target node's operand list.
9845 ///
9846 /// Constants are converted to TargetConstants purely as an optimization to
9847 /// avoid constant materialization and register allocation.
9848 ///
9849 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9850 /// generate addess computation nodes, and so FinalizeISel can convert the
9851 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9852 /// address materialization and register allocation, but may also be required
9853 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9854 /// alloca in the entry block, then the runtime may assume that the alloca's
9855 /// StackMap location can be read immediately after compilation and that the
9856 /// location is valid at any point during execution (this is similar to the
9857 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9858 /// only available in a register, then the runtime would need to trap when
9859 /// execution reaches the StackMap in order to read the alloca's location.
9860 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9861                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9862                                 SelectionDAGBuilder &Builder) {
9863   SelectionDAG &DAG = Builder.DAG;
9864   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9865     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9866 
9867     // Things on the stack are pointer-typed, meaning that they are already
9868     // legal and can be emitted directly to target nodes.
9869     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9870       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9871     } else {
9872       // Otherwise emit a target independent node to be legalised.
9873       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9874     }
9875   }
9876 }
9877 
9878 /// Lower llvm.experimental.stackmap.
9879 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9880   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9881   //                                  [live variables...])
9882 
9883   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9884 
9885   SDValue Chain, InGlue, Callee;
9886   SmallVector<SDValue, 32> Ops;
9887 
9888   SDLoc DL = getCurSDLoc();
9889   Callee = getValue(CI.getCalledOperand());
9890 
9891   // The stackmap intrinsic only records the live variables (the arguments
9892   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9893   // intrinsic, this won't be lowered to a function call. This means we don't
9894   // have to worry about calling conventions and target specific lowering code.
9895   // Instead we perform the call lowering right here.
9896   //
9897   // chain, flag = CALLSEQ_START(chain, 0, 0)
9898   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9899   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9900   //
9901   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9902   InGlue = Chain.getValue(1);
9903 
9904   // Add the STACKMAP operands, starting with DAG house-keeping.
9905   Ops.push_back(Chain);
9906   Ops.push_back(InGlue);
9907 
9908   // Add the <id>, <numShadowBytes> operands.
9909   //
9910   // These do not require legalisation, and can be emitted directly to target
9911   // constant nodes.
9912   SDValue ID = getValue(CI.getArgOperand(0));
9913   assert(ID.getValueType() == MVT::i64);
9914   SDValue IDConst = DAG.getTargetConstant(
9915       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9916   Ops.push_back(IDConst);
9917 
9918   SDValue Shad = getValue(CI.getArgOperand(1));
9919   assert(Shad.getValueType() == MVT::i32);
9920   SDValue ShadConst = DAG.getTargetConstant(
9921       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9922   Ops.push_back(ShadConst);
9923 
9924   // Add the live variables.
9925   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9926 
9927   // Create the STACKMAP node.
9928   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9929   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9930   InGlue = Chain.getValue(1);
9931 
9932   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9933 
9934   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9935 
9936   // Set the root to the target-lowered call chain.
9937   DAG.setRoot(Chain);
9938 
9939   // Inform the Frame Information that we have a stackmap in this function.
9940   FuncInfo.MF->getFrameInfo().setHasStackMap();
9941 }
9942 
9943 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9944 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9945                                           const BasicBlock *EHPadBB) {
9946   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9947   //                                                 i32 <numBytes>,
9948   //                                                 i8* <target>,
9949   //                                                 i32 <numArgs>,
9950   //                                                 [Args...],
9951   //                                                 [live variables...])
9952 
9953   CallingConv::ID CC = CB.getCallingConv();
9954   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9955   bool HasDef = !CB.getType()->isVoidTy();
9956   SDLoc dl = getCurSDLoc();
9957   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9958 
9959   // Handle immediate and symbolic callees.
9960   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9961     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9962                                    /*isTarget=*/true);
9963   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9964     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9965                                          SDLoc(SymbolicCallee),
9966                                          SymbolicCallee->getValueType(0));
9967 
9968   // Get the real number of arguments participating in the call <numArgs>
9969   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9970   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9971 
9972   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9973   // Intrinsics include all meta-operands up to but not including CC.
9974   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9975   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9976          "Not enough arguments provided to the patchpoint intrinsic");
9977 
9978   // For AnyRegCC the arguments are lowered later on manually.
9979   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9980   Type *ReturnTy =
9981       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9982 
9983   TargetLowering::CallLoweringInfo CLI(DAG);
9984   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9985                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
9986   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9987 
9988   SDNode *CallEnd = Result.second.getNode();
9989   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9990     CallEnd = CallEnd->getOperand(0).getNode();
9991 
9992   /// Get a call instruction from the call sequence chain.
9993   /// Tail calls are not allowed.
9994   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9995          "Expected a callseq node.");
9996   SDNode *Call = CallEnd->getOperand(0).getNode();
9997   bool HasGlue = Call->getGluedNode();
9998 
9999   // Replace the target specific call node with the patchable intrinsic.
10000   SmallVector<SDValue, 8> Ops;
10001 
10002   // Push the chain.
10003   Ops.push_back(*(Call->op_begin()));
10004 
10005   // Optionally, push the glue (if any).
10006   if (HasGlue)
10007     Ops.push_back(*(Call->op_end() - 1));
10008 
10009   // Push the register mask info.
10010   if (HasGlue)
10011     Ops.push_back(*(Call->op_end() - 2));
10012   else
10013     Ops.push_back(*(Call->op_end() - 1));
10014 
10015   // Add the <id> and <numBytes> constants.
10016   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10017   Ops.push_back(DAG.getTargetConstant(
10018                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
10019   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10020   Ops.push_back(DAG.getTargetConstant(
10021                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
10022                   MVT::i32));
10023 
10024   // Add the callee.
10025   Ops.push_back(Callee);
10026 
10027   // Adjust <numArgs> to account for any arguments that have been passed on the
10028   // stack instead.
10029   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10030   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10031   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10032   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10033 
10034   // Add the calling convention
10035   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10036 
10037   // Add the arguments we omitted previously. The register allocator should
10038   // place these in any free register.
10039   if (IsAnyRegCC)
10040     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10041       Ops.push_back(getValue(CB.getArgOperand(i)));
10042 
10043   // Push the arguments from the call instruction.
10044   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10045   Ops.append(Call->op_begin() + 2, e);
10046 
10047   // Push live variables for the stack map.
10048   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10049 
10050   SDVTList NodeTys;
10051   if (IsAnyRegCC && HasDef) {
10052     // Create the return types based on the intrinsic definition
10053     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10054     SmallVector<EVT, 3> ValueVTs;
10055     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10056     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10057 
10058     // There is always a chain and a glue type at the end
10059     ValueVTs.push_back(MVT::Other);
10060     ValueVTs.push_back(MVT::Glue);
10061     NodeTys = DAG.getVTList(ValueVTs);
10062   } else
10063     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10064 
10065   // Replace the target specific call node with a PATCHPOINT node.
10066   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10067 
10068   // Update the NodeMap.
10069   if (HasDef) {
10070     if (IsAnyRegCC)
10071       setValue(&CB, SDValue(PPV.getNode(), 0));
10072     else
10073       setValue(&CB, Result.first);
10074   }
10075 
10076   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10077   // call sequence. Furthermore the location of the chain and glue can change
10078   // when the AnyReg calling convention is used and the intrinsic returns a
10079   // value.
10080   if (IsAnyRegCC && HasDef) {
10081     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10082     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10083     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10084   } else
10085     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10086   DAG.DeleteNode(Call);
10087 
10088   // Inform the Frame Information that we have a patchpoint in this function.
10089   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10090 }
10091 
10092 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10093                                             unsigned Intrinsic) {
10094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10095   SDValue Op1 = getValue(I.getArgOperand(0));
10096   SDValue Op2;
10097   if (I.arg_size() > 1)
10098     Op2 = getValue(I.getArgOperand(1));
10099   SDLoc dl = getCurSDLoc();
10100   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10101   SDValue Res;
10102   SDNodeFlags SDFlags;
10103   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10104     SDFlags.copyFMF(*FPMO);
10105 
10106   switch (Intrinsic) {
10107   case Intrinsic::vector_reduce_fadd:
10108     if (SDFlags.hasAllowReassociation())
10109       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10110                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10111                         SDFlags);
10112     else
10113       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10114     break;
10115   case Intrinsic::vector_reduce_fmul:
10116     if (SDFlags.hasAllowReassociation())
10117       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10118                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10119                         SDFlags);
10120     else
10121       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10122     break;
10123   case Intrinsic::vector_reduce_add:
10124     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10125     break;
10126   case Intrinsic::vector_reduce_mul:
10127     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10128     break;
10129   case Intrinsic::vector_reduce_and:
10130     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10131     break;
10132   case Intrinsic::vector_reduce_or:
10133     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10134     break;
10135   case Intrinsic::vector_reduce_xor:
10136     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10137     break;
10138   case Intrinsic::vector_reduce_smax:
10139     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10140     break;
10141   case Intrinsic::vector_reduce_smin:
10142     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10143     break;
10144   case Intrinsic::vector_reduce_umax:
10145     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10146     break;
10147   case Intrinsic::vector_reduce_umin:
10148     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10149     break;
10150   case Intrinsic::vector_reduce_fmax:
10151     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10152     break;
10153   case Intrinsic::vector_reduce_fmin:
10154     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10155     break;
10156   case Intrinsic::vector_reduce_fmaximum:
10157     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10158     break;
10159   case Intrinsic::vector_reduce_fminimum:
10160     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10161     break;
10162   default:
10163     llvm_unreachable("Unhandled vector reduce intrinsic");
10164   }
10165   setValue(&I, Res);
10166 }
10167 
10168 /// Returns an AttributeList representing the attributes applied to the return
10169 /// value of the given call.
10170 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10171   SmallVector<Attribute::AttrKind, 2> Attrs;
10172   if (CLI.RetSExt)
10173     Attrs.push_back(Attribute::SExt);
10174   if (CLI.RetZExt)
10175     Attrs.push_back(Attribute::ZExt);
10176   if (CLI.IsInReg)
10177     Attrs.push_back(Attribute::InReg);
10178 
10179   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10180                             Attrs);
10181 }
10182 
10183 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10184 /// implementation, which just calls LowerCall.
10185 /// FIXME: When all targets are
10186 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10187 std::pair<SDValue, SDValue>
10188 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10189   // Handle the incoming return values from the call.
10190   CLI.Ins.clear();
10191   Type *OrigRetTy = CLI.RetTy;
10192   SmallVector<EVT, 4> RetTys;
10193   SmallVector<uint64_t, 4> Offsets;
10194   auto &DL = CLI.DAG.getDataLayout();
10195   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10196 
10197   if (CLI.IsPostTypeLegalization) {
10198     // If we are lowering a libcall after legalization, split the return type.
10199     SmallVector<EVT, 4> OldRetTys;
10200     SmallVector<uint64_t, 4> OldOffsets;
10201     RetTys.swap(OldRetTys);
10202     Offsets.swap(OldOffsets);
10203 
10204     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10205       EVT RetVT = OldRetTys[i];
10206       uint64_t Offset = OldOffsets[i];
10207       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10208       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10209       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10210       RetTys.append(NumRegs, RegisterVT);
10211       for (unsigned j = 0; j != NumRegs; ++j)
10212         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10213     }
10214   }
10215 
10216   SmallVector<ISD::OutputArg, 4> Outs;
10217   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10218 
10219   bool CanLowerReturn =
10220       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10221                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10222 
10223   SDValue DemoteStackSlot;
10224   int DemoteStackIdx = -100;
10225   if (!CanLowerReturn) {
10226     // FIXME: equivalent assert?
10227     // assert(!CS.hasInAllocaArgument() &&
10228     //        "sret demotion is incompatible with inalloca");
10229     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10230     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10231     MachineFunction &MF = CLI.DAG.getMachineFunction();
10232     DemoteStackIdx =
10233         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10234     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10235                                               DL.getAllocaAddrSpace());
10236 
10237     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10238     ArgListEntry Entry;
10239     Entry.Node = DemoteStackSlot;
10240     Entry.Ty = StackSlotPtrType;
10241     Entry.IsSExt = false;
10242     Entry.IsZExt = false;
10243     Entry.IsInReg = false;
10244     Entry.IsSRet = true;
10245     Entry.IsNest = false;
10246     Entry.IsByVal = false;
10247     Entry.IsByRef = false;
10248     Entry.IsReturned = false;
10249     Entry.IsSwiftSelf = false;
10250     Entry.IsSwiftAsync = false;
10251     Entry.IsSwiftError = false;
10252     Entry.IsCFGuardTarget = false;
10253     Entry.Alignment = Alignment;
10254     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10255     CLI.NumFixedArgs += 1;
10256     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10257     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10258 
10259     // sret demotion isn't compatible with tail-calls, since the sret argument
10260     // points into the callers stack frame.
10261     CLI.IsTailCall = false;
10262   } else {
10263     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10264         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10265     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10266       ISD::ArgFlagsTy Flags;
10267       if (NeedsRegBlock) {
10268         Flags.setInConsecutiveRegs();
10269         if (I == RetTys.size() - 1)
10270           Flags.setInConsecutiveRegsLast();
10271       }
10272       EVT VT = RetTys[I];
10273       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10274                                                      CLI.CallConv, VT);
10275       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10276                                                        CLI.CallConv, VT);
10277       for (unsigned i = 0; i != NumRegs; ++i) {
10278         ISD::InputArg MyFlags;
10279         MyFlags.Flags = Flags;
10280         MyFlags.VT = RegisterVT;
10281         MyFlags.ArgVT = VT;
10282         MyFlags.Used = CLI.IsReturnValueUsed;
10283         if (CLI.RetTy->isPointerTy()) {
10284           MyFlags.Flags.setPointer();
10285           MyFlags.Flags.setPointerAddrSpace(
10286               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10287         }
10288         if (CLI.RetSExt)
10289           MyFlags.Flags.setSExt();
10290         if (CLI.RetZExt)
10291           MyFlags.Flags.setZExt();
10292         if (CLI.IsInReg)
10293           MyFlags.Flags.setInReg();
10294         CLI.Ins.push_back(MyFlags);
10295       }
10296     }
10297   }
10298 
10299   // We push in swifterror return as the last element of CLI.Ins.
10300   ArgListTy &Args = CLI.getArgs();
10301   if (supportSwiftError()) {
10302     for (const ArgListEntry &Arg : Args) {
10303       if (Arg.IsSwiftError) {
10304         ISD::InputArg MyFlags;
10305         MyFlags.VT = getPointerTy(DL);
10306         MyFlags.ArgVT = EVT(getPointerTy(DL));
10307         MyFlags.Flags.setSwiftError();
10308         CLI.Ins.push_back(MyFlags);
10309       }
10310     }
10311   }
10312 
10313   // Handle all of the outgoing arguments.
10314   CLI.Outs.clear();
10315   CLI.OutVals.clear();
10316   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10317     SmallVector<EVT, 4> ValueVTs;
10318     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10319     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10320     Type *FinalType = Args[i].Ty;
10321     if (Args[i].IsByVal)
10322       FinalType = Args[i].IndirectType;
10323     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10324         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10325     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10326          ++Value) {
10327       EVT VT = ValueVTs[Value];
10328       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10329       SDValue Op = SDValue(Args[i].Node.getNode(),
10330                            Args[i].Node.getResNo() + Value);
10331       ISD::ArgFlagsTy Flags;
10332 
10333       // Certain targets (such as MIPS), may have a different ABI alignment
10334       // for a type depending on the context. Give the target a chance to
10335       // specify the alignment it wants.
10336       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10337       Flags.setOrigAlign(OriginalAlignment);
10338 
10339       if (Args[i].Ty->isPointerTy()) {
10340         Flags.setPointer();
10341         Flags.setPointerAddrSpace(
10342             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10343       }
10344       if (Args[i].IsZExt)
10345         Flags.setZExt();
10346       if (Args[i].IsSExt)
10347         Flags.setSExt();
10348       if (Args[i].IsInReg) {
10349         // If we are using vectorcall calling convention, a structure that is
10350         // passed InReg - is surely an HVA
10351         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10352             isa<StructType>(FinalType)) {
10353           // The first value of a structure is marked
10354           if (0 == Value)
10355             Flags.setHvaStart();
10356           Flags.setHva();
10357         }
10358         // Set InReg Flag
10359         Flags.setInReg();
10360       }
10361       if (Args[i].IsSRet)
10362         Flags.setSRet();
10363       if (Args[i].IsSwiftSelf)
10364         Flags.setSwiftSelf();
10365       if (Args[i].IsSwiftAsync)
10366         Flags.setSwiftAsync();
10367       if (Args[i].IsSwiftError)
10368         Flags.setSwiftError();
10369       if (Args[i].IsCFGuardTarget)
10370         Flags.setCFGuardTarget();
10371       if (Args[i].IsByVal)
10372         Flags.setByVal();
10373       if (Args[i].IsByRef)
10374         Flags.setByRef();
10375       if (Args[i].IsPreallocated) {
10376         Flags.setPreallocated();
10377         // Set the byval flag for CCAssignFn callbacks that don't know about
10378         // preallocated.  This way we can know how many bytes we should've
10379         // allocated and how many bytes a callee cleanup function will pop.  If
10380         // we port preallocated to more targets, we'll have to add custom
10381         // preallocated handling in the various CC lowering callbacks.
10382         Flags.setByVal();
10383       }
10384       if (Args[i].IsInAlloca) {
10385         Flags.setInAlloca();
10386         // Set the byval flag for CCAssignFn callbacks that don't know about
10387         // inalloca.  This way we can know how many bytes we should've allocated
10388         // and how many bytes a callee cleanup function will pop.  If we port
10389         // inalloca to more targets, we'll have to add custom inalloca handling
10390         // in the various CC lowering callbacks.
10391         Flags.setByVal();
10392       }
10393       Align MemAlign;
10394       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10395         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10396         Flags.setByValSize(FrameSize);
10397 
10398         // info is not there but there are cases it cannot get right.
10399         if (auto MA = Args[i].Alignment)
10400           MemAlign = *MA;
10401         else
10402           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10403       } else if (auto MA = Args[i].Alignment) {
10404         MemAlign = *MA;
10405       } else {
10406         MemAlign = OriginalAlignment;
10407       }
10408       Flags.setMemAlign(MemAlign);
10409       if (Args[i].IsNest)
10410         Flags.setNest();
10411       if (NeedsRegBlock)
10412         Flags.setInConsecutiveRegs();
10413 
10414       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10415                                                  CLI.CallConv, VT);
10416       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10417                                                         CLI.CallConv, VT);
10418       SmallVector<SDValue, 4> Parts(NumParts);
10419       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10420 
10421       if (Args[i].IsSExt)
10422         ExtendKind = ISD::SIGN_EXTEND;
10423       else if (Args[i].IsZExt)
10424         ExtendKind = ISD::ZERO_EXTEND;
10425 
10426       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10427       // for now.
10428       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10429           CanLowerReturn) {
10430         assert((CLI.RetTy == Args[i].Ty ||
10431                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10432                  CLI.RetTy->getPointerAddressSpace() ==
10433                      Args[i].Ty->getPointerAddressSpace())) &&
10434                RetTys.size() == NumValues && "unexpected use of 'returned'");
10435         // Before passing 'returned' to the target lowering code, ensure that
10436         // either the register MVT and the actual EVT are the same size or that
10437         // the return value and argument are extended in the same way; in these
10438         // cases it's safe to pass the argument register value unchanged as the
10439         // return register value (although it's at the target's option whether
10440         // to do so)
10441         // TODO: allow code generation to take advantage of partially preserved
10442         // registers rather than clobbering the entire register when the
10443         // parameter extension method is not compatible with the return
10444         // extension method
10445         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10446             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10447              CLI.RetZExt == Args[i].IsZExt))
10448           Flags.setReturned();
10449       }
10450 
10451       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10452                      CLI.CallConv, ExtendKind);
10453 
10454       for (unsigned j = 0; j != NumParts; ++j) {
10455         // if it isn't first piece, alignment must be 1
10456         // For scalable vectors the scalable part is currently handled
10457         // by individual targets, so we just use the known minimum size here.
10458         ISD::OutputArg MyFlags(
10459             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10460             i < CLI.NumFixedArgs, i,
10461             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10462         if (NumParts > 1 && j == 0)
10463           MyFlags.Flags.setSplit();
10464         else if (j != 0) {
10465           MyFlags.Flags.setOrigAlign(Align(1));
10466           if (j == NumParts - 1)
10467             MyFlags.Flags.setSplitEnd();
10468         }
10469 
10470         CLI.Outs.push_back(MyFlags);
10471         CLI.OutVals.push_back(Parts[j]);
10472       }
10473 
10474       if (NeedsRegBlock && Value == NumValues - 1)
10475         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10476     }
10477   }
10478 
10479   SmallVector<SDValue, 4> InVals;
10480   CLI.Chain = LowerCall(CLI, InVals);
10481 
10482   // Update CLI.InVals to use outside of this function.
10483   CLI.InVals = InVals;
10484 
10485   // Verify that the target's LowerCall behaved as expected.
10486   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10487          "LowerCall didn't return a valid chain!");
10488   assert((!CLI.IsTailCall || InVals.empty()) &&
10489          "LowerCall emitted a return value for a tail call!");
10490   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10491          "LowerCall didn't emit the correct number of values!");
10492 
10493   // For a tail call, the return value is merely live-out and there aren't
10494   // any nodes in the DAG representing it. Return a special value to
10495   // indicate that a tail call has been emitted and no more Instructions
10496   // should be processed in the current block.
10497   if (CLI.IsTailCall) {
10498     CLI.DAG.setRoot(CLI.Chain);
10499     return std::make_pair(SDValue(), SDValue());
10500   }
10501 
10502 #ifndef NDEBUG
10503   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10504     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10505     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10506            "LowerCall emitted a value with the wrong type!");
10507   }
10508 #endif
10509 
10510   SmallVector<SDValue, 4> ReturnValues;
10511   if (!CanLowerReturn) {
10512     // The instruction result is the result of loading from the
10513     // hidden sret parameter.
10514     SmallVector<EVT, 1> PVTs;
10515     Type *PtrRetTy =
10516         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10517 
10518     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10519     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10520     EVT PtrVT = PVTs[0];
10521 
10522     unsigned NumValues = RetTys.size();
10523     ReturnValues.resize(NumValues);
10524     SmallVector<SDValue, 4> Chains(NumValues);
10525 
10526     // An aggregate return value cannot wrap around the address space, so
10527     // offsets to its parts don't wrap either.
10528     SDNodeFlags Flags;
10529     Flags.setNoUnsignedWrap(true);
10530 
10531     MachineFunction &MF = CLI.DAG.getMachineFunction();
10532     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10533     for (unsigned i = 0; i < NumValues; ++i) {
10534       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10535                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10536                                                         PtrVT), Flags);
10537       SDValue L = CLI.DAG.getLoad(
10538           RetTys[i], CLI.DL, CLI.Chain, Add,
10539           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10540                                             DemoteStackIdx, Offsets[i]),
10541           HiddenSRetAlign);
10542       ReturnValues[i] = L;
10543       Chains[i] = L.getValue(1);
10544     }
10545 
10546     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10547   } else {
10548     // Collect the legal value parts into potentially illegal values
10549     // that correspond to the original function's return values.
10550     std::optional<ISD::NodeType> AssertOp;
10551     if (CLI.RetSExt)
10552       AssertOp = ISD::AssertSext;
10553     else if (CLI.RetZExt)
10554       AssertOp = ISD::AssertZext;
10555     unsigned CurReg = 0;
10556     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10557       EVT VT = RetTys[I];
10558       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10559                                                      CLI.CallConv, VT);
10560       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10561                                                        CLI.CallConv, VT);
10562 
10563       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10564                                               NumRegs, RegisterVT, VT, nullptr,
10565                                               CLI.CallConv, AssertOp));
10566       CurReg += NumRegs;
10567     }
10568 
10569     // For a function returning void, there is no return value. We can't create
10570     // such a node, so we just return a null return value in that case. In
10571     // that case, nothing will actually look at the value.
10572     if (ReturnValues.empty())
10573       return std::make_pair(SDValue(), CLI.Chain);
10574   }
10575 
10576   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10577                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10578   return std::make_pair(Res, CLI.Chain);
10579 }
10580 
10581 /// Places new result values for the node in Results (their number
10582 /// and types must exactly match those of the original return values of
10583 /// the node), or leaves Results empty, which indicates that the node is not
10584 /// to be custom lowered after all.
10585 void TargetLowering::LowerOperationWrapper(SDNode *N,
10586                                            SmallVectorImpl<SDValue> &Results,
10587                                            SelectionDAG &DAG) const {
10588   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10589 
10590   if (!Res.getNode())
10591     return;
10592 
10593   // If the original node has one result, take the return value from
10594   // LowerOperation as is. It might not be result number 0.
10595   if (N->getNumValues() == 1) {
10596     Results.push_back(Res);
10597     return;
10598   }
10599 
10600   // If the original node has multiple results, then the return node should
10601   // have the same number of results.
10602   assert((N->getNumValues() == Res->getNumValues()) &&
10603       "Lowering returned the wrong number of results!");
10604 
10605   // Places new result values base on N result number.
10606   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10607     Results.push_back(Res.getValue(I));
10608 }
10609 
10610 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10611   llvm_unreachable("LowerOperation not implemented for this target!");
10612 }
10613 
10614 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10615                                                      unsigned Reg,
10616                                                      ISD::NodeType ExtendType) {
10617   SDValue Op = getNonRegisterValue(V);
10618   assert((Op.getOpcode() != ISD::CopyFromReg ||
10619           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10620          "Copy from a reg to the same reg!");
10621   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10622 
10623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10624   // If this is an InlineAsm we have to match the registers required, not the
10625   // notional registers required by the type.
10626 
10627   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10628                    std::nullopt); // This is not an ABI copy.
10629   SDValue Chain = DAG.getEntryNode();
10630 
10631   if (ExtendType == ISD::ANY_EXTEND) {
10632     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10633     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10634       ExtendType = PreferredExtendIt->second;
10635   }
10636   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10637   PendingExports.push_back(Chain);
10638 }
10639 
10640 #include "llvm/CodeGen/SelectionDAGISel.h"
10641 
10642 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10643 /// entry block, return true.  This includes arguments used by switches, since
10644 /// the switch may expand into multiple basic blocks.
10645 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10646   // With FastISel active, we may be splitting blocks, so force creation
10647   // of virtual registers for all non-dead arguments.
10648   if (FastISel)
10649     return A->use_empty();
10650 
10651   const BasicBlock &Entry = A->getParent()->front();
10652   for (const User *U : A->users())
10653     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10654       return false;  // Use not in entry block.
10655 
10656   return true;
10657 }
10658 
10659 using ArgCopyElisionMapTy =
10660     DenseMap<const Argument *,
10661              std::pair<const AllocaInst *, const StoreInst *>>;
10662 
10663 /// Scan the entry block of the function in FuncInfo for arguments that look
10664 /// like copies into a local alloca. Record any copied arguments in
10665 /// ArgCopyElisionCandidates.
10666 static void
10667 findArgumentCopyElisionCandidates(const DataLayout &DL,
10668                                   FunctionLoweringInfo *FuncInfo,
10669                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10670   // Record the state of every static alloca used in the entry block. Argument
10671   // allocas are all used in the entry block, so we need approximately as many
10672   // entries as we have arguments.
10673   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10674   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10675   unsigned NumArgs = FuncInfo->Fn->arg_size();
10676   StaticAllocas.reserve(NumArgs * 2);
10677 
10678   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10679     if (!V)
10680       return nullptr;
10681     V = V->stripPointerCasts();
10682     const auto *AI = dyn_cast<AllocaInst>(V);
10683     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10684       return nullptr;
10685     auto Iter = StaticAllocas.insert({AI, Unknown});
10686     return &Iter.first->second;
10687   };
10688 
10689   // Look for stores of arguments to static allocas. Look through bitcasts and
10690   // GEPs to handle type coercions, as long as the alloca is fully initialized
10691   // by the store. Any non-store use of an alloca escapes it and any subsequent
10692   // unanalyzed store might write it.
10693   // FIXME: Handle structs initialized with multiple stores.
10694   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10695     // Look for stores, and handle non-store uses conservatively.
10696     const auto *SI = dyn_cast<StoreInst>(&I);
10697     if (!SI) {
10698       // We will look through cast uses, so ignore them completely.
10699       if (I.isCast())
10700         continue;
10701       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10702       // to allocas.
10703       if (I.isDebugOrPseudoInst())
10704         continue;
10705       // This is an unknown instruction. Assume it escapes or writes to all
10706       // static alloca operands.
10707       for (const Use &U : I.operands()) {
10708         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10709           *Info = StaticAllocaInfo::Clobbered;
10710       }
10711       continue;
10712     }
10713 
10714     // If the stored value is a static alloca, mark it as escaped.
10715     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10716       *Info = StaticAllocaInfo::Clobbered;
10717 
10718     // Check if the destination is a static alloca.
10719     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10720     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10721     if (!Info)
10722       continue;
10723     const AllocaInst *AI = cast<AllocaInst>(Dst);
10724 
10725     // Skip allocas that have been initialized or clobbered.
10726     if (*Info != StaticAllocaInfo::Unknown)
10727       continue;
10728 
10729     // Check if the stored value is an argument, and that this store fully
10730     // initializes the alloca.
10731     // If the argument type has padding bits we can't directly forward a pointer
10732     // as the upper bits may contain garbage.
10733     // Don't elide copies from the same argument twice.
10734     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10735     const auto *Arg = dyn_cast<Argument>(Val);
10736     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10737         Arg->getType()->isEmptyTy() ||
10738         DL.getTypeStoreSize(Arg->getType()) !=
10739             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10740         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10741         ArgCopyElisionCandidates.count(Arg)) {
10742       *Info = StaticAllocaInfo::Clobbered;
10743       continue;
10744     }
10745 
10746     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10747                       << '\n');
10748 
10749     // Mark this alloca and store for argument copy elision.
10750     *Info = StaticAllocaInfo::Elidable;
10751     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10752 
10753     // Stop scanning if we've seen all arguments. This will happen early in -O0
10754     // builds, which is useful, because -O0 builds have large entry blocks and
10755     // many allocas.
10756     if (ArgCopyElisionCandidates.size() == NumArgs)
10757       break;
10758   }
10759 }
10760 
10761 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10762 /// ArgVal is a load from a suitable fixed stack object.
10763 static void tryToElideArgumentCopy(
10764     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10765     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10766     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10767     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10768     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10769   // Check if this is a load from a fixed stack object.
10770   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10771   if (!LNode)
10772     return;
10773   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10774   if (!FINode)
10775     return;
10776 
10777   // Check that the fixed stack object is the right size and alignment.
10778   // Look at the alignment that the user wrote on the alloca instead of looking
10779   // at the stack object.
10780   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10781   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10782   const AllocaInst *AI = ArgCopyIter->second.first;
10783   int FixedIndex = FINode->getIndex();
10784   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10785   int OldIndex = AllocaIndex;
10786   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10787   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10788     LLVM_DEBUG(
10789         dbgs() << "  argument copy elision failed due to bad fixed stack "
10790                   "object size\n");
10791     return;
10792   }
10793   Align RequiredAlignment = AI->getAlign();
10794   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10795     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10796                          "greater than stack argument alignment ("
10797                       << DebugStr(RequiredAlignment) << " vs "
10798                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10799     return;
10800   }
10801 
10802   // Perform the elision. Delete the old stack object and replace its only use
10803   // in the variable info map. Mark the stack object as mutable.
10804   LLVM_DEBUG({
10805     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10806            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10807            << '\n';
10808   });
10809   MFI.RemoveStackObject(OldIndex);
10810   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10811   AllocaIndex = FixedIndex;
10812   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10813   for (SDValue ArgVal : ArgVals)
10814     Chains.push_back(ArgVal.getValue(1));
10815 
10816   // Avoid emitting code for the store implementing the copy.
10817   const StoreInst *SI = ArgCopyIter->second.second;
10818   ElidedArgCopyInstrs.insert(SI);
10819 
10820   // Check for uses of the argument again so that we can avoid exporting ArgVal
10821   // if it is't used by anything other than the store.
10822   for (const Value *U : Arg.users()) {
10823     if (U != SI) {
10824       ArgHasUses = true;
10825       break;
10826     }
10827   }
10828 }
10829 
10830 void SelectionDAGISel::LowerArguments(const Function &F) {
10831   SelectionDAG &DAG = SDB->DAG;
10832   SDLoc dl = SDB->getCurSDLoc();
10833   const DataLayout &DL = DAG.getDataLayout();
10834   SmallVector<ISD::InputArg, 16> Ins;
10835 
10836   // In Naked functions we aren't going to save any registers.
10837   if (F.hasFnAttribute(Attribute::Naked))
10838     return;
10839 
10840   if (!FuncInfo->CanLowerReturn) {
10841     // Put in an sret pointer parameter before all the other parameters.
10842     SmallVector<EVT, 1> ValueVTs;
10843     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10844                     PointerType::get(F.getContext(),
10845                                      DAG.getDataLayout().getAllocaAddrSpace()),
10846                     ValueVTs);
10847 
10848     // NOTE: Assuming that a pointer will never break down to more than one VT
10849     // or one register.
10850     ISD::ArgFlagsTy Flags;
10851     Flags.setSRet();
10852     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10853     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10854                          ISD::InputArg::NoArgIndex, 0);
10855     Ins.push_back(RetArg);
10856   }
10857 
10858   // Look for stores of arguments to static allocas. Mark such arguments with a
10859   // flag to ask the target to give us the memory location of that argument if
10860   // available.
10861   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10862   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10863                                     ArgCopyElisionCandidates);
10864 
10865   // Set up the incoming argument description vector.
10866   for (const Argument &Arg : F.args()) {
10867     unsigned ArgNo = Arg.getArgNo();
10868     SmallVector<EVT, 4> ValueVTs;
10869     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10870     bool isArgValueUsed = !Arg.use_empty();
10871     unsigned PartBase = 0;
10872     Type *FinalType = Arg.getType();
10873     if (Arg.hasAttribute(Attribute::ByVal))
10874       FinalType = Arg.getParamByValType();
10875     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10876         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10877     for (unsigned Value = 0, NumValues = ValueVTs.size();
10878          Value != NumValues; ++Value) {
10879       EVT VT = ValueVTs[Value];
10880       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10881       ISD::ArgFlagsTy Flags;
10882 
10883 
10884       if (Arg.getType()->isPointerTy()) {
10885         Flags.setPointer();
10886         Flags.setPointerAddrSpace(
10887             cast<PointerType>(Arg.getType())->getAddressSpace());
10888       }
10889       if (Arg.hasAttribute(Attribute::ZExt))
10890         Flags.setZExt();
10891       if (Arg.hasAttribute(Attribute::SExt))
10892         Flags.setSExt();
10893       if (Arg.hasAttribute(Attribute::InReg)) {
10894         // If we are using vectorcall calling convention, a structure that is
10895         // passed InReg - is surely an HVA
10896         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10897             isa<StructType>(Arg.getType())) {
10898           // The first value of a structure is marked
10899           if (0 == Value)
10900             Flags.setHvaStart();
10901           Flags.setHva();
10902         }
10903         // Set InReg Flag
10904         Flags.setInReg();
10905       }
10906       if (Arg.hasAttribute(Attribute::StructRet))
10907         Flags.setSRet();
10908       if (Arg.hasAttribute(Attribute::SwiftSelf))
10909         Flags.setSwiftSelf();
10910       if (Arg.hasAttribute(Attribute::SwiftAsync))
10911         Flags.setSwiftAsync();
10912       if (Arg.hasAttribute(Attribute::SwiftError))
10913         Flags.setSwiftError();
10914       if (Arg.hasAttribute(Attribute::ByVal))
10915         Flags.setByVal();
10916       if (Arg.hasAttribute(Attribute::ByRef))
10917         Flags.setByRef();
10918       if (Arg.hasAttribute(Attribute::InAlloca)) {
10919         Flags.setInAlloca();
10920         // Set the byval flag for CCAssignFn callbacks that don't know about
10921         // inalloca.  This way we can know how many bytes we should've allocated
10922         // and how many bytes a callee cleanup function will pop.  If we port
10923         // inalloca to more targets, we'll have to add custom inalloca handling
10924         // in the various CC lowering callbacks.
10925         Flags.setByVal();
10926       }
10927       if (Arg.hasAttribute(Attribute::Preallocated)) {
10928         Flags.setPreallocated();
10929         // Set the byval flag for CCAssignFn callbacks that don't know about
10930         // preallocated.  This way we can know how many bytes we should've
10931         // allocated and how many bytes a callee cleanup function will pop.  If
10932         // we port preallocated to more targets, we'll have to add custom
10933         // preallocated handling in the various CC lowering callbacks.
10934         Flags.setByVal();
10935       }
10936 
10937       // Certain targets (such as MIPS), may have a different ABI alignment
10938       // for a type depending on the context. Give the target a chance to
10939       // specify the alignment it wants.
10940       const Align OriginalAlignment(
10941           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10942       Flags.setOrigAlign(OriginalAlignment);
10943 
10944       Align MemAlign;
10945       Type *ArgMemTy = nullptr;
10946       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10947           Flags.isByRef()) {
10948         if (!ArgMemTy)
10949           ArgMemTy = Arg.getPointeeInMemoryValueType();
10950 
10951         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10952 
10953         // For in-memory arguments, size and alignment should be passed from FE.
10954         // BE will guess if this info is not there but there are cases it cannot
10955         // get right.
10956         if (auto ParamAlign = Arg.getParamStackAlign())
10957           MemAlign = *ParamAlign;
10958         else if ((ParamAlign = Arg.getParamAlign()))
10959           MemAlign = *ParamAlign;
10960         else
10961           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10962         if (Flags.isByRef())
10963           Flags.setByRefSize(MemSize);
10964         else
10965           Flags.setByValSize(MemSize);
10966       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10967         MemAlign = *ParamAlign;
10968       } else {
10969         MemAlign = OriginalAlignment;
10970       }
10971       Flags.setMemAlign(MemAlign);
10972 
10973       if (Arg.hasAttribute(Attribute::Nest))
10974         Flags.setNest();
10975       if (NeedsRegBlock)
10976         Flags.setInConsecutiveRegs();
10977       if (ArgCopyElisionCandidates.count(&Arg))
10978         Flags.setCopyElisionCandidate();
10979       if (Arg.hasAttribute(Attribute::Returned))
10980         Flags.setReturned();
10981 
10982       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10983           *CurDAG->getContext(), F.getCallingConv(), VT);
10984       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10985           *CurDAG->getContext(), F.getCallingConv(), VT);
10986       for (unsigned i = 0; i != NumRegs; ++i) {
10987         // For scalable vectors, use the minimum size; individual targets
10988         // are responsible for handling scalable vector arguments and
10989         // return values.
10990         ISD::InputArg MyFlags(
10991             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10992             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10993         if (NumRegs > 1 && i == 0)
10994           MyFlags.Flags.setSplit();
10995         // if it isn't first piece, alignment must be 1
10996         else if (i > 0) {
10997           MyFlags.Flags.setOrigAlign(Align(1));
10998           if (i == NumRegs - 1)
10999             MyFlags.Flags.setSplitEnd();
11000         }
11001         Ins.push_back(MyFlags);
11002       }
11003       if (NeedsRegBlock && Value == NumValues - 1)
11004         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11005       PartBase += VT.getStoreSize().getKnownMinValue();
11006     }
11007   }
11008 
11009   // Call the target to set up the argument values.
11010   SmallVector<SDValue, 8> InVals;
11011   SDValue NewRoot = TLI->LowerFormalArguments(
11012       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11013 
11014   // Verify that the target's LowerFormalArguments behaved as expected.
11015   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11016          "LowerFormalArguments didn't return a valid chain!");
11017   assert(InVals.size() == Ins.size() &&
11018          "LowerFormalArguments didn't emit the correct number of values!");
11019   LLVM_DEBUG({
11020     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11021       assert(InVals[i].getNode() &&
11022              "LowerFormalArguments emitted a null value!");
11023       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11024              "LowerFormalArguments emitted a value with the wrong type!");
11025     }
11026   });
11027 
11028   // Update the DAG with the new chain value resulting from argument lowering.
11029   DAG.setRoot(NewRoot);
11030 
11031   // Set up the argument values.
11032   unsigned i = 0;
11033   if (!FuncInfo->CanLowerReturn) {
11034     // Create a virtual register for the sret pointer, and put in a copy
11035     // from the sret argument into it.
11036     SmallVector<EVT, 1> ValueVTs;
11037     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11038                     PointerType::get(F.getContext(),
11039                                      DAG.getDataLayout().getAllocaAddrSpace()),
11040                     ValueVTs);
11041     MVT VT = ValueVTs[0].getSimpleVT();
11042     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11043     std::optional<ISD::NodeType> AssertOp;
11044     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
11045                                         nullptr, F.getCallingConv(), AssertOp);
11046 
11047     MachineFunction& MF = SDB->DAG.getMachineFunction();
11048     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11049     Register SRetReg =
11050         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11051     FuncInfo->DemoteRegister = SRetReg;
11052     NewRoot =
11053         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11054     DAG.setRoot(NewRoot);
11055 
11056     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11057     ++i;
11058   }
11059 
11060   SmallVector<SDValue, 4> Chains;
11061   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11062   for (const Argument &Arg : F.args()) {
11063     SmallVector<SDValue, 4> ArgValues;
11064     SmallVector<EVT, 4> ValueVTs;
11065     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11066     unsigned NumValues = ValueVTs.size();
11067     if (NumValues == 0)
11068       continue;
11069 
11070     bool ArgHasUses = !Arg.use_empty();
11071 
11072     // Elide the copying store if the target loaded this argument from a
11073     // suitable fixed stack object.
11074     if (Ins[i].Flags.isCopyElisionCandidate()) {
11075       unsigned NumParts = 0;
11076       for (EVT VT : ValueVTs)
11077         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11078                                                        F.getCallingConv(), VT);
11079 
11080       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11081                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11082                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11083     }
11084 
11085     // If this argument is unused then remember its value. It is used to generate
11086     // debugging information.
11087     bool isSwiftErrorArg =
11088         TLI->supportSwiftError() &&
11089         Arg.hasAttribute(Attribute::SwiftError);
11090     if (!ArgHasUses && !isSwiftErrorArg) {
11091       SDB->setUnusedArgValue(&Arg, InVals[i]);
11092 
11093       // Also remember any frame index for use in FastISel.
11094       if (FrameIndexSDNode *FI =
11095           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11096         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11097     }
11098 
11099     for (unsigned Val = 0; Val != NumValues; ++Val) {
11100       EVT VT = ValueVTs[Val];
11101       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11102                                                       F.getCallingConv(), VT);
11103       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11104           *CurDAG->getContext(), F.getCallingConv(), VT);
11105 
11106       // Even an apparent 'unused' swifterror argument needs to be returned. So
11107       // we do generate a copy for it that can be used on return from the
11108       // function.
11109       if (ArgHasUses || isSwiftErrorArg) {
11110         std::optional<ISD::NodeType> AssertOp;
11111         if (Arg.hasAttribute(Attribute::SExt))
11112           AssertOp = ISD::AssertSext;
11113         else if (Arg.hasAttribute(Attribute::ZExt))
11114           AssertOp = ISD::AssertZext;
11115 
11116         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11117                                              PartVT, VT, nullptr,
11118                                              F.getCallingConv(), AssertOp));
11119       }
11120 
11121       i += NumParts;
11122     }
11123 
11124     // We don't need to do anything else for unused arguments.
11125     if (ArgValues.empty())
11126       continue;
11127 
11128     // Note down frame index.
11129     if (FrameIndexSDNode *FI =
11130         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11131       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11132 
11133     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11134                                      SDB->getCurSDLoc());
11135 
11136     SDB->setValue(&Arg, Res);
11137     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11138       // We want to associate the argument with the frame index, among
11139       // involved operands, that correspond to the lowest address. The
11140       // getCopyFromParts function, called earlier, is swapping the order of
11141       // the operands to BUILD_PAIR depending on endianness. The result of
11142       // that swapping is that the least significant bits of the argument will
11143       // be in the first operand of the BUILD_PAIR node, and the most
11144       // significant bits will be in the second operand.
11145       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11146       if (LoadSDNode *LNode =
11147           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11148         if (FrameIndexSDNode *FI =
11149             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11150           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11151     }
11152 
11153     // Analyses past this point are naive and don't expect an assertion.
11154     if (Res.getOpcode() == ISD::AssertZext)
11155       Res = Res.getOperand(0);
11156 
11157     // Update the SwiftErrorVRegDefMap.
11158     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11159       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11160       if (Register::isVirtualRegister(Reg))
11161         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11162                                    Reg);
11163     }
11164 
11165     // If this argument is live outside of the entry block, insert a copy from
11166     // wherever we got it to the vreg that other BB's will reference it as.
11167     if (Res.getOpcode() == ISD::CopyFromReg) {
11168       // If we can, though, try to skip creating an unnecessary vreg.
11169       // FIXME: This isn't very clean... it would be nice to make this more
11170       // general.
11171       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11172       if (Register::isVirtualRegister(Reg)) {
11173         FuncInfo->ValueMap[&Arg] = Reg;
11174         continue;
11175       }
11176     }
11177     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11178       FuncInfo->InitializeRegForValue(&Arg);
11179       SDB->CopyToExportRegsIfNeeded(&Arg);
11180     }
11181   }
11182 
11183   if (!Chains.empty()) {
11184     Chains.push_back(NewRoot);
11185     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11186   }
11187 
11188   DAG.setRoot(NewRoot);
11189 
11190   assert(i == InVals.size() && "Argument register count mismatch!");
11191 
11192   // If any argument copy elisions occurred and we have debug info, update the
11193   // stale frame indices used in the dbg.declare variable info table.
11194   if (!ArgCopyElisionFrameIndexMap.empty()) {
11195     for (MachineFunction::VariableDbgInfo &VI :
11196          MF->getInStackSlotVariableDbgInfo()) {
11197       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11198       if (I != ArgCopyElisionFrameIndexMap.end())
11199         VI.updateStackSlot(I->second);
11200     }
11201   }
11202 
11203   // Finally, if the target has anything special to do, allow it to do so.
11204   emitFunctionEntryCode();
11205 }
11206 
11207 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11208 /// ensure constants are generated when needed.  Remember the virtual registers
11209 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11210 /// directly add them, because expansion might result in multiple MBB's for one
11211 /// BB.  As such, the start of the BB might correspond to a different MBB than
11212 /// the end.
11213 void
11214 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11216 
11217   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11218 
11219   // Check PHI nodes in successors that expect a value to be available from this
11220   // block.
11221   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11222     if (!isa<PHINode>(SuccBB->begin())) continue;
11223     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11224 
11225     // If this terminator has multiple identical successors (common for
11226     // switches), only handle each succ once.
11227     if (!SuccsHandled.insert(SuccMBB).second)
11228       continue;
11229 
11230     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11231 
11232     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11233     // nodes and Machine PHI nodes, but the incoming operands have not been
11234     // emitted yet.
11235     for (const PHINode &PN : SuccBB->phis()) {
11236       // Ignore dead phi's.
11237       if (PN.use_empty())
11238         continue;
11239 
11240       // Skip empty types
11241       if (PN.getType()->isEmptyTy())
11242         continue;
11243 
11244       unsigned Reg;
11245       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11246 
11247       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11248         unsigned &RegOut = ConstantsOut[C];
11249         if (RegOut == 0) {
11250           RegOut = FuncInfo.CreateRegs(C);
11251           // We need to zero/sign extend ConstantInt phi operands to match
11252           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11253           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11254           if (auto *CI = dyn_cast<ConstantInt>(C))
11255             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11256                                                     : ISD::ZERO_EXTEND;
11257           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11258         }
11259         Reg = RegOut;
11260       } else {
11261         DenseMap<const Value *, Register>::iterator I =
11262           FuncInfo.ValueMap.find(PHIOp);
11263         if (I != FuncInfo.ValueMap.end())
11264           Reg = I->second;
11265         else {
11266           assert(isa<AllocaInst>(PHIOp) &&
11267                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11268                  "Didn't codegen value into a register!??");
11269           Reg = FuncInfo.CreateRegs(PHIOp);
11270           CopyValueToVirtualRegister(PHIOp, Reg);
11271         }
11272       }
11273 
11274       // Remember that this register needs to added to the machine PHI node as
11275       // the input for this MBB.
11276       SmallVector<EVT, 4> ValueVTs;
11277       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11278       for (EVT VT : ValueVTs) {
11279         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11280         for (unsigned i = 0; i != NumRegisters; ++i)
11281           FuncInfo.PHINodesToUpdate.push_back(
11282               std::make_pair(&*MBBI++, Reg + i));
11283         Reg += NumRegisters;
11284       }
11285     }
11286   }
11287 
11288   ConstantsOut.clear();
11289 }
11290 
11291 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11292   MachineFunction::iterator I(MBB);
11293   if (++I == FuncInfo.MF->end())
11294     return nullptr;
11295   return &*I;
11296 }
11297 
11298 /// During lowering new call nodes can be created (such as memset, etc.).
11299 /// Those will become new roots of the current DAG, but complications arise
11300 /// when they are tail calls. In such cases, the call lowering will update
11301 /// the root, but the builder still needs to know that a tail call has been
11302 /// lowered in order to avoid generating an additional return.
11303 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11304   // If the node is null, we do have a tail call.
11305   if (MaybeTC.getNode() != nullptr)
11306     DAG.setRoot(MaybeTC);
11307   else
11308     HasTailCall = true;
11309 }
11310 
11311 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11312                                         MachineBasicBlock *SwitchMBB,
11313                                         MachineBasicBlock *DefaultMBB) {
11314   MachineFunction *CurMF = FuncInfo.MF;
11315   MachineBasicBlock *NextMBB = nullptr;
11316   MachineFunction::iterator BBI(W.MBB);
11317   if (++BBI != FuncInfo.MF->end())
11318     NextMBB = &*BBI;
11319 
11320   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11321 
11322   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11323 
11324   if (Size == 2 && W.MBB == SwitchMBB) {
11325     // If any two of the cases has the same destination, and if one value
11326     // is the same as the other, but has one bit unset that the other has set,
11327     // use bit manipulation to do two compares at once.  For example:
11328     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11329     // TODO: This could be extended to merge any 2 cases in switches with 3
11330     // cases.
11331     // TODO: Handle cases where W.CaseBB != SwitchBB.
11332     CaseCluster &Small = *W.FirstCluster;
11333     CaseCluster &Big = *W.LastCluster;
11334 
11335     if (Small.Low == Small.High && Big.Low == Big.High &&
11336         Small.MBB == Big.MBB) {
11337       const APInt &SmallValue = Small.Low->getValue();
11338       const APInt &BigValue = Big.Low->getValue();
11339 
11340       // Check that there is only one bit different.
11341       APInt CommonBit = BigValue ^ SmallValue;
11342       if (CommonBit.isPowerOf2()) {
11343         SDValue CondLHS = getValue(Cond);
11344         EVT VT = CondLHS.getValueType();
11345         SDLoc DL = getCurSDLoc();
11346 
11347         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11348                                  DAG.getConstant(CommonBit, DL, VT));
11349         SDValue Cond = DAG.getSetCC(
11350             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11351             ISD::SETEQ);
11352 
11353         // Update successor info.
11354         // Both Small and Big will jump to Small.BB, so we sum up the
11355         // probabilities.
11356         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11357         if (BPI)
11358           addSuccessorWithProb(
11359               SwitchMBB, DefaultMBB,
11360               // The default destination is the first successor in IR.
11361               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11362         else
11363           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11364 
11365         // Insert the true branch.
11366         SDValue BrCond =
11367             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11368                         DAG.getBasicBlock(Small.MBB));
11369         // Insert the false branch.
11370         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11371                              DAG.getBasicBlock(DefaultMBB));
11372 
11373         DAG.setRoot(BrCond);
11374         return;
11375       }
11376     }
11377   }
11378 
11379   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11380     // Here, we order cases by probability so the most likely case will be
11381     // checked first. However, two clusters can have the same probability in
11382     // which case their relative ordering is non-deterministic. So we use Low
11383     // as a tie-breaker as clusters are guaranteed to never overlap.
11384     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11385                [](const CaseCluster &a, const CaseCluster &b) {
11386       return a.Prob != b.Prob ?
11387              a.Prob > b.Prob :
11388              a.Low->getValue().slt(b.Low->getValue());
11389     });
11390 
11391     // Rearrange the case blocks so that the last one falls through if possible
11392     // without changing the order of probabilities.
11393     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11394       --I;
11395       if (I->Prob > W.LastCluster->Prob)
11396         break;
11397       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11398         std::swap(*I, *W.LastCluster);
11399         break;
11400       }
11401     }
11402   }
11403 
11404   // Compute total probability.
11405   BranchProbability DefaultProb = W.DefaultProb;
11406   BranchProbability UnhandledProbs = DefaultProb;
11407   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11408     UnhandledProbs += I->Prob;
11409 
11410   MachineBasicBlock *CurMBB = W.MBB;
11411   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11412     bool FallthroughUnreachable = false;
11413     MachineBasicBlock *Fallthrough;
11414     if (I == W.LastCluster) {
11415       // For the last cluster, fall through to the default destination.
11416       Fallthrough = DefaultMBB;
11417       FallthroughUnreachable = isa<UnreachableInst>(
11418           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11419     } else {
11420       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11421       CurMF->insert(BBI, Fallthrough);
11422       // Put Cond in a virtual register to make it available from the new blocks.
11423       ExportFromCurrentBlock(Cond);
11424     }
11425     UnhandledProbs -= I->Prob;
11426 
11427     switch (I->Kind) {
11428       case CC_JumpTable: {
11429         // FIXME: Optimize away range check based on pivot comparisons.
11430         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11431         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11432 
11433         // The jump block hasn't been inserted yet; insert it here.
11434         MachineBasicBlock *JumpMBB = JT->MBB;
11435         CurMF->insert(BBI, JumpMBB);
11436 
11437         auto JumpProb = I->Prob;
11438         auto FallthroughProb = UnhandledProbs;
11439 
11440         // If the default statement is a target of the jump table, we evenly
11441         // distribute the default probability to successors of CurMBB. Also
11442         // update the probability on the edge from JumpMBB to Fallthrough.
11443         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11444                                               SE = JumpMBB->succ_end();
11445              SI != SE; ++SI) {
11446           if (*SI == DefaultMBB) {
11447             JumpProb += DefaultProb / 2;
11448             FallthroughProb -= DefaultProb / 2;
11449             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11450             JumpMBB->normalizeSuccProbs();
11451             break;
11452           }
11453         }
11454 
11455         // If the default clause is unreachable, propagate that knowledge into
11456         // JTH->FallthroughUnreachable which will use it to suppress the range
11457         // check.
11458         //
11459         // However, don't do this if we're doing branch target enforcement,
11460         // because a table branch _without_ a range check can be a tempting JOP
11461         // gadget - out-of-bounds inputs that are impossible in correct
11462         // execution become possible again if an attacker can influence the
11463         // control flow. So if an attacker doesn't already have a BTI bypass
11464         // available, we don't want them to be able to get one out of this
11465         // table branch.
11466         if (FallthroughUnreachable) {
11467           Function &CurFunc = CurMF->getFunction();
11468           bool HasBranchTargetEnforcement = false;
11469           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11470             HasBranchTargetEnforcement =
11471                 CurFunc.getFnAttribute("branch-target-enforcement")
11472                     .getValueAsBool();
11473           } else {
11474             HasBranchTargetEnforcement =
11475                 CurMF->getMMI().getModule()->getModuleFlag(
11476                     "branch-target-enforcement");
11477           }
11478           if (!HasBranchTargetEnforcement)
11479             JTH->FallthroughUnreachable = true;
11480         }
11481 
11482         if (!JTH->FallthroughUnreachable)
11483           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11484         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11485         CurMBB->normalizeSuccProbs();
11486 
11487         // The jump table header will be inserted in our current block, do the
11488         // range check, and fall through to our fallthrough block.
11489         JTH->HeaderBB = CurMBB;
11490         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11491 
11492         // If we're in the right place, emit the jump table header right now.
11493         if (CurMBB == SwitchMBB) {
11494           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11495           JTH->Emitted = true;
11496         }
11497         break;
11498       }
11499       case CC_BitTests: {
11500         // FIXME: Optimize away range check based on pivot comparisons.
11501         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11502 
11503         // The bit test blocks haven't been inserted yet; insert them here.
11504         for (BitTestCase &BTC : BTB->Cases)
11505           CurMF->insert(BBI, BTC.ThisBB);
11506 
11507         // Fill in fields of the BitTestBlock.
11508         BTB->Parent = CurMBB;
11509         BTB->Default = Fallthrough;
11510 
11511         BTB->DefaultProb = UnhandledProbs;
11512         // If the cases in bit test don't form a contiguous range, we evenly
11513         // distribute the probability on the edge to Fallthrough to two
11514         // successors of CurMBB.
11515         if (!BTB->ContiguousRange) {
11516           BTB->Prob += DefaultProb / 2;
11517           BTB->DefaultProb -= DefaultProb / 2;
11518         }
11519 
11520         if (FallthroughUnreachable)
11521           BTB->FallthroughUnreachable = true;
11522 
11523         // If we're in the right place, emit the bit test header right now.
11524         if (CurMBB == SwitchMBB) {
11525           visitBitTestHeader(*BTB, SwitchMBB);
11526           BTB->Emitted = true;
11527         }
11528         break;
11529       }
11530       case CC_Range: {
11531         const Value *RHS, *LHS, *MHS;
11532         ISD::CondCode CC;
11533         if (I->Low == I->High) {
11534           // Check Cond == I->Low.
11535           CC = ISD::SETEQ;
11536           LHS = Cond;
11537           RHS=I->Low;
11538           MHS = nullptr;
11539         } else {
11540           // Check I->Low <= Cond <= I->High.
11541           CC = ISD::SETLE;
11542           LHS = I->Low;
11543           MHS = Cond;
11544           RHS = I->High;
11545         }
11546 
11547         // If Fallthrough is unreachable, fold away the comparison.
11548         if (FallthroughUnreachable)
11549           CC = ISD::SETTRUE;
11550 
11551         // The false probability is the sum of all unhandled cases.
11552         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11553                      getCurSDLoc(), I->Prob, UnhandledProbs);
11554 
11555         if (CurMBB == SwitchMBB)
11556           visitSwitchCase(CB, SwitchMBB);
11557         else
11558           SL->SwitchCases.push_back(CB);
11559 
11560         break;
11561       }
11562     }
11563     CurMBB = Fallthrough;
11564   }
11565 }
11566 
11567 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11568                                               CaseClusterIt First,
11569                                               CaseClusterIt Last) {
11570   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11571     if (X.Prob != CC.Prob)
11572       return X.Prob > CC.Prob;
11573 
11574     // Ties are broken by comparing the case value.
11575     return X.Low->getValue().slt(CC.Low->getValue());
11576   });
11577 }
11578 
11579 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11580                                         const SwitchWorkListItem &W,
11581                                         Value *Cond,
11582                                         MachineBasicBlock *SwitchMBB) {
11583   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11584          "Clusters not sorted?");
11585 
11586   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11587 
11588   // Balance the tree based on branch probabilities to create a near-optimal (in
11589   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11590   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11591   CaseClusterIt LastLeft = W.FirstCluster;
11592   CaseClusterIt FirstRight = W.LastCluster;
11593   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11594   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11595 
11596   // Move LastLeft and FirstRight towards each other from opposite directions to
11597   // find a partitioning of the clusters which balances the probability on both
11598   // sides. If LeftProb and RightProb are equal, alternate which side is
11599   // taken to ensure 0-probability nodes are distributed evenly.
11600   unsigned I = 0;
11601   while (LastLeft + 1 < FirstRight) {
11602     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11603       LeftProb += (++LastLeft)->Prob;
11604     else
11605       RightProb += (--FirstRight)->Prob;
11606     I++;
11607   }
11608 
11609   while (true) {
11610     // Our binary search tree differs from a typical BST in that ours can have up
11611     // to three values in each leaf. The pivot selection above doesn't take that
11612     // into account, which means the tree might require more nodes and be less
11613     // efficient. We compensate for this here.
11614 
11615     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11616     unsigned NumRight = W.LastCluster - FirstRight + 1;
11617 
11618     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11619       // If one side has less than 3 clusters, and the other has more than 3,
11620       // consider taking a cluster from the other side.
11621 
11622       if (NumLeft < NumRight) {
11623         // Consider moving the first cluster on the right to the left side.
11624         CaseCluster &CC = *FirstRight;
11625         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11626         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11627         if (LeftSideRank <= RightSideRank) {
11628           // Moving the cluster to the left does not demote it.
11629           ++LastLeft;
11630           ++FirstRight;
11631           continue;
11632         }
11633       } else {
11634         assert(NumRight < NumLeft);
11635         // Consider moving the last element on the left to the right side.
11636         CaseCluster &CC = *LastLeft;
11637         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11638         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11639         if (RightSideRank <= LeftSideRank) {
11640           // Moving the cluster to the right does not demot it.
11641           --LastLeft;
11642           --FirstRight;
11643           continue;
11644         }
11645       }
11646     }
11647     break;
11648   }
11649 
11650   assert(LastLeft + 1 == FirstRight);
11651   assert(LastLeft >= W.FirstCluster);
11652   assert(FirstRight <= W.LastCluster);
11653 
11654   // Use the first element on the right as pivot since we will make less-than
11655   // comparisons against it.
11656   CaseClusterIt PivotCluster = FirstRight;
11657   assert(PivotCluster > W.FirstCluster);
11658   assert(PivotCluster <= W.LastCluster);
11659 
11660   CaseClusterIt FirstLeft = W.FirstCluster;
11661   CaseClusterIt LastRight = W.LastCluster;
11662 
11663   const ConstantInt *Pivot = PivotCluster->Low;
11664 
11665   // New blocks will be inserted immediately after the current one.
11666   MachineFunction::iterator BBI(W.MBB);
11667   ++BBI;
11668 
11669   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11670   // we can branch to its destination directly if it's squeezed exactly in
11671   // between the known lower bound and Pivot - 1.
11672   MachineBasicBlock *LeftMBB;
11673   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11674       FirstLeft->Low == W.GE &&
11675       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11676     LeftMBB = FirstLeft->MBB;
11677   } else {
11678     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11679     FuncInfo.MF->insert(BBI, LeftMBB);
11680     WorkList.push_back(
11681         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11682     // Put Cond in a virtual register to make it available from the new blocks.
11683     ExportFromCurrentBlock(Cond);
11684   }
11685 
11686   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11687   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11688   // directly if RHS.High equals the current upper bound.
11689   MachineBasicBlock *RightMBB;
11690   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11691       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11692     RightMBB = FirstRight->MBB;
11693   } else {
11694     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11695     FuncInfo.MF->insert(BBI, RightMBB);
11696     WorkList.push_back(
11697         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11698     // Put Cond in a virtual register to make it available from the new blocks.
11699     ExportFromCurrentBlock(Cond);
11700   }
11701 
11702   // Create the CaseBlock record that will be used to lower the branch.
11703   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11704                getCurSDLoc(), LeftProb, RightProb);
11705 
11706   if (W.MBB == SwitchMBB)
11707     visitSwitchCase(CB, SwitchMBB);
11708   else
11709     SL->SwitchCases.push_back(CB);
11710 }
11711 
11712 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11713 // from the swith statement.
11714 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11715                                             BranchProbability PeeledCaseProb) {
11716   if (PeeledCaseProb == BranchProbability::getOne())
11717     return BranchProbability::getZero();
11718   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11719 
11720   uint32_t Numerator = CaseProb.getNumerator();
11721   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11722   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11723 }
11724 
11725 // Try to peel the top probability case if it exceeds the threshold.
11726 // Return current MachineBasicBlock for the switch statement if the peeling
11727 // does not occur.
11728 // If the peeling is performed, return the newly created MachineBasicBlock
11729 // for the peeled switch statement. Also update Clusters to remove the peeled
11730 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11731 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11732     const SwitchInst &SI, CaseClusterVector &Clusters,
11733     BranchProbability &PeeledCaseProb) {
11734   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11735   // Don't perform if there is only one cluster or optimizing for size.
11736   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11737       TM.getOptLevel() == CodeGenOptLevel::None ||
11738       SwitchMBB->getParent()->getFunction().hasMinSize())
11739     return SwitchMBB;
11740 
11741   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11742   unsigned PeeledCaseIndex = 0;
11743   bool SwitchPeeled = false;
11744   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11745     CaseCluster &CC = Clusters[Index];
11746     if (CC.Prob < TopCaseProb)
11747       continue;
11748     TopCaseProb = CC.Prob;
11749     PeeledCaseIndex = Index;
11750     SwitchPeeled = true;
11751   }
11752   if (!SwitchPeeled)
11753     return SwitchMBB;
11754 
11755   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11756                     << TopCaseProb << "\n");
11757 
11758   // Record the MBB for the peeled switch statement.
11759   MachineFunction::iterator BBI(SwitchMBB);
11760   ++BBI;
11761   MachineBasicBlock *PeeledSwitchMBB =
11762       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11763   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11764 
11765   ExportFromCurrentBlock(SI.getCondition());
11766   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11767   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11768                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11769   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11770 
11771   Clusters.erase(PeeledCaseIt);
11772   for (CaseCluster &CC : Clusters) {
11773     LLVM_DEBUG(
11774         dbgs() << "Scale the probablity for one cluster, before scaling: "
11775                << CC.Prob << "\n");
11776     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11777     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11778   }
11779   PeeledCaseProb = TopCaseProb;
11780   return PeeledSwitchMBB;
11781 }
11782 
11783 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11784   // Extract cases from the switch.
11785   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11786   CaseClusterVector Clusters;
11787   Clusters.reserve(SI.getNumCases());
11788   for (auto I : SI.cases()) {
11789     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11790     const ConstantInt *CaseVal = I.getCaseValue();
11791     BranchProbability Prob =
11792         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11793             : BranchProbability(1, SI.getNumCases() + 1);
11794     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11795   }
11796 
11797   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11798 
11799   // Cluster adjacent cases with the same destination. We do this at all
11800   // optimization levels because it's cheap to do and will make codegen faster
11801   // if there are many clusters.
11802   sortAndRangeify(Clusters);
11803 
11804   // The branch probablity of the peeled case.
11805   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11806   MachineBasicBlock *PeeledSwitchMBB =
11807       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11808 
11809   // If there is only the default destination, jump there directly.
11810   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11811   if (Clusters.empty()) {
11812     assert(PeeledSwitchMBB == SwitchMBB);
11813     SwitchMBB->addSuccessor(DefaultMBB);
11814     if (DefaultMBB != NextBlock(SwitchMBB)) {
11815       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11816                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11817     }
11818     return;
11819   }
11820 
11821   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11822   SL->findBitTestClusters(Clusters, &SI);
11823 
11824   LLVM_DEBUG({
11825     dbgs() << "Case clusters: ";
11826     for (const CaseCluster &C : Clusters) {
11827       if (C.Kind == CC_JumpTable)
11828         dbgs() << "JT:";
11829       if (C.Kind == CC_BitTests)
11830         dbgs() << "BT:";
11831 
11832       C.Low->getValue().print(dbgs(), true);
11833       if (C.Low != C.High) {
11834         dbgs() << '-';
11835         C.High->getValue().print(dbgs(), true);
11836       }
11837       dbgs() << ' ';
11838     }
11839     dbgs() << '\n';
11840   });
11841 
11842   assert(!Clusters.empty());
11843   SwitchWorkList WorkList;
11844   CaseClusterIt First = Clusters.begin();
11845   CaseClusterIt Last = Clusters.end() - 1;
11846   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11847   // Scale the branchprobability for DefaultMBB if the peel occurs and
11848   // DefaultMBB is not replaced.
11849   if (PeeledCaseProb != BranchProbability::getZero() &&
11850       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11851     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11852   WorkList.push_back(
11853       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11854 
11855   while (!WorkList.empty()) {
11856     SwitchWorkListItem W = WorkList.pop_back_val();
11857     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11858 
11859     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11860         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11861       // For optimized builds, lower large range as a balanced binary tree.
11862       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11863       continue;
11864     }
11865 
11866     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11867   }
11868 }
11869 
11870 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11871   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11872   auto DL = getCurSDLoc();
11873   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11874   setValue(&I, DAG.getStepVector(DL, ResultVT));
11875 }
11876 
11877 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11879   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11880 
11881   SDLoc DL = getCurSDLoc();
11882   SDValue V = getValue(I.getOperand(0));
11883   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11884 
11885   if (VT.isScalableVector()) {
11886     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11887     return;
11888   }
11889 
11890   // Use VECTOR_SHUFFLE for the fixed-length vector
11891   // to maintain existing behavior.
11892   SmallVector<int, 8> Mask;
11893   unsigned NumElts = VT.getVectorMinNumElements();
11894   for (unsigned i = 0; i != NumElts; ++i)
11895     Mask.push_back(NumElts - 1 - i);
11896 
11897   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11898 }
11899 
11900 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11901   auto DL = getCurSDLoc();
11902   SDValue InVec = getValue(I.getOperand(0));
11903   EVT OutVT =
11904       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11905 
11906   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11907 
11908   // ISD Node needs the input vectors split into two equal parts
11909   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11910                            DAG.getVectorIdxConstant(0, DL));
11911   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11912                            DAG.getVectorIdxConstant(OutNumElts, DL));
11913 
11914   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11915   // legalisation and combines.
11916   if (OutVT.isFixedLengthVector()) {
11917     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11918                                         createStrideMask(0, 2, OutNumElts));
11919     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11920                                        createStrideMask(1, 2, OutNumElts));
11921     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11922     setValue(&I, Res);
11923     return;
11924   }
11925 
11926   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11927                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11928   setValue(&I, Res);
11929 }
11930 
11931 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11932   auto DL = getCurSDLoc();
11933   EVT InVT = getValue(I.getOperand(0)).getValueType();
11934   SDValue InVec0 = getValue(I.getOperand(0));
11935   SDValue InVec1 = getValue(I.getOperand(1));
11936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11937   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11938 
11939   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11940   // legalisation and combines.
11941   if (OutVT.isFixedLengthVector()) {
11942     unsigned NumElts = InVT.getVectorMinNumElements();
11943     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11944     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11945                                       createInterleaveMask(NumElts, 2)));
11946     return;
11947   }
11948 
11949   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11950                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11951   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11952                     Res.getValue(1));
11953   setValue(&I, Res);
11954 }
11955 
11956 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11957   SmallVector<EVT, 4> ValueVTs;
11958   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11959                   ValueVTs);
11960   unsigned NumValues = ValueVTs.size();
11961   if (NumValues == 0) return;
11962 
11963   SmallVector<SDValue, 4> Values(NumValues);
11964   SDValue Op = getValue(I.getOperand(0));
11965 
11966   for (unsigned i = 0; i != NumValues; ++i)
11967     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11968                             SDValue(Op.getNode(), Op.getResNo() + i));
11969 
11970   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11971                            DAG.getVTList(ValueVTs), Values));
11972 }
11973 
11974 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11976   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11977 
11978   SDLoc DL = getCurSDLoc();
11979   SDValue V1 = getValue(I.getOperand(0));
11980   SDValue V2 = getValue(I.getOperand(1));
11981   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11982 
11983   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11984   if (VT.isScalableVector()) {
11985     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11986     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11987                              DAG.getConstant(Imm, DL, IdxVT)));
11988     return;
11989   }
11990 
11991   unsigned NumElts = VT.getVectorNumElements();
11992 
11993   uint64_t Idx = (NumElts + Imm) % NumElts;
11994 
11995   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11996   SmallVector<int, 8> Mask;
11997   for (unsigned i = 0; i < NumElts; ++i)
11998     Mask.push_back(Idx + i);
11999   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12000 }
12001 
12002 // Consider the following MIR after SelectionDAG, which produces output in
12003 // phyregs in the first case or virtregs in the second case.
12004 //
12005 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12006 // %5:gr32 = COPY $ebx
12007 // %6:gr32 = COPY $edx
12008 // %1:gr32 = COPY %6:gr32
12009 // %0:gr32 = COPY %5:gr32
12010 //
12011 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12012 // %1:gr32 = COPY %6:gr32
12013 // %0:gr32 = COPY %5:gr32
12014 //
12015 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12016 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12017 //
12018 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12019 // to a single virtreg (such as %0). The remaining outputs monotonically
12020 // increase in virtreg number from there. If a callbr has no outputs, then it
12021 // should not have a corresponding callbr landingpad; in fact, the callbr
12022 // landingpad would not even be able to refer to such a callbr.
12023 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12024   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12025   // There is definitely at least one copy.
12026   assert(MI->getOpcode() == TargetOpcode::COPY &&
12027          "start of copy chain MUST be COPY");
12028   Reg = MI->getOperand(1).getReg();
12029   MI = MRI.def_begin(Reg)->getParent();
12030   // There may be an optional second copy.
12031   if (MI->getOpcode() == TargetOpcode::COPY) {
12032     assert(Reg.isVirtual() && "expected COPY of virtual register");
12033     Reg = MI->getOperand(1).getReg();
12034     assert(Reg.isPhysical() && "expected COPY of physical register");
12035     MI = MRI.def_begin(Reg)->getParent();
12036   }
12037   // The start of the chain must be an INLINEASM_BR.
12038   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12039          "end of copy chain MUST be INLINEASM_BR");
12040   return Reg;
12041 }
12042 
12043 // We must do this walk rather than the simpler
12044 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12045 // otherwise we will end up with copies of virtregs only valid along direct
12046 // edges.
12047 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12048   SmallVector<EVT, 8> ResultVTs;
12049   SmallVector<SDValue, 8> ResultValues;
12050   const auto *CBR =
12051       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12052 
12053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12054   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12055   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12056 
12057   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12058   SDValue Chain = DAG.getRoot();
12059 
12060   // Re-parse the asm constraints string.
12061   TargetLowering::AsmOperandInfoVector TargetConstraints =
12062       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12063   for (auto &T : TargetConstraints) {
12064     SDISelAsmOperandInfo OpInfo(T);
12065     if (OpInfo.Type != InlineAsm::isOutput)
12066       continue;
12067 
12068     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12069     // individual constraint.
12070     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12071 
12072     switch (OpInfo.ConstraintType) {
12073     case TargetLowering::C_Register:
12074     case TargetLowering::C_RegisterClass: {
12075       // Fill in OpInfo.AssignedRegs.Regs.
12076       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12077 
12078       // getRegistersForValue may produce 1 to many registers based on whether
12079       // the OpInfo.ConstraintVT is legal on the target or not.
12080       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12081         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12082         if (Register::isPhysicalRegister(OriginalDef))
12083           FuncInfo.MBB->addLiveIn(OriginalDef);
12084         // Update the assigned registers to use the original defs.
12085         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12086       }
12087 
12088       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12089           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12090       ResultValues.push_back(V);
12091       ResultVTs.push_back(OpInfo.ConstraintVT);
12092       break;
12093     }
12094     case TargetLowering::C_Other: {
12095       SDValue Flag;
12096       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12097                                                   OpInfo, DAG);
12098       ++InitialDef;
12099       ResultValues.push_back(V);
12100       ResultVTs.push_back(OpInfo.ConstraintVT);
12101       break;
12102     }
12103     default:
12104       break;
12105     }
12106   }
12107   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12108                           DAG.getVTList(ResultVTs), ResultValues);
12109   setValue(&I, V);
12110 }
12111