xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 0ad92c0cbb34a6e24a9a32f03f3ddeb2114b378e)
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     VectorType *VecTy = cast<VectorType>(V->getType());
1742 
1743     // Now that we know the number and type of the elements, get that number of
1744     // elements into the Ops array based on what kind of constant it is.
1745     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1746       SmallVector<SDValue, 16> Ops;
1747       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1748       for (unsigned i = 0; i != NumElements; ++i)
1749         Ops.push_back(getValue(CV->getOperand(i)));
1750 
1751       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1752     }
1753 
1754     if (isa<ConstantAggregateZero>(C)) {
1755       EVT EltVT =
1756           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1757 
1758       SDValue Op;
1759       if (EltVT.isFloatingPoint())
1760         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1761       else
1762         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1763 
1764       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1765     }
1766 
1767     llvm_unreachable("Unknown vector constant");
1768   }
1769 
1770   // If this is a static alloca, generate it as the frameindex instead of
1771   // computation.
1772   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1773     DenseMap<const AllocaInst*, int>::iterator SI =
1774       FuncInfo.StaticAllocaMap.find(AI);
1775     if (SI != FuncInfo.StaticAllocaMap.end())
1776       return DAG.getFrameIndex(
1777           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1778   }
1779 
1780   // If this is an instruction which fast-isel has deferred, select it now.
1781   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1782     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1783 
1784     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1785                      Inst->getType(), std::nullopt);
1786     SDValue Chain = DAG.getEntryNode();
1787     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1788   }
1789 
1790   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1791     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1792 
1793   if (const auto *BB = dyn_cast<BasicBlock>(V))
1794     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1795 
1796   llvm_unreachable("Can't get register for value!");
1797 }
1798 
1799 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1800   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1801   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1802   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1803   bool IsSEH = isAsynchronousEHPersonality(Pers);
1804   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1805   if (!IsSEH)
1806     CatchPadMBB->setIsEHScopeEntry();
1807   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1808   if (IsMSVCCXX || IsCoreCLR)
1809     CatchPadMBB->setIsEHFuncletEntry();
1810 }
1811 
1812 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1813   // Update machine-CFG edge.
1814   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1815   FuncInfo.MBB->addSuccessor(TargetMBB);
1816   TargetMBB->setIsEHCatchretTarget(true);
1817   DAG.getMachineFunction().setHasEHCatchret(true);
1818 
1819   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1820   bool IsSEH = isAsynchronousEHPersonality(Pers);
1821   if (IsSEH) {
1822     // If this is not a fall-through branch or optimizations are switched off,
1823     // emit the branch.
1824     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1825         TM.getOptLevel() == CodeGenOptLevel::None)
1826       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1827                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1828     return;
1829   }
1830 
1831   // Figure out the funclet membership for the catchret's successor.
1832   // This will be used by the FuncletLayout pass to determine how to order the
1833   // BB's.
1834   // A 'catchret' returns to the outer scope's color.
1835   Value *ParentPad = I.getCatchSwitchParentPad();
1836   const BasicBlock *SuccessorColor;
1837   if (isa<ConstantTokenNone>(ParentPad))
1838     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1839   else
1840     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1841   assert(SuccessorColor && "No parent funclet for catchret!");
1842   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1843   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1844 
1845   // Create the terminator node.
1846   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1847                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1848                             DAG.getBasicBlock(SuccessorColorMBB));
1849   DAG.setRoot(Ret);
1850 }
1851 
1852 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1853   // Don't emit any special code for the cleanuppad instruction. It just marks
1854   // the start of an EH scope/funclet.
1855   FuncInfo.MBB->setIsEHScopeEntry();
1856   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1857   if (Pers != EHPersonality::Wasm_CXX) {
1858     FuncInfo.MBB->setIsEHFuncletEntry();
1859     FuncInfo.MBB->setIsCleanupFuncletEntry();
1860   }
1861 }
1862 
1863 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1864 // not match, it is OK to add only the first unwind destination catchpad to the
1865 // successors, because there will be at least one invoke instruction within the
1866 // catch scope that points to the next unwind destination, if one exists, so
1867 // CFGSort cannot mess up with BB sorting order.
1868 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1869 // call within them, and catchpads only consisting of 'catch (...)' have a
1870 // '__cxa_end_catch' call within them, both of which generate invokes in case
1871 // the next unwind destination exists, i.e., the next unwind destination is not
1872 // the caller.)
1873 //
1874 // Having at most one EH pad successor is also simpler and helps later
1875 // transformations.
1876 //
1877 // For example,
1878 // current:
1879 //   invoke void @foo to ... unwind label %catch.dispatch
1880 // catch.dispatch:
1881 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1882 // catch.start:
1883 //   ...
1884 //   ... in this BB or some other child BB dominated by this BB there will be an
1885 //   invoke that points to 'next' BB as an unwind destination
1886 //
1887 // next: ; We don't need to add this to 'current' BB's successor
1888 //   ...
1889 static void findWasmUnwindDestinations(
1890     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1891     BranchProbability Prob,
1892     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1893         &UnwindDests) {
1894   while (EHPadBB) {
1895     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1896     if (isa<CleanupPadInst>(Pad)) {
1897       // Stop on cleanup pads.
1898       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1899       UnwindDests.back().first->setIsEHScopeEntry();
1900       break;
1901     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1902       // Add the catchpad handlers to the possible destinations. We don't
1903       // continue to the unwind destination of the catchswitch for wasm.
1904       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1905         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1906         UnwindDests.back().first->setIsEHScopeEntry();
1907       }
1908       break;
1909     } else {
1910       continue;
1911     }
1912   }
1913 }
1914 
1915 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1916 /// many places it could ultimately go. In the IR, we have a single unwind
1917 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1918 /// This function skips over imaginary basic blocks that hold catchswitch
1919 /// instructions, and finds all the "real" machine
1920 /// basic block destinations. As those destinations may not be successors of
1921 /// EHPadBB, here we also calculate the edge probability to those destinations.
1922 /// The passed-in Prob is the edge probability to EHPadBB.
1923 static void findUnwindDestinations(
1924     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1925     BranchProbability Prob,
1926     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1927         &UnwindDests) {
1928   EHPersonality Personality =
1929     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1930   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1931   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1932   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1933   bool IsSEH = isAsynchronousEHPersonality(Personality);
1934 
1935   if (IsWasmCXX) {
1936     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1937     assert(UnwindDests.size() <= 1 &&
1938            "There should be at most one unwind destination for wasm");
1939     return;
1940   }
1941 
1942   while (EHPadBB) {
1943     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1944     BasicBlock *NewEHPadBB = nullptr;
1945     if (isa<LandingPadInst>(Pad)) {
1946       // Stop on landingpads. They are not funclets.
1947       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1948       break;
1949     } else if (isa<CleanupPadInst>(Pad)) {
1950       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1951       // personalities.
1952       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1953       UnwindDests.back().first->setIsEHScopeEntry();
1954       UnwindDests.back().first->setIsEHFuncletEntry();
1955       break;
1956     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1957       // Add the catchpad handlers to the possible destinations.
1958       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1959         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1960         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1961         if (IsMSVCCXX || IsCoreCLR)
1962           UnwindDests.back().first->setIsEHFuncletEntry();
1963         if (!IsSEH)
1964           UnwindDests.back().first->setIsEHScopeEntry();
1965       }
1966       NewEHPadBB = CatchSwitch->getUnwindDest();
1967     } else {
1968       continue;
1969     }
1970 
1971     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1972     if (BPI && NewEHPadBB)
1973       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1974     EHPadBB = NewEHPadBB;
1975   }
1976 }
1977 
1978 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1979   // Update successor info.
1980   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1981   auto UnwindDest = I.getUnwindDest();
1982   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1983   BranchProbability UnwindDestProb =
1984       (BPI && UnwindDest)
1985           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1986           : BranchProbability::getZero();
1987   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1988   for (auto &UnwindDest : UnwindDests) {
1989     UnwindDest.first->setIsEHPad();
1990     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1991   }
1992   FuncInfo.MBB->normalizeSuccProbs();
1993 
1994   // Create the terminator node.
1995   SDValue Ret =
1996       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1997   DAG.setRoot(Ret);
1998 }
1999 
2000 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2001   report_fatal_error("visitCatchSwitch not yet implemented!");
2002 }
2003 
2004 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2006   auto &DL = DAG.getDataLayout();
2007   SDValue Chain = getControlRoot();
2008   SmallVector<ISD::OutputArg, 8> Outs;
2009   SmallVector<SDValue, 8> OutVals;
2010 
2011   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2012   // lower
2013   //
2014   //   %val = call <ty> @llvm.experimental.deoptimize()
2015   //   ret <ty> %val
2016   //
2017   // differently.
2018   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2019     LowerDeoptimizingReturn();
2020     return;
2021   }
2022 
2023   if (!FuncInfo.CanLowerReturn) {
2024     unsigned DemoteReg = FuncInfo.DemoteRegister;
2025     const Function *F = I.getParent()->getParent();
2026 
2027     // Emit a store of the return value through the virtual register.
2028     // Leave Outs empty so that LowerReturn won't try to load return
2029     // registers the usual way.
2030     SmallVector<EVT, 1> PtrValueVTs;
2031     ComputeValueVTs(TLI, DL,
2032                     PointerType::get(F->getContext(),
2033                                      DAG.getDataLayout().getAllocaAddrSpace()),
2034                     PtrValueVTs);
2035 
2036     SDValue RetPtr =
2037         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2038     SDValue RetOp = getValue(I.getOperand(0));
2039 
2040     SmallVector<EVT, 4> ValueVTs, MemVTs;
2041     SmallVector<uint64_t, 4> Offsets;
2042     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2043                     &Offsets, 0);
2044     unsigned NumValues = ValueVTs.size();
2045 
2046     SmallVector<SDValue, 4> Chains(NumValues);
2047     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2048     for (unsigned i = 0; i != NumValues; ++i) {
2049       // An aggregate return value cannot wrap around the address space, so
2050       // offsets to its parts don't wrap either.
2051       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2052                                            TypeSize::Fixed(Offsets[i]));
2053 
2054       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2055       if (MemVTs[i] != ValueVTs[i])
2056         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2057       Chains[i] = DAG.getStore(
2058           Chain, getCurSDLoc(), Val,
2059           // FIXME: better loc info would be nice.
2060           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2061           commonAlignment(BaseAlign, Offsets[i]));
2062     }
2063 
2064     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2065                         MVT::Other, Chains);
2066   } else if (I.getNumOperands() != 0) {
2067     SmallVector<EVT, 4> ValueVTs;
2068     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2069     unsigned NumValues = ValueVTs.size();
2070     if (NumValues) {
2071       SDValue RetOp = getValue(I.getOperand(0));
2072 
2073       const Function *F = I.getParent()->getParent();
2074 
2075       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2076           I.getOperand(0)->getType(), F->getCallingConv(),
2077           /*IsVarArg*/ false, DL);
2078 
2079       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2080       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2081         ExtendKind = ISD::SIGN_EXTEND;
2082       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2083         ExtendKind = ISD::ZERO_EXTEND;
2084 
2085       LLVMContext &Context = F->getContext();
2086       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2087 
2088       for (unsigned j = 0; j != NumValues; ++j) {
2089         EVT VT = ValueVTs[j];
2090 
2091         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2092           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2093 
2094         CallingConv::ID CC = F->getCallingConv();
2095 
2096         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2097         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2098         SmallVector<SDValue, 4> Parts(NumParts);
2099         getCopyToParts(DAG, getCurSDLoc(),
2100                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2101                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2102 
2103         // 'inreg' on function refers to return value
2104         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2105         if (RetInReg)
2106           Flags.setInReg();
2107 
2108         if (I.getOperand(0)->getType()->isPointerTy()) {
2109           Flags.setPointer();
2110           Flags.setPointerAddrSpace(
2111               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2112         }
2113 
2114         if (NeedsRegBlock) {
2115           Flags.setInConsecutiveRegs();
2116           if (j == NumValues - 1)
2117             Flags.setInConsecutiveRegsLast();
2118         }
2119 
2120         // Propagate extension type if any
2121         if (ExtendKind == ISD::SIGN_EXTEND)
2122           Flags.setSExt();
2123         else if (ExtendKind == ISD::ZERO_EXTEND)
2124           Flags.setZExt();
2125 
2126         for (unsigned i = 0; i < NumParts; ++i) {
2127           Outs.push_back(ISD::OutputArg(Flags,
2128                                         Parts[i].getValueType().getSimpleVT(),
2129                                         VT, /*isfixed=*/true, 0, 0));
2130           OutVals.push_back(Parts[i]);
2131         }
2132       }
2133     }
2134   }
2135 
2136   // Push in swifterror virtual register as the last element of Outs. This makes
2137   // sure swifterror virtual register will be returned in the swifterror
2138   // physical register.
2139   const Function *F = I.getParent()->getParent();
2140   if (TLI.supportSwiftError() &&
2141       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2142     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2143     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2144     Flags.setSwiftError();
2145     Outs.push_back(ISD::OutputArg(
2146         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2147         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2148     // Create SDNode for the swifterror virtual register.
2149     OutVals.push_back(
2150         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2151                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2152                         EVT(TLI.getPointerTy(DL))));
2153   }
2154 
2155   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2156   CallingConv::ID CallConv =
2157     DAG.getMachineFunction().getFunction().getCallingConv();
2158   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2159       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2160 
2161   // Verify that the target's LowerReturn behaved as expected.
2162   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2163          "LowerReturn didn't return a valid chain!");
2164 
2165   // Update the DAG with the new chain value resulting from return lowering.
2166   DAG.setRoot(Chain);
2167 }
2168 
2169 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2170 /// created for it, emit nodes to copy the value into the virtual
2171 /// registers.
2172 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2173   // Skip empty types
2174   if (V->getType()->isEmptyTy())
2175     return;
2176 
2177   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2178   if (VMI != FuncInfo.ValueMap.end()) {
2179     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2180            "Unused value assigned virtual registers!");
2181     CopyValueToVirtualRegister(V, VMI->second);
2182   }
2183 }
2184 
2185 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2186 /// the current basic block, add it to ValueMap now so that we'll get a
2187 /// CopyTo/FromReg.
2188 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2189   // No need to export constants.
2190   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2191 
2192   // Already exported?
2193   if (FuncInfo.isExportedInst(V)) return;
2194 
2195   Register Reg = FuncInfo.InitializeRegForValue(V);
2196   CopyValueToVirtualRegister(V, Reg);
2197 }
2198 
2199 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2200                                                      const BasicBlock *FromBB) {
2201   // The operands of the setcc have to be in this block.  We don't know
2202   // how to export them from some other block.
2203   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2204     // Can export from current BB.
2205     if (VI->getParent() == FromBB)
2206       return true;
2207 
2208     // Is already exported, noop.
2209     return FuncInfo.isExportedInst(V);
2210   }
2211 
2212   // If this is an argument, we can export it if the BB is the entry block or
2213   // if it is already exported.
2214   if (isa<Argument>(V)) {
2215     if (FromBB->isEntryBlock())
2216       return true;
2217 
2218     // Otherwise, can only export this if it is already exported.
2219     return FuncInfo.isExportedInst(V);
2220   }
2221 
2222   // Otherwise, constants can always be exported.
2223   return true;
2224 }
2225 
2226 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2227 BranchProbability
2228 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2229                                         const MachineBasicBlock *Dst) const {
2230   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2231   const BasicBlock *SrcBB = Src->getBasicBlock();
2232   const BasicBlock *DstBB = Dst->getBasicBlock();
2233   if (!BPI) {
2234     // If BPI is not available, set the default probability as 1 / N, where N is
2235     // the number of successors.
2236     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2237     return BranchProbability(1, SuccSize);
2238   }
2239   return BPI->getEdgeProbability(SrcBB, DstBB);
2240 }
2241 
2242 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2243                                                MachineBasicBlock *Dst,
2244                                                BranchProbability Prob) {
2245   if (!FuncInfo.BPI)
2246     Src->addSuccessorWithoutProb(Dst);
2247   else {
2248     if (Prob.isUnknown())
2249       Prob = getEdgeProbability(Src, Dst);
2250     Src->addSuccessor(Dst, Prob);
2251   }
2252 }
2253 
2254 static bool InBlock(const Value *V, const BasicBlock *BB) {
2255   if (const Instruction *I = dyn_cast<Instruction>(V))
2256     return I->getParent() == BB;
2257   return true;
2258 }
2259 
2260 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2261 /// This function emits a branch and is used at the leaves of an OR or an
2262 /// AND operator tree.
2263 void
2264 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2265                                                   MachineBasicBlock *TBB,
2266                                                   MachineBasicBlock *FBB,
2267                                                   MachineBasicBlock *CurBB,
2268                                                   MachineBasicBlock *SwitchBB,
2269                                                   BranchProbability TProb,
2270                                                   BranchProbability FProb,
2271                                                   bool InvertCond) {
2272   const BasicBlock *BB = CurBB->getBasicBlock();
2273 
2274   // If the leaf of the tree is a comparison, merge the condition into
2275   // the caseblock.
2276   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2277     // The operands of the cmp have to be in this block.  We don't know
2278     // how to export them from some other block.  If this is the first block
2279     // of the sequence, no exporting is needed.
2280     if (CurBB == SwitchBB ||
2281         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2282          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2283       ISD::CondCode Condition;
2284       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2285         ICmpInst::Predicate Pred =
2286             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2287         Condition = getICmpCondCode(Pred);
2288       } else {
2289         const FCmpInst *FC = cast<FCmpInst>(Cond);
2290         FCmpInst::Predicate Pred =
2291             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2292         Condition = getFCmpCondCode(Pred);
2293         if (TM.Options.NoNaNsFPMath)
2294           Condition = getFCmpCodeWithoutNaN(Condition);
2295       }
2296 
2297       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2298                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2299       SL->SwitchCases.push_back(CB);
2300       return;
2301     }
2302   }
2303 
2304   // Create a CaseBlock record representing this branch.
2305   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2306   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2307                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2308   SL->SwitchCases.push_back(CB);
2309 }
2310 
2311 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2312                                                MachineBasicBlock *TBB,
2313                                                MachineBasicBlock *FBB,
2314                                                MachineBasicBlock *CurBB,
2315                                                MachineBasicBlock *SwitchBB,
2316                                                Instruction::BinaryOps Opc,
2317                                                BranchProbability TProb,
2318                                                BranchProbability FProb,
2319                                                bool InvertCond) {
2320   // Skip over not part of the tree and remember to invert op and operands at
2321   // next level.
2322   Value *NotCond;
2323   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2324       InBlock(NotCond, CurBB->getBasicBlock())) {
2325     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2326                          !InvertCond);
2327     return;
2328   }
2329 
2330   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2331   const Value *BOpOp0, *BOpOp1;
2332   // Compute the effective opcode for Cond, taking into account whether it needs
2333   // to be inverted, e.g.
2334   //   and (not (or A, B)), C
2335   // gets lowered as
2336   //   and (and (not A, not B), C)
2337   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2338   if (BOp) {
2339     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2340                ? Instruction::And
2341                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2342                       ? Instruction::Or
2343                       : (Instruction::BinaryOps)0);
2344     if (InvertCond) {
2345       if (BOpc == Instruction::And)
2346         BOpc = Instruction::Or;
2347       else if (BOpc == Instruction::Or)
2348         BOpc = Instruction::And;
2349     }
2350   }
2351 
2352   // If this node is not part of the or/and tree, emit it as a branch.
2353   // Note that all nodes in the tree should have same opcode.
2354   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2355   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2356       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2357       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2358     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2359                                  TProb, FProb, InvertCond);
2360     return;
2361   }
2362 
2363   //  Create TmpBB after CurBB.
2364   MachineFunction::iterator BBI(CurBB);
2365   MachineFunction &MF = DAG.getMachineFunction();
2366   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2367   CurBB->getParent()->insert(++BBI, TmpBB);
2368 
2369   if (Opc == Instruction::Or) {
2370     // Codegen X | Y as:
2371     // BB1:
2372     //   jmp_if_X TBB
2373     //   jmp TmpBB
2374     // TmpBB:
2375     //   jmp_if_Y TBB
2376     //   jmp FBB
2377     //
2378 
2379     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2380     // The requirement is that
2381     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2382     //     = TrueProb for original BB.
2383     // Assuming the original probabilities are A and B, one choice is to set
2384     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2385     // A/(1+B) and 2B/(1+B). This choice assumes that
2386     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2387     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2388     // TmpBB, but the math is more complicated.
2389 
2390     auto NewTrueProb = TProb / 2;
2391     auto NewFalseProb = TProb / 2 + FProb;
2392     // Emit the LHS condition.
2393     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2394                          NewFalseProb, InvertCond);
2395 
2396     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2397     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2398     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2399     // Emit the RHS condition into TmpBB.
2400     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2401                          Probs[1], InvertCond);
2402   } else {
2403     assert(Opc == Instruction::And && "Unknown merge op!");
2404     // Codegen X & Y as:
2405     // BB1:
2406     //   jmp_if_X TmpBB
2407     //   jmp FBB
2408     // TmpBB:
2409     //   jmp_if_Y TBB
2410     //   jmp FBB
2411     //
2412     //  This requires creation of TmpBB after CurBB.
2413 
2414     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2415     // The requirement is that
2416     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2417     //     = FalseProb for original BB.
2418     // Assuming the original probabilities are A and B, one choice is to set
2419     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2420     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2421     // TrueProb for BB1 * FalseProb for TmpBB.
2422 
2423     auto NewTrueProb = TProb + FProb / 2;
2424     auto NewFalseProb = FProb / 2;
2425     // Emit the LHS condition.
2426     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2427                          NewFalseProb, InvertCond);
2428 
2429     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2430     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2431     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2432     // Emit the RHS condition into TmpBB.
2433     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2434                          Probs[1], InvertCond);
2435   }
2436 }
2437 
2438 /// If the set of cases should be emitted as a series of branches, return true.
2439 /// If we should emit this as a bunch of and/or'd together conditions, return
2440 /// false.
2441 bool
2442 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2443   if (Cases.size() != 2) return true;
2444 
2445   // If this is two comparisons of the same values or'd or and'd together, they
2446   // will get folded into a single comparison, so don't emit two blocks.
2447   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2448        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2449       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2450        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2451     return false;
2452   }
2453 
2454   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2455   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2456   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2457       Cases[0].CC == Cases[1].CC &&
2458       isa<Constant>(Cases[0].CmpRHS) &&
2459       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2460     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2461       return false;
2462     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2463       return false;
2464   }
2465 
2466   return true;
2467 }
2468 
2469 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2470   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2471 
2472   // Update machine-CFG edges.
2473   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2474 
2475   if (I.isUnconditional()) {
2476     // Update machine-CFG edges.
2477     BrMBB->addSuccessor(Succ0MBB);
2478 
2479     // If this is not a fall-through branch or optimizations are switched off,
2480     // emit the branch.
2481     if (Succ0MBB != NextBlock(BrMBB) ||
2482         TM.getOptLevel() == CodeGenOptLevel::None) {
2483       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2484                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2485       setValue(&I, Br);
2486       DAG.setRoot(Br);
2487     }
2488 
2489     return;
2490   }
2491 
2492   // If this condition is one of the special cases we handle, do special stuff
2493   // now.
2494   const Value *CondVal = I.getCondition();
2495   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2496 
2497   // If this is a series of conditions that are or'd or and'd together, emit
2498   // this as a sequence of branches instead of setcc's with and/or operations.
2499   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2500   // unpredictable branches, and vector extracts because those jumps are likely
2501   // expensive for any target), this should improve performance.
2502   // For example, instead of something like:
2503   //     cmp A, B
2504   //     C = seteq
2505   //     cmp D, E
2506   //     F = setle
2507   //     or C, F
2508   //     jnz foo
2509   // Emit:
2510   //     cmp A, B
2511   //     je foo
2512   //     cmp D, E
2513   //     jle foo
2514   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2515   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2516       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2517     Value *Vec;
2518     const Value *BOp0, *BOp1;
2519     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2520     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2521       Opcode = Instruction::And;
2522     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2523       Opcode = Instruction::Or;
2524 
2525     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2526                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2527       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2528                            getEdgeProbability(BrMBB, Succ0MBB),
2529                            getEdgeProbability(BrMBB, Succ1MBB),
2530                            /*InvertCond=*/false);
2531       // If the compares in later blocks need to use values not currently
2532       // exported from this block, export them now.  This block should always
2533       // be the first entry.
2534       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2535 
2536       // Allow some cases to be rejected.
2537       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2538         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2539           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2540           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2541         }
2542 
2543         // Emit the branch for this block.
2544         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2545         SL->SwitchCases.erase(SL->SwitchCases.begin());
2546         return;
2547       }
2548 
2549       // Okay, we decided not to do this, remove any inserted MBB's and clear
2550       // SwitchCases.
2551       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2552         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2553 
2554       SL->SwitchCases.clear();
2555     }
2556   }
2557 
2558   // Create a CaseBlock record representing this branch.
2559   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2560                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2561 
2562   // Use visitSwitchCase to actually insert the fast branch sequence for this
2563   // cond branch.
2564   visitSwitchCase(CB, BrMBB);
2565 }
2566 
2567 /// visitSwitchCase - Emits the necessary code to represent a single node in
2568 /// the binary search tree resulting from lowering a switch instruction.
2569 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2570                                           MachineBasicBlock *SwitchBB) {
2571   SDValue Cond;
2572   SDValue CondLHS = getValue(CB.CmpLHS);
2573   SDLoc dl = CB.DL;
2574 
2575   if (CB.CC == ISD::SETTRUE) {
2576     // Branch or fall through to TrueBB.
2577     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2578     SwitchBB->normalizeSuccProbs();
2579     if (CB.TrueBB != NextBlock(SwitchBB)) {
2580       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2581                               DAG.getBasicBlock(CB.TrueBB)));
2582     }
2583     return;
2584   }
2585 
2586   auto &TLI = DAG.getTargetLoweringInfo();
2587   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2588 
2589   // Build the setcc now.
2590   if (!CB.CmpMHS) {
2591     // Fold "(X == true)" to X and "(X == false)" to !X to
2592     // handle common cases produced by branch lowering.
2593     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2594         CB.CC == ISD::SETEQ)
2595       Cond = CondLHS;
2596     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2597              CB.CC == ISD::SETEQ) {
2598       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2599       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2600     } else {
2601       SDValue CondRHS = getValue(CB.CmpRHS);
2602 
2603       // If a pointer's DAG type is larger than its memory type then the DAG
2604       // values are zero-extended. This breaks signed comparisons so truncate
2605       // back to the underlying type before doing the compare.
2606       if (CondLHS.getValueType() != MemVT) {
2607         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2608         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2609       }
2610       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2611     }
2612   } else {
2613     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2614 
2615     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2616     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2617 
2618     SDValue CmpOp = getValue(CB.CmpMHS);
2619     EVT VT = CmpOp.getValueType();
2620 
2621     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2622       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2623                           ISD::SETLE);
2624     } else {
2625       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2626                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2627       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2628                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2629     }
2630   }
2631 
2632   // Update successor info
2633   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2634   // TrueBB and FalseBB are always different unless the incoming IR is
2635   // degenerate. This only happens when running llc on weird IR.
2636   if (CB.TrueBB != CB.FalseBB)
2637     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2638   SwitchBB->normalizeSuccProbs();
2639 
2640   // If the lhs block is the next block, invert the condition so that we can
2641   // fall through to the lhs instead of the rhs block.
2642   if (CB.TrueBB == NextBlock(SwitchBB)) {
2643     std::swap(CB.TrueBB, CB.FalseBB);
2644     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2645     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2646   }
2647 
2648   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2649                                MVT::Other, getControlRoot(), Cond,
2650                                DAG.getBasicBlock(CB.TrueBB));
2651 
2652   setValue(CurInst, BrCond);
2653 
2654   // Insert the false branch. Do this even if it's a fall through branch,
2655   // this makes it easier to do DAG optimizations which require inverting
2656   // the branch condition.
2657   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2658                        DAG.getBasicBlock(CB.FalseBB));
2659 
2660   DAG.setRoot(BrCond);
2661 }
2662 
2663 /// visitJumpTable - Emit JumpTable node in the current MBB
2664 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2665   // Emit the code for the jump table
2666   assert(JT.Reg != -1U && "Should lower JT Header first!");
2667   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2668   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2669                                      JT.Reg, PTy);
2670   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2671   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2672                                     MVT::Other, Index.getValue(1),
2673                                     Table, Index);
2674   DAG.setRoot(BrJumpTable);
2675 }
2676 
2677 /// visitJumpTableHeader - This function emits necessary code to produce index
2678 /// in the JumpTable from switch case.
2679 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2680                                                JumpTableHeader &JTH,
2681                                                MachineBasicBlock *SwitchBB) {
2682   SDLoc dl = getCurSDLoc();
2683 
2684   // Subtract the lowest switch case value from the value being switched on.
2685   SDValue SwitchOp = getValue(JTH.SValue);
2686   EVT VT = SwitchOp.getValueType();
2687   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2688                             DAG.getConstant(JTH.First, dl, VT));
2689 
2690   // The SDNode we just created, which holds the value being switched on minus
2691   // the smallest case value, needs to be copied to a virtual register so it
2692   // can be used as an index into the jump table in a subsequent basic block.
2693   // This value may be smaller or larger than the target's pointer type, and
2694   // therefore require extension or truncating.
2695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2696   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2697 
2698   unsigned JumpTableReg =
2699       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2700   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2701                                     JumpTableReg, SwitchOp);
2702   JT.Reg = JumpTableReg;
2703 
2704   if (!JTH.FallthroughUnreachable) {
2705     // Emit the range check for the jump table, and branch to the default block
2706     // for the switch statement if the value being switched on exceeds the
2707     // largest case in the switch.
2708     SDValue CMP = DAG.getSetCC(
2709         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2710                                    Sub.getValueType()),
2711         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2712 
2713     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2714                                  MVT::Other, CopyTo, CMP,
2715                                  DAG.getBasicBlock(JT.Default));
2716 
2717     // Avoid emitting unnecessary branches to the next block.
2718     if (JT.MBB != NextBlock(SwitchBB))
2719       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2720                            DAG.getBasicBlock(JT.MBB));
2721 
2722     DAG.setRoot(BrCond);
2723   } else {
2724     // Avoid emitting unnecessary branches to the next block.
2725     if (JT.MBB != NextBlock(SwitchBB))
2726       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2727                               DAG.getBasicBlock(JT.MBB)));
2728     else
2729       DAG.setRoot(CopyTo);
2730   }
2731 }
2732 
2733 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2734 /// variable if there exists one.
2735 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2736                                  SDValue &Chain) {
2737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2738   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2739   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2740   MachineFunction &MF = DAG.getMachineFunction();
2741   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2742   MachineSDNode *Node =
2743       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2744   if (Global) {
2745     MachinePointerInfo MPInfo(Global);
2746     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2747                  MachineMemOperand::MODereferenceable;
2748     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2749         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2750     DAG.setNodeMemRefs(Node, {MemRef});
2751   }
2752   if (PtrTy != PtrMemTy)
2753     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2754   return SDValue(Node, 0);
2755 }
2756 
2757 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2758 /// tail spliced into a stack protector check success bb.
2759 ///
2760 /// For a high level explanation of how this fits into the stack protector
2761 /// generation see the comment on the declaration of class
2762 /// StackProtectorDescriptor.
2763 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2764                                                   MachineBasicBlock *ParentBB) {
2765 
2766   // First create the loads to the guard/stack slot for the comparison.
2767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2768   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2769   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2770 
2771   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2772   int FI = MFI.getStackProtectorIndex();
2773 
2774   SDValue Guard;
2775   SDLoc dl = getCurSDLoc();
2776   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2777   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2778   Align Align =
2779       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
2780 
2781   // Generate code to load the content of the guard slot.
2782   SDValue GuardVal = DAG.getLoad(
2783       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2784       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2785       MachineMemOperand::MOVolatile);
2786 
2787   if (TLI.useStackGuardXorFP())
2788     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2789 
2790   // Retrieve guard check function, nullptr if instrumentation is inlined.
2791   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2792     // The target provides a guard check function to validate the guard value.
2793     // Generate a call to that function with the content of the guard slot as
2794     // argument.
2795     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2796     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2797 
2798     TargetLowering::ArgListTy Args;
2799     TargetLowering::ArgListEntry Entry;
2800     Entry.Node = GuardVal;
2801     Entry.Ty = FnTy->getParamType(0);
2802     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2803       Entry.IsInReg = true;
2804     Args.push_back(Entry);
2805 
2806     TargetLowering::CallLoweringInfo CLI(DAG);
2807     CLI.setDebugLoc(getCurSDLoc())
2808         .setChain(DAG.getEntryNode())
2809         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2810                    getValue(GuardCheckFn), std::move(Args));
2811 
2812     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2813     DAG.setRoot(Result.second);
2814     return;
2815   }
2816 
2817   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2818   // Otherwise, emit a volatile load to retrieve the stack guard value.
2819   SDValue Chain = DAG.getEntryNode();
2820   if (TLI.useLoadStackGuardNode()) {
2821     Guard = getLoadStackGuard(DAG, dl, Chain);
2822   } else {
2823     const Value *IRGuard = TLI.getSDagStackGuard(M);
2824     SDValue GuardPtr = getValue(IRGuard);
2825 
2826     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2827                         MachinePointerInfo(IRGuard, 0), Align,
2828                         MachineMemOperand::MOVolatile);
2829   }
2830 
2831   // Perform the comparison via a getsetcc.
2832   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2833                                                         *DAG.getContext(),
2834                                                         Guard.getValueType()),
2835                              Guard, GuardVal, ISD::SETNE);
2836 
2837   // If the guard/stackslot do not equal, branch to failure MBB.
2838   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2839                                MVT::Other, GuardVal.getOperand(0),
2840                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2841   // Otherwise branch to success MBB.
2842   SDValue Br = DAG.getNode(ISD::BR, dl,
2843                            MVT::Other, BrCond,
2844                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2845 
2846   DAG.setRoot(Br);
2847 }
2848 
2849 /// Codegen the failure basic block for a stack protector check.
2850 ///
2851 /// A failure stack protector machine basic block consists simply of a call to
2852 /// __stack_chk_fail().
2853 ///
2854 /// For a high level explanation of how this fits into the stack protector
2855 /// generation see the comment on the declaration of class
2856 /// StackProtectorDescriptor.
2857 void
2858 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2860   TargetLowering::MakeLibCallOptions CallOptions;
2861   CallOptions.setDiscardResult(true);
2862   SDValue Chain =
2863       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2864                       std::nullopt, CallOptions, getCurSDLoc())
2865           .second;
2866   // On PS4/PS5, the "return address" must still be within the calling
2867   // function, even if it's at the very end, so emit an explicit TRAP here.
2868   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2869   if (TM.getTargetTriple().isPS())
2870     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2871   // WebAssembly needs an unreachable instruction after a non-returning call,
2872   // because the function return type can be different from __stack_chk_fail's
2873   // return type (void).
2874   if (TM.getTargetTriple().isWasm())
2875     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2876 
2877   DAG.setRoot(Chain);
2878 }
2879 
2880 /// visitBitTestHeader - This function emits necessary code to produce value
2881 /// suitable for "bit tests"
2882 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2883                                              MachineBasicBlock *SwitchBB) {
2884   SDLoc dl = getCurSDLoc();
2885 
2886   // Subtract the minimum value.
2887   SDValue SwitchOp = getValue(B.SValue);
2888   EVT VT = SwitchOp.getValueType();
2889   SDValue RangeSub =
2890       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2891 
2892   // Determine the type of the test operands.
2893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2894   bool UsePtrType = false;
2895   if (!TLI.isTypeLegal(VT)) {
2896     UsePtrType = true;
2897   } else {
2898     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2899       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2900         // Switch table case range are encoded into series of masks.
2901         // Just use pointer type, it's guaranteed to fit.
2902         UsePtrType = true;
2903         break;
2904       }
2905   }
2906   SDValue Sub = RangeSub;
2907   if (UsePtrType) {
2908     VT = TLI.getPointerTy(DAG.getDataLayout());
2909     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2910   }
2911 
2912   B.RegVT = VT.getSimpleVT();
2913   B.Reg = FuncInfo.CreateReg(B.RegVT);
2914   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2915 
2916   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2917 
2918   if (!B.FallthroughUnreachable)
2919     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2920   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2921   SwitchBB->normalizeSuccProbs();
2922 
2923   SDValue Root = CopyTo;
2924   if (!B.FallthroughUnreachable) {
2925     // Conditional branch to the default block.
2926     SDValue RangeCmp = DAG.getSetCC(dl,
2927         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2928                                RangeSub.getValueType()),
2929         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2930         ISD::SETUGT);
2931 
2932     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2933                        DAG.getBasicBlock(B.Default));
2934   }
2935 
2936   // Avoid emitting unnecessary branches to the next block.
2937   if (MBB != NextBlock(SwitchBB))
2938     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2939 
2940   DAG.setRoot(Root);
2941 }
2942 
2943 /// visitBitTestCase - this function produces one "bit test"
2944 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2945                                            MachineBasicBlock* NextMBB,
2946                                            BranchProbability BranchProbToNext,
2947                                            unsigned Reg,
2948                                            BitTestCase &B,
2949                                            MachineBasicBlock *SwitchBB) {
2950   SDLoc dl = getCurSDLoc();
2951   MVT VT = BB.RegVT;
2952   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2953   SDValue Cmp;
2954   unsigned PopCount = llvm::popcount(B.Mask);
2955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2956   if (PopCount == 1) {
2957     // Testing for a single bit; just compare the shift count with what it
2958     // would need to be to shift a 1 bit in that position.
2959     Cmp = DAG.getSetCC(
2960         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2961         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2962         ISD::SETEQ);
2963   } else if (PopCount == BB.Range) {
2964     // There is only one zero bit in the range, test for it directly.
2965     Cmp = DAG.getSetCC(
2966         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2967         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2968   } else {
2969     // Make desired shift
2970     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2971                                     DAG.getConstant(1, dl, VT), ShiftOp);
2972 
2973     // Emit bit tests and jumps
2974     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2975                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2976     Cmp = DAG.getSetCC(
2977         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2978         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2979   }
2980 
2981   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2982   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2983   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2984   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2985   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2986   // one as they are relative probabilities (and thus work more like weights),
2987   // and hence we need to normalize them to let the sum of them become one.
2988   SwitchBB->normalizeSuccProbs();
2989 
2990   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2991                               MVT::Other, getControlRoot(),
2992                               Cmp, DAG.getBasicBlock(B.TargetBB));
2993 
2994   // Avoid emitting unnecessary branches to the next block.
2995   if (NextMBB != NextBlock(SwitchBB))
2996     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2997                         DAG.getBasicBlock(NextMBB));
2998 
2999   DAG.setRoot(BrAnd);
3000 }
3001 
3002 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3003   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3004 
3005   // Retrieve successors. Look through artificial IR level blocks like
3006   // catchswitch for successors.
3007   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3008   const BasicBlock *EHPadBB = I.getSuccessor(1);
3009   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3010 
3011   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3012   // have to do anything here to lower funclet bundles.
3013   assert(!I.hasOperandBundlesOtherThan(
3014              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3015               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3016               LLVMContext::OB_cfguardtarget,
3017               LLVMContext::OB_clang_arc_attachedcall}) &&
3018          "Cannot lower invokes with arbitrary operand bundles yet!");
3019 
3020   const Value *Callee(I.getCalledOperand());
3021   const Function *Fn = dyn_cast<Function>(Callee);
3022   if (isa<InlineAsm>(Callee))
3023     visitInlineAsm(I, EHPadBB);
3024   else if (Fn && Fn->isIntrinsic()) {
3025     switch (Fn->getIntrinsicID()) {
3026     default:
3027       llvm_unreachable("Cannot invoke this intrinsic");
3028     case Intrinsic::donothing:
3029       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3030     case Intrinsic::seh_try_begin:
3031     case Intrinsic::seh_scope_begin:
3032     case Intrinsic::seh_try_end:
3033     case Intrinsic::seh_scope_end:
3034       if (EHPadMBB)
3035           // a block referenced by EH table
3036           // so dtor-funclet not removed by opts
3037           EHPadMBB->setMachineBlockAddressTaken();
3038       break;
3039     case Intrinsic::experimental_patchpoint_void:
3040     case Intrinsic::experimental_patchpoint_i64:
3041       visitPatchpoint(I, EHPadBB);
3042       break;
3043     case Intrinsic::experimental_gc_statepoint:
3044       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3045       break;
3046     case Intrinsic::wasm_rethrow: {
3047       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3048       // special because it can be invoked, so we manually lower it to a DAG
3049       // node here.
3050       SmallVector<SDValue, 8> Ops;
3051       Ops.push_back(getRoot()); // inchain
3052       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3053       Ops.push_back(
3054           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3055                                 TLI.getPointerTy(DAG.getDataLayout())));
3056       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3057       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3058       break;
3059     }
3060     }
3061   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3062     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3063     // Eventually we will support lowering the @llvm.experimental.deoptimize
3064     // intrinsic, and right now there are no plans to support other intrinsics
3065     // with deopt state.
3066     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3067   } else {
3068     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3069   }
3070 
3071   // If the value of the invoke is used outside of its defining block, make it
3072   // available as a virtual register.
3073   // We already took care of the exported value for the statepoint instruction
3074   // during call to the LowerStatepoint.
3075   if (!isa<GCStatepointInst>(I)) {
3076     CopyToExportRegsIfNeeded(&I);
3077   }
3078 
3079   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3080   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3081   BranchProbability EHPadBBProb =
3082       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3083           : BranchProbability::getZero();
3084   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3085 
3086   // Update successor info.
3087   addSuccessorWithProb(InvokeMBB, Return);
3088   for (auto &UnwindDest : UnwindDests) {
3089     UnwindDest.first->setIsEHPad();
3090     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3091   }
3092   InvokeMBB->normalizeSuccProbs();
3093 
3094   // Drop into normal successor.
3095   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3096                           DAG.getBasicBlock(Return)));
3097 }
3098 
3099 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3100   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3101 
3102   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3103   // have to do anything here to lower funclet bundles.
3104   assert(!I.hasOperandBundlesOtherThan(
3105              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3106          "Cannot lower callbrs with arbitrary operand bundles yet!");
3107 
3108   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3109   visitInlineAsm(I);
3110   CopyToExportRegsIfNeeded(&I);
3111 
3112   // Retrieve successors.
3113   SmallPtrSet<BasicBlock *, 8> Dests;
3114   Dests.insert(I.getDefaultDest());
3115   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3116 
3117   // Update successor info.
3118   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3119   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3120     BasicBlock *Dest = I.getIndirectDest(i);
3121     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3122     Target->setIsInlineAsmBrIndirectTarget();
3123     Target->setMachineBlockAddressTaken();
3124     Target->setLabelMustBeEmitted();
3125     // Don't add duplicate machine successors.
3126     if (Dests.insert(Dest).second)
3127       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3128   }
3129   CallBrMBB->normalizeSuccProbs();
3130 
3131   // Drop into default successor.
3132   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3133                           MVT::Other, getControlRoot(),
3134                           DAG.getBasicBlock(Return)));
3135 }
3136 
3137 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3138   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3139 }
3140 
3141 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3142   assert(FuncInfo.MBB->isEHPad() &&
3143          "Call to landingpad not in landing pad!");
3144 
3145   // If there aren't registers to copy the values into (e.g., during SjLj
3146   // exceptions), then don't bother to create these DAG nodes.
3147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3148   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3149   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3150       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3151     return;
3152 
3153   // If landingpad's return type is token type, we don't create DAG nodes
3154   // for its exception pointer and selector value. The extraction of exception
3155   // pointer or selector value from token type landingpads is not currently
3156   // supported.
3157   if (LP.getType()->isTokenTy())
3158     return;
3159 
3160   SmallVector<EVT, 2> ValueVTs;
3161   SDLoc dl = getCurSDLoc();
3162   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3163   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3164 
3165   // Get the two live-in registers as SDValues. The physregs have already been
3166   // copied into virtual registers.
3167   SDValue Ops[2];
3168   if (FuncInfo.ExceptionPointerVirtReg) {
3169     Ops[0] = DAG.getZExtOrTrunc(
3170         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3171                            FuncInfo.ExceptionPointerVirtReg,
3172                            TLI.getPointerTy(DAG.getDataLayout())),
3173         dl, ValueVTs[0]);
3174   } else {
3175     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3176   }
3177   Ops[1] = DAG.getZExtOrTrunc(
3178       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3179                          FuncInfo.ExceptionSelectorVirtReg,
3180                          TLI.getPointerTy(DAG.getDataLayout())),
3181       dl, ValueVTs[1]);
3182 
3183   // Merge into one.
3184   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3185                             DAG.getVTList(ValueVTs), Ops);
3186   setValue(&LP, Res);
3187 }
3188 
3189 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3190                                            MachineBasicBlock *Last) {
3191   // Update JTCases.
3192   for (JumpTableBlock &JTB : SL->JTCases)
3193     if (JTB.first.HeaderBB == First)
3194       JTB.first.HeaderBB = Last;
3195 
3196   // Update BitTestCases.
3197   for (BitTestBlock &BTB : SL->BitTestCases)
3198     if (BTB.Parent == First)
3199       BTB.Parent = Last;
3200 }
3201 
3202 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3203   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3204 
3205   // Update machine-CFG edges with unique successors.
3206   SmallSet<BasicBlock*, 32> Done;
3207   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3208     BasicBlock *BB = I.getSuccessor(i);
3209     bool Inserted = Done.insert(BB).second;
3210     if (!Inserted)
3211         continue;
3212 
3213     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3214     addSuccessorWithProb(IndirectBrMBB, Succ);
3215   }
3216   IndirectBrMBB->normalizeSuccProbs();
3217 
3218   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3219                           MVT::Other, getControlRoot(),
3220                           getValue(I.getAddress())));
3221 }
3222 
3223 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3224   if (!DAG.getTarget().Options.TrapUnreachable)
3225     return;
3226 
3227   // We may be able to ignore unreachable behind a noreturn call.
3228   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3229     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3230       if (Call->doesNotReturn())
3231         return;
3232     }
3233   }
3234 
3235   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3236 }
3237 
3238 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3239   SDNodeFlags Flags;
3240   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3241     Flags.copyFMF(*FPOp);
3242 
3243   SDValue Op = getValue(I.getOperand(0));
3244   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3245                                     Op, Flags);
3246   setValue(&I, UnNodeValue);
3247 }
3248 
3249 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3250   SDNodeFlags Flags;
3251   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3252     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3253     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3254   }
3255   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3256     Flags.setExact(ExactOp->isExact());
3257   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3258     Flags.copyFMF(*FPOp);
3259 
3260   SDValue Op1 = getValue(I.getOperand(0));
3261   SDValue Op2 = getValue(I.getOperand(1));
3262   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3263                                      Op1, Op2, Flags);
3264   setValue(&I, BinNodeValue);
3265 }
3266 
3267 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3268   SDValue Op1 = getValue(I.getOperand(0));
3269   SDValue Op2 = getValue(I.getOperand(1));
3270 
3271   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3272       Op1.getValueType(), DAG.getDataLayout());
3273 
3274   // Coerce the shift amount to the right type if we can. This exposes the
3275   // truncate or zext to optimization early.
3276   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3277     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3278            "Unexpected shift type");
3279     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3280   }
3281 
3282   bool nuw = false;
3283   bool nsw = false;
3284   bool exact = false;
3285 
3286   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3287 
3288     if (const OverflowingBinaryOperator *OFBinOp =
3289             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3290       nuw = OFBinOp->hasNoUnsignedWrap();
3291       nsw = OFBinOp->hasNoSignedWrap();
3292     }
3293     if (const PossiblyExactOperator *ExactOp =
3294             dyn_cast<const PossiblyExactOperator>(&I))
3295       exact = ExactOp->isExact();
3296   }
3297   SDNodeFlags Flags;
3298   Flags.setExact(exact);
3299   Flags.setNoSignedWrap(nsw);
3300   Flags.setNoUnsignedWrap(nuw);
3301   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3302                             Flags);
3303   setValue(&I, Res);
3304 }
3305 
3306 void SelectionDAGBuilder::visitSDiv(const User &I) {
3307   SDValue Op1 = getValue(I.getOperand(0));
3308   SDValue Op2 = getValue(I.getOperand(1));
3309 
3310   SDNodeFlags Flags;
3311   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3312                  cast<PossiblyExactOperator>(&I)->isExact());
3313   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3314                            Op2, Flags));
3315 }
3316 
3317 void SelectionDAGBuilder::visitICmp(const User &I) {
3318   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3319   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3320     predicate = IC->getPredicate();
3321   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3322     predicate = ICmpInst::Predicate(IC->getPredicate());
3323   SDValue Op1 = getValue(I.getOperand(0));
3324   SDValue Op2 = getValue(I.getOperand(1));
3325   ISD::CondCode Opcode = getICmpCondCode(predicate);
3326 
3327   auto &TLI = DAG.getTargetLoweringInfo();
3328   EVT MemVT =
3329       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3330 
3331   // If a pointer's DAG type is larger than its memory type then the DAG values
3332   // are zero-extended. This breaks signed comparisons so truncate back to the
3333   // underlying type before doing the compare.
3334   if (Op1.getValueType() != MemVT) {
3335     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3336     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3337   }
3338 
3339   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3340                                                         I.getType());
3341   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3342 }
3343 
3344 void SelectionDAGBuilder::visitFCmp(const User &I) {
3345   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3346   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3347     predicate = FC->getPredicate();
3348   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3349     predicate = FCmpInst::Predicate(FC->getPredicate());
3350   SDValue Op1 = getValue(I.getOperand(0));
3351   SDValue Op2 = getValue(I.getOperand(1));
3352 
3353   ISD::CondCode Condition = getFCmpCondCode(predicate);
3354   auto *FPMO = cast<FPMathOperator>(&I);
3355   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3356     Condition = getFCmpCodeWithoutNaN(Condition);
3357 
3358   SDNodeFlags Flags;
3359   Flags.copyFMF(*FPMO);
3360   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3361 
3362   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3363                                                         I.getType());
3364   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3365 }
3366 
3367 // Check if the condition of the select has one use or two users that are both
3368 // selects with the same condition.
3369 static bool hasOnlySelectUsers(const Value *Cond) {
3370   return llvm::all_of(Cond->users(), [](const Value *V) {
3371     return isa<SelectInst>(V);
3372   });
3373 }
3374 
3375 void SelectionDAGBuilder::visitSelect(const User &I) {
3376   SmallVector<EVT, 4> ValueVTs;
3377   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3378                   ValueVTs);
3379   unsigned NumValues = ValueVTs.size();
3380   if (NumValues == 0) return;
3381 
3382   SmallVector<SDValue, 4> Values(NumValues);
3383   SDValue Cond     = getValue(I.getOperand(0));
3384   SDValue LHSVal   = getValue(I.getOperand(1));
3385   SDValue RHSVal   = getValue(I.getOperand(2));
3386   SmallVector<SDValue, 1> BaseOps(1, Cond);
3387   ISD::NodeType OpCode =
3388       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3389 
3390   bool IsUnaryAbs = false;
3391   bool Negate = false;
3392 
3393   SDNodeFlags Flags;
3394   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3395     Flags.copyFMF(*FPOp);
3396 
3397   Flags.setUnpredictable(
3398       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3399 
3400   // Min/max matching is only viable if all output VTs are the same.
3401   if (all_equal(ValueVTs)) {
3402     EVT VT = ValueVTs[0];
3403     LLVMContext &Ctx = *DAG.getContext();
3404     auto &TLI = DAG.getTargetLoweringInfo();
3405 
3406     // We care about the legality of the operation after it has been type
3407     // legalized.
3408     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3409       VT = TLI.getTypeToTransformTo(Ctx, VT);
3410 
3411     // If the vselect is legal, assume we want to leave this as a vector setcc +
3412     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3413     // min/max is legal on the scalar type.
3414     bool UseScalarMinMax = VT.isVector() &&
3415       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3416 
3417     // ValueTracking's select pattern matching does not account for -0.0,
3418     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3419     // -0.0 is less than +0.0.
3420     Value *LHS, *RHS;
3421     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3422     ISD::NodeType Opc = ISD::DELETED_NODE;
3423     switch (SPR.Flavor) {
3424     case SPF_UMAX:    Opc = ISD::UMAX; break;
3425     case SPF_UMIN:    Opc = ISD::UMIN; break;
3426     case SPF_SMAX:    Opc = ISD::SMAX; break;
3427     case SPF_SMIN:    Opc = ISD::SMIN; break;
3428     case SPF_FMINNUM:
3429       switch (SPR.NaNBehavior) {
3430       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3431       case SPNB_RETURNS_NAN: break;
3432       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3433       case SPNB_RETURNS_ANY:
3434         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3435             (UseScalarMinMax &&
3436              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3437           Opc = ISD::FMINNUM;
3438         break;
3439       }
3440       break;
3441     case SPF_FMAXNUM:
3442       switch (SPR.NaNBehavior) {
3443       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3444       case SPNB_RETURNS_NAN: break;
3445       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3446       case SPNB_RETURNS_ANY:
3447         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3448             (UseScalarMinMax &&
3449              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3450           Opc = ISD::FMAXNUM;
3451         break;
3452       }
3453       break;
3454     case SPF_NABS:
3455       Negate = true;
3456       [[fallthrough]];
3457     case SPF_ABS:
3458       IsUnaryAbs = true;
3459       Opc = ISD::ABS;
3460       break;
3461     default: break;
3462     }
3463 
3464     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3465         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3466          (UseScalarMinMax &&
3467           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3468         // If the underlying comparison instruction is used by any other
3469         // instruction, the consumed instructions won't be destroyed, so it is
3470         // not profitable to convert to a min/max.
3471         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3472       OpCode = Opc;
3473       LHSVal = getValue(LHS);
3474       RHSVal = getValue(RHS);
3475       BaseOps.clear();
3476     }
3477 
3478     if (IsUnaryAbs) {
3479       OpCode = Opc;
3480       LHSVal = getValue(LHS);
3481       BaseOps.clear();
3482     }
3483   }
3484 
3485   if (IsUnaryAbs) {
3486     for (unsigned i = 0; i != NumValues; ++i) {
3487       SDLoc dl = getCurSDLoc();
3488       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3489       Values[i] =
3490           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3491       if (Negate)
3492         Values[i] = DAG.getNegative(Values[i], dl, VT);
3493     }
3494   } else {
3495     for (unsigned i = 0; i != NumValues; ++i) {
3496       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3497       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3498       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3499       Values[i] = DAG.getNode(
3500           OpCode, getCurSDLoc(),
3501           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3502     }
3503   }
3504 
3505   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3506                            DAG.getVTList(ValueVTs), Values));
3507 }
3508 
3509 void SelectionDAGBuilder::visitTrunc(const User &I) {
3510   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3511   SDValue N = getValue(I.getOperand(0));
3512   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3513                                                         I.getType());
3514   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3515 }
3516 
3517 void SelectionDAGBuilder::visitZExt(const User &I) {
3518   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3519   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3520   SDValue N = getValue(I.getOperand(0));
3521   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3522                                                         I.getType());
3523   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3524 }
3525 
3526 void SelectionDAGBuilder::visitSExt(const User &I) {
3527   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3528   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3529   SDValue N = getValue(I.getOperand(0));
3530   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3531                                                         I.getType());
3532   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3533 }
3534 
3535 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3536   // FPTrunc is never a no-op cast, no need to check
3537   SDValue N = getValue(I.getOperand(0));
3538   SDLoc dl = getCurSDLoc();
3539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3540   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3541   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3542                            DAG.getTargetConstant(
3543                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3544 }
3545 
3546 void SelectionDAGBuilder::visitFPExt(const User &I) {
3547   // FPExt is never a no-op cast, no need to check
3548   SDValue N = getValue(I.getOperand(0));
3549   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3550                                                         I.getType());
3551   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3552 }
3553 
3554 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3555   // FPToUI is never a no-op cast, no need to check
3556   SDValue N = getValue(I.getOperand(0));
3557   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3558                                                         I.getType());
3559   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3560 }
3561 
3562 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3563   // FPToSI is never a no-op cast, no need to check
3564   SDValue N = getValue(I.getOperand(0));
3565   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3566                                                         I.getType());
3567   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3568 }
3569 
3570 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3571   // UIToFP is never a no-op cast, no need to check
3572   SDValue N = getValue(I.getOperand(0));
3573   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3574                                                         I.getType());
3575   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3576 }
3577 
3578 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3579   // SIToFP is never a no-op cast, no need to check
3580   SDValue N = getValue(I.getOperand(0));
3581   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3582                                                         I.getType());
3583   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3584 }
3585 
3586 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3587   // What to do depends on the size of the integer and the size of the pointer.
3588   // We can either truncate, zero extend, or no-op, accordingly.
3589   SDValue N = getValue(I.getOperand(0));
3590   auto &TLI = DAG.getTargetLoweringInfo();
3591   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3592                                                         I.getType());
3593   EVT PtrMemVT =
3594       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3595   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3596   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3597   setValue(&I, N);
3598 }
3599 
3600 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3601   // What to do depends on the size of the integer and the size of the pointer.
3602   // We can either truncate, zero extend, or no-op, accordingly.
3603   SDValue N = getValue(I.getOperand(0));
3604   auto &TLI = DAG.getTargetLoweringInfo();
3605   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3606   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3607   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3608   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3609   setValue(&I, N);
3610 }
3611 
3612 void SelectionDAGBuilder::visitBitCast(const User &I) {
3613   SDValue N = getValue(I.getOperand(0));
3614   SDLoc dl = getCurSDLoc();
3615   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3616                                                         I.getType());
3617 
3618   // BitCast assures us that source and destination are the same size so this is
3619   // either a BITCAST or a no-op.
3620   if (DestVT != N.getValueType())
3621     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3622                              DestVT, N)); // convert types.
3623   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3624   // might fold any kind of constant expression to an integer constant and that
3625   // is not what we are looking for. Only recognize a bitcast of a genuine
3626   // constant integer as an opaque constant.
3627   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3628     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3629                                  /*isOpaque*/true));
3630   else
3631     setValue(&I, N);            // noop cast.
3632 }
3633 
3634 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3636   const Value *SV = I.getOperand(0);
3637   SDValue N = getValue(SV);
3638   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3639 
3640   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3641   unsigned DestAS = I.getType()->getPointerAddressSpace();
3642 
3643   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3644     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3645 
3646   setValue(&I, N);
3647 }
3648 
3649 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3651   SDValue InVec = getValue(I.getOperand(0));
3652   SDValue InVal = getValue(I.getOperand(1));
3653   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3654                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3655   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3656                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3657                            InVec, InVal, InIdx));
3658 }
3659 
3660 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3662   SDValue InVec = getValue(I.getOperand(0));
3663   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3664                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3665   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3666                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3667                            InVec, InIdx));
3668 }
3669 
3670 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3671   SDValue Src1 = getValue(I.getOperand(0));
3672   SDValue Src2 = getValue(I.getOperand(1));
3673   ArrayRef<int> Mask;
3674   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3675     Mask = SVI->getShuffleMask();
3676   else
3677     Mask = cast<ConstantExpr>(I).getShuffleMask();
3678   SDLoc DL = getCurSDLoc();
3679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3680   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3681   EVT SrcVT = Src1.getValueType();
3682 
3683   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3684       VT.isScalableVector()) {
3685     // Canonical splat form of first element of first input vector.
3686     SDValue FirstElt =
3687         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3688                     DAG.getVectorIdxConstant(0, DL));
3689     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3690     return;
3691   }
3692 
3693   // For now, we only handle splats for scalable vectors.
3694   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3695   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3696   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3697 
3698   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3699   unsigned MaskNumElts = Mask.size();
3700 
3701   if (SrcNumElts == MaskNumElts) {
3702     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3703     return;
3704   }
3705 
3706   // Normalize the shuffle vector since mask and vector length don't match.
3707   if (SrcNumElts < MaskNumElts) {
3708     // Mask is longer than the source vectors. We can use concatenate vector to
3709     // make the mask and vectors lengths match.
3710 
3711     if (MaskNumElts % SrcNumElts == 0) {
3712       // Mask length is a multiple of the source vector length.
3713       // Check if the shuffle is some kind of concatenation of the input
3714       // vectors.
3715       unsigned NumConcat = MaskNumElts / SrcNumElts;
3716       bool IsConcat = true;
3717       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3718       for (unsigned i = 0; i != MaskNumElts; ++i) {
3719         int Idx = Mask[i];
3720         if (Idx < 0)
3721           continue;
3722         // Ensure the indices in each SrcVT sized piece are sequential and that
3723         // the same source is used for the whole piece.
3724         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3725             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3726              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3727           IsConcat = false;
3728           break;
3729         }
3730         // Remember which source this index came from.
3731         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3732       }
3733 
3734       // The shuffle is concatenating multiple vectors together. Just emit
3735       // a CONCAT_VECTORS operation.
3736       if (IsConcat) {
3737         SmallVector<SDValue, 8> ConcatOps;
3738         for (auto Src : ConcatSrcs) {
3739           if (Src < 0)
3740             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3741           else if (Src == 0)
3742             ConcatOps.push_back(Src1);
3743           else
3744             ConcatOps.push_back(Src2);
3745         }
3746         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3747         return;
3748       }
3749     }
3750 
3751     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3752     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3753     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3754                                     PaddedMaskNumElts);
3755 
3756     // Pad both vectors with undefs to make them the same length as the mask.
3757     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3758 
3759     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3760     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3761     MOps1[0] = Src1;
3762     MOps2[0] = Src2;
3763 
3764     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3765     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3766 
3767     // Readjust mask for new input vector length.
3768     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3769     for (unsigned i = 0; i != MaskNumElts; ++i) {
3770       int Idx = Mask[i];
3771       if (Idx >= (int)SrcNumElts)
3772         Idx -= SrcNumElts - PaddedMaskNumElts;
3773       MappedOps[i] = Idx;
3774     }
3775 
3776     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3777 
3778     // If the concatenated vector was padded, extract a subvector with the
3779     // correct number of elements.
3780     if (MaskNumElts != PaddedMaskNumElts)
3781       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3782                            DAG.getVectorIdxConstant(0, DL));
3783 
3784     setValue(&I, Result);
3785     return;
3786   }
3787 
3788   if (SrcNumElts > MaskNumElts) {
3789     // Analyze the access pattern of the vector to see if we can extract
3790     // two subvectors and do the shuffle.
3791     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3792     bool CanExtract = true;
3793     for (int Idx : Mask) {
3794       unsigned Input = 0;
3795       if (Idx < 0)
3796         continue;
3797 
3798       if (Idx >= (int)SrcNumElts) {
3799         Input = 1;
3800         Idx -= SrcNumElts;
3801       }
3802 
3803       // If all the indices come from the same MaskNumElts sized portion of
3804       // the sources we can use extract. Also make sure the extract wouldn't
3805       // extract past the end of the source.
3806       int NewStartIdx = alignDown(Idx, MaskNumElts);
3807       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3808           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3809         CanExtract = false;
3810       // Make sure we always update StartIdx as we use it to track if all
3811       // elements are undef.
3812       StartIdx[Input] = NewStartIdx;
3813     }
3814 
3815     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3816       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3817       return;
3818     }
3819     if (CanExtract) {
3820       // Extract appropriate subvector and generate a vector shuffle
3821       for (unsigned Input = 0; Input < 2; ++Input) {
3822         SDValue &Src = Input == 0 ? Src1 : Src2;
3823         if (StartIdx[Input] < 0)
3824           Src = DAG.getUNDEF(VT);
3825         else {
3826           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3827                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3828         }
3829       }
3830 
3831       // Calculate new mask.
3832       SmallVector<int, 8> MappedOps(Mask);
3833       for (int &Idx : MappedOps) {
3834         if (Idx >= (int)SrcNumElts)
3835           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3836         else if (Idx >= 0)
3837           Idx -= StartIdx[0];
3838       }
3839 
3840       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3841       return;
3842     }
3843   }
3844 
3845   // We can't use either concat vectors or extract subvectors so fall back to
3846   // replacing the shuffle with extract and build vector.
3847   // to insert and build vector.
3848   EVT EltVT = VT.getVectorElementType();
3849   SmallVector<SDValue,8> Ops;
3850   for (int Idx : Mask) {
3851     SDValue Res;
3852 
3853     if (Idx < 0) {
3854       Res = DAG.getUNDEF(EltVT);
3855     } else {
3856       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3857       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3858 
3859       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3860                         DAG.getVectorIdxConstant(Idx, DL));
3861     }
3862 
3863     Ops.push_back(Res);
3864   }
3865 
3866   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3867 }
3868 
3869 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3870   ArrayRef<unsigned> Indices = I.getIndices();
3871   const Value *Op0 = I.getOperand(0);
3872   const Value *Op1 = I.getOperand(1);
3873   Type *AggTy = I.getType();
3874   Type *ValTy = Op1->getType();
3875   bool IntoUndef = isa<UndefValue>(Op0);
3876   bool FromUndef = isa<UndefValue>(Op1);
3877 
3878   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3879 
3880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3881   SmallVector<EVT, 4> AggValueVTs;
3882   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3883   SmallVector<EVT, 4> ValValueVTs;
3884   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3885 
3886   unsigned NumAggValues = AggValueVTs.size();
3887   unsigned NumValValues = ValValueVTs.size();
3888   SmallVector<SDValue, 4> Values(NumAggValues);
3889 
3890   // Ignore an insertvalue that produces an empty object
3891   if (!NumAggValues) {
3892     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3893     return;
3894   }
3895 
3896   SDValue Agg = getValue(Op0);
3897   unsigned i = 0;
3898   // Copy the beginning value(s) from the original aggregate.
3899   for (; i != LinearIndex; ++i)
3900     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3901                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3902   // Copy values from the inserted value(s).
3903   if (NumValValues) {
3904     SDValue Val = getValue(Op1);
3905     for (; i != LinearIndex + NumValValues; ++i)
3906       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3907                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3908   }
3909   // Copy remaining value(s) from the original aggregate.
3910   for (; i != NumAggValues; ++i)
3911     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3912                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3913 
3914   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3915                            DAG.getVTList(AggValueVTs), Values));
3916 }
3917 
3918 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3919   ArrayRef<unsigned> Indices = I.getIndices();
3920   const Value *Op0 = I.getOperand(0);
3921   Type *AggTy = Op0->getType();
3922   Type *ValTy = I.getType();
3923   bool OutOfUndef = isa<UndefValue>(Op0);
3924 
3925   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3926 
3927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3928   SmallVector<EVT, 4> ValValueVTs;
3929   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3930 
3931   unsigned NumValValues = ValValueVTs.size();
3932 
3933   // Ignore a extractvalue that produces an empty object
3934   if (!NumValValues) {
3935     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3936     return;
3937   }
3938 
3939   SmallVector<SDValue, 4> Values(NumValValues);
3940 
3941   SDValue Agg = getValue(Op0);
3942   // Copy out the selected value(s).
3943   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3944     Values[i - LinearIndex] =
3945       OutOfUndef ?
3946         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3947         SDValue(Agg.getNode(), Agg.getResNo() + i);
3948 
3949   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3950                            DAG.getVTList(ValValueVTs), Values));
3951 }
3952 
3953 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3954   Value *Op0 = I.getOperand(0);
3955   // Note that the pointer operand may be a vector of pointers. Take the scalar
3956   // element which holds a pointer.
3957   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3958   SDValue N = getValue(Op0);
3959   SDLoc dl = getCurSDLoc();
3960   auto &TLI = DAG.getTargetLoweringInfo();
3961 
3962   // Normalize Vector GEP - all scalar operands should be converted to the
3963   // splat vector.
3964   bool IsVectorGEP = I.getType()->isVectorTy();
3965   ElementCount VectorElementCount =
3966       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3967                   : ElementCount::getFixed(0);
3968 
3969   if (IsVectorGEP && !N.getValueType().isVector()) {
3970     LLVMContext &Context = *DAG.getContext();
3971     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3972     N = DAG.getSplat(VT, dl, N);
3973   }
3974 
3975   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3976        GTI != E; ++GTI) {
3977     const Value *Idx = GTI.getOperand();
3978     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3979       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3980       if (Field) {
3981         // N = N + Offset
3982         uint64_t Offset =
3983             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3984 
3985         // In an inbounds GEP with an offset that is nonnegative even when
3986         // interpreted as signed, assume there is no unsigned overflow.
3987         SDNodeFlags Flags;
3988         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3989           Flags.setNoUnsignedWrap(true);
3990 
3991         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3992                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3993       }
3994     } else {
3995       // IdxSize is the width of the arithmetic according to IR semantics.
3996       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3997       // (and fix up the result later).
3998       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3999       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4000       TypeSize ElementSize =
4001           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
4002       // We intentionally mask away the high bits here; ElementSize may not
4003       // fit in IdxTy.
4004       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4005       bool ElementScalable = ElementSize.isScalable();
4006 
4007       // If this is a scalar constant or a splat vector of constants,
4008       // handle it quickly.
4009       const auto *C = dyn_cast<Constant>(Idx);
4010       if (C && isa<VectorType>(C->getType()))
4011         C = C->getSplatValue();
4012 
4013       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4014       if (CI && CI->isZero())
4015         continue;
4016       if (CI && !ElementScalable) {
4017         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4018         LLVMContext &Context = *DAG.getContext();
4019         SDValue OffsVal;
4020         if (IsVectorGEP)
4021           OffsVal = DAG.getConstant(
4022               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4023         else
4024           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4025 
4026         // In an inbounds GEP with an offset that is nonnegative even when
4027         // interpreted as signed, assume there is no unsigned overflow.
4028         SDNodeFlags Flags;
4029         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4030           Flags.setNoUnsignedWrap(true);
4031 
4032         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4033 
4034         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4035         continue;
4036       }
4037 
4038       // N = N + Idx * ElementMul;
4039       SDValue IdxN = getValue(Idx);
4040 
4041       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4042         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4043                                   VectorElementCount);
4044         IdxN = DAG.getSplat(VT, dl, IdxN);
4045       }
4046 
4047       // If the index is smaller or larger than intptr_t, truncate or extend
4048       // it.
4049       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4050 
4051       if (ElementScalable) {
4052         EVT VScaleTy = N.getValueType().getScalarType();
4053         SDValue VScale = DAG.getNode(
4054             ISD::VSCALE, dl, VScaleTy,
4055             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4056         if (IsVectorGEP)
4057           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4058         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4059       } else {
4060         // If this is a multiply by a power of two, turn it into a shl
4061         // immediately.  This is a very common case.
4062         if (ElementMul != 1) {
4063           if (ElementMul.isPowerOf2()) {
4064             unsigned Amt = ElementMul.logBase2();
4065             IdxN = DAG.getNode(ISD::SHL, dl,
4066                                N.getValueType(), IdxN,
4067                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4068           } else {
4069             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4070                                             IdxN.getValueType());
4071             IdxN = DAG.getNode(ISD::MUL, dl,
4072                                N.getValueType(), IdxN, Scale);
4073           }
4074         }
4075       }
4076 
4077       N = DAG.getNode(ISD::ADD, dl,
4078                       N.getValueType(), N, IdxN);
4079     }
4080   }
4081 
4082   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4083   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4084   if (IsVectorGEP) {
4085     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4086     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4087   }
4088 
4089   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4090     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4091 
4092   setValue(&I, N);
4093 }
4094 
4095 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4096   // If this is a fixed sized alloca in the entry block of the function,
4097   // allocate it statically on the stack.
4098   if (FuncInfo.StaticAllocaMap.count(&I))
4099     return;   // getValue will auto-populate this.
4100 
4101   SDLoc dl = getCurSDLoc();
4102   Type *Ty = I.getAllocatedType();
4103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4104   auto &DL = DAG.getDataLayout();
4105   TypeSize TySize = DL.getTypeAllocSize(Ty);
4106   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4107 
4108   SDValue AllocSize = getValue(I.getArraySize());
4109 
4110   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4111   if (AllocSize.getValueType() != IntPtr)
4112     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4113 
4114   if (TySize.isScalable())
4115     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4116                             DAG.getVScale(dl, IntPtr,
4117                                           APInt(IntPtr.getScalarSizeInBits(),
4118                                                 TySize.getKnownMinValue())));
4119   else
4120     AllocSize =
4121         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4122                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4123 
4124   // Handle alignment.  If the requested alignment is less than or equal to
4125   // the stack alignment, ignore it.  If the size is greater than or equal to
4126   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4127   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4128   if (*Alignment <= StackAlign)
4129     Alignment = std::nullopt;
4130 
4131   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4132   // Round the size of the allocation up to the stack alignment size
4133   // by add SA-1 to the size. This doesn't overflow because we're computing
4134   // an address inside an alloca.
4135   SDNodeFlags Flags;
4136   Flags.setNoUnsignedWrap(true);
4137   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4138                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4139 
4140   // Mask out the low bits for alignment purposes.
4141   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4142                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4143 
4144   SDValue Ops[] = {
4145       getRoot(), AllocSize,
4146       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4147   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4148   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4149   setValue(&I, DSA);
4150   DAG.setRoot(DSA.getValue(1));
4151 
4152   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4153 }
4154 
4155 static const MDNode *getRangeMetadata(const Instruction &I) {
4156   // If !noundef is not present, then !range violation results in a poison
4157   // value rather than immediate undefined behavior. In theory, transferring
4158   // these annotations to SDAG is fine, but in practice there are key SDAG
4159   // transforms that are known not to be poison-safe, such as folding logical
4160   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4161   // also present.
4162   if (!I.hasMetadata(LLVMContext::MD_noundef))
4163     return nullptr;
4164   return I.getMetadata(LLVMContext::MD_range);
4165 }
4166 
4167 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4168   if (I.isAtomic())
4169     return visitAtomicLoad(I);
4170 
4171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172   const Value *SV = I.getOperand(0);
4173   if (TLI.supportSwiftError()) {
4174     // Swifterror values can come from either a function parameter with
4175     // swifterror attribute or an alloca with swifterror attribute.
4176     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4177       if (Arg->hasSwiftErrorAttr())
4178         return visitLoadFromSwiftError(I);
4179     }
4180 
4181     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4182       if (Alloca->isSwiftError())
4183         return visitLoadFromSwiftError(I);
4184     }
4185   }
4186 
4187   SDValue Ptr = getValue(SV);
4188 
4189   Type *Ty = I.getType();
4190   SmallVector<EVT, 4> ValueVTs, MemVTs;
4191   SmallVector<TypeSize, 4> Offsets;
4192   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0);
4193   unsigned NumValues = ValueVTs.size();
4194   if (NumValues == 0)
4195     return;
4196 
4197   Align Alignment = I.getAlign();
4198   AAMDNodes AAInfo = I.getAAMetadata();
4199   const MDNode *Ranges = getRangeMetadata(I);
4200   bool isVolatile = I.isVolatile();
4201   MachineMemOperand::Flags MMOFlags =
4202       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4203 
4204   SDValue Root;
4205   bool ConstantMemory = false;
4206   if (isVolatile)
4207     // Serialize volatile loads with other side effects.
4208     Root = getRoot();
4209   else if (NumValues > MaxParallelChains)
4210     Root = getMemoryRoot();
4211   else if (AA &&
4212            AA->pointsToConstantMemory(MemoryLocation(
4213                SV,
4214                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4215                AAInfo))) {
4216     // Do not serialize (non-volatile) loads of constant memory with anything.
4217     Root = DAG.getEntryNode();
4218     ConstantMemory = true;
4219     MMOFlags |= MachineMemOperand::MOInvariant;
4220   } else {
4221     // Do not serialize non-volatile loads against each other.
4222     Root = DAG.getRoot();
4223   }
4224 
4225   SDLoc dl = getCurSDLoc();
4226 
4227   if (isVolatile)
4228     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4229 
4230   SmallVector<SDValue, 4> Values(NumValues);
4231   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4232 
4233   unsigned ChainI = 0;
4234   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4235     // Serializing loads here may result in excessive register pressure, and
4236     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4237     // could recover a bit by hoisting nodes upward in the chain by recognizing
4238     // they are side-effect free or do not alias. The optimizer should really
4239     // avoid this case by converting large object/array copies to llvm.memcpy
4240     // (MaxParallelChains should always remain as failsafe).
4241     if (ChainI == MaxParallelChains) {
4242       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4243       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4244                                   ArrayRef(Chains.data(), ChainI));
4245       Root = Chain;
4246       ChainI = 0;
4247     }
4248 
4249     // TODO: MachinePointerInfo only supports a fixed length offset.
4250     MachinePointerInfo PtrInfo =
4251         !Offsets[i].isScalable() || Offsets[i].isZero()
4252             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4253             : MachinePointerInfo();
4254 
4255     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4256     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4257                             MMOFlags, AAInfo, Ranges);
4258     Chains[ChainI] = L.getValue(1);
4259 
4260     if (MemVTs[i] != ValueVTs[i])
4261       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4262 
4263     Values[i] = L;
4264   }
4265 
4266   if (!ConstantMemory) {
4267     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4268                                 ArrayRef(Chains.data(), ChainI));
4269     if (isVolatile)
4270       DAG.setRoot(Chain);
4271     else
4272       PendingLoads.push_back(Chain);
4273   }
4274 
4275   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4276                            DAG.getVTList(ValueVTs), Values));
4277 }
4278 
4279 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4280   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4281          "call visitStoreToSwiftError when backend supports swifterror");
4282 
4283   SmallVector<EVT, 4> ValueVTs;
4284   SmallVector<uint64_t, 4> Offsets;
4285   const Value *SrcV = I.getOperand(0);
4286   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4287                   SrcV->getType(), ValueVTs, &Offsets, 0);
4288   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4289          "expect a single EVT for swifterror");
4290 
4291   SDValue Src = getValue(SrcV);
4292   // Create a virtual register, then update the virtual register.
4293   Register VReg =
4294       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4295   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4296   // Chain can be getRoot or getControlRoot.
4297   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4298                                       SDValue(Src.getNode(), Src.getResNo()));
4299   DAG.setRoot(CopyNode);
4300 }
4301 
4302 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4303   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4304          "call visitLoadFromSwiftError when backend supports swifterror");
4305 
4306   assert(!I.isVolatile() &&
4307          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4308          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4309          "Support volatile, non temporal, invariant for load_from_swift_error");
4310 
4311   const Value *SV = I.getOperand(0);
4312   Type *Ty = I.getType();
4313   assert(
4314       (!AA ||
4315        !AA->pointsToConstantMemory(MemoryLocation(
4316            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4317            I.getAAMetadata()))) &&
4318       "load_from_swift_error should not be constant memory");
4319 
4320   SmallVector<EVT, 4> ValueVTs;
4321   SmallVector<uint64_t, 4> Offsets;
4322   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4323                   ValueVTs, &Offsets, 0);
4324   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4325          "expect a single EVT for swifterror");
4326 
4327   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4328   SDValue L = DAG.getCopyFromReg(
4329       getRoot(), getCurSDLoc(),
4330       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4331 
4332   setValue(&I, L);
4333 }
4334 
4335 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4336   if (I.isAtomic())
4337     return visitAtomicStore(I);
4338 
4339   const Value *SrcV = I.getOperand(0);
4340   const Value *PtrV = I.getOperand(1);
4341 
4342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4343   if (TLI.supportSwiftError()) {
4344     // Swifterror values can come from either a function parameter with
4345     // swifterror attribute or an alloca with swifterror attribute.
4346     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4347       if (Arg->hasSwiftErrorAttr())
4348         return visitStoreToSwiftError(I);
4349     }
4350 
4351     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4352       if (Alloca->isSwiftError())
4353         return visitStoreToSwiftError(I);
4354     }
4355   }
4356 
4357   SmallVector<EVT, 4> ValueVTs, MemVTs;
4358   SmallVector<TypeSize, 4> Offsets;
4359   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4360                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0);
4361   unsigned NumValues = ValueVTs.size();
4362   if (NumValues == 0)
4363     return;
4364 
4365   // Get the lowered operands. Note that we do this after
4366   // checking if NumResults is zero, because with zero results
4367   // the operands won't have values in the map.
4368   SDValue Src = getValue(SrcV);
4369   SDValue Ptr = getValue(PtrV);
4370 
4371   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4372   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4373   SDLoc dl = getCurSDLoc();
4374   Align Alignment = I.getAlign();
4375   AAMDNodes AAInfo = I.getAAMetadata();
4376 
4377   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4378 
4379   unsigned ChainI = 0;
4380   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4381     // See visitLoad comments.
4382     if (ChainI == MaxParallelChains) {
4383       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4384                                   ArrayRef(Chains.data(), ChainI));
4385       Root = Chain;
4386       ChainI = 0;
4387     }
4388 
4389     // TODO: MachinePointerInfo only supports a fixed length offset.
4390     MachinePointerInfo PtrInfo =
4391         !Offsets[i].isScalable() || Offsets[i].isZero()
4392             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4393             : MachinePointerInfo();
4394 
4395     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4396     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4397     if (MemVTs[i] != ValueVTs[i])
4398       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4399     SDValue St =
4400         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4401     Chains[ChainI] = St;
4402   }
4403 
4404   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4405                                   ArrayRef(Chains.data(), ChainI));
4406   setValue(&I, StoreNode);
4407   DAG.setRoot(StoreNode);
4408 }
4409 
4410 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4411                                            bool IsCompressing) {
4412   SDLoc sdl = getCurSDLoc();
4413 
4414   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4415                                MaybeAlign &Alignment) {
4416     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4417     Src0 = I.getArgOperand(0);
4418     Ptr = I.getArgOperand(1);
4419     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4420     Mask = I.getArgOperand(3);
4421   };
4422   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4423                                     MaybeAlign &Alignment) {
4424     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4425     Src0 = I.getArgOperand(0);
4426     Ptr = I.getArgOperand(1);
4427     Mask = I.getArgOperand(2);
4428     Alignment = std::nullopt;
4429   };
4430 
4431   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4432   MaybeAlign Alignment;
4433   if (IsCompressing)
4434     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4435   else
4436     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4437 
4438   SDValue Ptr = getValue(PtrOperand);
4439   SDValue Src0 = getValue(Src0Operand);
4440   SDValue Mask = getValue(MaskOperand);
4441   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4442 
4443   EVT VT = Src0.getValueType();
4444   if (!Alignment)
4445     Alignment = DAG.getEVTAlign(VT);
4446 
4447   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4448       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4449       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4450   SDValue StoreNode =
4451       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4452                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4453   DAG.setRoot(StoreNode);
4454   setValue(&I, StoreNode);
4455 }
4456 
4457 // Get a uniform base for the Gather/Scatter intrinsic.
4458 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4459 // We try to represent it as a base pointer + vector of indices.
4460 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4461 // The first operand of the GEP may be a single pointer or a vector of pointers
4462 // Example:
4463 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4464 //  or
4465 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4466 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4467 //
4468 // When the first GEP operand is a single pointer - it is the uniform base we
4469 // are looking for. If first operand of the GEP is a splat vector - we
4470 // extract the splat value and use it as a uniform base.
4471 // In all other cases the function returns 'false'.
4472 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4473                            ISD::MemIndexType &IndexType, SDValue &Scale,
4474                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4475                            uint64_t ElemSize) {
4476   SelectionDAG& DAG = SDB->DAG;
4477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4478   const DataLayout &DL = DAG.getDataLayout();
4479 
4480   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4481 
4482   // Handle splat constant pointer.
4483   if (auto *C = dyn_cast<Constant>(Ptr)) {
4484     C = C->getSplatValue();
4485     if (!C)
4486       return false;
4487 
4488     Base = SDB->getValue(C);
4489 
4490     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4491     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4492     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4493     IndexType = ISD::SIGNED_SCALED;
4494     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4495     return true;
4496   }
4497 
4498   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4499   if (!GEP || GEP->getParent() != CurBB)
4500     return false;
4501 
4502   if (GEP->getNumOperands() != 2)
4503     return false;
4504 
4505   const Value *BasePtr = GEP->getPointerOperand();
4506   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4507 
4508   // Make sure the base is scalar and the index is a vector.
4509   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4510     return false;
4511 
4512   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4513   if (ScaleVal.isScalable())
4514     return false;
4515 
4516   // Target may not support the required addressing mode.
4517   if (ScaleVal != 1 &&
4518       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4519     return false;
4520 
4521   Base = SDB->getValue(BasePtr);
4522   Index = SDB->getValue(IndexVal);
4523   IndexType = ISD::SIGNED_SCALED;
4524 
4525   Scale =
4526       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4527   return true;
4528 }
4529 
4530 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4531   SDLoc sdl = getCurSDLoc();
4532 
4533   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4534   const Value *Ptr = I.getArgOperand(1);
4535   SDValue Src0 = getValue(I.getArgOperand(0));
4536   SDValue Mask = getValue(I.getArgOperand(3));
4537   EVT VT = Src0.getValueType();
4538   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4539                         ->getMaybeAlignValue()
4540                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4542 
4543   SDValue Base;
4544   SDValue Index;
4545   ISD::MemIndexType IndexType;
4546   SDValue Scale;
4547   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4548                                     I.getParent(), VT.getScalarStoreSize());
4549 
4550   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4551   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4552       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4553       // TODO: Make MachineMemOperands aware of scalable
4554       // vectors.
4555       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4556   if (!UniformBase) {
4557     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4558     Index = getValue(Ptr);
4559     IndexType = ISD::SIGNED_SCALED;
4560     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4561   }
4562 
4563   EVT IdxVT = Index.getValueType();
4564   EVT EltTy = IdxVT.getVectorElementType();
4565   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4566     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4567     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4568   }
4569 
4570   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4571   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4572                                          Ops, MMO, IndexType, false);
4573   DAG.setRoot(Scatter);
4574   setValue(&I, Scatter);
4575 }
4576 
4577 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4578   SDLoc sdl = getCurSDLoc();
4579 
4580   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4581                               MaybeAlign &Alignment) {
4582     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4583     Ptr = I.getArgOperand(0);
4584     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4585     Mask = I.getArgOperand(2);
4586     Src0 = I.getArgOperand(3);
4587   };
4588   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4589                                  MaybeAlign &Alignment) {
4590     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4591     Ptr = I.getArgOperand(0);
4592     Alignment = std::nullopt;
4593     Mask = I.getArgOperand(1);
4594     Src0 = I.getArgOperand(2);
4595   };
4596 
4597   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4598   MaybeAlign Alignment;
4599   if (IsExpanding)
4600     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4601   else
4602     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4603 
4604   SDValue Ptr = getValue(PtrOperand);
4605   SDValue Src0 = getValue(Src0Operand);
4606   SDValue Mask = getValue(MaskOperand);
4607   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4608 
4609   EVT VT = Src0.getValueType();
4610   if (!Alignment)
4611     Alignment = DAG.getEVTAlign(VT);
4612 
4613   AAMDNodes AAInfo = I.getAAMetadata();
4614   const MDNode *Ranges = getRangeMetadata(I);
4615 
4616   // Do not serialize masked loads of constant memory with anything.
4617   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4618   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4619 
4620   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4621 
4622   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4623       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4624       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4625 
4626   SDValue Load =
4627       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4628                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4629   if (AddToChain)
4630     PendingLoads.push_back(Load.getValue(1));
4631   setValue(&I, Load);
4632 }
4633 
4634 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4635   SDLoc sdl = getCurSDLoc();
4636 
4637   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4638   const Value *Ptr = I.getArgOperand(0);
4639   SDValue Src0 = getValue(I.getArgOperand(3));
4640   SDValue Mask = getValue(I.getArgOperand(2));
4641 
4642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4643   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4644   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4645                         ->getMaybeAlignValue()
4646                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4647 
4648   const MDNode *Ranges = getRangeMetadata(I);
4649 
4650   SDValue Root = DAG.getRoot();
4651   SDValue Base;
4652   SDValue Index;
4653   ISD::MemIndexType IndexType;
4654   SDValue Scale;
4655   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4656                                     I.getParent(), VT.getScalarStoreSize());
4657   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4658   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4659       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4660       // TODO: Make MachineMemOperands aware of scalable
4661       // vectors.
4662       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4663 
4664   if (!UniformBase) {
4665     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4666     Index = getValue(Ptr);
4667     IndexType = ISD::SIGNED_SCALED;
4668     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4669   }
4670 
4671   EVT IdxVT = Index.getValueType();
4672   EVT EltTy = IdxVT.getVectorElementType();
4673   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4674     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4675     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4676   }
4677 
4678   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4679   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4680                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4681 
4682   PendingLoads.push_back(Gather.getValue(1));
4683   setValue(&I, Gather);
4684 }
4685 
4686 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4687   SDLoc dl = getCurSDLoc();
4688   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4689   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4690   SyncScope::ID SSID = I.getSyncScopeID();
4691 
4692   SDValue InChain = getRoot();
4693 
4694   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4695   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4696 
4697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4698   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4699 
4700   MachineFunction &MF = DAG.getMachineFunction();
4701   MachineMemOperand *MMO = MF.getMachineMemOperand(
4702       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4703       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4704       FailureOrdering);
4705 
4706   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4707                                    dl, MemVT, VTs, InChain,
4708                                    getValue(I.getPointerOperand()),
4709                                    getValue(I.getCompareOperand()),
4710                                    getValue(I.getNewValOperand()), MMO);
4711 
4712   SDValue OutChain = L.getValue(2);
4713 
4714   setValue(&I, L);
4715   DAG.setRoot(OutChain);
4716 }
4717 
4718 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4719   SDLoc dl = getCurSDLoc();
4720   ISD::NodeType NT;
4721   switch (I.getOperation()) {
4722   default: llvm_unreachable("Unknown atomicrmw operation");
4723   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4724   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4725   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4726   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4727   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4728   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4729   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4730   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4731   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4732   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4733   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4734   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4735   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4736   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4737   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4738   case AtomicRMWInst::UIncWrap:
4739     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4740     break;
4741   case AtomicRMWInst::UDecWrap:
4742     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4743     break;
4744   }
4745   AtomicOrdering Ordering = I.getOrdering();
4746   SyncScope::ID SSID = I.getSyncScopeID();
4747 
4748   SDValue InChain = getRoot();
4749 
4750   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4752   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4753 
4754   MachineFunction &MF = DAG.getMachineFunction();
4755   MachineMemOperand *MMO = MF.getMachineMemOperand(
4756       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4757       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4758 
4759   SDValue L =
4760     DAG.getAtomic(NT, dl, MemVT, InChain,
4761                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4762                   MMO);
4763 
4764   SDValue OutChain = L.getValue(1);
4765 
4766   setValue(&I, L);
4767   DAG.setRoot(OutChain);
4768 }
4769 
4770 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4771   SDLoc dl = getCurSDLoc();
4772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4773   SDValue Ops[3];
4774   Ops[0] = getRoot();
4775   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4776                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4777   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4778                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4779   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4780   setValue(&I, N);
4781   DAG.setRoot(N);
4782 }
4783 
4784 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4785   SDLoc dl = getCurSDLoc();
4786   AtomicOrdering Order = I.getOrdering();
4787   SyncScope::ID SSID = I.getSyncScopeID();
4788 
4789   SDValue InChain = getRoot();
4790 
4791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4792   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4793   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4794 
4795   if (!TLI.supportsUnalignedAtomics() &&
4796       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4797     report_fatal_error("Cannot generate unaligned atomic load");
4798 
4799   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4800 
4801   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4802       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4803       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4804 
4805   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4806 
4807   SDValue Ptr = getValue(I.getPointerOperand());
4808 
4809   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4810     // TODO: Once this is better exercised by tests, it should be merged with
4811     // the normal path for loads to prevent future divergence.
4812     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4813     if (MemVT != VT)
4814       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4815 
4816     setValue(&I, L);
4817     SDValue OutChain = L.getValue(1);
4818     if (!I.isUnordered())
4819       DAG.setRoot(OutChain);
4820     else
4821       PendingLoads.push_back(OutChain);
4822     return;
4823   }
4824 
4825   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4826                             Ptr, MMO);
4827 
4828   SDValue OutChain = L.getValue(1);
4829   if (MemVT != VT)
4830     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4831 
4832   setValue(&I, L);
4833   DAG.setRoot(OutChain);
4834 }
4835 
4836 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4837   SDLoc dl = getCurSDLoc();
4838 
4839   AtomicOrdering Ordering = I.getOrdering();
4840   SyncScope::ID SSID = I.getSyncScopeID();
4841 
4842   SDValue InChain = getRoot();
4843 
4844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4845   EVT MemVT =
4846       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4847 
4848   if (!TLI.supportsUnalignedAtomics() &&
4849       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4850     report_fatal_error("Cannot generate unaligned atomic store");
4851 
4852   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4853 
4854   MachineFunction &MF = DAG.getMachineFunction();
4855   MachineMemOperand *MMO = MF.getMachineMemOperand(
4856       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4857       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4858 
4859   SDValue Val = getValue(I.getValueOperand());
4860   if (Val.getValueType() != MemVT)
4861     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4862   SDValue Ptr = getValue(I.getPointerOperand());
4863 
4864   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4865     // TODO: Once this is better exercised by tests, it should be merged with
4866     // the normal path for stores to prevent future divergence.
4867     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4868     setValue(&I, S);
4869     DAG.setRoot(S);
4870     return;
4871   }
4872   SDValue OutChain =
4873       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
4874 
4875   setValue(&I, OutChain);
4876   DAG.setRoot(OutChain);
4877 }
4878 
4879 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4880 /// node.
4881 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4882                                                unsigned Intrinsic) {
4883   // Ignore the callsite's attributes. A specific call site may be marked with
4884   // readnone, but the lowering code will expect the chain based on the
4885   // definition.
4886   const Function *F = I.getCalledFunction();
4887   bool HasChain = !F->doesNotAccessMemory();
4888   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4889 
4890   // Build the operand list.
4891   SmallVector<SDValue, 8> Ops;
4892   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4893     if (OnlyLoad) {
4894       // We don't need to serialize loads against other loads.
4895       Ops.push_back(DAG.getRoot());
4896     } else {
4897       Ops.push_back(getRoot());
4898     }
4899   }
4900 
4901   // Info is set by getTgtMemIntrinsic
4902   TargetLowering::IntrinsicInfo Info;
4903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4904   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4905                                                DAG.getMachineFunction(),
4906                                                Intrinsic);
4907 
4908   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4909   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4910       Info.opc == ISD::INTRINSIC_W_CHAIN)
4911     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4912                                         TLI.getPointerTy(DAG.getDataLayout())));
4913 
4914   // Add all operands of the call to the operand list.
4915   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4916     const Value *Arg = I.getArgOperand(i);
4917     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4918       Ops.push_back(getValue(Arg));
4919       continue;
4920     }
4921 
4922     // Use TargetConstant instead of a regular constant for immarg.
4923     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4924     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4925       assert(CI->getBitWidth() <= 64 &&
4926              "large intrinsic immediates not handled");
4927       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4928     } else {
4929       Ops.push_back(
4930           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4931     }
4932   }
4933 
4934   SmallVector<EVT, 4> ValueVTs;
4935   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4936 
4937   if (HasChain)
4938     ValueVTs.push_back(MVT::Other);
4939 
4940   SDVTList VTs = DAG.getVTList(ValueVTs);
4941 
4942   // Propagate fast-math-flags from IR to node(s).
4943   SDNodeFlags Flags;
4944   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4945     Flags.copyFMF(*FPMO);
4946   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4947 
4948   // Create the node.
4949   SDValue Result;
4950   // In some cases, custom collection of operands from CallInst I may be needed.
4951   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4952   if (IsTgtIntrinsic) {
4953     // This is target intrinsic that touches memory
4954     //
4955     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4956     //       didn't yield anything useful.
4957     MachinePointerInfo MPI;
4958     if (Info.ptrVal)
4959       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4960     else if (Info.fallbackAddressSpace)
4961       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4962     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4963                                      Info.memVT, MPI, Info.align, Info.flags,
4964                                      Info.size, I.getAAMetadata());
4965   } else if (!HasChain) {
4966     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4967   } else if (!I.getType()->isVoidTy()) {
4968     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4969   } else {
4970     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4971   }
4972 
4973   if (HasChain) {
4974     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4975     if (OnlyLoad)
4976       PendingLoads.push_back(Chain);
4977     else
4978       DAG.setRoot(Chain);
4979   }
4980 
4981   if (!I.getType()->isVoidTy()) {
4982     if (!isa<VectorType>(I.getType()))
4983       Result = lowerRangeToAssertZExt(DAG, I, Result);
4984 
4985     MaybeAlign Alignment = I.getRetAlign();
4986 
4987     // Insert `assertalign` node if there's an alignment.
4988     if (InsertAssertAlign && Alignment) {
4989       Result =
4990           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4991     }
4992 
4993     setValue(&I, Result);
4994   }
4995 }
4996 
4997 /// GetSignificand - Get the significand and build it into a floating-point
4998 /// number with exponent of 1:
4999 ///
5000 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5001 ///
5002 /// where Op is the hexadecimal representation of floating point value.
5003 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5004   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5005                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5006   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5007                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5008   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5009 }
5010 
5011 /// GetExponent - Get the exponent:
5012 ///
5013 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5014 ///
5015 /// where Op is the hexadecimal representation of floating point value.
5016 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5017                            const TargetLowering &TLI, const SDLoc &dl) {
5018   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5019                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5020   SDValue t1 = DAG.getNode(
5021       ISD::SRL, dl, MVT::i32, t0,
5022       DAG.getConstant(23, dl,
5023                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5024   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5025                            DAG.getConstant(127, dl, MVT::i32));
5026   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5027 }
5028 
5029 /// getF32Constant - Get 32-bit floating point constant.
5030 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5031                               const SDLoc &dl) {
5032   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5033                            MVT::f32);
5034 }
5035 
5036 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5037                                        SelectionDAG &DAG) {
5038   // TODO: What fast-math-flags should be set on the floating-point nodes?
5039 
5040   //   IntegerPartOfX = ((int32_t)(t0);
5041   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5042 
5043   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5044   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5045   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5046 
5047   //   IntegerPartOfX <<= 23;
5048   IntegerPartOfX =
5049       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5050                   DAG.getConstant(23, dl,
5051                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5052                                       MVT::i32, DAG.getDataLayout())));
5053 
5054   SDValue TwoToFractionalPartOfX;
5055   if (LimitFloatPrecision <= 6) {
5056     // For floating-point precision of 6:
5057     //
5058     //   TwoToFractionalPartOfX =
5059     //     0.997535578f +
5060     //       (0.735607626f + 0.252464424f * x) * x;
5061     //
5062     // error 0.0144103317, which is 6 bits
5063     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5064                              getF32Constant(DAG, 0x3e814304, dl));
5065     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5066                              getF32Constant(DAG, 0x3f3c50c8, dl));
5067     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5068     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5069                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5070   } else if (LimitFloatPrecision <= 12) {
5071     // For floating-point precision of 12:
5072     //
5073     //   TwoToFractionalPartOfX =
5074     //     0.999892986f +
5075     //       (0.696457318f +
5076     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5077     //
5078     // error 0.000107046256, which is 13 to 14 bits
5079     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5080                              getF32Constant(DAG, 0x3da235e3, dl));
5081     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5082                              getF32Constant(DAG, 0x3e65b8f3, dl));
5083     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5084     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5085                              getF32Constant(DAG, 0x3f324b07, dl));
5086     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5087     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5088                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5089   } else { // LimitFloatPrecision <= 18
5090     // For floating-point precision of 18:
5091     //
5092     //   TwoToFractionalPartOfX =
5093     //     0.999999982f +
5094     //       (0.693148872f +
5095     //         (0.240227044f +
5096     //           (0.554906021e-1f +
5097     //             (0.961591928e-2f +
5098     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5099     // error 2.47208000*10^(-7), which is better than 18 bits
5100     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5101                              getF32Constant(DAG, 0x3924b03e, dl));
5102     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5103                              getF32Constant(DAG, 0x3ab24b87, dl));
5104     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5105     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5106                              getF32Constant(DAG, 0x3c1d8c17, dl));
5107     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5108     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5109                              getF32Constant(DAG, 0x3d634a1d, dl));
5110     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5111     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5112                              getF32Constant(DAG, 0x3e75fe14, dl));
5113     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5114     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5115                               getF32Constant(DAG, 0x3f317234, dl));
5116     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5117     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5118                                          getF32Constant(DAG, 0x3f800000, dl));
5119   }
5120 
5121   // Add the exponent into the result in integer domain.
5122   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5123   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5124                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5125 }
5126 
5127 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5128 /// limited-precision mode.
5129 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5130                          const TargetLowering &TLI, SDNodeFlags Flags) {
5131   if (Op.getValueType() == MVT::f32 &&
5132       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5133 
5134     // Put the exponent in the right bit position for later addition to the
5135     // final result:
5136     //
5137     // t0 = Op * log2(e)
5138 
5139     // TODO: What fast-math-flags should be set here?
5140     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5141                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5142     return getLimitedPrecisionExp2(t0, dl, DAG);
5143   }
5144 
5145   // No special expansion.
5146   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5147 }
5148 
5149 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5150 /// limited-precision mode.
5151 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5152                          const TargetLowering &TLI, SDNodeFlags Flags) {
5153   // TODO: What fast-math-flags should be set on the floating-point nodes?
5154 
5155   if (Op.getValueType() == MVT::f32 &&
5156       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5157     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5158 
5159     // Scale the exponent by log(2).
5160     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5161     SDValue LogOfExponent =
5162         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5163                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5164 
5165     // Get the significand and build it into a floating-point number with
5166     // exponent of 1.
5167     SDValue X = GetSignificand(DAG, Op1, dl);
5168 
5169     SDValue LogOfMantissa;
5170     if (LimitFloatPrecision <= 6) {
5171       // For floating-point precision of 6:
5172       //
5173       //   LogofMantissa =
5174       //     -1.1609546f +
5175       //       (1.4034025f - 0.23903021f * x) * x;
5176       //
5177       // error 0.0034276066, which is better than 8 bits
5178       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5179                                getF32Constant(DAG, 0xbe74c456, dl));
5180       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5181                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5182       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5183       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5184                                   getF32Constant(DAG, 0x3f949a29, dl));
5185     } else if (LimitFloatPrecision <= 12) {
5186       // For floating-point precision of 12:
5187       //
5188       //   LogOfMantissa =
5189       //     -1.7417939f +
5190       //       (2.8212026f +
5191       //         (-1.4699568f +
5192       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5193       //
5194       // error 0.000061011436, which is 14 bits
5195       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5196                                getF32Constant(DAG, 0xbd67b6d6, dl));
5197       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5198                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5199       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5200       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5201                                getF32Constant(DAG, 0x3fbc278b, dl));
5202       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5203       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5204                                getF32Constant(DAG, 0x40348e95, dl));
5205       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5206       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5207                                   getF32Constant(DAG, 0x3fdef31a, dl));
5208     } else { // LimitFloatPrecision <= 18
5209       // For floating-point precision of 18:
5210       //
5211       //   LogOfMantissa =
5212       //     -2.1072184f +
5213       //       (4.2372794f +
5214       //         (-3.7029485f +
5215       //           (2.2781945f +
5216       //             (-0.87823314f +
5217       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5218       //
5219       // error 0.0000023660568, which is better than 18 bits
5220       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5221                                getF32Constant(DAG, 0xbc91e5ac, dl));
5222       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5223                                getF32Constant(DAG, 0x3e4350aa, dl));
5224       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5225       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5226                                getF32Constant(DAG, 0x3f60d3e3, dl));
5227       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5228       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5229                                getF32Constant(DAG, 0x4011cdf0, dl));
5230       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5231       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5232                                getF32Constant(DAG, 0x406cfd1c, dl));
5233       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5234       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5235                                getF32Constant(DAG, 0x408797cb, dl));
5236       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5237       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5238                                   getF32Constant(DAG, 0x4006dcab, dl));
5239     }
5240 
5241     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5242   }
5243 
5244   // No special expansion.
5245   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5246 }
5247 
5248 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5249 /// limited-precision mode.
5250 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5251                           const TargetLowering &TLI, SDNodeFlags Flags) {
5252   // TODO: What fast-math-flags should be set on the floating-point nodes?
5253 
5254   if (Op.getValueType() == MVT::f32 &&
5255       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5256     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5257 
5258     // Get the exponent.
5259     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5260 
5261     // Get the significand and build it into a floating-point number with
5262     // exponent of 1.
5263     SDValue X = GetSignificand(DAG, Op1, dl);
5264 
5265     // Different possible minimax approximations of significand in
5266     // floating-point for various degrees of accuracy over [1,2].
5267     SDValue Log2ofMantissa;
5268     if (LimitFloatPrecision <= 6) {
5269       // For floating-point precision of 6:
5270       //
5271       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5272       //
5273       // error 0.0049451742, which is more than 7 bits
5274       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5275                                getF32Constant(DAG, 0xbeb08fe0, dl));
5276       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5277                                getF32Constant(DAG, 0x40019463, dl));
5278       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5279       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5280                                    getF32Constant(DAG, 0x3fd6633d, dl));
5281     } else if (LimitFloatPrecision <= 12) {
5282       // For floating-point precision of 12:
5283       //
5284       //   Log2ofMantissa =
5285       //     -2.51285454f +
5286       //       (4.07009056f +
5287       //         (-2.12067489f +
5288       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5289       //
5290       // error 0.0000876136000, which is better than 13 bits
5291       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5292                                getF32Constant(DAG, 0xbda7262e, dl));
5293       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5294                                getF32Constant(DAG, 0x3f25280b, dl));
5295       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5296       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5297                                getF32Constant(DAG, 0x4007b923, dl));
5298       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5299       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5300                                getF32Constant(DAG, 0x40823e2f, dl));
5301       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5302       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5303                                    getF32Constant(DAG, 0x4020d29c, dl));
5304     } else { // LimitFloatPrecision <= 18
5305       // For floating-point precision of 18:
5306       //
5307       //   Log2ofMantissa =
5308       //     -3.0400495f +
5309       //       (6.1129976f +
5310       //         (-5.3420409f +
5311       //           (3.2865683f +
5312       //             (-1.2669343f +
5313       //               (0.27515199f -
5314       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5315       //
5316       // error 0.0000018516, which is better than 18 bits
5317       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5318                                getF32Constant(DAG, 0xbcd2769e, dl));
5319       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5320                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5321       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5322       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5323                                getF32Constant(DAG, 0x3fa22ae7, dl));
5324       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5325       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5326                                getF32Constant(DAG, 0x40525723, dl));
5327       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5328       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5329                                getF32Constant(DAG, 0x40aaf200, dl));
5330       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5331       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5332                                getF32Constant(DAG, 0x40c39dad, dl));
5333       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5334       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5335                                    getF32Constant(DAG, 0x4042902c, dl));
5336     }
5337 
5338     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5339   }
5340 
5341   // No special expansion.
5342   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5343 }
5344 
5345 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5346 /// limited-precision mode.
5347 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5348                            const TargetLowering &TLI, SDNodeFlags Flags) {
5349   // TODO: What fast-math-flags should be set on the floating-point nodes?
5350 
5351   if (Op.getValueType() == MVT::f32 &&
5352       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5353     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5354 
5355     // Scale the exponent by log10(2) [0.30102999f].
5356     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5357     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5358                                         getF32Constant(DAG, 0x3e9a209a, dl));
5359 
5360     // Get the significand and build it into a floating-point number with
5361     // exponent of 1.
5362     SDValue X = GetSignificand(DAG, Op1, dl);
5363 
5364     SDValue Log10ofMantissa;
5365     if (LimitFloatPrecision <= 6) {
5366       // For floating-point precision of 6:
5367       //
5368       //   Log10ofMantissa =
5369       //     -0.50419619f +
5370       //       (0.60948995f - 0.10380950f * x) * x;
5371       //
5372       // error 0.0014886165, which is 6 bits
5373       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5374                                getF32Constant(DAG, 0xbdd49a13, dl));
5375       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5376                                getF32Constant(DAG, 0x3f1c0789, dl));
5377       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5378       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5379                                     getF32Constant(DAG, 0x3f011300, dl));
5380     } else if (LimitFloatPrecision <= 12) {
5381       // For floating-point precision of 12:
5382       //
5383       //   Log10ofMantissa =
5384       //     -0.64831180f +
5385       //       (0.91751397f +
5386       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5387       //
5388       // error 0.00019228036, which is better than 12 bits
5389       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5390                                getF32Constant(DAG, 0x3d431f31, dl));
5391       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5392                                getF32Constant(DAG, 0x3ea21fb2, dl));
5393       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5394       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5395                                getF32Constant(DAG, 0x3f6ae232, dl));
5396       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5397       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5398                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5399     } else { // LimitFloatPrecision <= 18
5400       // For floating-point precision of 18:
5401       //
5402       //   Log10ofMantissa =
5403       //     -0.84299375f +
5404       //       (1.5327582f +
5405       //         (-1.0688956f +
5406       //           (0.49102474f +
5407       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5408       //
5409       // error 0.0000037995730, which is better than 18 bits
5410       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5411                                getF32Constant(DAG, 0x3c5d51ce, dl));
5412       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5413                                getF32Constant(DAG, 0x3e00685a, dl));
5414       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5415       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5416                                getF32Constant(DAG, 0x3efb6798, dl));
5417       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5418       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5419                                getF32Constant(DAG, 0x3f88d192, dl));
5420       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5421       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5422                                getF32Constant(DAG, 0x3fc4316c, dl));
5423       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5424       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5425                                     getF32Constant(DAG, 0x3f57ce70, dl));
5426     }
5427 
5428     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5429   }
5430 
5431   // No special expansion.
5432   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5433 }
5434 
5435 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5436 /// limited-precision mode.
5437 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5438                           const TargetLowering &TLI, SDNodeFlags Flags) {
5439   if (Op.getValueType() == MVT::f32 &&
5440       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5441     return getLimitedPrecisionExp2(Op, dl, DAG);
5442 
5443   // No special expansion.
5444   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5445 }
5446 
5447 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5448 /// limited-precision mode with x == 10.0f.
5449 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5450                          SelectionDAG &DAG, const TargetLowering &TLI,
5451                          SDNodeFlags Flags) {
5452   bool IsExp10 = false;
5453   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5454       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5455     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5456       APFloat Ten(10.0f);
5457       IsExp10 = LHSC->isExactlyValue(Ten);
5458     }
5459   }
5460 
5461   // TODO: What fast-math-flags should be set on the FMUL node?
5462   if (IsExp10) {
5463     // Put the exponent in the right bit position for later addition to the
5464     // final result:
5465     //
5466     //   #define LOG2OF10 3.3219281f
5467     //   t0 = Op * LOG2OF10;
5468     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5469                              getF32Constant(DAG, 0x40549a78, dl));
5470     return getLimitedPrecisionExp2(t0, dl, DAG);
5471   }
5472 
5473   // No special expansion.
5474   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5475 }
5476 
5477 /// ExpandPowI - Expand a llvm.powi intrinsic.
5478 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5479                           SelectionDAG &DAG) {
5480   // If RHS is a constant, we can expand this out to a multiplication tree if
5481   // it's beneficial on the target, otherwise we end up lowering to a call to
5482   // __powidf2 (for example).
5483   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5484     unsigned Val = RHSC->getSExtValue();
5485 
5486     // powi(x, 0) -> 1.0
5487     if (Val == 0)
5488       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5489 
5490     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5491             Val, DAG.shouldOptForSize())) {
5492       // Get the exponent as a positive value.
5493       if ((int)Val < 0)
5494         Val = -Val;
5495       // We use the simple binary decomposition method to generate the multiply
5496       // sequence.  There are more optimal ways to do this (for example,
5497       // powi(x,15) generates one more multiply than it should), but this has
5498       // the benefit of being both really simple and much better than a libcall.
5499       SDValue Res; // Logically starts equal to 1.0
5500       SDValue CurSquare = LHS;
5501       // TODO: Intrinsics should have fast-math-flags that propagate to these
5502       // nodes.
5503       while (Val) {
5504         if (Val & 1) {
5505           if (Res.getNode())
5506             Res =
5507                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5508           else
5509             Res = CurSquare; // 1.0*CurSquare.
5510         }
5511 
5512         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5513                                 CurSquare, CurSquare);
5514         Val >>= 1;
5515       }
5516 
5517       // If the original was negative, invert the result, producing 1/(x*x*x).
5518       if (RHSC->getSExtValue() < 0)
5519         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5520                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5521       return Res;
5522     }
5523   }
5524 
5525   // Otherwise, expand to a libcall.
5526   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5527 }
5528 
5529 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5530                             SDValue LHS, SDValue RHS, SDValue Scale,
5531                             SelectionDAG &DAG, const TargetLowering &TLI) {
5532   EVT VT = LHS.getValueType();
5533   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5534   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5535   LLVMContext &Ctx = *DAG.getContext();
5536 
5537   // If the type is legal but the operation isn't, this node might survive all
5538   // the way to operation legalization. If we end up there and we do not have
5539   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5540   // node.
5541 
5542   // Coax the legalizer into expanding the node during type legalization instead
5543   // by bumping the size by one bit. This will force it to Promote, enabling the
5544   // early expansion and avoiding the need to expand later.
5545 
5546   // We don't have to do this if Scale is 0; that can always be expanded, unless
5547   // it's a saturating signed operation. Those can experience true integer
5548   // division overflow, a case which we must avoid.
5549 
5550   // FIXME: We wouldn't have to do this (or any of the early
5551   // expansion/promotion) if it was possible to expand a libcall of an
5552   // illegal type during operation legalization. But it's not, so things
5553   // get a bit hacky.
5554   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5555   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5556       (TLI.isTypeLegal(VT) ||
5557        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5558     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5559         Opcode, VT, ScaleInt);
5560     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5561       EVT PromVT;
5562       if (VT.isScalarInteger())
5563         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5564       else if (VT.isVector()) {
5565         PromVT = VT.getVectorElementType();
5566         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5567         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5568       } else
5569         llvm_unreachable("Wrong VT for DIVFIX?");
5570       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5571       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5572       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5573       // For saturating operations, we need to shift up the LHS to get the
5574       // proper saturation width, and then shift down again afterwards.
5575       if (Saturating)
5576         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5577                           DAG.getConstant(1, DL, ShiftTy));
5578       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5579       if (Saturating)
5580         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5581                           DAG.getConstant(1, DL, ShiftTy));
5582       return DAG.getZExtOrTrunc(Res, DL, VT);
5583     }
5584   }
5585 
5586   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5587 }
5588 
5589 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5590 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5591 static void
5592 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5593                      const SDValue &N) {
5594   switch (N.getOpcode()) {
5595   case ISD::CopyFromReg: {
5596     SDValue Op = N.getOperand(1);
5597     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5598                       Op.getValueType().getSizeInBits());
5599     return;
5600   }
5601   case ISD::BITCAST:
5602   case ISD::AssertZext:
5603   case ISD::AssertSext:
5604   case ISD::TRUNCATE:
5605     getUnderlyingArgRegs(Regs, N.getOperand(0));
5606     return;
5607   case ISD::BUILD_PAIR:
5608   case ISD::BUILD_VECTOR:
5609   case ISD::CONCAT_VECTORS:
5610     for (SDValue Op : N->op_values())
5611       getUnderlyingArgRegs(Regs, Op);
5612     return;
5613   default:
5614     return;
5615   }
5616 }
5617 
5618 /// If the DbgValueInst is a dbg_value of a function argument, create the
5619 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5620 /// instruction selection, they will be inserted to the entry BB.
5621 /// We don't currently support this for variadic dbg_values, as they shouldn't
5622 /// appear for function arguments or in the prologue.
5623 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5624     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5625     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5626   const Argument *Arg = dyn_cast<Argument>(V);
5627   if (!Arg)
5628     return false;
5629 
5630   MachineFunction &MF = DAG.getMachineFunction();
5631   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5632 
5633   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5634   // we've been asked to pursue.
5635   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5636                               bool Indirect) {
5637     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5638       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5639       // pointing at the VReg, which will be patched up later.
5640       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5641       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5642           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5643           /* isKill */ false, /* isDead */ false,
5644           /* isUndef */ false, /* isEarlyClobber */ false,
5645           /* SubReg */ 0, /* isDebug */ true)});
5646 
5647       auto *NewDIExpr = FragExpr;
5648       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5649       // the DIExpression.
5650       if (Indirect)
5651         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5652       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5653       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5654       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5655     } else {
5656       // Create a completely standard DBG_VALUE.
5657       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5658       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5659     }
5660   };
5661 
5662   if (Kind == FuncArgumentDbgValueKind::Value) {
5663     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5664     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5665     // the entry block.
5666     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5667     if (!IsInEntryBlock)
5668       return false;
5669 
5670     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5671     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5672     // variable that also is a param.
5673     //
5674     // Although, if we are at the top of the entry block already, we can still
5675     // emit using ArgDbgValue. This might catch some situations when the
5676     // dbg.value refers to an argument that isn't used in the entry block, so
5677     // any CopyToReg node would be optimized out and the only way to express
5678     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5679     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5680     // we should only emit as ArgDbgValue if the Variable is an argument to the
5681     // current function, and the dbg.value intrinsic is found in the entry
5682     // block.
5683     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5684         !DL->getInlinedAt();
5685     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5686     if (!IsInPrologue && !VariableIsFunctionInputArg)
5687       return false;
5688 
5689     // Here we assume that a function argument on IR level only can be used to
5690     // describe one input parameter on source level. If we for example have
5691     // source code like this
5692     //
5693     //    struct A { long x, y; };
5694     //    void foo(struct A a, long b) {
5695     //      ...
5696     //      b = a.x;
5697     //      ...
5698     //    }
5699     //
5700     // and IR like this
5701     //
5702     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5703     //  entry:
5704     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5705     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5706     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5707     //    ...
5708     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5709     //    ...
5710     //
5711     // then the last dbg.value is describing a parameter "b" using a value that
5712     // is an argument. But since we already has used %a1 to describe a parameter
5713     // we should not handle that last dbg.value here (that would result in an
5714     // incorrect hoisting of the DBG_VALUE to the function entry).
5715     // Notice that we allow one dbg.value per IR level argument, to accommodate
5716     // for the situation with fragments above.
5717     if (VariableIsFunctionInputArg) {
5718       unsigned ArgNo = Arg->getArgNo();
5719       if (ArgNo >= FuncInfo.DescribedArgs.size())
5720         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5721       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5722         return false;
5723       FuncInfo.DescribedArgs.set(ArgNo);
5724     }
5725   }
5726 
5727   bool IsIndirect = false;
5728   std::optional<MachineOperand> Op;
5729   // Some arguments' frame index is recorded during argument lowering.
5730   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5731   if (FI != std::numeric_limits<int>::max())
5732     Op = MachineOperand::CreateFI(FI);
5733 
5734   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5735   if (!Op && N.getNode()) {
5736     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5737     Register Reg;
5738     if (ArgRegsAndSizes.size() == 1)
5739       Reg = ArgRegsAndSizes.front().first;
5740 
5741     if (Reg && Reg.isVirtual()) {
5742       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5743       Register PR = RegInfo.getLiveInPhysReg(Reg);
5744       if (PR)
5745         Reg = PR;
5746     }
5747     if (Reg) {
5748       Op = MachineOperand::CreateReg(Reg, false);
5749       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5750     }
5751   }
5752 
5753   if (!Op && N.getNode()) {
5754     // Check if frame index is available.
5755     SDValue LCandidate = peekThroughBitcasts(N);
5756     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5757       if (FrameIndexSDNode *FINode =
5758           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5759         Op = MachineOperand::CreateFI(FINode->getIndex());
5760   }
5761 
5762   if (!Op) {
5763     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5764     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5765                                          SplitRegs) {
5766       unsigned Offset = 0;
5767       for (const auto &RegAndSize : SplitRegs) {
5768         // If the expression is already a fragment, the current register
5769         // offset+size might extend beyond the fragment. In this case, only
5770         // the register bits that are inside the fragment are relevant.
5771         int RegFragmentSizeInBits = RegAndSize.second;
5772         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5773           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5774           // The register is entirely outside the expression fragment,
5775           // so is irrelevant for debug info.
5776           if (Offset >= ExprFragmentSizeInBits)
5777             break;
5778           // The register is partially outside the expression fragment, only
5779           // the low bits within the fragment are relevant for debug info.
5780           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5781             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5782           }
5783         }
5784 
5785         auto FragmentExpr = DIExpression::createFragmentExpression(
5786             Expr, Offset, RegFragmentSizeInBits);
5787         Offset += RegAndSize.second;
5788         // If a valid fragment expression cannot be created, the variable's
5789         // correct value cannot be determined and so it is set as Undef.
5790         if (!FragmentExpr) {
5791           SDDbgValue *SDV = DAG.getConstantDbgValue(
5792               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5793           DAG.AddDbgValue(SDV, false);
5794           continue;
5795         }
5796         MachineInstr *NewMI =
5797             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5798                              Kind != FuncArgumentDbgValueKind::Value);
5799         FuncInfo.ArgDbgValues.push_back(NewMI);
5800       }
5801     };
5802 
5803     // Check if ValueMap has reg number.
5804     DenseMap<const Value *, Register>::const_iterator
5805       VMI = FuncInfo.ValueMap.find(V);
5806     if (VMI != FuncInfo.ValueMap.end()) {
5807       const auto &TLI = DAG.getTargetLoweringInfo();
5808       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5809                        V->getType(), std::nullopt);
5810       if (RFV.occupiesMultipleRegs()) {
5811         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5812         return true;
5813       }
5814 
5815       Op = MachineOperand::CreateReg(VMI->second, false);
5816       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5817     } else if (ArgRegsAndSizes.size() > 1) {
5818       // This was split due to the calling convention, and no virtual register
5819       // mapping exists for the value.
5820       splitMultiRegDbgValue(ArgRegsAndSizes);
5821       return true;
5822     }
5823   }
5824 
5825   if (!Op)
5826     return false;
5827 
5828   assert(Variable->isValidLocationForIntrinsic(DL) &&
5829          "Expected inlined-at fields to agree");
5830   MachineInstr *NewMI = nullptr;
5831 
5832   if (Op->isReg())
5833     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5834   else
5835     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5836                     Variable, Expr);
5837 
5838   // Otherwise, use ArgDbgValues.
5839   FuncInfo.ArgDbgValues.push_back(NewMI);
5840   return true;
5841 }
5842 
5843 /// Return the appropriate SDDbgValue based on N.
5844 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5845                                              DILocalVariable *Variable,
5846                                              DIExpression *Expr,
5847                                              const DebugLoc &dl,
5848                                              unsigned DbgSDNodeOrder) {
5849   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5850     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5851     // stack slot locations.
5852     //
5853     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5854     // debug values here after optimization:
5855     //
5856     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5857     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5858     //
5859     // Both describe the direct values of their associated variables.
5860     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5861                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5862   }
5863   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5864                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5865 }
5866 
5867 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5868   switch (Intrinsic) {
5869   case Intrinsic::smul_fix:
5870     return ISD::SMULFIX;
5871   case Intrinsic::umul_fix:
5872     return ISD::UMULFIX;
5873   case Intrinsic::smul_fix_sat:
5874     return ISD::SMULFIXSAT;
5875   case Intrinsic::umul_fix_sat:
5876     return ISD::UMULFIXSAT;
5877   case Intrinsic::sdiv_fix:
5878     return ISD::SDIVFIX;
5879   case Intrinsic::udiv_fix:
5880     return ISD::UDIVFIX;
5881   case Intrinsic::sdiv_fix_sat:
5882     return ISD::SDIVFIXSAT;
5883   case Intrinsic::udiv_fix_sat:
5884     return ISD::UDIVFIXSAT;
5885   default:
5886     llvm_unreachable("Unhandled fixed point intrinsic");
5887   }
5888 }
5889 
5890 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5891                                            const char *FunctionName) {
5892   assert(FunctionName && "FunctionName must not be nullptr");
5893   SDValue Callee = DAG.getExternalSymbol(
5894       FunctionName,
5895       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5896   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5897 }
5898 
5899 /// Given a @llvm.call.preallocated.setup, return the corresponding
5900 /// preallocated call.
5901 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5902   assert(cast<CallBase>(PreallocatedSetup)
5903                  ->getCalledFunction()
5904                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5905          "expected call_preallocated_setup Value");
5906   for (const auto *U : PreallocatedSetup->users()) {
5907     auto *UseCall = cast<CallBase>(U);
5908     const Function *Fn = UseCall->getCalledFunction();
5909     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5910       return UseCall;
5911     }
5912   }
5913   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5914 }
5915 
5916 /// If DI is a debug value with an EntryValue expression, lower it using the
5917 /// corresponding physical register of the associated Argument value
5918 /// (guaranteed to exist by the verifier).
5919 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) {
5920   DILocalVariable *Variable = DI.getVariable();
5921   DIExpression *Expr = DI.getExpression();
5922   if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues()))
5923     return false;
5924 
5925   // These properties are guaranteed by the verifier.
5926   Argument *Arg = cast<Argument>(DI.getValue(0));
5927   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
5928 
5929   auto ArgIt = FuncInfo.ValueMap.find(Arg);
5930   if (ArgIt == FuncInfo.ValueMap.end()) {
5931     LLVM_DEBUG(
5932         dbgs() << "Dropping dbg.value: expression is entry_value but "
5933                   "couldn't find an associated register for the Argument\n");
5934     return true;
5935   }
5936   Register ArgVReg = ArgIt->getSecond();
5937 
5938   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
5939     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
5940       SDDbgValue *SDV =
5941           DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/,
5942                               DI.getDebugLoc(), SDNodeOrder);
5943       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
5944       return true;
5945     }
5946   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
5947                        "couldn't find a physical register\n");
5948   return true;
5949 }
5950 
5951 /// Lower the call to the specified intrinsic function.
5952 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5953                                              unsigned Intrinsic) {
5954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5955   SDLoc sdl = getCurSDLoc();
5956   DebugLoc dl = getCurDebugLoc();
5957   SDValue Res;
5958 
5959   SDNodeFlags Flags;
5960   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5961     Flags.copyFMF(*FPOp);
5962 
5963   switch (Intrinsic) {
5964   default:
5965     // By default, turn this into a target intrinsic node.
5966     visitTargetIntrinsic(I, Intrinsic);
5967     return;
5968   case Intrinsic::vscale: {
5969     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5970     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5971     return;
5972   }
5973   case Intrinsic::vastart:  visitVAStart(I); return;
5974   case Intrinsic::vaend:    visitVAEnd(I); return;
5975   case Intrinsic::vacopy:   visitVACopy(I); return;
5976   case Intrinsic::returnaddress:
5977     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5978                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5979                              getValue(I.getArgOperand(0))));
5980     return;
5981   case Intrinsic::addressofreturnaddress:
5982     setValue(&I,
5983              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5984                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5985     return;
5986   case Intrinsic::sponentry:
5987     setValue(&I,
5988              DAG.getNode(ISD::SPONENTRY, sdl,
5989                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5990     return;
5991   case Intrinsic::frameaddress:
5992     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5993                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5994                              getValue(I.getArgOperand(0))));
5995     return;
5996   case Intrinsic::read_volatile_register:
5997   case Intrinsic::read_register: {
5998     Value *Reg = I.getArgOperand(0);
5999     SDValue Chain = getRoot();
6000     SDValue RegName =
6001         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6002     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6003     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6004       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6005     setValue(&I, Res);
6006     DAG.setRoot(Res.getValue(1));
6007     return;
6008   }
6009   case Intrinsic::write_register: {
6010     Value *Reg = I.getArgOperand(0);
6011     Value *RegValue = I.getArgOperand(1);
6012     SDValue Chain = getRoot();
6013     SDValue RegName =
6014         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6015     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6016                             RegName, getValue(RegValue)));
6017     return;
6018   }
6019   case Intrinsic::memcpy: {
6020     const auto &MCI = cast<MemCpyInst>(I);
6021     SDValue Op1 = getValue(I.getArgOperand(0));
6022     SDValue Op2 = getValue(I.getArgOperand(1));
6023     SDValue Op3 = getValue(I.getArgOperand(2));
6024     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6025     Align DstAlign = MCI.getDestAlign().valueOrOne();
6026     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6027     Align Alignment = std::min(DstAlign, SrcAlign);
6028     bool isVol = MCI.isVolatile();
6029     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6030     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6031     // node.
6032     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6033     SDValue MC = DAG.getMemcpy(
6034         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6035         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6036         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6037     updateDAGForMaybeTailCall(MC);
6038     return;
6039   }
6040   case Intrinsic::memcpy_inline: {
6041     const auto &MCI = cast<MemCpyInlineInst>(I);
6042     SDValue Dst = getValue(I.getArgOperand(0));
6043     SDValue Src = getValue(I.getArgOperand(1));
6044     SDValue Size = getValue(I.getArgOperand(2));
6045     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6046     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6047     Align DstAlign = MCI.getDestAlign().valueOrOne();
6048     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6049     Align Alignment = std::min(DstAlign, SrcAlign);
6050     bool isVol = MCI.isVolatile();
6051     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6052     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6053     // node.
6054     SDValue MC = DAG.getMemcpy(
6055         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6056         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6057         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6058     updateDAGForMaybeTailCall(MC);
6059     return;
6060   }
6061   case Intrinsic::memset: {
6062     const auto &MSI = cast<MemSetInst>(I);
6063     SDValue Op1 = getValue(I.getArgOperand(0));
6064     SDValue Op2 = getValue(I.getArgOperand(1));
6065     SDValue Op3 = getValue(I.getArgOperand(2));
6066     // @llvm.memset defines 0 and 1 to both mean no alignment.
6067     Align Alignment = MSI.getDestAlign().valueOrOne();
6068     bool isVol = MSI.isVolatile();
6069     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6070     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6071     SDValue MS = DAG.getMemset(
6072         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6073         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6074     updateDAGForMaybeTailCall(MS);
6075     return;
6076   }
6077   case Intrinsic::memset_inline: {
6078     const auto &MSII = cast<MemSetInlineInst>(I);
6079     SDValue Dst = getValue(I.getArgOperand(0));
6080     SDValue Value = getValue(I.getArgOperand(1));
6081     SDValue Size = getValue(I.getArgOperand(2));
6082     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6083     // @llvm.memset defines 0 and 1 to both mean no alignment.
6084     Align DstAlign = MSII.getDestAlign().valueOrOne();
6085     bool isVol = MSII.isVolatile();
6086     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6087     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6088     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6089                                /* AlwaysInline */ true, isTC,
6090                                MachinePointerInfo(I.getArgOperand(0)),
6091                                I.getAAMetadata());
6092     updateDAGForMaybeTailCall(MC);
6093     return;
6094   }
6095   case Intrinsic::memmove: {
6096     const auto &MMI = cast<MemMoveInst>(I);
6097     SDValue Op1 = getValue(I.getArgOperand(0));
6098     SDValue Op2 = getValue(I.getArgOperand(1));
6099     SDValue Op3 = getValue(I.getArgOperand(2));
6100     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6101     Align DstAlign = MMI.getDestAlign().valueOrOne();
6102     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6103     Align Alignment = std::min(DstAlign, SrcAlign);
6104     bool isVol = MMI.isVolatile();
6105     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6106     // FIXME: Support passing different dest/src alignments to the memmove DAG
6107     // node.
6108     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6109     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6110                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6111                                 MachinePointerInfo(I.getArgOperand(1)),
6112                                 I.getAAMetadata(), AA);
6113     updateDAGForMaybeTailCall(MM);
6114     return;
6115   }
6116   case Intrinsic::memcpy_element_unordered_atomic: {
6117     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6118     SDValue Dst = getValue(MI.getRawDest());
6119     SDValue Src = getValue(MI.getRawSource());
6120     SDValue Length = getValue(MI.getLength());
6121 
6122     Type *LengthTy = MI.getLength()->getType();
6123     unsigned ElemSz = MI.getElementSizeInBytes();
6124     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6125     SDValue MC =
6126         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6127                             isTC, MachinePointerInfo(MI.getRawDest()),
6128                             MachinePointerInfo(MI.getRawSource()));
6129     updateDAGForMaybeTailCall(MC);
6130     return;
6131   }
6132   case Intrinsic::memmove_element_unordered_atomic: {
6133     auto &MI = cast<AtomicMemMoveInst>(I);
6134     SDValue Dst = getValue(MI.getRawDest());
6135     SDValue Src = getValue(MI.getRawSource());
6136     SDValue Length = getValue(MI.getLength());
6137 
6138     Type *LengthTy = MI.getLength()->getType();
6139     unsigned ElemSz = MI.getElementSizeInBytes();
6140     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6141     SDValue MC =
6142         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6143                              isTC, MachinePointerInfo(MI.getRawDest()),
6144                              MachinePointerInfo(MI.getRawSource()));
6145     updateDAGForMaybeTailCall(MC);
6146     return;
6147   }
6148   case Intrinsic::memset_element_unordered_atomic: {
6149     auto &MI = cast<AtomicMemSetInst>(I);
6150     SDValue Dst = getValue(MI.getRawDest());
6151     SDValue Val = getValue(MI.getValue());
6152     SDValue Length = getValue(MI.getLength());
6153 
6154     Type *LengthTy = MI.getLength()->getType();
6155     unsigned ElemSz = MI.getElementSizeInBytes();
6156     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6157     SDValue MC =
6158         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6159                             isTC, MachinePointerInfo(MI.getRawDest()));
6160     updateDAGForMaybeTailCall(MC);
6161     return;
6162   }
6163   case Intrinsic::call_preallocated_setup: {
6164     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6165     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6166     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6167                               getRoot(), SrcValue);
6168     setValue(&I, Res);
6169     DAG.setRoot(Res);
6170     return;
6171   }
6172   case Intrinsic::call_preallocated_arg: {
6173     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6174     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6175     SDValue Ops[3];
6176     Ops[0] = getRoot();
6177     Ops[1] = SrcValue;
6178     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6179                                    MVT::i32); // arg index
6180     SDValue Res = DAG.getNode(
6181         ISD::PREALLOCATED_ARG, sdl,
6182         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6183     setValue(&I, Res);
6184     DAG.setRoot(Res.getValue(1));
6185     return;
6186   }
6187   case Intrinsic::dbg_declare: {
6188     const auto &DI = cast<DbgDeclareInst>(I);
6189     // Debug intrinsics are handled separately in assignment tracking mode.
6190     // Some intrinsics are handled right after Argument lowering.
6191     if (AssignmentTrackingEnabled ||
6192         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6193       return;
6194     // Assume dbg.declare can not currently use DIArgList, i.e.
6195     // it is non-variadic.
6196     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6197     DILocalVariable *Variable = DI.getVariable();
6198     DIExpression *Expression = DI.getExpression();
6199     dropDanglingDebugInfo(Variable, Expression);
6200     assert(Variable && "Missing variable");
6201     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6202                       << "\n");
6203     // Check if address has undef value.
6204     const Value *Address = DI.getVariableLocationOp(0);
6205     if (!Address || isa<UndefValue>(Address) ||
6206         (Address->use_empty() && !isa<Argument>(Address))) {
6207       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6208                         << " (bad/undef/unused-arg address)\n");
6209       return;
6210     }
6211 
6212     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6213 
6214     SDValue &N = NodeMap[Address];
6215     if (!N.getNode() && isa<Argument>(Address))
6216       // Check unused arguments map.
6217       N = UnusedArgNodeMap[Address];
6218     SDDbgValue *SDV;
6219     if (N.getNode()) {
6220       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6221         Address = BCI->getOperand(0);
6222       // Parameters are handled specially.
6223       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6224       if (isParameter && FINode) {
6225         // Byval parameter. We have a frame index at this point.
6226         SDV =
6227             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6228                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6229       } else if (isa<Argument>(Address)) {
6230         // Address is an argument, so try to emit its dbg value using
6231         // virtual register info from the FuncInfo.ValueMap.
6232         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6233                                  FuncArgumentDbgValueKind::Declare, N);
6234         return;
6235       } else {
6236         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6237                               true, dl, SDNodeOrder);
6238       }
6239       DAG.AddDbgValue(SDV, isParameter);
6240     } else {
6241       // If Address is an argument then try to emit its dbg value using
6242       // virtual register info from the FuncInfo.ValueMap.
6243       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6244                                     FuncArgumentDbgValueKind::Declare, N)) {
6245         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6246                           << " (could not emit func-arg dbg_value)\n");
6247       }
6248     }
6249     return;
6250   }
6251   case Intrinsic::dbg_label: {
6252     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6253     DILabel *Label = DI.getLabel();
6254     assert(Label && "Missing label");
6255 
6256     SDDbgLabel *SDV;
6257     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6258     DAG.AddDbgLabel(SDV);
6259     return;
6260   }
6261   case Intrinsic::dbg_assign: {
6262     // Debug intrinsics are handled seperately in assignment tracking mode.
6263     if (AssignmentTrackingEnabled)
6264       return;
6265     // If assignment tracking hasn't been enabled then fall through and treat
6266     // the dbg.assign as a dbg.value.
6267     [[fallthrough]];
6268   }
6269   case Intrinsic::dbg_value: {
6270     // Debug intrinsics are handled seperately in assignment tracking mode.
6271     if (AssignmentTrackingEnabled)
6272       return;
6273     const DbgValueInst &DI = cast<DbgValueInst>(I);
6274     assert(DI.getVariable() && "Missing variable");
6275 
6276     DILocalVariable *Variable = DI.getVariable();
6277     DIExpression *Expression = DI.getExpression();
6278     dropDanglingDebugInfo(Variable, Expression);
6279 
6280     if (visitEntryValueDbgValue(DI))
6281       return;
6282 
6283     if (DI.isKillLocation()) {
6284       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6285       return;
6286     }
6287 
6288     SmallVector<Value *, 4> Values(DI.getValues());
6289     if (Values.empty())
6290       return;
6291 
6292     bool IsVariadic = DI.hasArgList();
6293     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6294                           SDNodeOrder, IsVariadic))
6295       addDanglingDebugInfo(&DI, SDNodeOrder);
6296     return;
6297   }
6298 
6299   case Intrinsic::eh_typeid_for: {
6300     // Find the type id for the given typeinfo.
6301     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6302     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6303     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6304     setValue(&I, Res);
6305     return;
6306   }
6307 
6308   case Intrinsic::eh_return_i32:
6309   case Intrinsic::eh_return_i64:
6310     DAG.getMachineFunction().setCallsEHReturn(true);
6311     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6312                             MVT::Other,
6313                             getControlRoot(),
6314                             getValue(I.getArgOperand(0)),
6315                             getValue(I.getArgOperand(1))));
6316     return;
6317   case Intrinsic::eh_unwind_init:
6318     DAG.getMachineFunction().setCallsUnwindInit(true);
6319     return;
6320   case Intrinsic::eh_dwarf_cfa:
6321     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6322                              TLI.getPointerTy(DAG.getDataLayout()),
6323                              getValue(I.getArgOperand(0))));
6324     return;
6325   case Intrinsic::eh_sjlj_callsite: {
6326     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6327     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6328     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6329 
6330     MMI.setCurrentCallSite(CI->getZExtValue());
6331     return;
6332   }
6333   case Intrinsic::eh_sjlj_functioncontext: {
6334     // Get and store the index of the function context.
6335     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6336     AllocaInst *FnCtx =
6337       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6338     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6339     MFI.setFunctionContextIndex(FI);
6340     return;
6341   }
6342   case Intrinsic::eh_sjlj_setjmp: {
6343     SDValue Ops[2];
6344     Ops[0] = getRoot();
6345     Ops[1] = getValue(I.getArgOperand(0));
6346     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6347                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6348     setValue(&I, Op.getValue(0));
6349     DAG.setRoot(Op.getValue(1));
6350     return;
6351   }
6352   case Intrinsic::eh_sjlj_longjmp:
6353     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6354                             getRoot(), getValue(I.getArgOperand(0))));
6355     return;
6356   case Intrinsic::eh_sjlj_setup_dispatch:
6357     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6358                             getRoot()));
6359     return;
6360   case Intrinsic::masked_gather:
6361     visitMaskedGather(I);
6362     return;
6363   case Intrinsic::masked_load:
6364     visitMaskedLoad(I);
6365     return;
6366   case Intrinsic::masked_scatter:
6367     visitMaskedScatter(I);
6368     return;
6369   case Intrinsic::masked_store:
6370     visitMaskedStore(I);
6371     return;
6372   case Intrinsic::masked_expandload:
6373     visitMaskedLoad(I, true /* IsExpanding */);
6374     return;
6375   case Intrinsic::masked_compressstore:
6376     visitMaskedStore(I, true /* IsCompressing */);
6377     return;
6378   case Intrinsic::powi:
6379     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6380                             getValue(I.getArgOperand(1)), DAG));
6381     return;
6382   case Intrinsic::log:
6383     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6384     return;
6385   case Intrinsic::log2:
6386     setValue(&I,
6387              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6388     return;
6389   case Intrinsic::log10:
6390     setValue(&I,
6391              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6392     return;
6393   case Intrinsic::exp:
6394     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6395     return;
6396   case Intrinsic::exp2:
6397     setValue(&I,
6398              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6399     return;
6400   case Intrinsic::pow:
6401     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6402                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6403     return;
6404   case Intrinsic::sqrt:
6405   case Intrinsic::fabs:
6406   case Intrinsic::sin:
6407   case Intrinsic::cos:
6408   case Intrinsic::exp10:
6409   case Intrinsic::floor:
6410   case Intrinsic::ceil:
6411   case Intrinsic::trunc:
6412   case Intrinsic::rint:
6413   case Intrinsic::nearbyint:
6414   case Intrinsic::round:
6415   case Intrinsic::roundeven:
6416   case Intrinsic::canonicalize: {
6417     unsigned Opcode;
6418     switch (Intrinsic) {
6419     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6420     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6421     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6422     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6423     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6424     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6425     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6426     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6427     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6428     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6429     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6430     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6431     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6432     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6433     }
6434 
6435     setValue(&I, DAG.getNode(Opcode, sdl,
6436                              getValue(I.getArgOperand(0)).getValueType(),
6437                              getValue(I.getArgOperand(0)), Flags));
6438     return;
6439   }
6440   case Intrinsic::lround:
6441   case Intrinsic::llround:
6442   case Intrinsic::lrint:
6443   case Intrinsic::llrint: {
6444     unsigned Opcode;
6445     switch (Intrinsic) {
6446     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6447     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6448     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6449     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6450     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6451     }
6452 
6453     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6454     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6455                              getValue(I.getArgOperand(0))));
6456     return;
6457   }
6458   case Intrinsic::minnum:
6459     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6460                              getValue(I.getArgOperand(0)).getValueType(),
6461                              getValue(I.getArgOperand(0)),
6462                              getValue(I.getArgOperand(1)), Flags));
6463     return;
6464   case Intrinsic::maxnum:
6465     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6466                              getValue(I.getArgOperand(0)).getValueType(),
6467                              getValue(I.getArgOperand(0)),
6468                              getValue(I.getArgOperand(1)), Flags));
6469     return;
6470   case Intrinsic::minimum:
6471     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6472                              getValue(I.getArgOperand(0)).getValueType(),
6473                              getValue(I.getArgOperand(0)),
6474                              getValue(I.getArgOperand(1)), Flags));
6475     return;
6476   case Intrinsic::maximum:
6477     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6478                              getValue(I.getArgOperand(0)).getValueType(),
6479                              getValue(I.getArgOperand(0)),
6480                              getValue(I.getArgOperand(1)), Flags));
6481     return;
6482   case Intrinsic::copysign:
6483     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6484                              getValue(I.getArgOperand(0)).getValueType(),
6485                              getValue(I.getArgOperand(0)),
6486                              getValue(I.getArgOperand(1)), Flags));
6487     return;
6488   case Intrinsic::ldexp:
6489     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6490                              getValue(I.getArgOperand(0)).getValueType(),
6491                              getValue(I.getArgOperand(0)),
6492                              getValue(I.getArgOperand(1)), Flags));
6493     return;
6494   case Intrinsic::frexp: {
6495     SmallVector<EVT, 2> ValueVTs;
6496     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6497     SDVTList VTs = DAG.getVTList(ValueVTs);
6498     setValue(&I,
6499              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6500     return;
6501   }
6502   case Intrinsic::arithmetic_fence: {
6503     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6504                              getValue(I.getArgOperand(0)).getValueType(),
6505                              getValue(I.getArgOperand(0)), Flags));
6506     return;
6507   }
6508   case Intrinsic::fma:
6509     setValue(&I, DAG.getNode(
6510                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6511                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6512                      getValue(I.getArgOperand(2)), Flags));
6513     return;
6514 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6515   case Intrinsic::INTRINSIC:
6516 #include "llvm/IR/ConstrainedOps.def"
6517     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6518     return;
6519 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6520 #include "llvm/IR/VPIntrinsics.def"
6521     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6522     return;
6523   case Intrinsic::fptrunc_round: {
6524     // Get the last argument, the metadata and convert it to an integer in the
6525     // call
6526     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6527     std::optional<RoundingMode> RoundMode =
6528         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6529 
6530     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6531 
6532     // Propagate fast-math-flags from IR to node(s).
6533     SDNodeFlags Flags;
6534     Flags.copyFMF(*cast<FPMathOperator>(&I));
6535     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6536 
6537     SDValue Result;
6538     Result = DAG.getNode(
6539         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6540         DAG.getTargetConstant((int)*RoundMode, sdl,
6541                               TLI.getPointerTy(DAG.getDataLayout())));
6542     setValue(&I, Result);
6543 
6544     return;
6545   }
6546   case Intrinsic::fmuladd: {
6547     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6548     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6549         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6550       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6551                                getValue(I.getArgOperand(0)).getValueType(),
6552                                getValue(I.getArgOperand(0)),
6553                                getValue(I.getArgOperand(1)),
6554                                getValue(I.getArgOperand(2)), Flags));
6555     } else {
6556       // TODO: Intrinsic calls should have fast-math-flags.
6557       SDValue Mul = DAG.getNode(
6558           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6559           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6560       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6561                                 getValue(I.getArgOperand(0)).getValueType(),
6562                                 Mul, getValue(I.getArgOperand(2)), Flags);
6563       setValue(&I, Add);
6564     }
6565     return;
6566   }
6567   case Intrinsic::convert_to_fp16:
6568     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6569                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6570                                          getValue(I.getArgOperand(0)),
6571                                          DAG.getTargetConstant(0, sdl,
6572                                                                MVT::i32))));
6573     return;
6574   case Intrinsic::convert_from_fp16:
6575     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6576                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6577                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6578                                          getValue(I.getArgOperand(0)))));
6579     return;
6580   case Intrinsic::fptosi_sat: {
6581     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6582     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6583                              getValue(I.getArgOperand(0)),
6584                              DAG.getValueType(VT.getScalarType())));
6585     return;
6586   }
6587   case Intrinsic::fptoui_sat: {
6588     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6589     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6590                              getValue(I.getArgOperand(0)),
6591                              DAG.getValueType(VT.getScalarType())));
6592     return;
6593   }
6594   case Intrinsic::set_rounding:
6595     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6596                       {getRoot(), getValue(I.getArgOperand(0))});
6597     setValue(&I, Res);
6598     DAG.setRoot(Res.getValue(0));
6599     return;
6600   case Intrinsic::is_fpclass: {
6601     const DataLayout DLayout = DAG.getDataLayout();
6602     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6603     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6604     FPClassTest Test = static_cast<FPClassTest>(
6605         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6606     MachineFunction &MF = DAG.getMachineFunction();
6607     const Function &F = MF.getFunction();
6608     SDValue Op = getValue(I.getArgOperand(0));
6609     SDNodeFlags Flags;
6610     Flags.setNoFPExcept(
6611         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6612     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6613     // expansion can use illegal types. Making expansion early allows
6614     // legalizing these types prior to selection.
6615     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6616       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6617       setValue(&I, Result);
6618       return;
6619     }
6620 
6621     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6622     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6623     setValue(&I, V);
6624     return;
6625   }
6626   case Intrinsic::get_fpenv: {
6627     const DataLayout DLayout = DAG.getDataLayout();
6628     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6629     Align TempAlign = DAG.getEVTAlign(EnvVT);
6630     SDValue Chain = getRoot();
6631     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6632     // and temporary storage in stack.
6633     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6634       Res = DAG.getNode(
6635           ISD::GET_FPENV, sdl,
6636           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6637                         MVT::Other),
6638           Chain);
6639     } else {
6640       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6641       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6642       auto MPI =
6643           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6644       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6645           MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize,
6646           TempAlign);
6647       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6648       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6649     }
6650     setValue(&I, Res);
6651     DAG.setRoot(Res.getValue(1));
6652     return;
6653   }
6654   case Intrinsic::set_fpenv: {
6655     const DataLayout DLayout = DAG.getDataLayout();
6656     SDValue Env = getValue(I.getArgOperand(0));
6657     EVT EnvVT = Env.getValueType();
6658     Align TempAlign = DAG.getEVTAlign(EnvVT);
6659     SDValue Chain = getRoot();
6660     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6661     // environment from memory.
6662     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6663       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6664     } else {
6665       // Allocate space in stack, copy environment bits into it and use this
6666       // memory in SET_FPENV_MEM.
6667       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6668       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6669       auto MPI =
6670           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6671       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6672                            MachineMemOperand::MOStore);
6673       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6674           MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize,
6675           TempAlign);
6676       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6677     }
6678     DAG.setRoot(Chain);
6679     return;
6680   }
6681   case Intrinsic::reset_fpenv:
6682     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6683     return;
6684   case Intrinsic::get_fpmode:
6685     Res = DAG.getNode(
6686         ISD::GET_FPMODE, sdl,
6687         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6688                       MVT::Other),
6689         DAG.getRoot());
6690     setValue(&I, Res);
6691     DAG.setRoot(Res.getValue(1));
6692     return;
6693   case Intrinsic::set_fpmode:
6694     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6695                       getValue(I.getArgOperand(0)));
6696     DAG.setRoot(Res);
6697     return;
6698   case Intrinsic::reset_fpmode: {
6699     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6700     DAG.setRoot(Res);
6701     return;
6702   }
6703   case Intrinsic::pcmarker: {
6704     SDValue Tmp = getValue(I.getArgOperand(0));
6705     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6706     return;
6707   }
6708   case Intrinsic::readcyclecounter: {
6709     SDValue Op = getRoot();
6710     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6711                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6712     setValue(&I, Res);
6713     DAG.setRoot(Res.getValue(1));
6714     return;
6715   }
6716   case Intrinsic::bitreverse:
6717     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6718                              getValue(I.getArgOperand(0)).getValueType(),
6719                              getValue(I.getArgOperand(0))));
6720     return;
6721   case Intrinsic::bswap:
6722     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6723                              getValue(I.getArgOperand(0)).getValueType(),
6724                              getValue(I.getArgOperand(0))));
6725     return;
6726   case Intrinsic::cttz: {
6727     SDValue Arg = getValue(I.getArgOperand(0));
6728     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6729     EVT Ty = Arg.getValueType();
6730     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6731                              sdl, Ty, Arg));
6732     return;
6733   }
6734   case Intrinsic::ctlz: {
6735     SDValue Arg = getValue(I.getArgOperand(0));
6736     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6737     EVT Ty = Arg.getValueType();
6738     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6739                              sdl, Ty, Arg));
6740     return;
6741   }
6742   case Intrinsic::ctpop: {
6743     SDValue Arg = getValue(I.getArgOperand(0));
6744     EVT Ty = Arg.getValueType();
6745     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6746     return;
6747   }
6748   case Intrinsic::fshl:
6749   case Intrinsic::fshr: {
6750     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6751     SDValue X = getValue(I.getArgOperand(0));
6752     SDValue Y = getValue(I.getArgOperand(1));
6753     SDValue Z = getValue(I.getArgOperand(2));
6754     EVT VT = X.getValueType();
6755 
6756     if (X == Y) {
6757       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6758       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6759     } else {
6760       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6761       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6762     }
6763     return;
6764   }
6765   case Intrinsic::sadd_sat: {
6766     SDValue Op1 = getValue(I.getArgOperand(0));
6767     SDValue Op2 = getValue(I.getArgOperand(1));
6768     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6769     return;
6770   }
6771   case Intrinsic::uadd_sat: {
6772     SDValue Op1 = getValue(I.getArgOperand(0));
6773     SDValue Op2 = getValue(I.getArgOperand(1));
6774     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6775     return;
6776   }
6777   case Intrinsic::ssub_sat: {
6778     SDValue Op1 = getValue(I.getArgOperand(0));
6779     SDValue Op2 = getValue(I.getArgOperand(1));
6780     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6781     return;
6782   }
6783   case Intrinsic::usub_sat: {
6784     SDValue Op1 = getValue(I.getArgOperand(0));
6785     SDValue Op2 = getValue(I.getArgOperand(1));
6786     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6787     return;
6788   }
6789   case Intrinsic::sshl_sat: {
6790     SDValue Op1 = getValue(I.getArgOperand(0));
6791     SDValue Op2 = getValue(I.getArgOperand(1));
6792     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6793     return;
6794   }
6795   case Intrinsic::ushl_sat: {
6796     SDValue Op1 = getValue(I.getArgOperand(0));
6797     SDValue Op2 = getValue(I.getArgOperand(1));
6798     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6799     return;
6800   }
6801   case Intrinsic::smul_fix:
6802   case Intrinsic::umul_fix:
6803   case Intrinsic::smul_fix_sat:
6804   case Intrinsic::umul_fix_sat: {
6805     SDValue Op1 = getValue(I.getArgOperand(0));
6806     SDValue Op2 = getValue(I.getArgOperand(1));
6807     SDValue Op3 = getValue(I.getArgOperand(2));
6808     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6809                              Op1.getValueType(), Op1, Op2, Op3));
6810     return;
6811   }
6812   case Intrinsic::sdiv_fix:
6813   case Intrinsic::udiv_fix:
6814   case Intrinsic::sdiv_fix_sat:
6815   case Intrinsic::udiv_fix_sat: {
6816     SDValue Op1 = getValue(I.getArgOperand(0));
6817     SDValue Op2 = getValue(I.getArgOperand(1));
6818     SDValue Op3 = getValue(I.getArgOperand(2));
6819     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6820                               Op1, Op2, Op3, DAG, TLI));
6821     return;
6822   }
6823   case Intrinsic::smax: {
6824     SDValue Op1 = getValue(I.getArgOperand(0));
6825     SDValue Op2 = getValue(I.getArgOperand(1));
6826     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6827     return;
6828   }
6829   case Intrinsic::smin: {
6830     SDValue Op1 = getValue(I.getArgOperand(0));
6831     SDValue Op2 = getValue(I.getArgOperand(1));
6832     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6833     return;
6834   }
6835   case Intrinsic::umax: {
6836     SDValue Op1 = getValue(I.getArgOperand(0));
6837     SDValue Op2 = getValue(I.getArgOperand(1));
6838     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6839     return;
6840   }
6841   case Intrinsic::umin: {
6842     SDValue Op1 = getValue(I.getArgOperand(0));
6843     SDValue Op2 = getValue(I.getArgOperand(1));
6844     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6845     return;
6846   }
6847   case Intrinsic::abs: {
6848     // TODO: Preserve "int min is poison" arg in SDAG?
6849     SDValue Op1 = getValue(I.getArgOperand(0));
6850     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6851     return;
6852   }
6853   case Intrinsic::stacksave: {
6854     SDValue Op = getRoot();
6855     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6856     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6857     setValue(&I, Res);
6858     DAG.setRoot(Res.getValue(1));
6859     return;
6860   }
6861   case Intrinsic::stackrestore:
6862     Res = getValue(I.getArgOperand(0));
6863     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6864     return;
6865   case Intrinsic::get_dynamic_area_offset: {
6866     SDValue Op = getRoot();
6867     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6868     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6869     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6870     // target.
6871     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6872       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6873                          " intrinsic!");
6874     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6875                       Op);
6876     DAG.setRoot(Op);
6877     setValue(&I, Res);
6878     return;
6879   }
6880   case Intrinsic::stackguard: {
6881     MachineFunction &MF = DAG.getMachineFunction();
6882     const Module &M = *MF.getFunction().getParent();
6883     SDValue Chain = getRoot();
6884     if (TLI.useLoadStackGuardNode()) {
6885       Res = getLoadStackGuard(DAG, sdl, Chain);
6886     } else {
6887       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6888       const Value *Global = TLI.getSDagStackGuard(M);
6889       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6890       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6891                         MachinePointerInfo(Global, 0), Align,
6892                         MachineMemOperand::MOVolatile);
6893     }
6894     if (TLI.useStackGuardXorFP())
6895       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6896     DAG.setRoot(Chain);
6897     setValue(&I, Res);
6898     return;
6899   }
6900   case Intrinsic::stackprotector: {
6901     // Emit code into the DAG to store the stack guard onto the stack.
6902     MachineFunction &MF = DAG.getMachineFunction();
6903     MachineFrameInfo &MFI = MF.getFrameInfo();
6904     SDValue Src, Chain = getRoot();
6905 
6906     if (TLI.useLoadStackGuardNode())
6907       Src = getLoadStackGuard(DAG, sdl, Chain);
6908     else
6909       Src = getValue(I.getArgOperand(0));   // The guard's value.
6910 
6911     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6912 
6913     int FI = FuncInfo.StaticAllocaMap[Slot];
6914     MFI.setStackProtectorIndex(FI);
6915     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6916 
6917     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6918 
6919     // Store the stack protector onto the stack.
6920     Res = DAG.getStore(
6921         Chain, sdl, Src, FIN,
6922         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6923         MaybeAlign(), MachineMemOperand::MOVolatile);
6924     setValue(&I, Res);
6925     DAG.setRoot(Res);
6926     return;
6927   }
6928   case Intrinsic::objectsize:
6929     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6930 
6931   case Intrinsic::is_constant:
6932     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6933 
6934   case Intrinsic::annotation:
6935   case Intrinsic::ptr_annotation:
6936   case Intrinsic::launder_invariant_group:
6937   case Intrinsic::strip_invariant_group:
6938     // Drop the intrinsic, but forward the value
6939     setValue(&I, getValue(I.getOperand(0)));
6940     return;
6941 
6942   case Intrinsic::assume:
6943   case Intrinsic::experimental_noalias_scope_decl:
6944   case Intrinsic::var_annotation:
6945   case Intrinsic::sideeffect:
6946     // Discard annotate attributes, noalias scope declarations, assumptions, and
6947     // artificial side-effects.
6948     return;
6949 
6950   case Intrinsic::codeview_annotation: {
6951     // Emit a label associated with this metadata.
6952     MachineFunction &MF = DAG.getMachineFunction();
6953     MCSymbol *Label =
6954         MF.getMMI().getContext().createTempSymbol("annotation", true);
6955     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6956     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6957     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6958     DAG.setRoot(Res);
6959     return;
6960   }
6961 
6962   case Intrinsic::init_trampoline: {
6963     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6964 
6965     SDValue Ops[6];
6966     Ops[0] = getRoot();
6967     Ops[1] = getValue(I.getArgOperand(0));
6968     Ops[2] = getValue(I.getArgOperand(1));
6969     Ops[3] = getValue(I.getArgOperand(2));
6970     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6971     Ops[5] = DAG.getSrcValue(F);
6972 
6973     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6974 
6975     DAG.setRoot(Res);
6976     return;
6977   }
6978   case Intrinsic::adjust_trampoline:
6979     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6980                              TLI.getPointerTy(DAG.getDataLayout()),
6981                              getValue(I.getArgOperand(0))));
6982     return;
6983   case Intrinsic::gcroot: {
6984     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6985            "only valid in functions with gc specified, enforced by Verifier");
6986     assert(GFI && "implied by previous");
6987     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6988     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6989 
6990     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6991     GFI->addStackRoot(FI->getIndex(), TypeMap);
6992     return;
6993   }
6994   case Intrinsic::gcread:
6995   case Intrinsic::gcwrite:
6996     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6997   case Intrinsic::get_rounding:
6998     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6999     setValue(&I, Res);
7000     DAG.setRoot(Res.getValue(1));
7001     return;
7002 
7003   case Intrinsic::expect:
7004     // Just replace __builtin_expect(exp, c) with EXP.
7005     setValue(&I, getValue(I.getArgOperand(0)));
7006     return;
7007 
7008   case Intrinsic::ubsantrap:
7009   case Intrinsic::debugtrap:
7010   case Intrinsic::trap: {
7011     StringRef TrapFuncName =
7012         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7013     if (TrapFuncName.empty()) {
7014       switch (Intrinsic) {
7015       case Intrinsic::trap:
7016         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7017         break;
7018       case Intrinsic::debugtrap:
7019         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7020         break;
7021       case Intrinsic::ubsantrap:
7022         DAG.setRoot(DAG.getNode(
7023             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7024             DAG.getTargetConstant(
7025                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7026                 MVT::i32)));
7027         break;
7028       default: llvm_unreachable("unknown trap intrinsic");
7029       }
7030       return;
7031     }
7032     TargetLowering::ArgListTy Args;
7033     if (Intrinsic == Intrinsic::ubsantrap) {
7034       Args.push_back(TargetLoweringBase::ArgListEntry());
7035       Args[0].Val = I.getArgOperand(0);
7036       Args[0].Node = getValue(Args[0].Val);
7037       Args[0].Ty = Args[0].Val->getType();
7038     }
7039 
7040     TargetLowering::CallLoweringInfo CLI(DAG);
7041     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7042         CallingConv::C, I.getType(),
7043         DAG.getExternalSymbol(TrapFuncName.data(),
7044                               TLI.getPointerTy(DAG.getDataLayout())),
7045         std::move(Args));
7046 
7047     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7048     DAG.setRoot(Result.second);
7049     return;
7050   }
7051 
7052   case Intrinsic::uadd_with_overflow:
7053   case Intrinsic::sadd_with_overflow:
7054   case Intrinsic::usub_with_overflow:
7055   case Intrinsic::ssub_with_overflow:
7056   case Intrinsic::umul_with_overflow:
7057   case Intrinsic::smul_with_overflow: {
7058     ISD::NodeType Op;
7059     switch (Intrinsic) {
7060     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7061     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7062     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7063     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7064     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7065     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7066     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7067     }
7068     SDValue Op1 = getValue(I.getArgOperand(0));
7069     SDValue Op2 = getValue(I.getArgOperand(1));
7070 
7071     EVT ResultVT = Op1.getValueType();
7072     EVT OverflowVT = MVT::i1;
7073     if (ResultVT.isVector())
7074       OverflowVT = EVT::getVectorVT(
7075           *Context, OverflowVT, ResultVT.getVectorElementCount());
7076 
7077     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7078     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7079     return;
7080   }
7081   case Intrinsic::prefetch: {
7082     SDValue Ops[5];
7083     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7084     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7085     Ops[0] = DAG.getRoot();
7086     Ops[1] = getValue(I.getArgOperand(0));
7087     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7088                                    MVT::i32);
7089     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7090                                    MVT::i32);
7091     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7092                                    MVT::i32);
7093     SDValue Result = DAG.getMemIntrinsicNode(
7094         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7095         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7096         /* align */ std::nullopt, Flags);
7097 
7098     // Chain the prefetch in parallell with any pending loads, to stay out of
7099     // the way of later optimizations.
7100     PendingLoads.push_back(Result);
7101     Result = getRoot();
7102     DAG.setRoot(Result);
7103     return;
7104   }
7105   case Intrinsic::lifetime_start:
7106   case Intrinsic::lifetime_end: {
7107     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7108     // Stack coloring is not enabled in O0, discard region information.
7109     if (TM.getOptLevel() == CodeGenOptLevel::None)
7110       return;
7111 
7112     const int64_t ObjectSize =
7113         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7114     Value *const ObjectPtr = I.getArgOperand(1);
7115     SmallVector<const Value *, 4> Allocas;
7116     getUnderlyingObjects(ObjectPtr, Allocas);
7117 
7118     for (const Value *Alloca : Allocas) {
7119       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7120 
7121       // Could not find an Alloca.
7122       if (!LifetimeObject)
7123         continue;
7124 
7125       // First check that the Alloca is static, otherwise it won't have a
7126       // valid frame index.
7127       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7128       if (SI == FuncInfo.StaticAllocaMap.end())
7129         return;
7130 
7131       const int FrameIndex = SI->second;
7132       int64_t Offset;
7133       if (GetPointerBaseWithConstantOffset(
7134               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7135         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7136       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7137                                 Offset);
7138       DAG.setRoot(Res);
7139     }
7140     return;
7141   }
7142   case Intrinsic::pseudoprobe: {
7143     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7144     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7145     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7146     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7147     DAG.setRoot(Res);
7148     return;
7149   }
7150   case Intrinsic::invariant_start:
7151     // Discard region information.
7152     setValue(&I,
7153              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7154     return;
7155   case Intrinsic::invariant_end:
7156     // Discard region information.
7157     return;
7158   case Intrinsic::clear_cache:
7159     /// FunctionName may be null.
7160     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7161       lowerCallToExternalSymbol(I, FunctionName);
7162     return;
7163   case Intrinsic::donothing:
7164   case Intrinsic::seh_try_begin:
7165   case Intrinsic::seh_scope_begin:
7166   case Intrinsic::seh_try_end:
7167   case Intrinsic::seh_scope_end:
7168     // ignore
7169     return;
7170   case Intrinsic::experimental_stackmap:
7171     visitStackmap(I);
7172     return;
7173   case Intrinsic::experimental_patchpoint_void:
7174   case Intrinsic::experimental_patchpoint_i64:
7175     visitPatchpoint(I);
7176     return;
7177   case Intrinsic::experimental_gc_statepoint:
7178     LowerStatepoint(cast<GCStatepointInst>(I));
7179     return;
7180   case Intrinsic::experimental_gc_result:
7181     visitGCResult(cast<GCResultInst>(I));
7182     return;
7183   case Intrinsic::experimental_gc_relocate:
7184     visitGCRelocate(cast<GCRelocateInst>(I));
7185     return;
7186   case Intrinsic::instrprof_cover:
7187     llvm_unreachable("instrprof failed to lower a cover");
7188   case Intrinsic::instrprof_increment:
7189     llvm_unreachable("instrprof failed to lower an increment");
7190   case Intrinsic::instrprof_timestamp:
7191     llvm_unreachable("instrprof failed to lower a timestamp");
7192   case Intrinsic::instrprof_value_profile:
7193     llvm_unreachable("instrprof failed to lower a value profiling call");
7194   case Intrinsic::localescape: {
7195     MachineFunction &MF = DAG.getMachineFunction();
7196     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7197 
7198     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7199     // is the same on all targets.
7200     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7201       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7202       if (isa<ConstantPointerNull>(Arg))
7203         continue; // Skip null pointers. They represent a hole in index space.
7204       AllocaInst *Slot = cast<AllocaInst>(Arg);
7205       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7206              "can only escape static allocas");
7207       int FI = FuncInfo.StaticAllocaMap[Slot];
7208       MCSymbol *FrameAllocSym =
7209           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7210               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7211       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7212               TII->get(TargetOpcode::LOCAL_ESCAPE))
7213           .addSym(FrameAllocSym)
7214           .addFrameIndex(FI);
7215     }
7216 
7217     return;
7218   }
7219 
7220   case Intrinsic::localrecover: {
7221     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7222     MachineFunction &MF = DAG.getMachineFunction();
7223 
7224     // Get the symbol that defines the frame offset.
7225     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7226     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7227     unsigned IdxVal =
7228         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7229     MCSymbol *FrameAllocSym =
7230         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7231             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7232 
7233     Value *FP = I.getArgOperand(1);
7234     SDValue FPVal = getValue(FP);
7235     EVT PtrVT = FPVal.getValueType();
7236 
7237     // Create a MCSymbol for the label to avoid any target lowering
7238     // that would make this PC relative.
7239     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7240     SDValue OffsetVal =
7241         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7242 
7243     // Add the offset to the FP.
7244     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7245     setValue(&I, Add);
7246 
7247     return;
7248   }
7249 
7250   case Intrinsic::eh_exceptionpointer:
7251   case Intrinsic::eh_exceptioncode: {
7252     // Get the exception pointer vreg, copy from it, and resize it to fit.
7253     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7254     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7255     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7256     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7257     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7258     if (Intrinsic == Intrinsic::eh_exceptioncode)
7259       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7260     setValue(&I, N);
7261     return;
7262   }
7263   case Intrinsic::xray_customevent: {
7264     // Here we want to make sure that the intrinsic behaves as if it has a
7265     // specific calling convention.
7266     const auto &Triple = DAG.getTarget().getTargetTriple();
7267     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7268       return;
7269 
7270     SmallVector<SDValue, 8> Ops;
7271 
7272     // We want to say that we always want the arguments in registers.
7273     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7274     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7275     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7276     SDValue Chain = getRoot();
7277     Ops.push_back(LogEntryVal);
7278     Ops.push_back(StrSizeVal);
7279     Ops.push_back(Chain);
7280 
7281     // We need to enforce the calling convention for the callsite, so that
7282     // argument ordering is enforced correctly, and that register allocation can
7283     // see that some registers may be assumed clobbered and have to preserve
7284     // them across calls to the intrinsic.
7285     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7286                                            sdl, NodeTys, Ops);
7287     SDValue patchableNode = SDValue(MN, 0);
7288     DAG.setRoot(patchableNode);
7289     setValue(&I, patchableNode);
7290     return;
7291   }
7292   case Intrinsic::xray_typedevent: {
7293     // Here we want to make sure that the intrinsic behaves as if it has a
7294     // specific calling convention.
7295     const auto &Triple = DAG.getTarget().getTargetTriple();
7296     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7297       return;
7298 
7299     SmallVector<SDValue, 8> Ops;
7300 
7301     // We want to say that we always want the arguments in registers.
7302     // It's unclear to me how manipulating the selection DAG here forces callers
7303     // to provide arguments in registers instead of on the stack.
7304     SDValue LogTypeId = getValue(I.getArgOperand(0));
7305     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7306     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7307     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7308     SDValue Chain = getRoot();
7309     Ops.push_back(LogTypeId);
7310     Ops.push_back(LogEntryVal);
7311     Ops.push_back(StrSizeVal);
7312     Ops.push_back(Chain);
7313 
7314     // We need to enforce the calling convention for the callsite, so that
7315     // argument ordering is enforced correctly, and that register allocation can
7316     // see that some registers may be assumed clobbered and have to preserve
7317     // them across calls to the intrinsic.
7318     MachineSDNode *MN = DAG.getMachineNode(
7319         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7320     SDValue patchableNode = SDValue(MN, 0);
7321     DAG.setRoot(patchableNode);
7322     setValue(&I, patchableNode);
7323     return;
7324   }
7325   case Intrinsic::experimental_deoptimize:
7326     LowerDeoptimizeCall(&I);
7327     return;
7328   case Intrinsic::experimental_stepvector:
7329     visitStepVector(I);
7330     return;
7331   case Intrinsic::vector_reduce_fadd:
7332   case Intrinsic::vector_reduce_fmul:
7333   case Intrinsic::vector_reduce_add:
7334   case Intrinsic::vector_reduce_mul:
7335   case Intrinsic::vector_reduce_and:
7336   case Intrinsic::vector_reduce_or:
7337   case Intrinsic::vector_reduce_xor:
7338   case Intrinsic::vector_reduce_smax:
7339   case Intrinsic::vector_reduce_smin:
7340   case Intrinsic::vector_reduce_umax:
7341   case Intrinsic::vector_reduce_umin:
7342   case Intrinsic::vector_reduce_fmax:
7343   case Intrinsic::vector_reduce_fmin:
7344   case Intrinsic::vector_reduce_fmaximum:
7345   case Intrinsic::vector_reduce_fminimum:
7346     visitVectorReduce(I, Intrinsic);
7347     return;
7348 
7349   case Intrinsic::icall_branch_funnel: {
7350     SmallVector<SDValue, 16> Ops;
7351     Ops.push_back(getValue(I.getArgOperand(0)));
7352 
7353     int64_t Offset;
7354     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7355         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7356     if (!Base)
7357       report_fatal_error(
7358           "llvm.icall.branch.funnel operand must be a GlobalValue");
7359     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7360 
7361     struct BranchFunnelTarget {
7362       int64_t Offset;
7363       SDValue Target;
7364     };
7365     SmallVector<BranchFunnelTarget, 8> Targets;
7366 
7367     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7368       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7369           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7370       if (ElemBase != Base)
7371         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7372                            "to the same GlobalValue");
7373 
7374       SDValue Val = getValue(I.getArgOperand(Op + 1));
7375       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7376       if (!GA)
7377         report_fatal_error(
7378             "llvm.icall.branch.funnel operand must be a GlobalValue");
7379       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7380                                      GA->getGlobal(), sdl, Val.getValueType(),
7381                                      GA->getOffset())});
7382     }
7383     llvm::sort(Targets,
7384                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7385                  return T1.Offset < T2.Offset;
7386                });
7387 
7388     for (auto &T : Targets) {
7389       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7390       Ops.push_back(T.Target);
7391     }
7392 
7393     Ops.push_back(DAG.getRoot()); // Chain
7394     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7395                                  MVT::Other, Ops),
7396               0);
7397     DAG.setRoot(N);
7398     setValue(&I, N);
7399     HasTailCall = true;
7400     return;
7401   }
7402 
7403   case Intrinsic::wasm_landingpad_index:
7404     // Information this intrinsic contained has been transferred to
7405     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7406     // delete it now.
7407     return;
7408 
7409   case Intrinsic::aarch64_settag:
7410   case Intrinsic::aarch64_settag_zero: {
7411     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7412     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7413     SDValue Val = TSI.EmitTargetCodeForSetTag(
7414         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7415         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7416         ZeroMemory);
7417     DAG.setRoot(Val);
7418     setValue(&I, Val);
7419     return;
7420   }
7421   case Intrinsic::ptrmask: {
7422     SDValue Ptr = getValue(I.getOperand(0));
7423     SDValue Const = getValue(I.getOperand(1));
7424 
7425     EVT PtrVT = Ptr.getValueType();
7426     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7427                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7428     return;
7429   }
7430   case Intrinsic::threadlocal_address: {
7431     setValue(&I, getValue(I.getOperand(0)));
7432     return;
7433   }
7434   case Intrinsic::get_active_lane_mask: {
7435     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7436     SDValue Index = getValue(I.getOperand(0));
7437     EVT ElementVT = Index.getValueType();
7438 
7439     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7440       visitTargetIntrinsic(I, Intrinsic);
7441       return;
7442     }
7443 
7444     SDValue TripCount = getValue(I.getOperand(1));
7445     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7446                                  CCVT.getVectorElementCount());
7447 
7448     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7449     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7450     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7451     SDValue VectorInduction = DAG.getNode(
7452         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7453     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7454                                  VectorTripCount, ISD::CondCode::SETULT);
7455     setValue(&I, SetCC);
7456     return;
7457   }
7458   case Intrinsic::experimental_get_vector_length: {
7459     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7460            "Expected positive VF");
7461     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7462     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7463 
7464     SDValue Count = getValue(I.getOperand(0));
7465     EVT CountVT = Count.getValueType();
7466 
7467     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7468       visitTargetIntrinsic(I, Intrinsic);
7469       return;
7470     }
7471 
7472     // Expand to a umin between the trip count and the maximum elements the type
7473     // can hold.
7474     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7475 
7476     // Extend the trip count to at least the result VT.
7477     if (CountVT.bitsLT(VT)) {
7478       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7479       CountVT = VT;
7480     }
7481 
7482     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7483                                          ElementCount::get(VF, IsScalable));
7484 
7485     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7486     // Clip to the result type if needed.
7487     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7488 
7489     setValue(&I, Trunc);
7490     return;
7491   }
7492   case Intrinsic::vector_insert: {
7493     SDValue Vec = getValue(I.getOperand(0));
7494     SDValue SubVec = getValue(I.getOperand(1));
7495     SDValue Index = getValue(I.getOperand(2));
7496 
7497     // The intrinsic's index type is i64, but the SDNode requires an index type
7498     // suitable for the target. Convert the index as required.
7499     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7500     if (Index.getValueType() != VectorIdxTy)
7501       Index = DAG.getVectorIdxConstant(
7502           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7503 
7504     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7505     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7506                              Index));
7507     return;
7508   }
7509   case Intrinsic::vector_extract: {
7510     SDValue Vec = getValue(I.getOperand(0));
7511     SDValue Index = getValue(I.getOperand(1));
7512     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7513 
7514     // The intrinsic's index type is i64, but the SDNode requires an index type
7515     // suitable for the target. Convert the index as required.
7516     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7517     if (Index.getValueType() != VectorIdxTy)
7518       Index = DAG.getVectorIdxConstant(
7519           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7520 
7521     setValue(&I,
7522              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7523     return;
7524   }
7525   case Intrinsic::experimental_vector_reverse:
7526     visitVectorReverse(I);
7527     return;
7528   case Intrinsic::experimental_vector_splice:
7529     visitVectorSplice(I);
7530     return;
7531   case Intrinsic::callbr_landingpad:
7532     visitCallBrLandingPad(I);
7533     return;
7534   case Intrinsic::experimental_vector_interleave2:
7535     visitVectorInterleave(I);
7536     return;
7537   case Intrinsic::experimental_vector_deinterleave2:
7538     visitVectorDeinterleave(I);
7539     return;
7540   }
7541 }
7542 
7543 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7544     const ConstrainedFPIntrinsic &FPI) {
7545   SDLoc sdl = getCurSDLoc();
7546 
7547   // We do not need to serialize constrained FP intrinsics against
7548   // each other or against (nonvolatile) loads, so they can be
7549   // chained like loads.
7550   SDValue Chain = DAG.getRoot();
7551   SmallVector<SDValue, 4> Opers;
7552   Opers.push_back(Chain);
7553   if (FPI.isUnaryOp()) {
7554     Opers.push_back(getValue(FPI.getArgOperand(0)));
7555   } else if (FPI.isTernaryOp()) {
7556     Opers.push_back(getValue(FPI.getArgOperand(0)));
7557     Opers.push_back(getValue(FPI.getArgOperand(1)));
7558     Opers.push_back(getValue(FPI.getArgOperand(2)));
7559   } else {
7560     Opers.push_back(getValue(FPI.getArgOperand(0)));
7561     Opers.push_back(getValue(FPI.getArgOperand(1)));
7562   }
7563 
7564   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7565     assert(Result.getNode()->getNumValues() == 2);
7566 
7567     // Push node to the appropriate list so that future instructions can be
7568     // chained up correctly.
7569     SDValue OutChain = Result.getValue(1);
7570     switch (EB) {
7571     case fp::ExceptionBehavior::ebIgnore:
7572       // The only reason why ebIgnore nodes still need to be chained is that
7573       // they might depend on the current rounding mode, and therefore must
7574       // not be moved across instruction that may change that mode.
7575       [[fallthrough]];
7576     case fp::ExceptionBehavior::ebMayTrap:
7577       // These must not be moved across calls or instructions that may change
7578       // floating-point exception masks.
7579       PendingConstrainedFP.push_back(OutChain);
7580       break;
7581     case fp::ExceptionBehavior::ebStrict:
7582       // These must not be moved across calls or instructions that may change
7583       // floating-point exception masks or read floating-point exception flags.
7584       // In addition, they cannot be optimized out even if unused.
7585       PendingConstrainedFPStrict.push_back(OutChain);
7586       break;
7587     }
7588   };
7589 
7590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7591   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7592   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7593   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7594 
7595   SDNodeFlags Flags;
7596   if (EB == fp::ExceptionBehavior::ebIgnore)
7597     Flags.setNoFPExcept(true);
7598 
7599   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7600     Flags.copyFMF(*FPOp);
7601 
7602   unsigned Opcode;
7603   switch (FPI.getIntrinsicID()) {
7604   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7605 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7606   case Intrinsic::INTRINSIC:                                                   \
7607     Opcode = ISD::STRICT_##DAGN;                                               \
7608     break;
7609 #include "llvm/IR/ConstrainedOps.def"
7610   case Intrinsic::experimental_constrained_fmuladd: {
7611     Opcode = ISD::STRICT_FMA;
7612     // Break fmuladd into fmul and fadd.
7613     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7614         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7615       Opers.pop_back();
7616       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7617       pushOutChain(Mul, EB);
7618       Opcode = ISD::STRICT_FADD;
7619       Opers.clear();
7620       Opers.push_back(Mul.getValue(1));
7621       Opers.push_back(Mul.getValue(0));
7622       Opers.push_back(getValue(FPI.getArgOperand(2)));
7623     }
7624     break;
7625   }
7626   }
7627 
7628   // A few strict DAG nodes carry additional operands that are not
7629   // set up by the default code above.
7630   switch (Opcode) {
7631   default: break;
7632   case ISD::STRICT_FP_ROUND:
7633     Opers.push_back(
7634         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7635     break;
7636   case ISD::STRICT_FSETCC:
7637   case ISD::STRICT_FSETCCS: {
7638     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7639     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7640     if (TM.Options.NoNaNsFPMath)
7641       Condition = getFCmpCodeWithoutNaN(Condition);
7642     Opers.push_back(DAG.getCondCode(Condition));
7643     break;
7644   }
7645   }
7646 
7647   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7648   pushOutChain(Result, EB);
7649 
7650   SDValue FPResult = Result.getValue(0);
7651   setValue(&FPI, FPResult);
7652 }
7653 
7654 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7655   std::optional<unsigned> ResOPC;
7656   switch (VPIntrin.getIntrinsicID()) {
7657   case Intrinsic::vp_ctlz: {
7658     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7659     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7660     break;
7661   }
7662   case Intrinsic::vp_cttz: {
7663     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
7664     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7665     break;
7666   }
7667 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7668   case Intrinsic::VPID:                                                        \
7669     ResOPC = ISD::VPSD;                                                        \
7670     break;
7671 #include "llvm/IR/VPIntrinsics.def"
7672   }
7673 
7674   if (!ResOPC)
7675     llvm_unreachable(
7676         "Inconsistency: no SDNode available for this VPIntrinsic!");
7677 
7678   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7679       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7680     if (VPIntrin.getFastMathFlags().allowReassoc())
7681       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7682                                                 : ISD::VP_REDUCE_FMUL;
7683   }
7684 
7685   return *ResOPC;
7686 }
7687 
7688 void SelectionDAGBuilder::visitVPLoad(
7689     const VPIntrinsic &VPIntrin, EVT VT,
7690     const SmallVectorImpl<SDValue> &OpValues) {
7691   SDLoc DL = getCurSDLoc();
7692   Value *PtrOperand = VPIntrin.getArgOperand(0);
7693   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7694   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7695   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7696   SDValue LD;
7697   // Do not serialize variable-length loads of constant memory with
7698   // anything.
7699   if (!Alignment)
7700     Alignment = DAG.getEVTAlign(VT);
7701   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7702   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7703   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7704   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7705       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7706       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7707   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7708                      MMO, false /*IsExpanding */);
7709   if (AddToChain)
7710     PendingLoads.push_back(LD.getValue(1));
7711   setValue(&VPIntrin, LD);
7712 }
7713 
7714 void SelectionDAGBuilder::visitVPGather(
7715     const VPIntrinsic &VPIntrin, EVT VT,
7716     const SmallVectorImpl<SDValue> &OpValues) {
7717   SDLoc DL = getCurSDLoc();
7718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7719   Value *PtrOperand = VPIntrin.getArgOperand(0);
7720   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7721   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7722   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7723   SDValue LD;
7724   if (!Alignment)
7725     Alignment = DAG.getEVTAlign(VT.getScalarType());
7726   unsigned AS =
7727     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7728   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7729      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7730      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7731   SDValue Base, Index, Scale;
7732   ISD::MemIndexType IndexType;
7733   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7734                                     this, VPIntrin.getParent(),
7735                                     VT.getScalarStoreSize());
7736   if (!UniformBase) {
7737     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7738     Index = getValue(PtrOperand);
7739     IndexType = ISD::SIGNED_SCALED;
7740     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7741   }
7742   EVT IdxVT = Index.getValueType();
7743   EVT EltTy = IdxVT.getVectorElementType();
7744   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7745     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7746     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7747   }
7748   LD = DAG.getGatherVP(
7749       DAG.getVTList(VT, MVT::Other), VT, DL,
7750       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7751       IndexType);
7752   PendingLoads.push_back(LD.getValue(1));
7753   setValue(&VPIntrin, LD);
7754 }
7755 
7756 void SelectionDAGBuilder::visitVPStore(
7757     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7758   SDLoc DL = getCurSDLoc();
7759   Value *PtrOperand = VPIntrin.getArgOperand(1);
7760   EVT VT = OpValues[0].getValueType();
7761   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7762   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7763   SDValue ST;
7764   if (!Alignment)
7765     Alignment = DAG.getEVTAlign(VT);
7766   SDValue Ptr = OpValues[1];
7767   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7768   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7769       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7770       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7771   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7772                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7773                       /* IsTruncating */ false, /*IsCompressing*/ false);
7774   DAG.setRoot(ST);
7775   setValue(&VPIntrin, ST);
7776 }
7777 
7778 void SelectionDAGBuilder::visitVPScatter(
7779     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7780   SDLoc DL = getCurSDLoc();
7781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7782   Value *PtrOperand = VPIntrin.getArgOperand(1);
7783   EVT VT = OpValues[0].getValueType();
7784   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7785   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7786   SDValue ST;
7787   if (!Alignment)
7788     Alignment = DAG.getEVTAlign(VT.getScalarType());
7789   unsigned AS =
7790       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7791   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7792       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7793       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7794   SDValue Base, Index, Scale;
7795   ISD::MemIndexType IndexType;
7796   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7797                                     this, VPIntrin.getParent(),
7798                                     VT.getScalarStoreSize());
7799   if (!UniformBase) {
7800     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7801     Index = getValue(PtrOperand);
7802     IndexType = ISD::SIGNED_SCALED;
7803     Scale =
7804       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7805   }
7806   EVT IdxVT = Index.getValueType();
7807   EVT EltTy = IdxVT.getVectorElementType();
7808   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7809     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7810     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7811   }
7812   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7813                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7814                          OpValues[2], OpValues[3]},
7815                         MMO, IndexType);
7816   DAG.setRoot(ST);
7817   setValue(&VPIntrin, ST);
7818 }
7819 
7820 void SelectionDAGBuilder::visitVPStridedLoad(
7821     const VPIntrinsic &VPIntrin, EVT VT,
7822     const SmallVectorImpl<SDValue> &OpValues) {
7823   SDLoc DL = getCurSDLoc();
7824   Value *PtrOperand = VPIntrin.getArgOperand(0);
7825   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7826   if (!Alignment)
7827     Alignment = DAG.getEVTAlign(VT.getScalarType());
7828   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7829   const MDNode *Ranges = getRangeMetadata(VPIntrin);
7830   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7831   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7832   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7833   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7834       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7835       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7836 
7837   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7838                                     OpValues[2], OpValues[3], MMO,
7839                                     false /*IsExpanding*/);
7840 
7841   if (AddToChain)
7842     PendingLoads.push_back(LD.getValue(1));
7843   setValue(&VPIntrin, LD);
7844 }
7845 
7846 void SelectionDAGBuilder::visitVPStridedStore(
7847     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
7848   SDLoc DL = getCurSDLoc();
7849   Value *PtrOperand = VPIntrin.getArgOperand(1);
7850   EVT VT = OpValues[0].getValueType();
7851   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7852   if (!Alignment)
7853     Alignment = DAG.getEVTAlign(VT.getScalarType());
7854   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7855   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7856       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7857       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7858 
7859   SDValue ST = DAG.getStridedStoreVP(
7860       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7861       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7862       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7863       /*IsCompressing*/ false);
7864 
7865   DAG.setRoot(ST);
7866   setValue(&VPIntrin, ST);
7867 }
7868 
7869 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7871   SDLoc DL = getCurSDLoc();
7872 
7873   ISD::CondCode Condition;
7874   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7875   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7876   if (IsFP) {
7877     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7878     // flags, but calls that don't return floating-point types can't be
7879     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7880     Condition = getFCmpCondCode(CondCode);
7881     if (TM.Options.NoNaNsFPMath)
7882       Condition = getFCmpCodeWithoutNaN(Condition);
7883   } else {
7884     Condition = getICmpCondCode(CondCode);
7885   }
7886 
7887   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7888   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7889   // #2 is the condition code
7890   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7891   SDValue EVL = getValue(VPIntrin.getOperand(4));
7892   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7893   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7894          "Unexpected target EVL type");
7895   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7896 
7897   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7898                                                         VPIntrin.getType());
7899   setValue(&VPIntrin,
7900            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7901 }
7902 
7903 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7904     const VPIntrinsic &VPIntrin) {
7905   SDLoc DL = getCurSDLoc();
7906   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7907 
7908   auto IID = VPIntrin.getIntrinsicID();
7909 
7910   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7911     return visitVPCmp(*CmpI);
7912 
7913   SmallVector<EVT, 4> ValueVTs;
7914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7915   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7916   SDVTList VTs = DAG.getVTList(ValueVTs);
7917 
7918   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7919 
7920   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7921   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7922          "Unexpected target EVL type");
7923 
7924   // Request operands.
7925   SmallVector<SDValue, 7> OpValues;
7926   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7927     auto Op = getValue(VPIntrin.getArgOperand(I));
7928     if (I == EVLParamPos)
7929       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7930     OpValues.push_back(Op);
7931   }
7932 
7933   switch (Opcode) {
7934   default: {
7935     SDNodeFlags SDFlags;
7936     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7937       SDFlags.copyFMF(*FPMO);
7938     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7939     setValue(&VPIntrin, Result);
7940     break;
7941   }
7942   case ISD::VP_LOAD:
7943     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7944     break;
7945   case ISD::VP_GATHER:
7946     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7947     break;
7948   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7949     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7950     break;
7951   case ISD::VP_STORE:
7952     visitVPStore(VPIntrin, OpValues);
7953     break;
7954   case ISD::VP_SCATTER:
7955     visitVPScatter(VPIntrin, OpValues);
7956     break;
7957   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7958     visitVPStridedStore(VPIntrin, OpValues);
7959     break;
7960   case ISD::VP_FMULADD: {
7961     assert(OpValues.size() == 5 && "Unexpected number of operands");
7962     SDNodeFlags SDFlags;
7963     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7964       SDFlags.copyFMF(*FPMO);
7965     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7966         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7967       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7968     } else {
7969       SDValue Mul = DAG.getNode(
7970           ISD::VP_FMUL, DL, VTs,
7971           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7972       SDValue Add =
7973           DAG.getNode(ISD::VP_FADD, DL, VTs,
7974                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7975       setValue(&VPIntrin, Add);
7976     }
7977     break;
7978   }
7979   case ISD::VP_IS_FPCLASS: {
7980     const DataLayout DLayout = DAG.getDataLayout();
7981     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
7982     auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue();
7983     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
7984     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
7985                             {OpValues[0], Check, OpValues[2], OpValues[3]});
7986     setValue(&VPIntrin, V);
7987     return;
7988   }
7989   case ISD::VP_INTTOPTR: {
7990     SDValue N = OpValues[0];
7991     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7992     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7993     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7994                                OpValues[2]);
7995     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7996                              OpValues[2]);
7997     setValue(&VPIntrin, N);
7998     break;
7999   }
8000   case ISD::VP_PTRTOINT: {
8001     SDValue N = OpValues[0];
8002     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8003                                                           VPIntrin.getType());
8004     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8005                                        VPIntrin.getOperand(0)->getType());
8006     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8007                                OpValues[2]);
8008     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8009                              OpValues[2]);
8010     setValue(&VPIntrin, N);
8011     break;
8012   }
8013   case ISD::VP_ABS:
8014   case ISD::VP_CTLZ:
8015   case ISD::VP_CTLZ_ZERO_UNDEF:
8016   case ISD::VP_CTTZ:
8017   case ISD::VP_CTTZ_ZERO_UNDEF: {
8018     SDValue Result =
8019         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8020     setValue(&VPIntrin, Result);
8021     break;
8022   }
8023   }
8024 }
8025 
8026 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8027                                           const BasicBlock *EHPadBB,
8028                                           MCSymbol *&BeginLabel) {
8029   MachineFunction &MF = DAG.getMachineFunction();
8030   MachineModuleInfo &MMI = MF.getMMI();
8031 
8032   // Insert a label before the invoke call to mark the try range.  This can be
8033   // used to detect deletion of the invoke via the MachineModuleInfo.
8034   BeginLabel = MMI.getContext().createTempSymbol();
8035 
8036   // For SjLj, keep track of which landing pads go with which invokes
8037   // so as to maintain the ordering of pads in the LSDA.
8038   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8039   if (CallSiteIndex) {
8040     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8041     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8042 
8043     // Now that the call site is handled, stop tracking it.
8044     MMI.setCurrentCallSite(0);
8045   }
8046 
8047   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8048 }
8049 
8050 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8051                                         const BasicBlock *EHPadBB,
8052                                         MCSymbol *BeginLabel) {
8053   assert(BeginLabel && "BeginLabel should've been set");
8054 
8055   MachineFunction &MF = DAG.getMachineFunction();
8056   MachineModuleInfo &MMI = MF.getMMI();
8057 
8058   // Insert a label at the end of the invoke call to mark the try range.  This
8059   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8060   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8061   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8062 
8063   // Inform MachineModuleInfo of range.
8064   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8065   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8066   // actually use outlined funclets and their LSDA info style.
8067   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8068     assert(II && "II should've been set");
8069     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8070     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8071   } else if (!isScopedEHPersonality(Pers)) {
8072     assert(EHPadBB);
8073     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8074   }
8075 
8076   return Chain;
8077 }
8078 
8079 std::pair<SDValue, SDValue>
8080 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8081                                     const BasicBlock *EHPadBB) {
8082   MCSymbol *BeginLabel = nullptr;
8083 
8084   if (EHPadBB) {
8085     // Both PendingLoads and PendingExports must be flushed here;
8086     // this call might not return.
8087     (void)getRoot();
8088     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8089     CLI.setChain(getRoot());
8090   }
8091 
8092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8093   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8094 
8095   assert((CLI.IsTailCall || Result.second.getNode()) &&
8096          "Non-null chain expected with non-tail call!");
8097   assert((Result.second.getNode() || !Result.first.getNode()) &&
8098          "Null value expected with tail call!");
8099 
8100   if (!Result.second.getNode()) {
8101     // As a special case, a null chain means that a tail call has been emitted
8102     // and the DAG root is already updated.
8103     HasTailCall = true;
8104 
8105     // Since there's no actual continuation from this block, nothing can be
8106     // relying on us setting vregs for them.
8107     PendingExports.clear();
8108   } else {
8109     DAG.setRoot(Result.second);
8110   }
8111 
8112   if (EHPadBB) {
8113     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8114                            BeginLabel));
8115   }
8116 
8117   return Result;
8118 }
8119 
8120 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8121                                       bool isTailCall,
8122                                       bool isMustTailCall,
8123                                       const BasicBlock *EHPadBB) {
8124   auto &DL = DAG.getDataLayout();
8125   FunctionType *FTy = CB.getFunctionType();
8126   Type *RetTy = CB.getType();
8127 
8128   TargetLowering::ArgListTy Args;
8129   Args.reserve(CB.arg_size());
8130 
8131   const Value *SwiftErrorVal = nullptr;
8132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8133 
8134   if (isTailCall) {
8135     // Avoid emitting tail calls in functions with the disable-tail-calls
8136     // attribute.
8137     auto *Caller = CB.getParent()->getParent();
8138     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8139         "true" && !isMustTailCall)
8140       isTailCall = false;
8141 
8142     // We can't tail call inside a function with a swifterror argument. Lowering
8143     // does not support this yet. It would have to move into the swifterror
8144     // register before the call.
8145     if (TLI.supportSwiftError() &&
8146         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8147       isTailCall = false;
8148   }
8149 
8150   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8151     TargetLowering::ArgListEntry Entry;
8152     const Value *V = *I;
8153 
8154     // Skip empty types
8155     if (V->getType()->isEmptyTy())
8156       continue;
8157 
8158     SDValue ArgNode = getValue(V);
8159     Entry.Node = ArgNode; Entry.Ty = V->getType();
8160 
8161     Entry.setAttributes(&CB, I - CB.arg_begin());
8162 
8163     // Use swifterror virtual register as input to the call.
8164     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8165       SwiftErrorVal = V;
8166       // We find the virtual register for the actual swifterror argument.
8167       // Instead of using the Value, we use the virtual register instead.
8168       Entry.Node =
8169           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8170                           EVT(TLI.getPointerTy(DL)));
8171     }
8172 
8173     Args.push_back(Entry);
8174 
8175     // If we have an explicit sret argument that is an Instruction, (i.e., it
8176     // might point to function-local memory), we can't meaningfully tail-call.
8177     if (Entry.IsSRet && isa<Instruction>(V))
8178       isTailCall = false;
8179   }
8180 
8181   // If call site has a cfguardtarget operand bundle, create and add an
8182   // additional ArgListEntry.
8183   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8184     TargetLowering::ArgListEntry Entry;
8185     Value *V = Bundle->Inputs[0];
8186     SDValue ArgNode = getValue(V);
8187     Entry.Node = ArgNode;
8188     Entry.Ty = V->getType();
8189     Entry.IsCFGuardTarget = true;
8190     Args.push_back(Entry);
8191   }
8192 
8193   // Check if target-independent constraints permit a tail call here.
8194   // Target-dependent constraints are checked within TLI->LowerCallTo.
8195   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8196     isTailCall = false;
8197 
8198   // Disable tail calls if there is an swifterror argument. Targets have not
8199   // been updated to support tail calls.
8200   if (TLI.supportSwiftError() && SwiftErrorVal)
8201     isTailCall = false;
8202 
8203   ConstantInt *CFIType = nullptr;
8204   if (CB.isIndirectCall()) {
8205     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8206       if (!TLI.supportKCFIBundles())
8207         report_fatal_error(
8208             "Target doesn't support calls with kcfi operand bundles.");
8209       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8210       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8211     }
8212   }
8213 
8214   TargetLowering::CallLoweringInfo CLI(DAG);
8215   CLI.setDebugLoc(getCurSDLoc())
8216       .setChain(getRoot())
8217       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8218       .setTailCall(isTailCall)
8219       .setConvergent(CB.isConvergent())
8220       .setIsPreallocated(
8221           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8222       .setCFIType(CFIType);
8223   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8224 
8225   if (Result.first.getNode()) {
8226     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8227     setValue(&CB, Result.first);
8228   }
8229 
8230   // The last element of CLI.InVals has the SDValue for swifterror return.
8231   // Here we copy it to a virtual register and update SwiftErrorMap for
8232   // book-keeping.
8233   if (SwiftErrorVal && TLI.supportSwiftError()) {
8234     // Get the last element of InVals.
8235     SDValue Src = CLI.InVals.back();
8236     Register VReg =
8237         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8238     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8239     DAG.setRoot(CopyNode);
8240   }
8241 }
8242 
8243 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8244                              SelectionDAGBuilder &Builder) {
8245   // Check to see if this load can be trivially constant folded, e.g. if the
8246   // input is from a string literal.
8247   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8248     // Cast pointer to the type we really want to load.
8249     Type *LoadTy =
8250         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8251     if (LoadVT.isVector())
8252       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8253 
8254     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8255                                          PointerType::getUnqual(LoadTy));
8256 
8257     if (const Constant *LoadCst =
8258             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8259                                          LoadTy, Builder.DAG.getDataLayout()))
8260       return Builder.getValue(LoadCst);
8261   }
8262 
8263   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8264   // still constant memory, the input chain can be the entry node.
8265   SDValue Root;
8266   bool ConstantMemory = false;
8267 
8268   // Do not serialize (non-volatile) loads of constant memory with anything.
8269   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8270     Root = Builder.DAG.getEntryNode();
8271     ConstantMemory = true;
8272   } else {
8273     // Do not serialize non-volatile loads against each other.
8274     Root = Builder.DAG.getRoot();
8275   }
8276 
8277   SDValue Ptr = Builder.getValue(PtrVal);
8278   SDValue LoadVal =
8279       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8280                           MachinePointerInfo(PtrVal), Align(1));
8281 
8282   if (!ConstantMemory)
8283     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8284   return LoadVal;
8285 }
8286 
8287 /// Record the value for an instruction that produces an integer result,
8288 /// converting the type where necessary.
8289 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8290                                                   SDValue Value,
8291                                                   bool IsSigned) {
8292   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8293                                                     I.getType(), true);
8294   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8295   setValue(&I, Value);
8296 }
8297 
8298 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8299 /// true and lower it. Otherwise return false, and it will be lowered like a
8300 /// normal call.
8301 /// The caller already checked that \p I calls the appropriate LibFunc with a
8302 /// correct prototype.
8303 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8304   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8305   const Value *Size = I.getArgOperand(2);
8306   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8307   if (CSize && CSize->getZExtValue() == 0) {
8308     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8309                                                           I.getType(), true);
8310     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8311     return true;
8312   }
8313 
8314   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8315   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8316       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8317       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8318   if (Res.first.getNode()) {
8319     processIntegerCallValue(I, Res.first, true);
8320     PendingLoads.push_back(Res.second);
8321     return true;
8322   }
8323 
8324   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8325   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8326   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8327     return false;
8328 
8329   // If the target has a fast compare for the given size, it will return a
8330   // preferred load type for that size. Require that the load VT is legal and
8331   // that the target supports unaligned loads of that type. Otherwise, return
8332   // INVALID.
8333   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8334     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8335     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8336     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8337       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8338       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8339       // TODO: Check alignment of src and dest ptrs.
8340       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8341       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8342       if (!TLI.isTypeLegal(LVT) ||
8343           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8344           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8345         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8346     }
8347 
8348     return LVT;
8349   };
8350 
8351   // This turns into unaligned loads. We only do this if the target natively
8352   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8353   // we'll only produce a small number of byte loads.
8354   MVT LoadVT;
8355   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8356   switch (NumBitsToCompare) {
8357   default:
8358     return false;
8359   case 16:
8360     LoadVT = MVT::i16;
8361     break;
8362   case 32:
8363     LoadVT = MVT::i32;
8364     break;
8365   case 64:
8366   case 128:
8367   case 256:
8368     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8369     break;
8370   }
8371 
8372   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8373     return false;
8374 
8375   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8376   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8377 
8378   // Bitcast to a wide integer type if the loads are vectors.
8379   if (LoadVT.isVector()) {
8380     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8381     LoadL = DAG.getBitcast(CmpVT, LoadL);
8382     LoadR = DAG.getBitcast(CmpVT, LoadR);
8383   }
8384 
8385   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8386   processIntegerCallValue(I, Cmp, false);
8387   return true;
8388 }
8389 
8390 /// See if we can lower a memchr call into an optimized form. If so, return
8391 /// true and lower it. Otherwise return false, and it will be lowered like a
8392 /// normal call.
8393 /// The caller already checked that \p I calls the appropriate LibFunc with a
8394 /// correct prototype.
8395 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8396   const Value *Src = I.getArgOperand(0);
8397   const Value *Char = I.getArgOperand(1);
8398   const Value *Length = I.getArgOperand(2);
8399 
8400   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8401   std::pair<SDValue, SDValue> Res =
8402     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8403                                 getValue(Src), getValue(Char), getValue(Length),
8404                                 MachinePointerInfo(Src));
8405   if (Res.first.getNode()) {
8406     setValue(&I, Res.first);
8407     PendingLoads.push_back(Res.second);
8408     return true;
8409   }
8410 
8411   return false;
8412 }
8413 
8414 /// See if we can lower a mempcpy call into an optimized form. If so, return
8415 /// true and lower it. Otherwise return false, and it will be lowered like a
8416 /// normal call.
8417 /// The caller already checked that \p I calls the appropriate LibFunc with a
8418 /// correct prototype.
8419 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8420   SDValue Dst = getValue(I.getArgOperand(0));
8421   SDValue Src = getValue(I.getArgOperand(1));
8422   SDValue Size = getValue(I.getArgOperand(2));
8423 
8424   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8425   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8426   // DAG::getMemcpy needs Alignment to be defined.
8427   Align Alignment = std::min(DstAlign, SrcAlign);
8428 
8429   SDLoc sdl = getCurSDLoc();
8430 
8431   // In the mempcpy context we need to pass in a false value for isTailCall
8432   // because the return pointer needs to be adjusted by the size of
8433   // the copied memory.
8434   SDValue Root = getMemoryRoot();
8435   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8436                              /*isTailCall=*/false,
8437                              MachinePointerInfo(I.getArgOperand(0)),
8438                              MachinePointerInfo(I.getArgOperand(1)),
8439                              I.getAAMetadata());
8440   assert(MC.getNode() != nullptr &&
8441          "** memcpy should not be lowered as TailCall in mempcpy context **");
8442   DAG.setRoot(MC);
8443 
8444   // Check if Size needs to be truncated or extended.
8445   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8446 
8447   // Adjust return pointer to point just past the last dst byte.
8448   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8449                                     Dst, Size);
8450   setValue(&I, DstPlusSize);
8451   return true;
8452 }
8453 
8454 /// See if we can lower a strcpy call into an optimized form.  If so, return
8455 /// true and lower it, otherwise return false and it will be lowered like a
8456 /// normal call.
8457 /// The caller already checked that \p I calls the appropriate LibFunc with a
8458 /// correct prototype.
8459 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8460   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8461 
8462   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8463   std::pair<SDValue, SDValue> Res =
8464     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8465                                 getValue(Arg0), getValue(Arg1),
8466                                 MachinePointerInfo(Arg0),
8467                                 MachinePointerInfo(Arg1), isStpcpy);
8468   if (Res.first.getNode()) {
8469     setValue(&I, Res.first);
8470     DAG.setRoot(Res.second);
8471     return true;
8472   }
8473 
8474   return false;
8475 }
8476 
8477 /// See if we can lower a strcmp call into an optimized form.  If so, return
8478 /// true and lower it, otherwise return false and it will be lowered like a
8479 /// normal call.
8480 /// The caller already checked that \p I calls the appropriate LibFunc with a
8481 /// correct prototype.
8482 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8483   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8484 
8485   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8486   std::pair<SDValue, SDValue> Res =
8487     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8488                                 getValue(Arg0), getValue(Arg1),
8489                                 MachinePointerInfo(Arg0),
8490                                 MachinePointerInfo(Arg1));
8491   if (Res.first.getNode()) {
8492     processIntegerCallValue(I, Res.first, true);
8493     PendingLoads.push_back(Res.second);
8494     return true;
8495   }
8496 
8497   return false;
8498 }
8499 
8500 /// See if we can lower a strlen call into an optimized form.  If so, return
8501 /// true and lower it, otherwise return false and it will be lowered like a
8502 /// normal call.
8503 /// The caller already checked that \p I calls the appropriate LibFunc with a
8504 /// correct prototype.
8505 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8506   const Value *Arg0 = I.getArgOperand(0);
8507 
8508   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8509   std::pair<SDValue, SDValue> Res =
8510     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8511                                 getValue(Arg0), MachinePointerInfo(Arg0));
8512   if (Res.first.getNode()) {
8513     processIntegerCallValue(I, Res.first, false);
8514     PendingLoads.push_back(Res.second);
8515     return true;
8516   }
8517 
8518   return false;
8519 }
8520 
8521 /// See if we can lower a strnlen call into an optimized form.  If so, return
8522 /// true and lower it, otherwise return false and it will be lowered like a
8523 /// normal call.
8524 /// The caller already checked that \p I calls the appropriate LibFunc with a
8525 /// correct prototype.
8526 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8527   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8528 
8529   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8530   std::pair<SDValue, SDValue> Res =
8531     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8532                                  getValue(Arg0), getValue(Arg1),
8533                                  MachinePointerInfo(Arg0));
8534   if (Res.first.getNode()) {
8535     processIntegerCallValue(I, Res.first, false);
8536     PendingLoads.push_back(Res.second);
8537     return true;
8538   }
8539 
8540   return false;
8541 }
8542 
8543 /// See if we can lower a unary floating-point operation into an SDNode with
8544 /// the specified Opcode.  If so, return true and lower it, otherwise return
8545 /// false and it will be lowered like a normal call.
8546 /// The caller already checked that \p I calls the appropriate LibFunc with a
8547 /// correct prototype.
8548 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8549                                               unsigned Opcode) {
8550   // We already checked this call's prototype; verify it doesn't modify errno.
8551   if (!I.onlyReadsMemory())
8552     return false;
8553 
8554   SDNodeFlags Flags;
8555   Flags.copyFMF(cast<FPMathOperator>(I));
8556 
8557   SDValue Tmp = getValue(I.getArgOperand(0));
8558   setValue(&I,
8559            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8560   return true;
8561 }
8562 
8563 /// See if we can lower a binary floating-point operation into an SDNode with
8564 /// the specified Opcode. If so, return true and lower it. Otherwise return
8565 /// false, and it will be lowered like a normal call.
8566 /// The caller already checked that \p I calls the appropriate LibFunc with a
8567 /// correct prototype.
8568 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8569                                                unsigned Opcode) {
8570   // We already checked this call's prototype; verify it doesn't modify errno.
8571   if (!I.onlyReadsMemory())
8572     return false;
8573 
8574   SDNodeFlags Flags;
8575   Flags.copyFMF(cast<FPMathOperator>(I));
8576 
8577   SDValue Tmp0 = getValue(I.getArgOperand(0));
8578   SDValue Tmp1 = getValue(I.getArgOperand(1));
8579   EVT VT = Tmp0.getValueType();
8580   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8581   return true;
8582 }
8583 
8584 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8585   // Handle inline assembly differently.
8586   if (I.isInlineAsm()) {
8587     visitInlineAsm(I);
8588     return;
8589   }
8590 
8591   diagnoseDontCall(I);
8592 
8593   if (Function *F = I.getCalledFunction()) {
8594     if (F->isDeclaration()) {
8595       // Is this an LLVM intrinsic or a target-specific intrinsic?
8596       unsigned IID = F->getIntrinsicID();
8597       if (!IID)
8598         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8599           IID = II->getIntrinsicID(F);
8600 
8601       if (IID) {
8602         visitIntrinsicCall(I, IID);
8603         return;
8604       }
8605     }
8606 
8607     // Check for well-known libc/libm calls.  If the function is internal, it
8608     // can't be a library call.  Don't do the check if marked as nobuiltin for
8609     // some reason or the call site requires strict floating point semantics.
8610     LibFunc Func;
8611     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8612         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8613         LibInfo->hasOptimizedCodeGen(Func)) {
8614       switch (Func) {
8615       default: break;
8616       case LibFunc_bcmp:
8617         if (visitMemCmpBCmpCall(I))
8618           return;
8619         break;
8620       case LibFunc_copysign:
8621       case LibFunc_copysignf:
8622       case LibFunc_copysignl:
8623         // We already checked this call's prototype; verify it doesn't modify
8624         // errno.
8625         if (I.onlyReadsMemory()) {
8626           SDValue LHS = getValue(I.getArgOperand(0));
8627           SDValue RHS = getValue(I.getArgOperand(1));
8628           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8629                                    LHS.getValueType(), LHS, RHS));
8630           return;
8631         }
8632         break;
8633       case LibFunc_fabs:
8634       case LibFunc_fabsf:
8635       case LibFunc_fabsl:
8636         if (visitUnaryFloatCall(I, ISD::FABS))
8637           return;
8638         break;
8639       case LibFunc_fmin:
8640       case LibFunc_fminf:
8641       case LibFunc_fminl:
8642         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8643           return;
8644         break;
8645       case LibFunc_fmax:
8646       case LibFunc_fmaxf:
8647       case LibFunc_fmaxl:
8648         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8649           return;
8650         break;
8651       case LibFunc_sin:
8652       case LibFunc_sinf:
8653       case LibFunc_sinl:
8654         if (visitUnaryFloatCall(I, ISD::FSIN))
8655           return;
8656         break;
8657       case LibFunc_cos:
8658       case LibFunc_cosf:
8659       case LibFunc_cosl:
8660         if (visitUnaryFloatCall(I, ISD::FCOS))
8661           return;
8662         break;
8663       case LibFunc_sqrt:
8664       case LibFunc_sqrtf:
8665       case LibFunc_sqrtl:
8666       case LibFunc_sqrt_finite:
8667       case LibFunc_sqrtf_finite:
8668       case LibFunc_sqrtl_finite:
8669         if (visitUnaryFloatCall(I, ISD::FSQRT))
8670           return;
8671         break;
8672       case LibFunc_floor:
8673       case LibFunc_floorf:
8674       case LibFunc_floorl:
8675         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8676           return;
8677         break;
8678       case LibFunc_nearbyint:
8679       case LibFunc_nearbyintf:
8680       case LibFunc_nearbyintl:
8681         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8682           return;
8683         break;
8684       case LibFunc_ceil:
8685       case LibFunc_ceilf:
8686       case LibFunc_ceill:
8687         if (visitUnaryFloatCall(I, ISD::FCEIL))
8688           return;
8689         break;
8690       case LibFunc_rint:
8691       case LibFunc_rintf:
8692       case LibFunc_rintl:
8693         if (visitUnaryFloatCall(I, ISD::FRINT))
8694           return;
8695         break;
8696       case LibFunc_round:
8697       case LibFunc_roundf:
8698       case LibFunc_roundl:
8699         if (visitUnaryFloatCall(I, ISD::FROUND))
8700           return;
8701         break;
8702       case LibFunc_trunc:
8703       case LibFunc_truncf:
8704       case LibFunc_truncl:
8705         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8706           return;
8707         break;
8708       case LibFunc_log2:
8709       case LibFunc_log2f:
8710       case LibFunc_log2l:
8711         if (visitUnaryFloatCall(I, ISD::FLOG2))
8712           return;
8713         break;
8714       case LibFunc_exp2:
8715       case LibFunc_exp2f:
8716       case LibFunc_exp2l:
8717         if (visitUnaryFloatCall(I, ISD::FEXP2))
8718           return;
8719         break;
8720       case LibFunc_exp10:
8721       case LibFunc_exp10f:
8722       case LibFunc_exp10l:
8723         if (visitUnaryFloatCall(I, ISD::FEXP10))
8724           return;
8725         break;
8726       case LibFunc_ldexp:
8727       case LibFunc_ldexpf:
8728       case LibFunc_ldexpl:
8729         if (visitBinaryFloatCall(I, ISD::FLDEXP))
8730           return;
8731         break;
8732       case LibFunc_memcmp:
8733         if (visitMemCmpBCmpCall(I))
8734           return;
8735         break;
8736       case LibFunc_mempcpy:
8737         if (visitMemPCpyCall(I))
8738           return;
8739         break;
8740       case LibFunc_memchr:
8741         if (visitMemChrCall(I))
8742           return;
8743         break;
8744       case LibFunc_strcpy:
8745         if (visitStrCpyCall(I, false))
8746           return;
8747         break;
8748       case LibFunc_stpcpy:
8749         if (visitStrCpyCall(I, true))
8750           return;
8751         break;
8752       case LibFunc_strcmp:
8753         if (visitStrCmpCall(I))
8754           return;
8755         break;
8756       case LibFunc_strlen:
8757         if (visitStrLenCall(I))
8758           return;
8759         break;
8760       case LibFunc_strnlen:
8761         if (visitStrNLenCall(I))
8762           return;
8763         break;
8764       }
8765     }
8766   }
8767 
8768   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8769   // have to do anything here to lower funclet bundles.
8770   // CFGuardTarget bundles are lowered in LowerCallTo.
8771   assert(!I.hasOperandBundlesOtherThan(
8772              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8773               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8774               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8775          "Cannot lower calls with arbitrary operand bundles!");
8776 
8777   SDValue Callee = getValue(I.getCalledOperand());
8778 
8779   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8780     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8781   else
8782     // Check if we can potentially perform a tail call. More detailed checking
8783     // is be done within LowerCallTo, after more information about the call is
8784     // known.
8785     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8786 }
8787 
8788 namespace {
8789 
8790 /// AsmOperandInfo - This contains information for each constraint that we are
8791 /// lowering.
8792 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8793 public:
8794   /// CallOperand - If this is the result output operand or a clobber
8795   /// this is null, otherwise it is the incoming operand to the CallInst.
8796   /// This gets modified as the asm is processed.
8797   SDValue CallOperand;
8798 
8799   /// AssignedRegs - If this is a register or register class operand, this
8800   /// contains the set of register corresponding to the operand.
8801   RegsForValue AssignedRegs;
8802 
8803   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8804     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8805   }
8806 
8807   /// Whether or not this operand accesses memory
8808   bool hasMemory(const TargetLowering &TLI) const {
8809     // Indirect operand accesses access memory.
8810     if (isIndirect)
8811       return true;
8812 
8813     for (const auto &Code : Codes)
8814       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8815         return true;
8816 
8817     return false;
8818   }
8819 };
8820 
8821 
8822 } // end anonymous namespace
8823 
8824 /// Make sure that the output operand \p OpInfo and its corresponding input
8825 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8826 /// out).
8827 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8828                                SDISelAsmOperandInfo &MatchingOpInfo,
8829                                SelectionDAG &DAG) {
8830   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8831     return;
8832 
8833   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8834   const auto &TLI = DAG.getTargetLoweringInfo();
8835 
8836   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8837       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8838                                        OpInfo.ConstraintVT);
8839   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8840       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8841                                        MatchingOpInfo.ConstraintVT);
8842   if ((OpInfo.ConstraintVT.isInteger() !=
8843        MatchingOpInfo.ConstraintVT.isInteger()) ||
8844       (MatchRC.second != InputRC.second)) {
8845     // FIXME: error out in a more elegant fashion
8846     report_fatal_error("Unsupported asm: input constraint"
8847                        " with a matching output constraint of"
8848                        " incompatible type!");
8849   }
8850   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8851 }
8852 
8853 /// Get a direct memory input to behave well as an indirect operand.
8854 /// This may introduce stores, hence the need for a \p Chain.
8855 /// \return The (possibly updated) chain.
8856 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8857                                         SDISelAsmOperandInfo &OpInfo,
8858                                         SelectionDAG &DAG) {
8859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8860 
8861   // If we don't have an indirect input, put it in the constpool if we can,
8862   // otherwise spill it to a stack slot.
8863   // TODO: This isn't quite right. We need to handle these according to
8864   // the addressing mode that the constraint wants. Also, this may take
8865   // an additional register for the computation and we don't want that
8866   // either.
8867 
8868   // If the operand is a float, integer, or vector constant, spill to a
8869   // constant pool entry to get its address.
8870   const Value *OpVal = OpInfo.CallOperandVal;
8871   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8872       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8873     OpInfo.CallOperand = DAG.getConstantPool(
8874         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8875     return Chain;
8876   }
8877 
8878   // Otherwise, create a stack slot and emit a store to it before the asm.
8879   Type *Ty = OpVal->getType();
8880   auto &DL = DAG.getDataLayout();
8881   uint64_t TySize = DL.getTypeAllocSize(Ty);
8882   MachineFunction &MF = DAG.getMachineFunction();
8883   int SSFI = MF.getFrameInfo().CreateStackObject(
8884       TySize, DL.getPrefTypeAlign(Ty), false);
8885   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8886   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8887                             MachinePointerInfo::getFixedStack(MF, SSFI),
8888                             TLI.getMemValueType(DL, Ty));
8889   OpInfo.CallOperand = StackSlot;
8890 
8891   return Chain;
8892 }
8893 
8894 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8895 /// specified operand.  We prefer to assign virtual registers, to allow the
8896 /// register allocator to handle the assignment process.  However, if the asm
8897 /// uses features that we can't model on machineinstrs, we have SDISel do the
8898 /// allocation.  This produces generally horrible, but correct, code.
8899 ///
8900 ///   OpInfo describes the operand
8901 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8902 static std::optional<unsigned>
8903 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8904                      SDISelAsmOperandInfo &OpInfo,
8905                      SDISelAsmOperandInfo &RefOpInfo) {
8906   LLVMContext &Context = *DAG.getContext();
8907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8908 
8909   MachineFunction &MF = DAG.getMachineFunction();
8910   SmallVector<unsigned, 4> Regs;
8911   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8912 
8913   // No work to do for memory/address operands.
8914   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8915       OpInfo.ConstraintType == TargetLowering::C_Address)
8916     return std::nullopt;
8917 
8918   // If this is a constraint for a single physreg, or a constraint for a
8919   // register class, find it.
8920   unsigned AssignedReg;
8921   const TargetRegisterClass *RC;
8922   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8923       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8924   // RC is unset only on failure. Return immediately.
8925   if (!RC)
8926     return std::nullopt;
8927 
8928   // Get the actual register value type.  This is important, because the user
8929   // may have asked for (e.g.) the AX register in i32 type.  We need to
8930   // remember that AX is actually i16 to get the right extension.
8931   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8932 
8933   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8934     // If this is an FP operand in an integer register (or visa versa), or more
8935     // generally if the operand value disagrees with the register class we plan
8936     // to stick it in, fix the operand type.
8937     //
8938     // If this is an input value, the bitcast to the new type is done now.
8939     // Bitcast for output value is done at the end of visitInlineAsm().
8940     if ((OpInfo.Type == InlineAsm::isOutput ||
8941          OpInfo.Type == InlineAsm::isInput) &&
8942         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8943       // Try to convert to the first EVT that the reg class contains.  If the
8944       // types are identical size, use a bitcast to convert (e.g. two differing
8945       // vector types).  Note: output bitcast is done at the end of
8946       // visitInlineAsm().
8947       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8948         // Exclude indirect inputs while they are unsupported because the code
8949         // to perform the load is missing and thus OpInfo.CallOperand still
8950         // refers to the input address rather than the pointed-to value.
8951         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8952           OpInfo.CallOperand =
8953               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8954         OpInfo.ConstraintVT = RegVT;
8955         // If the operand is an FP value and we want it in integer registers,
8956         // use the corresponding integer type. This turns an f64 value into
8957         // i64, which can be passed with two i32 values on a 32-bit machine.
8958       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8959         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8960         if (OpInfo.Type == InlineAsm::isInput)
8961           OpInfo.CallOperand =
8962               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8963         OpInfo.ConstraintVT = VT;
8964       }
8965     }
8966   }
8967 
8968   // No need to allocate a matching input constraint since the constraint it's
8969   // matching to has already been allocated.
8970   if (OpInfo.isMatchingInputConstraint())
8971     return std::nullopt;
8972 
8973   EVT ValueVT = OpInfo.ConstraintVT;
8974   if (OpInfo.ConstraintVT == MVT::Other)
8975     ValueVT = RegVT;
8976 
8977   // Initialize NumRegs.
8978   unsigned NumRegs = 1;
8979   if (OpInfo.ConstraintVT != MVT::Other)
8980     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8981 
8982   // If this is a constraint for a specific physical register, like {r17},
8983   // assign it now.
8984 
8985   // If this associated to a specific register, initialize iterator to correct
8986   // place. If virtual, make sure we have enough registers
8987 
8988   // Initialize iterator if necessary
8989   TargetRegisterClass::iterator I = RC->begin();
8990   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8991 
8992   // Do not check for single registers.
8993   if (AssignedReg) {
8994     I = std::find(I, RC->end(), AssignedReg);
8995     if (I == RC->end()) {
8996       // RC does not contain the selected register, which indicates a
8997       // mismatch between the register and the required type/bitwidth.
8998       return {AssignedReg};
8999     }
9000   }
9001 
9002   for (; NumRegs; --NumRegs, ++I) {
9003     assert(I != RC->end() && "Ran out of registers to allocate!");
9004     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9005     Regs.push_back(R);
9006   }
9007 
9008   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9009   return std::nullopt;
9010 }
9011 
9012 static unsigned
9013 findMatchingInlineAsmOperand(unsigned OperandNo,
9014                              const std::vector<SDValue> &AsmNodeOperands) {
9015   // Scan until we find the definition we already emitted of this operand.
9016   unsigned CurOp = InlineAsm::Op_FirstOperand;
9017   for (; OperandNo; --OperandNo) {
9018     // Advance to the next operand.
9019     unsigned OpFlag =
9020         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9021     const InlineAsm::Flag F(OpFlag);
9022     assert(
9023         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9024         "Skipped past definitions?");
9025     CurOp += F.getNumOperandRegisters() + 1;
9026   }
9027   return CurOp;
9028 }
9029 
9030 namespace {
9031 
9032 class ExtraFlags {
9033   unsigned Flags = 0;
9034 
9035 public:
9036   explicit ExtraFlags(const CallBase &Call) {
9037     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9038     if (IA->hasSideEffects())
9039       Flags |= InlineAsm::Extra_HasSideEffects;
9040     if (IA->isAlignStack())
9041       Flags |= InlineAsm::Extra_IsAlignStack;
9042     if (Call.isConvergent())
9043       Flags |= InlineAsm::Extra_IsConvergent;
9044     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9045   }
9046 
9047   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9048     // Ideally, we would only check against memory constraints.  However, the
9049     // meaning of an Other constraint can be target-specific and we can't easily
9050     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9051     // for Other constraints as well.
9052     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9053         OpInfo.ConstraintType == TargetLowering::C_Other) {
9054       if (OpInfo.Type == InlineAsm::isInput)
9055         Flags |= InlineAsm::Extra_MayLoad;
9056       else if (OpInfo.Type == InlineAsm::isOutput)
9057         Flags |= InlineAsm::Extra_MayStore;
9058       else if (OpInfo.Type == InlineAsm::isClobber)
9059         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9060     }
9061   }
9062 
9063   unsigned get() const { return Flags; }
9064 };
9065 
9066 } // end anonymous namespace
9067 
9068 static bool isFunction(SDValue Op) {
9069   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9070     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9071       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9072 
9073       // In normal "call dllimport func" instruction (non-inlineasm) it force
9074       // indirect access by specifing call opcode. And usually specially print
9075       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9076       // not do in this way now. (In fact, this is similar with "Data Access"
9077       // action). So here we ignore dllimport function.
9078       if (Fn && !Fn->hasDLLImportStorageClass())
9079         return true;
9080     }
9081   }
9082   return false;
9083 }
9084 
9085 /// visitInlineAsm - Handle a call to an InlineAsm object.
9086 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9087                                          const BasicBlock *EHPadBB) {
9088   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9089 
9090   /// ConstraintOperands - Information about all of the constraints.
9091   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9092 
9093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9094   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9095       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9096 
9097   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9098   // AsmDialect, MayLoad, MayStore).
9099   bool HasSideEffect = IA->hasSideEffects();
9100   ExtraFlags ExtraInfo(Call);
9101 
9102   for (auto &T : TargetConstraints) {
9103     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9104     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9105 
9106     if (OpInfo.CallOperandVal)
9107       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9108 
9109     if (!HasSideEffect)
9110       HasSideEffect = OpInfo.hasMemory(TLI);
9111 
9112     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9113     // FIXME: Could we compute this on OpInfo rather than T?
9114 
9115     // Compute the constraint code and ConstraintType to use.
9116     TLI.ComputeConstraintToUse(T, SDValue());
9117 
9118     if (T.ConstraintType == TargetLowering::C_Immediate &&
9119         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9120       // We've delayed emitting a diagnostic like the "n" constraint because
9121       // inlining could cause an integer showing up.
9122       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9123                                           "' expects an integer constant "
9124                                           "expression");
9125 
9126     ExtraInfo.update(T);
9127   }
9128 
9129   // We won't need to flush pending loads if this asm doesn't touch
9130   // memory and is nonvolatile.
9131   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9132 
9133   bool EmitEHLabels = isa<InvokeInst>(Call);
9134   if (EmitEHLabels) {
9135     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9136   }
9137   bool IsCallBr = isa<CallBrInst>(Call);
9138 
9139   if (IsCallBr || EmitEHLabels) {
9140     // If this is a callbr or invoke we need to flush pending exports since
9141     // inlineasm_br and invoke are terminators.
9142     // We need to do this before nodes are glued to the inlineasm_br node.
9143     Chain = getControlRoot();
9144   }
9145 
9146   MCSymbol *BeginLabel = nullptr;
9147   if (EmitEHLabels) {
9148     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9149   }
9150 
9151   int OpNo = -1;
9152   SmallVector<StringRef> AsmStrs;
9153   IA->collectAsmStrs(AsmStrs);
9154 
9155   // Second pass over the constraints: compute which constraint option to use.
9156   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9157     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9158       OpNo++;
9159 
9160     // If this is an output operand with a matching input operand, look up the
9161     // matching input. If their types mismatch, e.g. one is an integer, the
9162     // other is floating point, or their sizes are different, flag it as an
9163     // error.
9164     if (OpInfo.hasMatchingInput()) {
9165       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9166       patchMatchingInput(OpInfo, Input, DAG);
9167     }
9168 
9169     // Compute the constraint code and ConstraintType to use.
9170     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9171 
9172     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9173          OpInfo.Type == InlineAsm::isClobber) ||
9174         OpInfo.ConstraintType == TargetLowering::C_Address)
9175       continue;
9176 
9177     // In Linux PIC model, there are 4 cases about value/label addressing:
9178     //
9179     // 1: Function call or Label jmp inside the module.
9180     // 2: Data access (such as global variable, static variable) inside module.
9181     // 3: Function call or Label jmp outside the module.
9182     // 4: Data access (such as global variable) outside the module.
9183     //
9184     // Due to current llvm inline asm architecture designed to not "recognize"
9185     // the asm code, there are quite troubles for us to treat mem addressing
9186     // differently for same value/adress used in different instuctions.
9187     // For example, in pic model, call a func may in plt way or direclty
9188     // pc-related, but lea/mov a function adress may use got.
9189     //
9190     // Here we try to "recognize" function call for the case 1 and case 3 in
9191     // inline asm. And try to adjust the constraint for them.
9192     //
9193     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9194     // label, so here we don't handle jmp function label now, but we need to
9195     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9196     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9197         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9198         TM.getCodeModel() != CodeModel::Large) {
9199       OpInfo.isIndirect = false;
9200       OpInfo.ConstraintType = TargetLowering::C_Address;
9201     }
9202 
9203     // If this is a memory input, and if the operand is not indirect, do what we
9204     // need to provide an address for the memory input.
9205     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9206         !OpInfo.isIndirect) {
9207       assert((OpInfo.isMultipleAlternative ||
9208               (OpInfo.Type == InlineAsm::isInput)) &&
9209              "Can only indirectify direct input operands!");
9210 
9211       // Memory operands really want the address of the value.
9212       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9213 
9214       // There is no longer a Value* corresponding to this operand.
9215       OpInfo.CallOperandVal = nullptr;
9216 
9217       // It is now an indirect operand.
9218       OpInfo.isIndirect = true;
9219     }
9220 
9221   }
9222 
9223   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9224   std::vector<SDValue> AsmNodeOperands;
9225   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9226   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9227       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9228 
9229   // If we have a !srcloc metadata node associated with it, we want to attach
9230   // this to the ultimately generated inline asm machineinstr.  To do this, we
9231   // pass in the third operand as this (potentially null) inline asm MDNode.
9232   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9233   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9234 
9235   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9236   // bits as operand 3.
9237   AsmNodeOperands.push_back(DAG.getTargetConstant(
9238       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9239 
9240   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9241   // this, assign virtual and physical registers for inputs and otput.
9242   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9243     // Assign Registers.
9244     SDISelAsmOperandInfo &RefOpInfo =
9245         OpInfo.isMatchingInputConstraint()
9246             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9247             : OpInfo;
9248     const auto RegError =
9249         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9250     if (RegError) {
9251       const MachineFunction &MF = DAG.getMachineFunction();
9252       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9253       const char *RegName = TRI.getName(*RegError);
9254       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9255                                    "' allocated for constraint '" +
9256                                    Twine(OpInfo.ConstraintCode) +
9257                                    "' does not match required type");
9258       return;
9259     }
9260 
9261     auto DetectWriteToReservedRegister = [&]() {
9262       const MachineFunction &MF = DAG.getMachineFunction();
9263       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9264       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9265         if (Register::isPhysicalRegister(Reg) &&
9266             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9267           const char *RegName = TRI.getName(Reg);
9268           emitInlineAsmError(Call, "write to reserved register '" +
9269                                        Twine(RegName) + "'");
9270           return true;
9271         }
9272       }
9273       return false;
9274     };
9275     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9276             (OpInfo.Type == InlineAsm::isInput &&
9277              !OpInfo.isMatchingInputConstraint())) &&
9278            "Only address as input operand is allowed.");
9279 
9280     switch (OpInfo.Type) {
9281     case InlineAsm::isOutput:
9282       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9283         const InlineAsm::ConstraintCode ConstraintID =
9284             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9285         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9286                "Failed to convert memory constraint code to constraint id.");
9287 
9288         // Add information to the INLINEASM node to know about this output.
9289         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9290         OpFlags.setMemConstraint(ConstraintID);
9291         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9292                                                         MVT::i32));
9293         AsmNodeOperands.push_back(OpInfo.CallOperand);
9294       } else {
9295         // Otherwise, this outputs to a register (directly for C_Register /
9296         // C_RegisterClass, and a target-defined fashion for
9297         // C_Immediate/C_Other). Find a register that we can use.
9298         if (OpInfo.AssignedRegs.Regs.empty()) {
9299           emitInlineAsmError(
9300               Call, "couldn't allocate output register for constraint '" +
9301                         Twine(OpInfo.ConstraintCode) + "'");
9302           return;
9303         }
9304 
9305         if (DetectWriteToReservedRegister())
9306           return;
9307 
9308         // Add information to the INLINEASM node to know that this register is
9309         // set.
9310         OpInfo.AssignedRegs.AddInlineAsmOperands(
9311             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9312                                   : InlineAsm::Kind::RegDef,
9313             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9314       }
9315       break;
9316 
9317     case InlineAsm::isInput:
9318     case InlineAsm::isLabel: {
9319       SDValue InOperandVal = OpInfo.CallOperand;
9320 
9321       if (OpInfo.isMatchingInputConstraint()) {
9322         // If this is required to match an output register we have already set,
9323         // just use its register.
9324         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9325                                                   AsmNodeOperands);
9326         InlineAsm::Flag Flag(
9327             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue());
9328         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9329           if (OpInfo.isIndirect) {
9330             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9331             emitInlineAsmError(Call, "inline asm not supported yet: "
9332                                      "don't know how to handle tied "
9333                                      "indirect register inputs");
9334             return;
9335           }
9336 
9337           SmallVector<unsigned, 4> Regs;
9338           MachineFunction &MF = DAG.getMachineFunction();
9339           MachineRegisterInfo &MRI = MF.getRegInfo();
9340           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9341           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9342           Register TiedReg = R->getReg();
9343           MVT RegVT = R->getSimpleValueType(0);
9344           const TargetRegisterClass *RC =
9345               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9346               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9347                                       : TRI.getMinimalPhysRegClass(TiedReg);
9348           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9349             Regs.push_back(MRI.createVirtualRegister(RC));
9350 
9351           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9352 
9353           SDLoc dl = getCurSDLoc();
9354           // Use the produced MatchedRegs object to
9355           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9356           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9357                                            OpInfo.getMatchedOperand(), dl, DAG,
9358                                            AsmNodeOperands);
9359           break;
9360         }
9361 
9362         assert(Flag.isMemKind() && "Unknown matching constraint!");
9363         assert(Flag.getNumOperandRegisters() == 1 &&
9364                "Unexpected number of operands");
9365         // Add information to the INLINEASM node to know about this input.
9366         // See InlineAsm.h isUseOperandTiedToDef.
9367         Flag.clearMemConstraint();
9368         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9369         AsmNodeOperands.push_back(DAG.getTargetConstant(
9370             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9371         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9372         break;
9373       }
9374 
9375       // Treat indirect 'X' constraint as memory.
9376       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9377           OpInfo.isIndirect)
9378         OpInfo.ConstraintType = TargetLowering::C_Memory;
9379 
9380       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9381           OpInfo.ConstraintType == TargetLowering::C_Other) {
9382         std::vector<SDValue> Ops;
9383         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9384                                           Ops, DAG);
9385         if (Ops.empty()) {
9386           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9387             if (isa<ConstantSDNode>(InOperandVal)) {
9388               emitInlineAsmError(Call, "value out of range for constraint '" +
9389                                            Twine(OpInfo.ConstraintCode) + "'");
9390               return;
9391             }
9392 
9393           emitInlineAsmError(Call,
9394                              "invalid operand for inline asm constraint '" +
9395                                  Twine(OpInfo.ConstraintCode) + "'");
9396           return;
9397         }
9398 
9399         // Add information to the INLINEASM node to know about this input.
9400         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9401         AsmNodeOperands.push_back(DAG.getTargetConstant(
9402             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9403         llvm::append_range(AsmNodeOperands, Ops);
9404         break;
9405       }
9406 
9407       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9408         assert((OpInfo.isIndirect ||
9409                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9410                "Operand must be indirect to be a mem!");
9411         assert(InOperandVal.getValueType() ==
9412                    TLI.getPointerTy(DAG.getDataLayout()) &&
9413                "Memory operands expect pointer values");
9414 
9415         const InlineAsm::ConstraintCode ConstraintID =
9416             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9417         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9418                "Failed to convert memory constraint code to constraint id.");
9419 
9420         // Add information to the INLINEASM node to know about this input.
9421         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9422         ResOpType.setMemConstraint(ConstraintID);
9423         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9424                                                         getCurSDLoc(),
9425                                                         MVT::i32));
9426         AsmNodeOperands.push_back(InOperandVal);
9427         break;
9428       }
9429 
9430       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9431         const InlineAsm::ConstraintCode ConstraintID =
9432             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9433         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9434                "Failed to convert memory constraint code to constraint id.");
9435 
9436         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9437 
9438         SDValue AsmOp = InOperandVal;
9439         if (isFunction(InOperandVal)) {
9440           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9441           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9442           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9443                                              InOperandVal.getValueType(),
9444                                              GA->getOffset());
9445         }
9446 
9447         // Add information to the INLINEASM node to know about this input.
9448         ResOpType.setMemConstraint(ConstraintID);
9449 
9450         AsmNodeOperands.push_back(
9451             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9452 
9453         AsmNodeOperands.push_back(AsmOp);
9454         break;
9455       }
9456 
9457       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9458               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9459              "Unknown constraint type!");
9460 
9461       // TODO: Support this.
9462       if (OpInfo.isIndirect) {
9463         emitInlineAsmError(
9464             Call, "Don't know how to handle indirect register inputs yet "
9465                   "for constraint '" +
9466                       Twine(OpInfo.ConstraintCode) + "'");
9467         return;
9468       }
9469 
9470       // Copy the input into the appropriate registers.
9471       if (OpInfo.AssignedRegs.Regs.empty()) {
9472         emitInlineAsmError(Call,
9473                            "couldn't allocate input reg for constraint '" +
9474                                Twine(OpInfo.ConstraintCode) + "'");
9475         return;
9476       }
9477 
9478       if (DetectWriteToReservedRegister())
9479         return;
9480 
9481       SDLoc dl = getCurSDLoc();
9482 
9483       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9484                                         &Call);
9485 
9486       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9487                                                0, dl, DAG, AsmNodeOperands);
9488       break;
9489     }
9490     case InlineAsm::isClobber:
9491       // Add the clobbered value to the operand list, so that the register
9492       // allocator is aware that the physreg got clobbered.
9493       if (!OpInfo.AssignedRegs.Regs.empty())
9494         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9495                                                  false, 0, getCurSDLoc(), DAG,
9496                                                  AsmNodeOperands);
9497       break;
9498     }
9499   }
9500 
9501   // Finish up input operands.  Set the input chain and add the flag last.
9502   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9503   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9504 
9505   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9506   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9507                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9508   Glue = Chain.getValue(1);
9509 
9510   // Do additional work to generate outputs.
9511 
9512   SmallVector<EVT, 1> ResultVTs;
9513   SmallVector<SDValue, 1> ResultValues;
9514   SmallVector<SDValue, 8> OutChains;
9515 
9516   llvm::Type *CallResultType = Call.getType();
9517   ArrayRef<Type *> ResultTypes;
9518   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9519     ResultTypes = StructResult->elements();
9520   else if (!CallResultType->isVoidTy())
9521     ResultTypes = ArrayRef(CallResultType);
9522 
9523   auto CurResultType = ResultTypes.begin();
9524   auto handleRegAssign = [&](SDValue V) {
9525     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9526     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9527     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9528     ++CurResultType;
9529     // If the type of the inline asm call site return value is different but has
9530     // same size as the type of the asm output bitcast it.  One example of this
9531     // is for vectors with different width / number of elements.  This can
9532     // happen for register classes that can contain multiple different value
9533     // types.  The preg or vreg allocated may not have the same VT as was
9534     // expected.
9535     //
9536     // This can also happen for a return value that disagrees with the register
9537     // class it is put in, eg. a double in a general-purpose register on a
9538     // 32-bit machine.
9539     if (ResultVT != V.getValueType() &&
9540         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9541       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9542     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9543              V.getValueType().isInteger()) {
9544       // If a result value was tied to an input value, the computed result
9545       // may have a wider width than the expected result.  Extract the
9546       // relevant portion.
9547       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9548     }
9549     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9550     ResultVTs.push_back(ResultVT);
9551     ResultValues.push_back(V);
9552   };
9553 
9554   // Deal with output operands.
9555   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9556     if (OpInfo.Type == InlineAsm::isOutput) {
9557       SDValue Val;
9558       // Skip trivial output operands.
9559       if (OpInfo.AssignedRegs.Regs.empty())
9560         continue;
9561 
9562       switch (OpInfo.ConstraintType) {
9563       case TargetLowering::C_Register:
9564       case TargetLowering::C_RegisterClass:
9565         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9566                                                   Chain, &Glue, &Call);
9567         break;
9568       case TargetLowering::C_Immediate:
9569       case TargetLowering::C_Other:
9570         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9571                                               OpInfo, DAG);
9572         break;
9573       case TargetLowering::C_Memory:
9574         break; // Already handled.
9575       case TargetLowering::C_Address:
9576         break; // Silence warning.
9577       case TargetLowering::C_Unknown:
9578         assert(false && "Unexpected unknown constraint");
9579       }
9580 
9581       // Indirect output manifest as stores. Record output chains.
9582       if (OpInfo.isIndirect) {
9583         const Value *Ptr = OpInfo.CallOperandVal;
9584         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9585         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9586                                      MachinePointerInfo(Ptr));
9587         OutChains.push_back(Store);
9588       } else {
9589         // generate CopyFromRegs to associated registers.
9590         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9591         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9592           for (const SDValue &V : Val->op_values())
9593             handleRegAssign(V);
9594         } else
9595           handleRegAssign(Val);
9596       }
9597     }
9598   }
9599 
9600   // Set results.
9601   if (!ResultValues.empty()) {
9602     assert(CurResultType == ResultTypes.end() &&
9603            "Mismatch in number of ResultTypes");
9604     assert(ResultValues.size() == ResultTypes.size() &&
9605            "Mismatch in number of output operands in asm result");
9606 
9607     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9608                             DAG.getVTList(ResultVTs), ResultValues);
9609     setValue(&Call, V);
9610   }
9611 
9612   // Collect store chains.
9613   if (!OutChains.empty())
9614     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9615 
9616   if (EmitEHLabels) {
9617     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9618   }
9619 
9620   // Only Update Root if inline assembly has a memory effect.
9621   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9622       EmitEHLabels)
9623     DAG.setRoot(Chain);
9624 }
9625 
9626 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9627                                              const Twine &Message) {
9628   LLVMContext &Ctx = *DAG.getContext();
9629   Ctx.emitError(&Call, Message);
9630 
9631   // Make sure we leave the DAG in a valid state
9632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9633   SmallVector<EVT, 1> ValueVTs;
9634   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9635 
9636   if (ValueVTs.empty())
9637     return;
9638 
9639   SmallVector<SDValue, 1> Ops;
9640   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9641     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9642 
9643   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9644 }
9645 
9646 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9647   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9648                           MVT::Other, getRoot(),
9649                           getValue(I.getArgOperand(0)),
9650                           DAG.getSrcValue(I.getArgOperand(0))));
9651 }
9652 
9653 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655   const DataLayout &DL = DAG.getDataLayout();
9656   SDValue V = DAG.getVAArg(
9657       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9658       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9659       DL.getABITypeAlign(I.getType()).value());
9660   DAG.setRoot(V.getValue(1));
9661 
9662   if (I.getType()->isPointerTy())
9663     V = DAG.getPtrExtOrTrunc(
9664         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9665   setValue(&I, V);
9666 }
9667 
9668 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9669   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9670                           MVT::Other, getRoot(),
9671                           getValue(I.getArgOperand(0)),
9672                           DAG.getSrcValue(I.getArgOperand(0))));
9673 }
9674 
9675 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9676   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9677                           MVT::Other, getRoot(),
9678                           getValue(I.getArgOperand(0)),
9679                           getValue(I.getArgOperand(1)),
9680                           DAG.getSrcValue(I.getArgOperand(0)),
9681                           DAG.getSrcValue(I.getArgOperand(1))));
9682 }
9683 
9684 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9685                                                     const Instruction &I,
9686                                                     SDValue Op) {
9687   const MDNode *Range = getRangeMetadata(I);
9688   if (!Range)
9689     return Op;
9690 
9691   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9692   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9693     return Op;
9694 
9695   APInt Lo = CR.getUnsignedMin();
9696   if (!Lo.isMinValue())
9697     return Op;
9698 
9699   APInt Hi = CR.getUnsignedMax();
9700   unsigned Bits = std::max(Hi.getActiveBits(),
9701                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9702 
9703   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9704 
9705   SDLoc SL = getCurSDLoc();
9706 
9707   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9708                              DAG.getValueType(SmallVT));
9709   unsigned NumVals = Op.getNode()->getNumValues();
9710   if (NumVals == 1)
9711     return ZExt;
9712 
9713   SmallVector<SDValue, 4> Ops;
9714 
9715   Ops.push_back(ZExt);
9716   for (unsigned I = 1; I != NumVals; ++I)
9717     Ops.push_back(Op.getValue(I));
9718 
9719   return DAG.getMergeValues(Ops, SL);
9720 }
9721 
9722 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9723 /// the call being lowered.
9724 ///
9725 /// This is a helper for lowering intrinsics that follow a target calling
9726 /// convention or require stack pointer adjustment. Only a subset of the
9727 /// intrinsic's operands need to participate in the calling convention.
9728 void SelectionDAGBuilder::populateCallLoweringInfo(
9729     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9730     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9731     AttributeSet RetAttrs, bool IsPatchPoint) {
9732   TargetLowering::ArgListTy Args;
9733   Args.reserve(NumArgs);
9734 
9735   // Populate the argument list.
9736   // Attributes for args start at offset 1, after the return attribute.
9737   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9738        ArgI != ArgE; ++ArgI) {
9739     const Value *V = Call->getOperand(ArgI);
9740 
9741     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9742 
9743     TargetLowering::ArgListEntry Entry;
9744     Entry.Node = getValue(V);
9745     Entry.Ty = V->getType();
9746     Entry.setAttributes(Call, ArgI);
9747     Args.push_back(Entry);
9748   }
9749 
9750   CLI.setDebugLoc(getCurSDLoc())
9751       .setChain(getRoot())
9752       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
9753                  RetAttrs)
9754       .setDiscardResult(Call->use_empty())
9755       .setIsPatchPoint(IsPatchPoint)
9756       .setIsPreallocated(
9757           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9758 }
9759 
9760 /// Add a stack map intrinsic call's live variable operands to a stackmap
9761 /// or patchpoint target node's operand list.
9762 ///
9763 /// Constants are converted to TargetConstants purely as an optimization to
9764 /// avoid constant materialization and register allocation.
9765 ///
9766 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9767 /// generate addess computation nodes, and so FinalizeISel can convert the
9768 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9769 /// address materialization and register allocation, but may also be required
9770 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9771 /// alloca in the entry block, then the runtime may assume that the alloca's
9772 /// StackMap location can be read immediately after compilation and that the
9773 /// location is valid at any point during execution (this is similar to the
9774 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9775 /// only available in a register, then the runtime would need to trap when
9776 /// execution reaches the StackMap in order to read the alloca's location.
9777 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9778                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9779                                 SelectionDAGBuilder &Builder) {
9780   SelectionDAG &DAG = Builder.DAG;
9781   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9782     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9783 
9784     // Things on the stack are pointer-typed, meaning that they are already
9785     // legal and can be emitted directly to target nodes.
9786     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9787       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9788     } else {
9789       // Otherwise emit a target independent node to be legalised.
9790       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9791     }
9792   }
9793 }
9794 
9795 /// Lower llvm.experimental.stackmap.
9796 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9797   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9798   //                                  [live variables...])
9799 
9800   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9801 
9802   SDValue Chain, InGlue, Callee;
9803   SmallVector<SDValue, 32> Ops;
9804 
9805   SDLoc DL = getCurSDLoc();
9806   Callee = getValue(CI.getCalledOperand());
9807 
9808   // The stackmap intrinsic only records the live variables (the arguments
9809   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9810   // intrinsic, this won't be lowered to a function call. This means we don't
9811   // have to worry about calling conventions and target specific lowering code.
9812   // Instead we perform the call lowering right here.
9813   //
9814   // chain, flag = CALLSEQ_START(chain, 0, 0)
9815   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9816   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9817   //
9818   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9819   InGlue = Chain.getValue(1);
9820 
9821   // Add the STACKMAP operands, starting with DAG house-keeping.
9822   Ops.push_back(Chain);
9823   Ops.push_back(InGlue);
9824 
9825   // Add the <id>, <numShadowBytes> operands.
9826   //
9827   // These do not require legalisation, and can be emitted directly to target
9828   // constant nodes.
9829   SDValue ID = getValue(CI.getArgOperand(0));
9830   assert(ID.getValueType() == MVT::i64);
9831   SDValue IDConst = DAG.getTargetConstant(
9832       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9833   Ops.push_back(IDConst);
9834 
9835   SDValue Shad = getValue(CI.getArgOperand(1));
9836   assert(Shad.getValueType() == MVT::i32);
9837   SDValue ShadConst = DAG.getTargetConstant(
9838       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9839   Ops.push_back(ShadConst);
9840 
9841   // Add the live variables.
9842   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9843 
9844   // Create the STACKMAP node.
9845   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9846   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9847   InGlue = Chain.getValue(1);
9848 
9849   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
9850 
9851   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9852 
9853   // Set the root to the target-lowered call chain.
9854   DAG.setRoot(Chain);
9855 
9856   // Inform the Frame Information that we have a stackmap in this function.
9857   FuncInfo.MF->getFrameInfo().setHasStackMap();
9858 }
9859 
9860 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9861 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9862                                           const BasicBlock *EHPadBB) {
9863   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9864   //                                                 i32 <numBytes>,
9865   //                                                 i8* <target>,
9866   //                                                 i32 <numArgs>,
9867   //                                                 [Args...],
9868   //                                                 [live variables...])
9869 
9870   CallingConv::ID CC = CB.getCallingConv();
9871   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9872   bool HasDef = !CB.getType()->isVoidTy();
9873   SDLoc dl = getCurSDLoc();
9874   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9875 
9876   // Handle immediate and symbolic callees.
9877   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9878     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9879                                    /*isTarget=*/true);
9880   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9881     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9882                                          SDLoc(SymbolicCallee),
9883                                          SymbolicCallee->getValueType(0));
9884 
9885   // Get the real number of arguments participating in the call <numArgs>
9886   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9887   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9888 
9889   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9890   // Intrinsics include all meta-operands up to but not including CC.
9891   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9892   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9893          "Not enough arguments provided to the patchpoint intrinsic");
9894 
9895   // For AnyRegCC the arguments are lowered later on manually.
9896   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9897   Type *ReturnTy =
9898       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9899 
9900   TargetLowering::CallLoweringInfo CLI(DAG);
9901   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9902                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
9903   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9904 
9905   SDNode *CallEnd = Result.second.getNode();
9906   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9907     CallEnd = CallEnd->getOperand(0).getNode();
9908 
9909   /// Get a call instruction from the call sequence chain.
9910   /// Tail calls are not allowed.
9911   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9912          "Expected a callseq node.");
9913   SDNode *Call = CallEnd->getOperand(0).getNode();
9914   bool HasGlue = Call->getGluedNode();
9915 
9916   // Replace the target specific call node with the patchable intrinsic.
9917   SmallVector<SDValue, 8> Ops;
9918 
9919   // Push the chain.
9920   Ops.push_back(*(Call->op_begin()));
9921 
9922   // Optionally, push the glue (if any).
9923   if (HasGlue)
9924     Ops.push_back(*(Call->op_end() - 1));
9925 
9926   // Push the register mask info.
9927   if (HasGlue)
9928     Ops.push_back(*(Call->op_end() - 2));
9929   else
9930     Ops.push_back(*(Call->op_end() - 1));
9931 
9932   // Add the <id> and <numBytes> constants.
9933   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9934   Ops.push_back(DAG.getTargetConstant(
9935                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9936   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9937   Ops.push_back(DAG.getTargetConstant(
9938                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9939                   MVT::i32));
9940 
9941   // Add the callee.
9942   Ops.push_back(Callee);
9943 
9944   // Adjust <numArgs> to account for any arguments that have been passed on the
9945   // stack instead.
9946   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9947   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9948   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9949   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9950 
9951   // Add the calling convention
9952   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9953 
9954   // Add the arguments we omitted previously. The register allocator should
9955   // place these in any free register.
9956   if (IsAnyRegCC)
9957     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9958       Ops.push_back(getValue(CB.getArgOperand(i)));
9959 
9960   // Push the arguments from the call instruction.
9961   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9962   Ops.append(Call->op_begin() + 2, e);
9963 
9964   // Push live variables for the stack map.
9965   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9966 
9967   SDVTList NodeTys;
9968   if (IsAnyRegCC && HasDef) {
9969     // Create the return types based on the intrinsic definition
9970     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9971     SmallVector<EVT, 3> ValueVTs;
9972     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9973     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9974 
9975     // There is always a chain and a glue type at the end
9976     ValueVTs.push_back(MVT::Other);
9977     ValueVTs.push_back(MVT::Glue);
9978     NodeTys = DAG.getVTList(ValueVTs);
9979   } else
9980     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9981 
9982   // Replace the target specific call node with a PATCHPOINT node.
9983   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9984 
9985   // Update the NodeMap.
9986   if (HasDef) {
9987     if (IsAnyRegCC)
9988       setValue(&CB, SDValue(PPV.getNode(), 0));
9989     else
9990       setValue(&CB, Result.first);
9991   }
9992 
9993   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9994   // call sequence. Furthermore the location of the chain and glue can change
9995   // when the AnyReg calling convention is used and the intrinsic returns a
9996   // value.
9997   if (IsAnyRegCC && HasDef) {
9998     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9999     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10000     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10001   } else
10002     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10003   DAG.DeleteNode(Call);
10004 
10005   // Inform the Frame Information that we have a patchpoint in this function.
10006   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10007 }
10008 
10009 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10010                                             unsigned Intrinsic) {
10011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10012   SDValue Op1 = getValue(I.getArgOperand(0));
10013   SDValue Op2;
10014   if (I.arg_size() > 1)
10015     Op2 = getValue(I.getArgOperand(1));
10016   SDLoc dl = getCurSDLoc();
10017   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10018   SDValue Res;
10019   SDNodeFlags SDFlags;
10020   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10021     SDFlags.copyFMF(*FPMO);
10022 
10023   switch (Intrinsic) {
10024   case Intrinsic::vector_reduce_fadd:
10025     if (SDFlags.hasAllowReassociation())
10026       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10027                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10028                         SDFlags);
10029     else
10030       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10031     break;
10032   case Intrinsic::vector_reduce_fmul:
10033     if (SDFlags.hasAllowReassociation())
10034       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10035                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10036                         SDFlags);
10037     else
10038       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10039     break;
10040   case Intrinsic::vector_reduce_add:
10041     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10042     break;
10043   case Intrinsic::vector_reduce_mul:
10044     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10045     break;
10046   case Intrinsic::vector_reduce_and:
10047     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10048     break;
10049   case Intrinsic::vector_reduce_or:
10050     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10051     break;
10052   case Intrinsic::vector_reduce_xor:
10053     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10054     break;
10055   case Intrinsic::vector_reduce_smax:
10056     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10057     break;
10058   case Intrinsic::vector_reduce_smin:
10059     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10060     break;
10061   case Intrinsic::vector_reduce_umax:
10062     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10063     break;
10064   case Intrinsic::vector_reduce_umin:
10065     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10066     break;
10067   case Intrinsic::vector_reduce_fmax:
10068     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10069     break;
10070   case Intrinsic::vector_reduce_fmin:
10071     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10072     break;
10073   case Intrinsic::vector_reduce_fmaximum:
10074     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10075     break;
10076   case Intrinsic::vector_reduce_fminimum:
10077     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10078     break;
10079   default:
10080     llvm_unreachable("Unhandled vector reduce intrinsic");
10081   }
10082   setValue(&I, Res);
10083 }
10084 
10085 /// Returns an AttributeList representing the attributes applied to the return
10086 /// value of the given call.
10087 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10088   SmallVector<Attribute::AttrKind, 2> Attrs;
10089   if (CLI.RetSExt)
10090     Attrs.push_back(Attribute::SExt);
10091   if (CLI.RetZExt)
10092     Attrs.push_back(Attribute::ZExt);
10093   if (CLI.IsInReg)
10094     Attrs.push_back(Attribute::InReg);
10095 
10096   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10097                             Attrs);
10098 }
10099 
10100 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10101 /// implementation, which just calls LowerCall.
10102 /// FIXME: When all targets are
10103 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10104 std::pair<SDValue, SDValue>
10105 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10106   // Handle the incoming return values from the call.
10107   CLI.Ins.clear();
10108   Type *OrigRetTy = CLI.RetTy;
10109   SmallVector<EVT, 4> RetTys;
10110   SmallVector<uint64_t, 4> Offsets;
10111   auto &DL = CLI.DAG.getDataLayout();
10112   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0);
10113 
10114   if (CLI.IsPostTypeLegalization) {
10115     // If we are lowering a libcall after legalization, split the return type.
10116     SmallVector<EVT, 4> OldRetTys;
10117     SmallVector<uint64_t, 4> OldOffsets;
10118     RetTys.swap(OldRetTys);
10119     Offsets.swap(OldOffsets);
10120 
10121     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10122       EVT RetVT = OldRetTys[i];
10123       uint64_t Offset = OldOffsets[i];
10124       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10125       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10126       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10127       RetTys.append(NumRegs, RegisterVT);
10128       for (unsigned j = 0; j != NumRegs; ++j)
10129         Offsets.push_back(Offset + j * RegisterVTByteSZ);
10130     }
10131   }
10132 
10133   SmallVector<ISD::OutputArg, 4> Outs;
10134   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10135 
10136   bool CanLowerReturn =
10137       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10138                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10139 
10140   SDValue DemoteStackSlot;
10141   int DemoteStackIdx = -100;
10142   if (!CanLowerReturn) {
10143     // FIXME: equivalent assert?
10144     // assert(!CS.hasInAllocaArgument() &&
10145     //        "sret demotion is incompatible with inalloca");
10146     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10147     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10148     MachineFunction &MF = CLI.DAG.getMachineFunction();
10149     DemoteStackIdx =
10150         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10151     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10152                                               DL.getAllocaAddrSpace());
10153 
10154     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10155     ArgListEntry Entry;
10156     Entry.Node = DemoteStackSlot;
10157     Entry.Ty = StackSlotPtrType;
10158     Entry.IsSExt = false;
10159     Entry.IsZExt = false;
10160     Entry.IsInReg = false;
10161     Entry.IsSRet = true;
10162     Entry.IsNest = false;
10163     Entry.IsByVal = false;
10164     Entry.IsByRef = false;
10165     Entry.IsReturned = false;
10166     Entry.IsSwiftSelf = false;
10167     Entry.IsSwiftAsync = false;
10168     Entry.IsSwiftError = false;
10169     Entry.IsCFGuardTarget = false;
10170     Entry.Alignment = Alignment;
10171     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10172     CLI.NumFixedArgs += 1;
10173     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10174     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10175 
10176     // sret demotion isn't compatible with tail-calls, since the sret argument
10177     // points into the callers stack frame.
10178     CLI.IsTailCall = false;
10179   } else {
10180     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10181         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10182     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10183       ISD::ArgFlagsTy Flags;
10184       if (NeedsRegBlock) {
10185         Flags.setInConsecutiveRegs();
10186         if (I == RetTys.size() - 1)
10187           Flags.setInConsecutiveRegsLast();
10188       }
10189       EVT VT = RetTys[I];
10190       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10191                                                      CLI.CallConv, VT);
10192       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10193                                                        CLI.CallConv, VT);
10194       for (unsigned i = 0; i != NumRegs; ++i) {
10195         ISD::InputArg MyFlags;
10196         MyFlags.Flags = Flags;
10197         MyFlags.VT = RegisterVT;
10198         MyFlags.ArgVT = VT;
10199         MyFlags.Used = CLI.IsReturnValueUsed;
10200         if (CLI.RetTy->isPointerTy()) {
10201           MyFlags.Flags.setPointer();
10202           MyFlags.Flags.setPointerAddrSpace(
10203               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10204         }
10205         if (CLI.RetSExt)
10206           MyFlags.Flags.setSExt();
10207         if (CLI.RetZExt)
10208           MyFlags.Flags.setZExt();
10209         if (CLI.IsInReg)
10210           MyFlags.Flags.setInReg();
10211         CLI.Ins.push_back(MyFlags);
10212       }
10213     }
10214   }
10215 
10216   // We push in swifterror return as the last element of CLI.Ins.
10217   ArgListTy &Args = CLI.getArgs();
10218   if (supportSwiftError()) {
10219     for (const ArgListEntry &Arg : Args) {
10220       if (Arg.IsSwiftError) {
10221         ISD::InputArg MyFlags;
10222         MyFlags.VT = getPointerTy(DL);
10223         MyFlags.ArgVT = EVT(getPointerTy(DL));
10224         MyFlags.Flags.setSwiftError();
10225         CLI.Ins.push_back(MyFlags);
10226       }
10227     }
10228   }
10229 
10230   // Handle all of the outgoing arguments.
10231   CLI.Outs.clear();
10232   CLI.OutVals.clear();
10233   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10234     SmallVector<EVT, 4> ValueVTs;
10235     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10236     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10237     Type *FinalType = Args[i].Ty;
10238     if (Args[i].IsByVal)
10239       FinalType = Args[i].IndirectType;
10240     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10241         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10242     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10243          ++Value) {
10244       EVT VT = ValueVTs[Value];
10245       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10246       SDValue Op = SDValue(Args[i].Node.getNode(),
10247                            Args[i].Node.getResNo() + Value);
10248       ISD::ArgFlagsTy Flags;
10249 
10250       // Certain targets (such as MIPS), may have a different ABI alignment
10251       // for a type depending on the context. Give the target a chance to
10252       // specify the alignment it wants.
10253       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10254       Flags.setOrigAlign(OriginalAlignment);
10255 
10256       if (Args[i].Ty->isPointerTy()) {
10257         Flags.setPointer();
10258         Flags.setPointerAddrSpace(
10259             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10260       }
10261       if (Args[i].IsZExt)
10262         Flags.setZExt();
10263       if (Args[i].IsSExt)
10264         Flags.setSExt();
10265       if (Args[i].IsInReg) {
10266         // If we are using vectorcall calling convention, a structure that is
10267         // passed InReg - is surely an HVA
10268         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10269             isa<StructType>(FinalType)) {
10270           // The first value of a structure is marked
10271           if (0 == Value)
10272             Flags.setHvaStart();
10273           Flags.setHva();
10274         }
10275         // Set InReg Flag
10276         Flags.setInReg();
10277       }
10278       if (Args[i].IsSRet)
10279         Flags.setSRet();
10280       if (Args[i].IsSwiftSelf)
10281         Flags.setSwiftSelf();
10282       if (Args[i].IsSwiftAsync)
10283         Flags.setSwiftAsync();
10284       if (Args[i].IsSwiftError)
10285         Flags.setSwiftError();
10286       if (Args[i].IsCFGuardTarget)
10287         Flags.setCFGuardTarget();
10288       if (Args[i].IsByVal)
10289         Flags.setByVal();
10290       if (Args[i].IsByRef)
10291         Flags.setByRef();
10292       if (Args[i].IsPreallocated) {
10293         Flags.setPreallocated();
10294         // Set the byval flag for CCAssignFn callbacks that don't know about
10295         // preallocated.  This way we can know how many bytes we should've
10296         // allocated and how many bytes a callee cleanup function will pop.  If
10297         // we port preallocated to more targets, we'll have to add custom
10298         // preallocated handling in the various CC lowering callbacks.
10299         Flags.setByVal();
10300       }
10301       if (Args[i].IsInAlloca) {
10302         Flags.setInAlloca();
10303         // Set the byval flag for CCAssignFn callbacks that don't know about
10304         // inalloca.  This way we can know how many bytes we should've allocated
10305         // and how many bytes a callee cleanup function will pop.  If we port
10306         // inalloca to more targets, we'll have to add custom inalloca handling
10307         // in the various CC lowering callbacks.
10308         Flags.setByVal();
10309       }
10310       Align MemAlign;
10311       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10312         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10313         Flags.setByValSize(FrameSize);
10314 
10315         // info is not there but there are cases it cannot get right.
10316         if (auto MA = Args[i].Alignment)
10317           MemAlign = *MA;
10318         else
10319           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10320       } else if (auto MA = Args[i].Alignment) {
10321         MemAlign = *MA;
10322       } else {
10323         MemAlign = OriginalAlignment;
10324       }
10325       Flags.setMemAlign(MemAlign);
10326       if (Args[i].IsNest)
10327         Flags.setNest();
10328       if (NeedsRegBlock)
10329         Flags.setInConsecutiveRegs();
10330 
10331       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10332                                                  CLI.CallConv, VT);
10333       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10334                                                         CLI.CallConv, VT);
10335       SmallVector<SDValue, 4> Parts(NumParts);
10336       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10337 
10338       if (Args[i].IsSExt)
10339         ExtendKind = ISD::SIGN_EXTEND;
10340       else if (Args[i].IsZExt)
10341         ExtendKind = ISD::ZERO_EXTEND;
10342 
10343       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10344       // for now.
10345       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10346           CanLowerReturn) {
10347         assert((CLI.RetTy == Args[i].Ty ||
10348                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10349                  CLI.RetTy->getPointerAddressSpace() ==
10350                      Args[i].Ty->getPointerAddressSpace())) &&
10351                RetTys.size() == NumValues && "unexpected use of 'returned'");
10352         // Before passing 'returned' to the target lowering code, ensure that
10353         // either the register MVT and the actual EVT are the same size or that
10354         // the return value and argument are extended in the same way; in these
10355         // cases it's safe to pass the argument register value unchanged as the
10356         // return register value (although it's at the target's option whether
10357         // to do so)
10358         // TODO: allow code generation to take advantage of partially preserved
10359         // registers rather than clobbering the entire register when the
10360         // parameter extension method is not compatible with the return
10361         // extension method
10362         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10363             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10364              CLI.RetZExt == Args[i].IsZExt))
10365           Flags.setReturned();
10366       }
10367 
10368       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10369                      CLI.CallConv, ExtendKind);
10370 
10371       for (unsigned j = 0; j != NumParts; ++j) {
10372         // if it isn't first piece, alignment must be 1
10373         // For scalable vectors the scalable part is currently handled
10374         // by individual targets, so we just use the known minimum size here.
10375         ISD::OutputArg MyFlags(
10376             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10377             i < CLI.NumFixedArgs, i,
10378             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10379         if (NumParts > 1 && j == 0)
10380           MyFlags.Flags.setSplit();
10381         else if (j != 0) {
10382           MyFlags.Flags.setOrigAlign(Align(1));
10383           if (j == NumParts - 1)
10384             MyFlags.Flags.setSplitEnd();
10385         }
10386 
10387         CLI.Outs.push_back(MyFlags);
10388         CLI.OutVals.push_back(Parts[j]);
10389       }
10390 
10391       if (NeedsRegBlock && Value == NumValues - 1)
10392         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10393     }
10394   }
10395 
10396   SmallVector<SDValue, 4> InVals;
10397   CLI.Chain = LowerCall(CLI, InVals);
10398 
10399   // Update CLI.InVals to use outside of this function.
10400   CLI.InVals = InVals;
10401 
10402   // Verify that the target's LowerCall behaved as expected.
10403   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10404          "LowerCall didn't return a valid chain!");
10405   assert((!CLI.IsTailCall || InVals.empty()) &&
10406          "LowerCall emitted a return value for a tail call!");
10407   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10408          "LowerCall didn't emit the correct number of values!");
10409 
10410   // For a tail call, the return value is merely live-out and there aren't
10411   // any nodes in the DAG representing it. Return a special value to
10412   // indicate that a tail call has been emitted and no more Instructions
10413   // should be processed in the current block.
10414   if (CLI.IsTailCall) {
10415     CLI.DAG.setRoot(CLI.Chain);
10416     return std::make_pair(SDValue(), SDValue());
10417   }
10418 
10419 #ifndef NDEBUG
10420   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10421     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10422     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10423            "LowerCall emitted a value with the wrong type!");
10424   }
10425 #endif
10426 
10427   SmallVector<SDValue, 4> ReturnValues;
10428   if (!CanLowerReturn) {
10429     // The instruction result is the result of loading from the
10430     // hidden sret parameter.
10431     SmallVector<EVT, 1> PVTs;
10432     Type *PtrRetTy =
10433         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10434 
10435     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10436     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10437     EVT PtrVT = PVTs[0];
10438 
10439     unsigned NumValues = RetTys.size();
10440     ReturnValues.resize(NumValues);
10441     SmallVector<SDValue, 4> Chains(NumValues);
10442 
10443     // An aggregate return value cannot wrap around the address space, so
10444     // offsets to its parts don't wrap either.
10445     SDNodeFlags Flags;
10446     Flags.setNoUnsignedWrap(true);
10447 
10448     MachineFunction &MF = CLI.DAG.getMachineFunction();
10449     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10450     for (unsigned i = 0; i < NumValues; ++i) {
10451       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10452                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10453                                                         PtrVT), Flags);
10454       SDValue L = CLI.DAG.getLoad(
10455           RetTys[i], CLI.DL, CLI.Chain, Add,
10456           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10457                                             DemoteStackIdx, Offsets[i]),
10458           HiddenSRetAlign);
10459       ReturnValues[i] = L;
10460       Chains[i] = L.getValue(1);
10461     }
10462 
10463     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10464   } else {
10465     // Collect the legal value parts into potentially illegal values
10466     // that correspond to the original function's return values.
10467     std::optional<ISD::NodeType> AssertOp;
10468     if (CLI.RetSExt)
10469       AssertOp = ISD::AssertSext;
10470     else if (CLI.RetZExt)
10471       AssertOp = ISD::AssertZext;
10472     unsigned CurReg = 0;
10473     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10474       EVT VT = RetTys[I];
10475       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10476                                                      CLI.CallConv, VT);
10477       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10478                                                        CLI.CallConv, VT);
10479 
10480       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10481                                               NumRegs, RegisterVT, VT, nullptr,
10482                                               CLI.CallConv, AssertOp));
10483       CurReg += NumRegs;
10484     }
10485 
10486     // For a function returning void, there is no return value. We can't create
10487     // such a node, so we just return a null return value in that case. In
10488     // that case, nothing will actually look at the value.
10489     if (ReturnValues.empty())
10490       return std::make_pair(SDValue(), CLI.Chain);
10491   }
10492 
10493   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10494                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10495   return std::make_pair(Res, CLI.Chain);
10496 }
10497 
10498 /// Places new result values for the node in Results (their number
10499 /// and types must exactly match those of the original return values of
10500 /// the node), or leaves Results empty, which indicates that the node is not
10501 /// to be custom lowered after all.
10502 void TargetLowering::LowerOperationWrapper(SDNode *N,
10503                                            SmallVectorImpl<SDValue> &Results,
10504                                            SelectionDAG &DAG) const {
10505   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10506 
10507   if (!Res.getNode())
10508     return;
10509 
10510   // If the original node has one result, take the return value from
10511   // LowerOperation as is. It might not be result number 0.
10512   if (N->getNumValues() == 1) {
10513     Results.push_back(Res);
10514     return;
10515   }
10516 
10517   // If the original node has multiple results, then the return node should
10518   // have the same number of results.
10519   assert((N->getNumValues() == Res->getNumValues()) &&
10520       "Lowering returned the wrong number of results!");
10521 
10522   // Places new result values base on N result number.
10523   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10524     Results.push_back(Res.getValue(I));
10525 }
10526 
10527 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10528   llvm_unreachable("LowerOperation not implemented for this target!");
10529 }
10530 
10531 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10532                                                      unsigned Reg,
10533                                                      ISD::NodeType ExtendType) {
10534   SDValue Op = getNonRegisterValue(V);
10535   assert((Op.getOpcode() != ISD::CopyFromReg ||
10536           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10537          "Copy from a reg to the same reg!");
10538   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10539 
10540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10541   // If this is an InlineAsm we have to match the registers required, not the
10542   // notional registers required by the type.
10543 
10544   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10545                    std::nullopt); // This is not an ABI copy.
10546   SDValue Chain = DAG.getEntryNode();
10547 
10548   if (ExtendType == ISD::ANY_EXTEND) {
10549     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10550     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10551       ExtendType = PreferredExtendIt->second;
10552   }
10553   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10554   PendingExports.push_back(Chain);
10555 }
10556 
10557 #include "llvm/CodeGen/SelectionDAGISel.h"
10558 
10559 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10560 /// entry block, return true.  This includes arguments used by switches, since
10561 /// the switch may expand into multiple basic blocks.
10562 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10563   // With FastISel active, we may be splitting blocks, so force creation
10564   // of virtual registers for all non-dead arguments.
10565   if (FastISel)
10566     return A->use_empty();
10567 
10568   const BasicBlock &Entry = A->getParent()->front();
10569   for (const User *U : A->users())
10570     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10571       return false;  // Use not in entry block.
10572 
10573   return true;
10574 }
10575 
10576 using ArgCopyElisionMapTy =
10577     DenseMap<const Argument *,
10578              std::pair<const AllocaInst *, const StoreInst *>>;
10579 
10580 /// Scan the entry block of the function in FuncInfo for arguments that look
10581 /// like copies into a local alloca. Record any copied arguments in
10582 /// ArgCopyElisionCandidates.
10583 static void
10584 findArgumentCopyElisionCandidates(const DataLayout &DL,
10585                                   FunctionLoweringInfo *FuncInfo,
10586                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10587   // Record the state of every static alloca used in the entry block. Argument
10588   // allocas are all used in the entry block, so we need approximately as many
10589   // entries as we have arguments.
10590   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10591   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10592   unsigned NumArgs = FuncInfo->Fn->arg_size();
10593   StaticAllocas.reserve(NumArgs * 2);
10594 
10595   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10596     if (!V)
10597       return nullptr;
10598     V = V->stripPointerCasts();
10599     const auto *AI = dyn_cast<AllocaInst>(V);
10600     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10601       return nullptr;
10602     auto Iter = StaticAllocas.insert({AI, Unknown});
10603     return &Iter.first->second;
10604   };
10605 
10606   // Look for stores of arguments to static allocas. Look through bitcasts and
10607   // GEPs to handle type coercions, as long as the alloca is fully initialized
10608   // by the store. Any non-store use of an alloca escapes it and any subsequent
10609   // unanalyzed store might write it.
10610   // FIXME: Handle structs initialized with multiple stores.
10611   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10612     // Look for stores, and handle non-store uses conservatively.
10613     const auto *SI = dyn_cast<StoreInst>(&I);
10614     if (!SI) {
10615       // We will look through cast uses, so ignore them completely.
10616       if (I.isCast())
10617         continue;
10618       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10619       // to allocas.
10620       if (I.isDebugOrPseudoInst())
10621         continue;
10622       // This is an unknown instruction. Assume it escapes or writes to all
10623       // static alloca operands.
10624       for (const Use &U : I.operands()) {
10625         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10626           *Info = StaticAllocaInfo::Clobbered;
10627       }
10628       continue;
10629     }
10630 
10631     // If the stored value is a static alloca, mark it as escaped.
10632     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10633       *Info = StaticAllocaInfo::Clobbered;
10634 
10635     // Check if the destination is a static alloca.
10636     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10637     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10638     if (!Info)
10639       continue;
10640     const AllocaInst *AI = cast<AllocaInst>(Dst);
10641 
10642     // Skip allocas that have been initialized or clobbered.
10643     if (*Info != StaticAllocaInfo::Unknown)
10644       continue;
10645 
10646     // Check if the stored value is an argument, and that this store fully
10647     // initializes the alloca.
10648     // If the argument type has padding bits we can't directly forward a pointer
10649     // as the upper bits may contain garbage.
10650     // Don't elide copies from the same argument twice.
10651     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10652     const auto *Arg = dyn_cast<Argument>(Val);
10653     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10654         Arg->getType()->isEmptyTy() ||
10655         DL.getTypeStoreSize(Arg->getType()) !=
10656             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10657         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10658         ArgCopyElisionCandidates.count(Arg)) {
10659       *Info = StaticAllocaInfo::Clobbered;
10660       continue;
10661     }
10662 
10663     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10664                       << '\n');
10665 
10666     // Mark this alloca and store for argument copy elision.
10667     *Info = StaticAllocaInfo::Elidable;
10668     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10669 
10670     // Stop scanning if we've seen all arguments. This will happen early in -O0
10671     // builds, which is useful, because -O0 builds have large entry blocks and
10672     // many allocas.
10673     if (ArgCopyElisionCandidates.size() == NumArgs)
10674       break;
10675   }
10676 }
10677 
10678 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10679 /// ArgVal is a load from a suitable fixed stack object.
10680 static void tryToElideArgumentCopy(
10681     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10682     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10683     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10684     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10685     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
10686   // Check if this is a load from a fixed stack object.
10687   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
10688   if (!LNode)
10689     return;
10690   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10691   if (!FINode)
10692     return;
10693 
10694   // Check that the fixed stack object is the right size and alignment.
10695   // Look at the alignment that the user wrote on the alloca instead of looking
10696   // at the stack object.
10697   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10698   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10699   const AllocaInst *AI = ArgCopyIter->second.first;
10700   int FixedIndex = FINode->getIndex();
10701   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10702   int OldIndex = AllocaIndex;
10703   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10704   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10705     LLVM_DEBUG(
10706         dbgs() << "  argument copy elision failed due to bad fixed stack "
10707                   "object size\n");
10708     return;
10709   }
10710   Align RequiredAlignment = AI->getAlign();
10711   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10712     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10713                          "greater than stack argument alignment ("
10714                       << DebugStr(RequiredAlignment) << " vs "
10715                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10716     return;
10717   }
10718 
10719   // Perform the elision. Delete the old stack object and replace its only use
10720   // in the variable info map. Mark the stack object as mutable.
10721   LLVM_DEBUG({
10722     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10723            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10724            << '\n';
10725   });
10726   MFI.RemoveStackObject(OldIndex);
10727   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10728   AllocaIndex = FixedIndex;
10729   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10730   for (SDValue ArgVal : ArgVals)
10731     Chains.push_back(ArgVal.getValue(1));
10732 
10733   // Avoid emitting code for the store implementing the copy.
10734   const StoreInst *SI = ArgCopyIter->second.second;
10735   ElidedArgCopyInstrs.insert(SI);
10736 
10737   // Check for uses of the argument again so that we can avoid exporting ArgVal
10738   // if it is't used by anything other than the store.
10739   for (const Value *U : Arg.users()) {
10740     if (U != SI) {
10741       ArgHasUses = true;
10742       break;
10743     }
10744   }
10745 }
10746 
10747 void SelectionDAGISel::LowerArguments(const Function &F) {
10748   SelectionDAG &DAG = SDB->DAG;
10749   SDLoc dl = SDB->getCurSDLoc();
10750   const DataLayout &DL = DAG.getDataLayout();
10751   SmallVector<ISD::InputArg, 16> Ins;
10752 
10753   // In Naked functions we aren't going to save any registers.
10754   if (F.hasFnAttribute(Attribute::Naked))
10755     return;
10756 
10757   if (!FuncInfo->CanLowerReturn) {
10758     // Put in an sret pointer parameter before all the other parameters.
10759     SmallVector<EVT, 1> ValueVTs;
10760     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10761                     PointerType::get(F.getContext(),
10762                                      DAG.getDataLayout().getAllocaAddrSpace()),
10763                     ValueVTs);
10764 
10765     // NOTE: Assuming that a pointer will never break down to more than one VT
10766     // or one register.
10767     ISD::ArgFlagsTy Flags;
10768     Flags.setSRet();
10769     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10770     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10771                          ISD::InputArg::NoArgIndex, 0);
10772     Ins.push_back(RetArg);
10773   }
10774 
10775   // Look for stores of arguments to static allocas. Mark such arguments with a
10776   // flag to ask the target to give us the memory location of that argument if
10777   // available.
10778   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10779   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10780                                     ArgCopyElisionCandidates);
10781 
10782   // Set up the incoming argument description vector.
10783   for (const Argument &Arg : F.args()) {
10784     unsigned ArgNo = Arg.getArgNo();
10785     SmallVector<EVT, 4> ValueVTs;
10786     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10787     bool isArgValueUsed = !Arg.use_empty();
10788     unsigned PartBase = 0;
10789     Type *FinalType = Arg.getType();
10790     if (Arg.hasAttribute(Attribute::ByVal))
10791       FinalType = Arg.getParamByValType();
10792     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10793         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10794     for (unsigned Value = 0, NumValues = ValueVTs.size();
10795          Value != NumValues; ++Value) {
10796       EVT VT = ValueVTs[Value];
10797       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10798       ISD::ArgFlagsTy Flags;
10799 
10800 
10801       if (Arg.getType()->isPointerTy()) {
10802         Flags.setPointer();
10803         Flags.setPointerAddrSpace(
10804             cast<PointerType>(Arg.getType())->getAddressSpace());
10805       }
10806       if (Arg.hasAttribute(Attribute::ZExt))
10807         Flags.setZExt();
10808       if (Arg.hasAttribute(Attribute::SExt))
10809         Flags.setSExt();
10810       if (Arg.hasAttribute(Attribute::InReg)) {
10811         // If we are using vectorcall calling convention, a structure that is
10812         // passed InReg - is surely an HVA
10813         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10814             isa<StructType>(Arg.getType())) {
10815           // The first value of a structure is marked
10816           if (0 == Value)
10817             Flags.setHvaStart();
10818           Flags.setHva();
10819         }
10820         // Set InReg Flag
10821         Flags.setInReg();
10822       }
10823       if (Arg.hasAttribute(Attribute::StructRet))
10824         Flags.setSRet();
10825       if (Arg.hasAttribute(Attribute::SwiftSelf))
10826         Flags.setSwiftSelf();
10827       if (Arg.hasAttribute(Attribute::SwiftAsync))
10828         Flags.setSwiftAsync();
10829       if (Arg.hasAttribute(Attribute::SwiftError))
10830         Flags.setSwiftError();
10831       if (Arg.hasAttribute(Attribute::ByVal))
10832         Flags.setByVal();
10833       if (Arg.hasAttribute(Attribute::ByRef))
10834         Flags.setByRef();
10835       if (Arg.hasAttribute(Attribute::InAlloca)) {
10836         Flags.setInAlloca();
10837         // Set the byval flag for CCAssignFn callbacks that don't know about
10838         // inalloca.  This way we can know how many bytes we should've allocated
10839         // and how many bytes a callee cleanup function will pop.  If we port
10840         // inalloca to more targets, we'll have to add custom inalloca handling
10841         // in the various CC lowering callbacks.
10842         Flags.setByVal();
10843       }
10844       if (Arg.hasAttribute(Attribute::Preallocated)) {
10845         Flags.setPreallocated();
10846         // Set the byval flag for CCAssignFn callbacks that don't know about
10847         // preallocated.  This way we can know how many bytes we should've
10848         // allocated and how many bytes a callee cleanup function will pop.  If
10849         // we port preallocated to more targets, we'll have to add custom
10850         // preallocated handling in the various CC lowering callbacks.
10851         Flags.setByVal();
10852       }
10853 
10854       // Certain targets (such as MIPS), may have a different ABI alignment
10855       // for a type depending on the context. Give the target a chance to
10856       // specify the alignment it wants.
10857       const Align OriginalAlignment(
10858           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10859       Flags.setOrigAlign(OriginalAlignment);
10860 
10861       Align MemAlign;
10862       Type *ArgMemTy = nullptr;
10863       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10864           Flags.isByRef()) {
10865         if (!ArgMemTy)
10866           ArgMemTy = Arg.getPointeeInMemoryValueType();
10867 
10868         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10869 
10870         // For in-memory arguments, size and alignment should be passed from FE.
10871         // BE will guess if this info is not there but there are cases it cannot
10872         // get right.
10873         if (auto ParamAlign = Arg.getParamStackAlign())
10874           MemAlign = *ParamAlign;
10875         else if ((ParamAlign = Arg.getParamAlign()))
10876           MemAlign = *ParamAlign;
10877         else
10878           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10879         if (Flags.isByRef())
10880           Flags.setByRefSize(MemSize);
10881         else
10882           Flags.setByValSize(MemSize);
10883       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10884         MemAlign = *ParamAlign;
10885       } else {
10886         MemAlign = OriginalAlignment;
10887       }
10888       Flags.setMemAlign(MemAlign);
10889 
10890       if (Arg.hasAttribute(Attribute::Nest))
10891         Flags.setNest();
10892       if (NeedsRegBlock)
10893         Flags.setInConsecutiveRegs();
10894       if (ArgCopyElisionCandidates.count(&Arg))
10895         Flags.setCopyElisionCandidate();
10896       if (Arg.hasAttribute(Attribute::Returned))
10897         Flags.setReturned();
10898 
10899       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10900           *CurDAG->getContext(), F.getCallingConv(), VT);
10901       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10902           *CurDAG->getContext(), F.getCallingConv(), VT);
10903       for (unsigned i = 0; i != NumRegs; ++i) {
10904         // For scalable vectors, use the minimum size; individual targets
10905         // are responsible for handling scalable vector arguments and
10906         // return values.
10907         ISD::InputArg MyFlags(
10908             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10909             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10910         if (NumRegs > 1 && i == 0)
10911           MyFlags.Flags.setSplit();
10912         // if it isn't first piece, alignment must be 1
10913         else if (i > 0) {
10914           MyFlags.Flags.setOrigAlign(Align(1));
10915           if (i == NumRegs - 1)
10916             MyFlags.Flags.setSplitEnd();
10917         }
10918         Ins.push_back(MyFlags);
10919       }
10920       if (NeedsRegBlock && Value == NumValues - 1)
10921         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10922       PartBase += VT.getStoreSize().getKnownMinValue();
10923     }
10924   }
10925 
10926   // Call the target to set up the argument values.
10927   SmallVector<SDValue, 8> InVals;
10928   SDValue NewRoot = TLI->LowerFormalArguments(
10929       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10930 
10931   // Verify that the target's LowerFormalArguments behaved as expected.
10932   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10933          "LowerFormalArguments didn't return a valid chain!");
10934   assert(InVals.size() == Ins.size() &&
10935          "LowerFormalArguments didn't emit the correct number of values!");
10936   LLVM_DEBUG({
10937     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10938       assert(InVals[i].getNode() &&
10939              "LowerFormalArguments emitted a null value!");
10940       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10941              "LowerFormalArguments emitted a value with the wrong type!");
10942     }
10943   });
10944 
10945   // Update the DAG with the new chain value resulting from argument lowering.
10946   DAG.setRoot(NewRoot);
10947 
10948   // Set up the argument values.
10949   unsigned i = 0;
10950   if (!FuncInfo->CanLowerReturn) {
10951     // Create a virtual register for the sret pointer, and put in a copy
10952     // from the sret argument into it.
10953     SmallVector<EVT, 1> ValueVTs;
10954     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10955                     PointerType::get(F.getContext(),
10956                                      DAG.getDataLayout().getAllocaAddrSpace()),
10957                     ValueVTs);
10958     MVT VT = ValueVTs[0].getSimpleVT();
10959     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10960     std::optional<ISD::NodeType> AssertOp;
10961     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10962                                         nullptr, F.getCallingConv(), AssertOp);
10963 
10964     MachineFunction& MF = SDB->DAG.getMachineFunction();
10965     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10966     Register SRetReg =
10967         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10968     FuncInfo->DemoteRegister = SRetReg;
10969     NewRoot =
10970         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10971     DAG.setRoot(NewRoot);
10972 
10973     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10974     ++i;
10975   }
10976 
10977   SmallVector<SDValue, 4> Chains;
10978   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10979   for (const Argument &Arg : F.args()) {
10980     SmallVector<SDValue, 4> ArgValues;
10981     SmallVector<EVT, 4> ValueVTs;
10982     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10983     unsigned NumValues = ValueVTs.size();
10984     if (NumValues == 0)
10985       continue;
10986 
10987     bool ArgHasUses = !Arg.use_empty();
10988 
10989     // Elide the copying store if the target loaded this argument from a
10990     // suitable fixed stack object.
10991     if (Ins[i].Flags.isCopyElisionCandidate()) {
10992       unsigned NumParts = 0;
10993       for (EVT VT : ValueVTs)
10994         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
10995                                                        F.getCallingConv(), VT);
10996 
10997       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10998                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10999                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11000     }
11001 
11002     // If this argument is unused then remember its value. It is used to generate
11003     // debugging information.
11004     bool isSwiftErrorArg =
11005         TLI->supportSwiftError() &&
11006         Arg.hasAttribute(Attribute::SwiftError);
11007     if (!ArgHasUses && !isSwiftErrorArg) {
11008       SDB->setUnusedArgValue(&Arg, InVals[i]);
11009 
11010       // Also remember any frame index for use in FastISel.
11011       if (FrameIndexSDNode *FI =
11012           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11013         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11014     }
11015 
11016     for (unsigned Val = 0; Val != NumValues; ++Val) {
11017       EVT VT = ValueVTs[Val];
11018       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11019                                                       F.getCallingConv(), VT);
11020       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11021           *CurDAG->getContext(), F.getCallingConv(), VT);
11022 
11023       // Even an apparent 'unused' swifterror argument needs to be returned. So
11024       // we do generate a copy for it that can be used on return from the
11025       // function.
11026       if (ArgHasUses || isSwiftErrorArg) {
11027         std::optional<ISD::NodeType> AssertOp;
11028         if (Arg.hasAttribute(Attribute::SExt))
11029           AssertOp = ISD::AssertSext;
11030         else if (Arg.hasAttribute(Attribute::ZExt))
11031           AssertOp = ISD::AssertZext;
11032 
11033         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11034                                              PartVT, VT, nullptr,
11035                                              F.getCallingConv(), AssertOp));
11036       }
11037 
11038       i += NumParts;
11039     }
11040 
11041     // We don't need to do anything else for unused arguments.
11042     if (ArgValues.empty())
11043       continue;
11044 
11045     // Note down frame index.
11046     if (FrameIndexSDNode *FI =
11047         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11048       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11049 
11050     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11051                                      SDB->getCurSDLoc());
11052 
11053     SDB->setValue(&Arg, Res);
11054     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11055       // We want to associate the argument with the frame index, among
11056       // involved operands, that correspond to the lowest address. The
11057       // getCopyFromParts function, called earlier, is swapping the order of
11058       // the operands to BUILD_PAIR depending on endianness. The result of
11059       // that swapping is that the least significant bits of the argument will
11060       // be in the first operand of the BUILD_PAIR node, and the most
11061       // significant bits will be in the second operand.
11062       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11063       if (LoadSDNode *LNode =
11064           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11065         if (FrameIndexSDNode *FI =
11066             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11067           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11068     }
11069 
11070     // Analyses past this point are naive and don't expect an assertion.
11071     if (Res.getOpcode() == ISD::AssertZext)
11072       Res = Res.getOperand(0);
11073 
11074     // Update the SwiftErrorVRegDefMap.
11075     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11076       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11077       if (Register::isVirtualRegister(Reg))
11078         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11079                                    Reg);
11080     }
11081 
11082     // If this argument is live outside of the entry block, insert a copy from
11083     // wherever we got it to the vreg that other BB's will reference it as.
11084     if (Res.getOpcode() == ISD::CopyFromReg) {
11085       // If we can, though, try to skip creating an unnecessary vreg.
11086       // FIXME: This isn't very clean... it would be nice to make this more
11087       // general.
11088       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11089       if (Register::isVirtualRegister(Reg)) {
11090         FuncInfo->ValueMap[&Arg] = Reg;
11091         continue;
11092       }
11093     }
11094     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11095       FuncInfo->InitializeRegForValue(&Arg);
11096       SDB->CopyToExportRegsIfNeeded(&Arg);
11097     }
11098   }
11099 
11100   if (!Chains.empty()) {
11101     Chains.push_back(NewRoot);
11102     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11103   }
11104 
11105   DAG.setRoot(NewRoot);
11106 
11107   assert(i == InVals.size() && "Argument register count mismatch!");
11108 
11109   // If any argument copy elisions occurred and we have debug info, update the
11110   // stale frame indices used in the dbg.declare variable info table.
11111   if (!ArgCopyElisionFrameIndexMap.empty()) {
11112     for (MachineFunction::VariableDbgInfo &VI :
11113          MF->getInStackSlotVariableDbgInfo()) {
11114       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11115       if (I != ArgCopyElisionFrameIndexMap.end())
11116         VI.updateStackSlot(I->second);
11117     }
11118   }
11119 
11120   // Finally, if the target has anything special to do, allow it to do so.
11121   emitFunctionEntryCode();
11122 }
11123 
11124 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11125 /// ensure constants are generated when needed.  Remember the virtual registers
11126 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11127 /// directly add them, because expansion might result in multiple MBB's for one
11128 /// BB.  As such, the start of the BB might correspond to a different MBB than
11129 /// the end.
11130 void
11131 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11133 
11134   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11135 
11136   // Check PHI nodes in successors that expect a value to be available from this
11137   // block.
11138   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11139     if (!isa<PHINode>(SuccBB->begin())) continue;
11140     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11141 
11142     // If this terminator has multiple identical successors (common for
11143     // switches), only handle each succ once.
11144     if (!SuccsHandled.insert(SuccMBB).second)
11145       continue;
11146 
11147     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11148 
11149     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11150     // nodes and Machine PHI nodes, but the incoming operands have not been
11151     // emitted yet.
11152     for (const PHINode &PN : SuccBB->phis()) {
11153       // Ignore dead phi's.
11154       if (PN.use_empty())
11155         continue;
11156 
11157       // Skip empty types
11158       if (PN.getType()->isEmptyTy())
11159         continue;
11160 
11161       unsigned Reg;
11162       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11163 
11164       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11165         unsigned &RegOut = ConstantsOut[C];
11166         if (RegOut == 0) {
11167           RegOut = FuncInfo.CreateRegs(C);
11168           // We need to zero/sign extend ConstantInt phi operands to match
11169           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11170           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11171           if (auto *CI = dyn_cast<ConstantInt>(C))
11172             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11173                                                     : ISD::ZERO_EXTEND;
11174           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11175         }
11176         Reg = RegOut;
11177       } else {
11178         DenseMap<const Value *, Register>::iterator I =
11179           FuncInfo.ValueMap.find(PHIOp);
11180         if (I != FuncInfo.ValueMap.end())
11181           Reg = I->second;
11182         else {
11183           assert(isa<AllocaInst>(PHIOp) &&
11184                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11185                  "Didn't codegen value into a register!??");
11186           Reg = FuncInfo.CreateRegs(PHIOp);
11187           CopyValueToVirtualRegister(PHIOp, Reg);
11188         }
11189       }
11190 
11191       // Remember that this register needs to added to the machine PHI node as
11192       // the input for this MBB.
11193       SmallVector<EVT, 4> ValueVTs;
11194       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11195       for (EVT VT : ValueVTs) {
11196         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11197         for (unsigned i = 0; i != NumRegisters; ++i)
11198           FuncInfo.PHINodesToUpdate.push_back(
11199               std::make_pair(&*MBBI++, Reg + i));
11200         Reg += NumRegisters;
11201       }
11202     }
11203   }
11204 
11205   ConstantsOut.clear();
11206 }
11207 
11208 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11209   MachineFunction::iterator I(MBB);
11210   if (++I == FuncInfo.MF->end())
11211     return nullptr;
11212   return &*I;
11213 }
11214 
11215 /// During lowering new call nodes can be created (such as memset, etc.).
11216 /// Those will become new roots of the current DAG, but complications arise
11217 /// when they are tail calls. In such cases, the call lowering will update
11218 /// the root, but the builder still needs to know that a tail call has been
11219 /// lowered in order to avoid generating an additional return.
11220 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11221   // If the node is null, we do have a tail call.
11222   if (MaybeTC.getNode() != nullptr)
11223     DAG.setRoot(MaybeTC);
11224   else
11225     HasTailCall = true;
11226 }
11227 
11228 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11229                                         MachineBasicBlock *SwitchMBB,
11230                                         MachineBasicBlock *DefaultMBB) {
11231   MachineFunction *CurMF = FuncInfo.MF;
11232   MachineBasicBlock *NextMBB = nullptr;
11233   MachineFunction::iterator BBI(W.MBB);
11234   if (++BBI != FuncInfo.MF->end())
11235     NextMBB = &*BBI;
11236 
11237   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11238 
11239   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11240 
11241   if (Size == 2 && W.MBB == SwitchMBB) {
11242     // If any two of the cases has the same destination, and if one value
11243     // is the same as the other, but has one bit unset that the other has set,
11244     // use bit manipulation to do two compares at once.  For example:
11245     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11246     // TODO: This could be extended to merge any 2 cases in switches with 3
11247     // cases.
11248     // TODO: Handle cases where W.CaseBB != SwitchBB.
11249     CaseCluster &Small = *W.FirstCluster;
11250     CaseCluster &Big = *W.LastCluster;
11251 
11252     if (Small.Low == Small.High && Big.Low == Big.High &&
11253         Small.MBB == Big.MBB) {
11254       const APInt &SmallValue = Small.Low->getValue();
11255       const APInt &BigValue = Big.Low->getValue();
11256 
11257       // Check that there is only one bit different.
11258       APInt CommonBit = BigValue ^ SmallValue;
11259       if (CommonBit.isPowerOf2()) {
11260         SDValue CondLHS = getValue(Cond);
11261         EVT VT = CondLHS.getValueType();
11262         SDLoc DL = getCurSDLoc();
11263 
11264         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11265                                  DAG.getConstant(CommonBit, DL, VT));
11266         SDValue Cond = DAG.getSetCC(
11267             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11268             ISD::SETEQ);
11269 
11270         // Update successor info.
11271         // Both Small and Big will jump to Small.BB, so we sum up the
11272         // probabilities.
11273         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11274         if (BPI)
11275           addSuccessorWithProb(
11276               SwitchMBB, DefaultMBB,
11277               // The default destination is the first successor in IR.
11278               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11279         else
11280           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11281 
11282         // Insert the true branch.
11283         SDValue BrCond =
11284             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11285                         DAG.getBasicBlock(Small.MBB));
11286         // Insert the false branch.
11287         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11288                              DAG.getBasicBlock(DefaultMBB));
11289 
11290         DAG.setRoot(BrCond);
11291         return;
11292       }
11293     }
11294   }
11295 
11296   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11297     // Here, we order cases by probability so the most likely case will be
11298     // checked first. However, two clusters can have the same probability in
11299     // which case their relative ordering is non-deterministic. So we use Low
11300     // as a tie-breaker as clusters are guaranteed to never overlap.
11301     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11302                [](const CaseCluster &a, const CaseCluster &b) {
11303       return a.Prob != b.Prob ?
11304              a.Prob > b.Prob :
11305              a.Low->getValue().slt(b.Low->getValue());
11306     });
11307 
11308     // Rearrange the case blocks so that the last one falls through if possible
11309     // without changing the order of probabilities.
11310     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11311       --I;
11312       if (I->Prob > W.LastCluster->Prob)
11313         break;
11314       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11315         std::swap(*I, *W.LastCluster);
11316         break;
11317       }
11318     }
11319   }
11320 
11321   // Compute total probability.
11322   BranchProbability DefaultProb = W.DefaultProb;
11323   BranchProbability UnhandledProbs = DefaultProb;
11324   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11325     UnhandledProbs += I->Prob;
11326 
11327   MachineBasicBlock *CurMBB = W.MBB;
11328   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11329     bool FallthroughUnreachable = false;
11330     MachineBasicBlock *Fallthrough;
11331     if (I == W.LastCluster) {
11332       // For the last cluster, fall through to the default destination.
11333       Fallthrough = DefaultMBB;
11334       FallthroughUnreachable = isa<UnreachableInst>(
11335           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11336     } else {
11337       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11338       CurMF->insert(BBI, Fallthrough);
11339       // Put Cond in a virtual register to make it available from the new blocks.
11340       ExportFromCurrentBlock(Cond);
11341     }
11342     UnhandledProbs -= I->Prob;
11343 
11344     switch (I->Kind) {
11345       case CC_JumpTable: {
11346         // FIXME: Optimize away range check based on pivot comparisons.
11347         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11348         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11349 
11350         // The jump block hasn't been inserted yet; insert it here.
11351         MachineBasicBlock *JumpMBB = JT->MBB;
11352         CurMF->insert(BBI, JumpMBB);
11353 
11354         auto JumpProb = I->Prob;
11355         auto FallthroughProb = UnhandledProbs;
11356 
11357         // If the default statement is a target of the jump table, we evenly
11358         // distribute the default probability to successors of CurMBB. Also
11359         // update the probability on the edge from JumpMBB to Fallthrough.
11360         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11361                                               SE = JumpMBB->succ_end();
11362              SI != SE; ++SI) {
11363           if (*SI == DefaultMBB) {
11364             JumpProb += DefaultProb / 2;
11365             FallthroughProb -= DefaultProb / 2;
11366             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11367             JumpMBB->normalizeSuccProbs();
11368             break;
11369           }
11370         }
11371 
11372         // If the default clause is unreachable, propagate that knowledge into
11373         // JTH->FallthroughUnreachable which will use it to suppress the range
11374         // check.
11375         //
11376         // However, don't do this if we're doing branch target enforcement,
11377         // because a table branch _without_ a range check can be a tempting JOP
11378         // gadget - out-of-bounds inputs that are impossible in correct
11379         // execution become possible again if an attacker can influence the
11380         // control flow. So if an attacker doesn't already have a BTI bypass
11381         // available, we don't want them to be able to get one out of this
11382         // table branch.
11383         if (FallthroughUnreachable) {
11384           Function &CurFunc = CurMF->getFunction();
11385           bool HasBranchTargetEnforcement = false;
11386           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11387             HasBranchTargetEnforcement =
11388                 CurFunc.getFnAttribute("branch-target-enforcement")
11389                     .getValueAsBool();
11390           } else {
11391             HasBranchTargetEnforcement =
11392                 CurMF->getMMI().getModule()->getModuleFlag(
11393                     "branch-target-enforcement");
11394           }
11395           if (!HasBranchTargetEnforcement)
11396             JTH->FallthroughUnreachable = true;
11397         }
11398 
11399         if (!JTH->FallthroughUnreachable)
11400           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11401         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11402         CurMBB->normalizeSuccProbs();
11403 
11404         // The jump table header will be inserted in our current block, do the
11405         // range check, and fall through to our fallthrough block.
11406         JTH->HeaderBB = CurMBB;
11407         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11408 
11409         // If we're in the right place, emit the jump table header right now.
11410         if (CurMBB == SwitchMBB) {
11411           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11412           JTH->Emitted = true;
11413         }
11414         break;
11415       }
11416       case CC_BitTests: {
11417         // FIXME: Optimize away range check based on pivot comparisons.
11418         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11419 
11420         // The bit test blocks haven't been inserted yet; insert them here.
11421         for (BitTestCase &BTC : BTB->Cases)
11422           CurMF->insert(BBI, BTC.ThisBB);
11423 
11424         // Fill in fields of the BitTestBlock.
11425         BTB->Parent = CurMBB;
11426         BTB->Default = Fallthrough;
11427 
11428         BTB->DefaultProb = UnhandledProbs;
11429         // If the cases in bit test don't form a contiguous range, we evenly
11430         // distribute the probability on the edge to Fallthrough to two
11431         // successors of CurMBB.
11432         if (!BTB->ContiguousRange) {
11433           BTB->Prob += DefaultProb / 2;
11434           BTB->DefaultProb -= DefaultProb / 2;
11435         }
11436 
11437         if (FallthroughUnreachable)
11438           BTB->FallthroughUnreachable = true;
11439 
11440         // If we're in the right place, emit the bit test header right now.
11441         if (CurMBB == SwitchMBB) {
11442           visitBitTestHeader(*BTB, SwitchMBB);
11443           BTB->Emitted = true;
11444         }
11445         break;
11446       }
11447       case CC_Range: {
11448         const Value *RHS, *LHS, *MHS;
11449         ISD::CondCode CC;
11450         if (I->Low == I->High) {
11451           // Check Cond == I->Low.
11452           CC = ISD::SETEQ;
11453           LHS = Cond;
11454           RHS=I->Low;
11455           MHS = nullptr;
11456         } else {
11457           // Check I->Low <= Cond <= I->High.
11458           CC = ISD::SETLE;
11459           LHS = I->Low;
11460           MHS = Cond;
11461           RHS = I->High;
11462         }
11463 
11464         // If Fallthrough is unreachable, fold away the comparison.
11465         if (FallthroughUnreachable)
11466           CC = ISD::SETTRUE;
11467 
11468         // The false probability is the sum of all unhandled cases.
11469         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11470                      getCurSDLoc(), I->Prob, UnhandledProbs);
11471 
11472         if (CurMBB == SwitchMBB)
11473           visitSwitchCase(CB, SwitchMBB);
11474         else
11475           SL->SwitchCases.push_back(CB);
11476 
11477         break;
11478       }
11479     }
11480     CurMBB = Fallthrough;
11481   }
11482 }
11483 
11484 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11485                                               CaseClusterIt First,
11486                                               CaseClusterIt Last) {
11487   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11488     if (X.Prob != CC.Prob)
11489       return X.Prob > CC.Prob;
11490 
11491     // Ties are broken by comparing the case value.
11492     return X.Low->getValue().slt(CC.Low->getValue());
11493   });
11494 }
11495 
11496 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11497                                         const SwitchWorkListItem &W,
11498                                         Value *Cond,
11499                                         MachineBasicBlock *SwitchMBB) {
11500   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11501          "Clusters not sorted?");
11502 
11503   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11504 
11505   // Balance the tree based on branch probabilities to create a near-optimal (in
11506   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11507   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11508   CaseClusterIt LastLeft = W.FirstCluster;
11509   CaseClusterIt FirstRight = W.LastCluster;
11510   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11511   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11512 
11513   // Move LastLeft and FirstRight towards each other from opposite directions to
11514   // find a partitioning of the clusters which balances the probability on both
11515   // sides. If LeftProb and RightProb are equal, alternate which side is
11516   // taken to ensure 0-probability nodes are distributed evenly.
11517   unsigned I = 0;
11518   while (LastLeft + 1 < FirstRight) {
11519     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11520       LeftProb += (++LastLeft)->Prob;
11521     else
11522       RightProb += (--FirstRight)->Prob;
11523     I++;
11524   }
11525 
11526   while (true) {
11527     // Our binary search tree differs from a typical BST in that ours can have up
11528     // to three values in each leaf. The pivot selection above doesn't take that
11529     // into account, which means the tree might require more nodes and be less
11530     // efficient. We compensate for this here.
11531 
11532     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11533     unsigned NumRight = W.LastCluster - FirstRight + 1;
11534 
11535     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11536       // If one side has less than 3 clusters, and the other has more than 3,
11537       // consider taking a cluster from the other side.
11538 
11539       if (NumLeft < NumRight) {
11540         // Consider moving the first cluster on the right to the left side.
11541         CaseCluster &CC = *FirstRight;
11542         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11543         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11544         if (LeftSideRank <= RightSideRank) {
11545           // Moving the cluster to the left does not demote it.
11546           ++LastLeft;
11547           ++FirstRight;
11548           continue;
11549         }
11550       } else {
11551         assert(NumRight < NumLeft);
11552         // Consider moving the last element on the left to the right side.
11553         CaseCluster &CC = *LastLeft;
11554         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11555         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11556         if (RightSideRank <= LeftSideRank) {
11557           // Moving the cluster to the right does not demot it.
11558           --LastLeft;
11559           --FirstRight;
11560           continue;
11561         }
11562       }
11563     }
11564     break;
11565   }
11566 
11567   assert(LastLeft + 1 == FirstRight);
11568   assert(LastLeft >= W.FirstCluster);
11569   assert(FirstRight <= W.LastCluster);
11570 
11571   // Use the first element on the right as pivot since we will make less-than
11572   // comparisons against it.
11573   CaseClusterIt PivotCluster = FirstRight;
11574   assert(PivotCluster > W.FirstCluster);
11575   assert(PivotCluster <= W.LastCluster);
11576 
11577   CaseClusterIt FirstLeft = W.FirstCluster;
11578   CaseClusterIt LastRight = W.LastCluster;
11579 
11580   const ConstantInt *Pivot = PivotCluster->Low;
11581 
11582   // New blocks will be inserted immediately after the current one.
11583   MachineFunction::iterator BBI(W.MBB);
11584   ++BBI;
11585 
11586   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11587   // we can branch to its destination directly if it's squeezed exactly in
11588   // between the known lower bound and Pivot - 1.
11589   MachineBasicBlock *LeftMBB;
11590   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11591       FirstLeft->Low == W.GE &&
11592       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11593     LeftMBB = FirstLeft->MBB;
11594   } else {
11595     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11596     FuncInfo.MF->insert(BBI, LeftMBB);
11597     WorkList.push_back(
11598         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11599     // Put Cond in a virtual register to make it available from the new blocks.
11600     ExportFromCurrentBlock(Cond);
11601   }
11602 
11603   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11604   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11605   // directly if RHS.High equals the current upper bound.
11606   MachineBasicBlock *RightMBB;
11607   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11608       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11609     RightMBB = FirstRight->MBB;
11610   } else {
11611     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11612     FuncInfo.MF->insert(BBI, RightMBB);
11613     WorkList.push_back(
11614         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11615     // Put Cond in a virtual register to make it available from the new blocks.
11616     ExportFromCurrentBlock(Cond);
11617   }
11618 
11619   // Create the CaseBlock record that will be used to lower the branch.
11620   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11621                getCurSDLoc(), LeftProb, RightProb);
11622 
11623   if (W.MBB == SwitchMBB)
11624     visitSwitchCase(CB, SwitchMBB);
11625   else
11626     SL->SwitchCases.push_back(CB);
11627 }
11628 
11629 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11630 // from the swith statement.
11631 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11632                                             BranchProbability PeeledCaseProb) {
11633   if (PeeledCaseProb == BranchProbability::getOne())
11634     return BranchProbability::getZero();
11635   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11636 
11637   uint32_t Numerator = CaseProb.getNumerator();
11638   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11639   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11640 }
11641 
11642 // Try to peel the top probability case if it exceeds the threshold.
11643 // Return current MachineBasicBlock for the switch statement if the peeling
11644 // does not occur.
11645 // If the peeling is performed, return the newly created MachineBasicBlock
11646 // for the peeled switch statement. Also update Clusters to remove the peeled
11647 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11648 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11649     const SwitchInst &SI, CaseClusterVector &Clusters,
11650     BranchProbability &PeeledCaseProb) {
11651   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11652   // Don't perform if there is only one cluster or optimizing for size.
11653   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11654       TM.getOptLevel() == CodeGenOptLevel::None ||
11655       SwitchMBB->getParent()->getFunction().hasMinSize())
11656     return SwitchMBB;
11657 
11658   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11659   unsigned PeeledCaseIndex = 0;
11660   bool SwitchPeeled = false;
11661   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11662     CaseCluster &CC = Clusters[Index];
11663     if (CC.Prob < TopCaseProb)
11664       continue;
11665     TopCaseProb = CC.Prob;
11666     PeeledCaseIndex = Index;
11667     SwitchPeeled = true;
11668   }
11669   if (!SwitchPeeled)
11670     return SwitchMBB;
11671 
11672   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11673                     << TopCaseProb << "\n");
11674 
11675   // Record the MBB for the peeled switch statement.
11676   MachineFunction::iterator BBI(SwitchMBB);
11677   ++BBI;
11678   MachineBasicBlock *PeeledSwitchMBB =
11679       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11680   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11681 
11682   ExportFromCurrentBlock(SI.getCondition());
11683   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11684   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11685                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11686   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11687 
11688   Clusters.erase(PeeledCaseIt);
11689   for (CaseCluster &CC : Clusters) {
11690     LLVM_DEBUG(
11691         dbgs() << "Scale the probablity for one cluster, before scaling: "
11692                << CC.Prob << "\n");
11693     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11694     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11695   }
11696   PeeledCaseProb = TopCaseProb;
11697   return PeeledSwitchMBB;
11698 }
11699 
11700 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11701   // Extract cases from the switch.
11702   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11703   CaseClusterVector Clusters;
11704   Clusters.reserve(SI.getNumCases());
11705   for (auto I : SI.cases()) {
11706     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11707     const ConstantInt *CaseVal = I.getCaseValue();
11708     BranchProbability Prob =
11709         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11710             : BranchProbability(1, SI.getNumCases() + 1);
11711     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11712   }
11713 
11714   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11715 
11716   // Cluster adjacent cases with the same destination. We do this at all
11717   // optimization levels because it's cheap to do and will make codegen faster
11718   // if there are many clusters.
11719   sortAndRangeify(Clusters);
11720 
11721   // The branch probablity of the peeled case.
11722   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11723   MachineBasicBlock *PeeledSwitchMBB =
11724       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11725 
11726   // If there is only the default destination, jump there directly.
11727   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11728   if (Clusters.empty()) {
11729     assert(PeeledSwitchMBB == SwitchMBB);
11730     SwitchMBB->addSuccessor(DefaultMBB);
11731     if (DefaultMBB != NextBlock(SwitchMBB)) {
11732       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11733                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11734     }
11735     return;
11736   }
11737 
11738   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11739   SL->findBitTestClusters(Clusters, &SI);
11740 
11741   LLVM_DEBUG({
11742     dbgs() << "Case clusters: ";
11743     for (const CaseCluster &C : Clusters) {
11744       if (C.Kind == CC_JumpTable)
11745         dbgs() << "JT:";
11746       if (C.Kind == CC_BitTests)
11747         dbgs() << "BT:";
11748 
11749       C.Low->getValue().print(dbgs(), true);
11750       if (C.Low != C.High) {
11751         dbgs() << '-';
11752         C.High->getValue().print(dbgs(), true);
11753       }
11754       dbgs() << ' ';
11755     }
11756     dbgs() << '\n';
11757   });
11758 
11759   assert(!Clusters.empty());
11760   SwitchWorkList WorkList;
11761   CaseClusterIt First = Clusters.begin();
11762   CaseClusterIt Last = Clusters.end() - 1;
11763   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11764   // Scale the branchprobability for DefaultMBB if the peel occurs and
11765   // DefaultMBB is not replaced.
11766   if (PeeledCaseProb != BranchProbability::getZero() &&
11767       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11768     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11769   WorkList.push_back(
11770       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11771 
11772   while (!WorkList.empty()) {
11773     SwitchWorkListItem W = WorkList.pop_back_val();
11774     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11775 
11776     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
11777         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11778       // For optimized builds, lower large range as a balanced binary tree.
11779       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11780       continue;
11781     }
11782 
11783     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11784   }
11785 }
11786 
11787 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11789   auto DL = getCurSDLoc();
11790   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11791   setValue(&I, DAG.getStepVector(DL, ResultVT));
11792 }
11793 
11794 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11796   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11797 
11798   SDLoc DL = getCurSDLoc();
11799   SDValue V = getValue(I.getOperand(0));
11800   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11801 
11802   if (VT.isScalableVector()) {
11803     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11804     return;
11805   }
11806 
11807   // Use VECTOR_SHUFFLE for the fixed-length vector
11808   // to maintain existing behavior.
11809   SmallVector<int, 8> Mask;
11810   unsigned NumElts = VT.getVectorMinNumElements();
11811   for (unsigned i = 0; i != NumElts; ++i)
11812     Mask.push_back(NumElts - 1 - i);
11813 
11814   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11815 }
11816 
11817 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
11818   auto DL = getCurSDLoc();
11819   SDValue InVec = getValue(I.getOperand(0));
11820   EVT OutVT =
11821       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
11822 
11823   unsigned OutNumElts = OutVT.getVectorMinNumElements();
11824 
11825   // ISD Node needs the input vectors split into two equal parts
11826   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11827                            DAG.getVectorIdxConstant(0, DL));
11828   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
11829                            DAG.getVectorIdxConstant(OutNumElts, DL));
11830 
11831   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11832   // legalisation and combines.
11833   if (OutVT.isFixedLengthVector()) {
11834     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11835                                         createStrideMask(0, 2, OutNumElts));
11836     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
11837                                        createStrideMask(1, 2, OutNumElts));
11838     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
11839     setValue(&I, Res);
11840     return;
11841   }
11842 
11843   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
11844                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
11845   setValue(&I, Res);
11846 }
11847 
11848 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
11849   auto DL = getCurSDLoc();
11850   EVT InVT = getValue(I.getOperand(0)).getValueType();
11851   SDValue InVec0 = getValue(I.getOperand(0));
11852   SDValue InVec1 = getValue(I.getOperand(1));
11853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11854   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11855 
11856   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
11857   // legalisation and combines.
11858   if (OutVT.isFixedLengthVector()) {
11859     unsigned NumElts = InVT.getVectorMinNumElements();
11860     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
11861     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
11862                                       createInterleaveMask(NumElts, 2)));
11863     return;
11864   }
11865 
11866   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
11867                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
11868   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
11869                     Res.getValue(1));
11870   setValue(&I, Res);
11871 }
11872 
11873 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11874   SmallVector<EVT, 4> ValueVTs;
11875   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11876                   ValueVTs);
11877   unsigned NumValues = ValueVTs.size();
11878   if (NumValues == 0) return;
11879 
11880   SmallVector<SDValue, 4> Values(NumValues);
11881   SDValue Op = getValue(I.getOperand(0));
11882 
11883   for (unsigned i = 0; i != NumValues; ++i)
11884     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11885                             SDValue(Op.getNode(), Op.getResNo() + i));
11886 
11887   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11888                            DAG.getVTList(ValueVTs), Values));
11889 }
11890 
11891 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11893   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11894 
11895   SDLoc DL = getCurSDLoc();
11896   SDValue V1 = getValue(I.getOperand(0));
11897   SDValue V2 = getValue(I.getOperand(1));
11898   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11899 
11900   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11901   if (VT.isScalableVector()) {
11902     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11903     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11904                              DAG.getConstant(Imm, DL, IdxVT)));
11905     return;
11906   }
11907 
11908   unsigned NumElts = VT.getVectorNumElements();
11909 
11910   uint64_t Idx = (NumElts + Imm) % NumElts;
11911 
11912   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11913   SmallVector<int, 8> Mask;
11914   for (unsigned i = 0; i < NumElts; ++i)
11915     Mask.push_back(Idx + i);
11916   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11917 }
11918 
11919 // Consider the following MIR after SelectionDAG, which produces output in
11920 // phyregs in the first case or virtregs in the second case.
11921 //
11922 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
11923 // %5:gr32 = COPY $ebx
11924 // %6:gr32 = COPY $edx
11925 // %1:gr32 = COPY %6:gr32
11926 // %0:gr32 = COPY %5:gr32
11927 //
11928 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
11929 // %1:gr32 = COPY %6:gr32
11930 // %0:gr32 = COPY %5:gr32
11931 //
11932 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
11933 // Given %1, we'd like to return $edx in the first case and %6 in the second.
11934 //
11935 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
11936 // to a single virtreg (such as %0). The remaining outputs monotonically
11937 // increase in virtreg number from there. If a callbr has no outputs, then it
11938 // should not have a corresponding callbr landingpad; in fact, the callbr
11939 // landingpad would not even be able to refer to such a callbr.
11940 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
11941   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
11942   // There is definitely at least one copy.
11943   assert(MI->getOpcode() == TargetOpcode::COPY &&
11944          "start of copy chain MUST be COPY");
11945   Reg = MI->getOperand(1).getReg();
11946   MI = MRI.def_begin(Reg)->getParent();
11947   // There may be an optional second copy.
11948   if (MI->getOpcode() == TargetOpcode::COPY) {
11949     assert(Reg.isVirtual() && "expected COPY of virtual register");
11950     Reg = MI->getOperand(1).getReg();
11951     assert(Reg.isPhysical() && "expected COPY of physical register");
11952     MI = MRI.def_begin(Reg)->getParent();
11953   }
11954   // The start of the chain must be an INLINEASM_BR.
11955   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
11956          "end of copy chain MUST be INLINEASM_BR");
11957   return Reg;
11958 }
11959 
11960 // We must do this walk rather than the simpler
11961 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
11962 // otherwise we will end up with copies of virtregs only valid along direct
11963 // edges.
11964 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
11965   SmallVector<EVT, 8> ResultVTs;
11966   SmallVector<SDValue, 8> ResultValues;
11967   const auto *CBR =
11968       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
11969 
11970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11971   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
11972   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11973 
11974   unsigned InitialDef = FuncInfo.ValueMap[CBR];
11975   SDValue Chain = DAG.getRoot();
11976 
11977   // Re-parse the asm constraints string.
11978   TargetLowering::AsmOperandInfoVector TargetConstraints =
11979       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
11980   for (auto &T : TargetConstraints) {
11981     SDISelAsmOperandInfo OpInfo(T);
11982     if (OpInfo.Type != InlineAsm::isOutput)
11983       continue;
11984 
11985     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
11986     // individual constraint.
11987     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
11988 
11989     switch (OpInfo.ConstraintType) {
11990     case TargetLowering::C_Register:
11991     case TargetLowering::C_RegisterClass: {
11992       // Fill in OpInfo.AssignedRegs.Regs.
11993       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
11994 
11995       // getRegistersForValue may produce 1 to many registers based on whether
11996       // the OpInfo.ConstraintVT is legal on the target or not.
11997       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
11998         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
11999         if (Register::isPhysicalRegister(OriginalDef))
12000           FuncInfo.MBB->addLiveIn(OriginalDef);
12001         // Update the assigned registers to use the original defs.
12002         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12003       }
12004 
12005       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12006           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12007       ResultValues.push_back(V);
12008       ResultVTs.push_back(OpInfo.ConstraintVT);
12009       break;
12010     }
12011     case TargetLowering::C_Other: {
12012       SDValue Flag;
12013       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12014                                                   OpInfo, DAG);
12015       ++InitialDef;
12016       ResultValues.push_back(V);
12017       ResultVTs.push_back(OpInfo.ConstraintVT);
12018       break;
12019     }
12020     default:
12021       break;
12022     }
12023   }
12024   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12025                           DAG.getVTList(ResultVTs), ResultValues);
12026   setValue(&I, V);
12027 }
12028