xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 43b86bf9921be5741017db47ae2fa1c8148680b4)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryLocation.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CodeGenCommonISel.h"
36 #include "llvm/CodeGen/FunctionLoweringInfo.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GetElementPtrTypeIterator.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/InstrTypes.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/IntrinsicsAArch64.h"
78 #include "llvm/IR/IntrinsicsWebAssembly.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Metadata.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/Operator.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Statepoint.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/Support/AtomicOrdering.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Compiler.h"
93 #include "llvm/Support/Debug.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetIntrinsicInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include "llvm/Transforms/Utils/Local.h"
100 #include <cstddef>
101 #include <iterator>
102 #include <limits>
103 #include <optional>
104 #include <tuple>
105 
106 using namespace llvm;
107 using namespace PatternMatch;
108 using namespace SwitchCG;
109 
110 #define DEBUG_TYPE "isel"
111 
112 /// LimitFloatPrecision - Generate low-precision inline sequences for
113 /// some float libcalls (6, 8 or 12 bits).
114 static unsigned LimitFloatPrecision;
115 
116 static cl::opt<bool>
117     InsertAssertAlign("insert-assert-align", cl::init(true),
118                       cl::desc("Insert the experimental `assertalign` node."),
119                       cl::ReallyHidden);
120 
121 static cl::opt<unsigned, true>
122     LimitFPPrecision("limit-float-precision",
123                      cl::desc("Generate low-precision inline sequences "
124                               "for some float libcalls"),
125                      cl::location(LimitFloatPrecision), cl::Hidden,
126                      cl::init(0));
127 
128 static cl::opt<unsigned> SwitchPeelThreshold(
129     "switch-peel-threshold", cl::Hidden, cl::init(66),
130     cl::desc("Set the case probability threshold for peeling the case from a "
131              "switch statement. A value greater than 100 will void this "
132              "optimization"));
133 
134 // Limit the width of DAG chains. This is important in general to prevent
135 // DAG-based analysis from blowing up. For example, alias analysis and
136 // load clustering may not complete in reasonable time. It is difficult to
137 // recognize and avoid this situation within each individual analysis, and
138 // future analyses are likely to have the same behavior. Limiting DAG width is
139 // the safe approach and will be especially important with global DAGs.
140 //
141 // MaxParallelChains default is arbitrarily high to avoid affecting
142 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
143 // sequence over this should have been converted to llvm.memcpy by the
144 // frontend. It is easy to induce this behavior with .ll code such as:
145 // %buffer = alloca [4096 x i8]
146 // %data = load [4096 x i8]* %argPtr
147 // store [4096 x i8] %data, [4096 x i8]* %buffer
148 static const unsigned MaxParallelChains = 64;
149 
150 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
151                                       const SDValue *Parts, unsigned NumParts,
152                                       MVT PartVT, EVT ValueVT, const Value *V,
153                                       Optional<CallingConv::ID> CC);
154 
155 /// getCopyFromParts - Create a value that contains the specified legal parts
156 /// combined into the value they represent.  If the parts combine to a type
157 /// larger than ValueVT then AssertOp can be used to specify whether the extra
158 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
159 /// (ISD::AssertSext).
160 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
161                                 const SDValue *Parts, unsigned NumParts,
162                                 MVT PartVT, EVT ValueVT, const Value *V,
163                                 Optional<CallingConv::ID> CC = None,
164                                 Optional<ISD::NodeType> AssertOp = None) {
165   // Let the target assemble the parts if it wants to
166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
167   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
168                                                    PartVT, ValueVT, CC))
169     return Val;
170 
171   if (ValueVT.isVector())
172     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
173                                   CC);
174 
175   assert(NumParts > 0 && "No parts to assemble!");
176   SDValue Val = Parts[0];
177 
178   if (NumParts > 1) {
179     // Assemble the value from multiple parts.
180     if (ValueVT.isInteger()) {
181       unsigned PartBits = PartVT.getSizeInBits();
182       unsigned ValueBits = ValueVT.getSizeInBits();
183 
184       // Assemble the power of 2 part.
185       unsigned RoundParts =
186           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
187       unsigned RoundBits = PartBits * RoundParts;
188       EVT RoundVT = RoundBits == ValueBits ?
189         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
190       SDValue Lo, Hi;
191 
192       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
193 
194       if (RoundParts > 2) {
195         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
196                               PartVT, HalfVT, V);
197         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
198                               RoundParts / 2, PartVT, HalfVT, V);
199       } else {
200         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
201         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
202       }
203 
204       if (DAG.getDataLayout().isBigEndian())
205         std::swap(Lo, Hi);
206 
207       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
208 
209       if (RoundParts < NumParts) {
210         // Assemble the trailing non-power-of-2 part.
211         unsigned OddParts = NumParts - RoundParts;
212         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
213         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
214                               OddVT, V, CC);
215 
216         // Combine the round and odd parts.
217         Lo = Val;
218         if (DAG.getDataLayout().isBigEndian())
219           std::swap(Lo, Hi);
220         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
221         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
222         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
223                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
224                                          TLI.getShiftAmountTy(
225                                              TotalVT, DAG.getDataLayout())));
226         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
227         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
228       }
229     } else if (PartVT.isFloatingPoint()) {
230       // FP split into multiple FP parts (for ppcf128)
231       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
232              "Unexpected split");
233       SDValue Lo, Hi;
234       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
235       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
236       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
237         std::swap(Lo, Hi);
238       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
239     } else {
240       // FP split into integer parts (soft fp)
241       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
242              !PartVT.isVector() && "Unexpected split");
243       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
244       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
245     }
246   }
247 
248   // There is now one part, held in Val.  Correct it to match ValueVT.
249   // PartEVT is the type of the register class that holds the value.
250   // ValueVT is the type of the inline asm operation.
251   EVT PartEVT = Val.getValueType();
252 
253   if (PartEVT == ValueVT)
254     return Val;
255 
256   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
257       ValueVT.bitsLT(PartEVT)) {
258     // For an FP value in an integer part, we need to truncate to the right
259     // width first.
260     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
261     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
262   }
263 
264   // Handle types that have the same size.
265   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
266     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
267 
268   // Handle types with different sizes.
269   if (PartEVT.isInteger() && ValueVT.isInteger()) {
270     if (ValueVT.bitsLT(PartEVT)) {
271       // For a truncate, see if we have any information to
272       // indicate whether the truncated bits will always be
273       // zero or sign-extension.
274       if (AssertOp)
275         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
276                           DAG.getValueType(ValueVT));
277       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
278     }
279     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
280   }
281 
282   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
283     // FP_ROUND's are always exact here.
284     if (ValueVT.bitsLT(Val.getValueType()))
285       return DAG.getNode(
286           ISD::FP_ROUND, DL, ValueVT, Val,
287           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
288 
289     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
290   }
291 
292   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
293   // then truncating.
294   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
295       ValueVT.bitsLT(PartEVT)) {
296     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
297     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
298   }
299 
300   report_fatal_error("Unknown mismatch in getCopyFromParts!");
301 }
302 
303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
304                                               const Twine &ErrMsg) {
305   const Instruction *I = dyn_cast_or_null<Instruction>(V);
306   if (!V)
307     return Ctx.emitError(ErrMsg);
308 
309   const char *AsmError = ", possible invalid constraint for vector type";
310   if (const CallInst *CI = dyn_cast<CallInst>(I))
311     if (CI->isInlineAsm())
312       return Ctx.emitError(I, ErrMsg + AsmError);
313 
314   return Ctx.emitError(I, ErrMsg);
315 }
316 
317 /// getCopyFromPartsVector - Create a value that contains the specified legal
318 /// parts combined into the value they represent.  If the parts combine to a
319 /// type larger than ValueVT then AssertOp can be used to specify whether the
320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
321 /// ValueVT (ISD::AssertSext).
322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
323                                       const SDValue *Parts, unsigned NumParts,
324                                       MVT PartVT, EVT ValueVT, const Value *V,
325                                       Optional<CallingConv::ID> CallConv) {
326   assert(ValueVT.isVector() && "Not a vector value");
327   assert(NumParts > 0 && "No parts to assemble!");
328   const bool IsABIRegCopy = CallConv.has_value();
329 
330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
331   SDValue Val = Parts[0];
332 
333   // Handle a multi-element vector.
334   if (NumParts > 1) {
335     EVT IntermediateVT;
336     MVT RegisterVT;
337     unsigned NumIntermediates;
338     unsigned NumRegs;
339 
340     if (IsABIRegCopy) {
341       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
342           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
343           NumIntermediates, RegisterVT);
344     } else {
345       NumRegs =
346           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
347                                      NumIntermediates, RegisterVT);
348     }
349 
350     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
351     NumParts = NumRegs; // Silence a compiler warning.
352     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
353     assert(RegisterVT.getSizeInBits() ==
354            Parts[0].getSimpleValueType().getSizeInBits() &&
355            "Part type sizes don't match!");
356 
357     // Assemble the parts into intermediate operands.
358     SmallVector<SDValue, 8> Ops(NumIntermediates);
359     if (NumIntermediates == NumParts) {
360       // If the register was not expanded, truncate or copy the value,
361       // as appropriate.
362       for (unsigned i = 0; i != NumParts; ++i)
363         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
364                                   PartVT, IntermediateVT, V, CallConv);
365     } else if (NumParts > 0) {
366       // If the intermediate type was expanded, build the intermediate
367       // operands from the parts.
368       assert(NumParts % NumIntermediates == 0 &&
369              "Must expand into a divisible number of parts!");
370       unsigned Factor = NumParts / NumIntermediates;
371       for (unsigned i = 0; i != NumIntermediates; ++i)
372         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
373                                   PartVT, IntermediateVT, V, CallConv);
374     }
375 
376     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
377     // intermediate operands.
378     EVT BuiltVectorTy =
379         IntermediateVT.isVector()
380             ? EVT::getVectorVT(
381                   *DAG.getContext(), IntermediateVT.getScalarType(),
382                   IntermediateVT.getVectorElementCount() * NumParts)
383             : EVT::getVectorVT(*DAG.getContext(),
384                                IntermediateVT.getScalarType(),
385                                NumIntermediates);
386     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
387                                                 : ISD::BUILD_VECTOR,
388                       DL, BuiltVectorTy, Ops);
389   }
390 
391   // There is now one part, held in Val.  Correct it to match ValueVT.
392   EVT PartEVT = Val.getValueType();
393 
394   if (PartEVT == ValueVT)
395     return Val;
396 
397   if (PartEVT.isVector()) {
398     // Vector/Vector bitcast.
399     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
400       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
401 
402     // If the parts vector has more elements than the value vector, then we
403     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
404     // Extract the elements we want.
405     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
406       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
407               ValueVT.getVectorElementCount().getKnownMinValue()) &&
408              (PartEVT.getVectorElementCount().isScalable() ==
409               ValueVT.getVectorElementCount().isScalable()) &&
410              "Cannot narrow, it would be a lossy transformation");
411       PartEVT =
412           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
413                            ValueVT.getVectorElementCount());
414       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
415                         DAG.getVectorIdxConstant(0, DL));
416       if (PartEVT == ValueVT)
417         return Val;
418       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
419         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420     }
421 
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424   }
425 
426   // Trivial bitcast if the types are the same size and the destination
427   // vector type is legal.
428   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
429       TLI.isTypeLegal(ValueVT))
430     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
431 
432   if (ValueVT.getVectorNumElements() != 1) {
433      // Certain ABIs require that vectors are passed as integers. For vectors
434      // are the same size, this is an obvious bitcast.
435      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
436        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437      } else if (ValueVT.bitsLT(PartEVT)) {
438        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
439        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
440        // Drop the extra bits.
441        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
442        return DAG.getBitcast(ValueVT, Val);
443      }
444 
445      diagnosePossiblyInvalidConstraint(
446          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
447      return DAG.getUNDEF(ValueVT);
448   }
449 
450   // Handle cases such as i8 -> <1 x i1>
451   EVT ValueSVT = ValueVT.getVectorElementType();
452   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
453     unsigned ValueSize = ValueSVT.getSizeInBits();
454     if (ValueSize == PartEVT.getSizeInBits()) {
455       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
457       // It's possible a scalar floating point type gets softened to integer and
458       // then promoted to a larger integer. If PartEVT is the larger integer
459       // we need to truncate it and then bitcast to the FP type.
460       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
461       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463       Val = DAG.getBitcast(ValueSVT, Val);
464     } else {
465       Val = ValueVT.isFloatingPoint()
466                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
467                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
468     }
469   }
470 
471   return DAG.getBuildVector(ValueVT, DL, Val);
472 }
473 
474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
475                                  SDValue Val, SDValue *Parts, unsigned NumParts,
476                                  MVT PartVT, const Value *V,
477                                  Optional<CallingConv::ID> CallConv);
478 
479 /// getCopyToParts - Create a series of nodes that contain the specified value
480 /// split into legal parts.  If the parts contain more bits than Val, then, for
481 /// integers, ExtendKind can be used to specify how to generate the extra bits.
482 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
483                            SDValue *Parts, unsigned NumParts, MVT PartVT,
484                            const Value *V,
485                            Optional<CallingConv::ID> CallConv = None,
486                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
487   // Let the target split the parts if it wants to
488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
489   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
490                                       CallConv))
491     return;
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned PartBits = PartVT.getSizeInBits();
500   unsigned OrigNumParts = NumParts;
501   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
502          "Copying to an illegal type!");
503 
504   if (NumParts == 0)
505     return;
506 
507   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
508   EVT PartEVT = PartVT;
509   if (PartEVT == ValueVT) {
510     assert(NumParts == 1 && "No-op copy with multiple parts!");
511     Parts[0] = Val;
512     return;
513   }
514 
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = 1 << Log2_32(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
576 
577     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578                    CallConv);
579 
580     if (DAG.getDataLayout().isBigEndian())
581       // The odd parts were reversed by getCopyToParts - unreverse them.
582       std::reverse(Parts + RoundParts, Parts + NumParts);
583 
584     NumParts = RoundParts;
585     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587   }
588 
589   // The number of parts is a power of 2.  Repeatedly bisect the value using
590   // EXTRACT_ELEMENT.
591   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592                          EVT::getIntegerVT(*DAG.getContext(),
593                                            ValueVT.getSizeInBits()),
594                          Val);
595 
596   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597     for (unsigned i = 0; i < NumParts; i += StepSize) {
598       unsigned ThisBits = StepSize * PartBits / 2;
599       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600       SDValue &Part0 = Parts[i];
601       SDValue &Part1 = Parts[i+StepSize/2];
602 
603       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607 
608       if (ThisBits == PartBits && ThisVT != PartVT) {
609         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611       }
612     }
613   }
614 
615   if (DAG.getDataLayout().isBigEndian())
616     std::reverse(Parts, Parts + OrigNumParts);
617 }
618 
619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
620                                      const SDLoc &DL, EVT PartVT) {
621   if (!PartVT.isVector())
622     return SDValue();
623 
624   EVT ValueVT = Val.getValueType();
625   ElementCount PartNumElts = PartVT.getVectorElementCount();
626   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
627 
628   // We only support widening vectors with equivalent element types and
629   // fixed/scalable properties. If a target needs to widen a fixed-length type
630   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
631   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
632       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
633       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
634     return SDValue();
635 
636   // Widening a scalable vector to another scalable vector is done by inserting
637   // the vector into a larger undef one.
638   if (PartNumElts.isScalable())
639     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
640                        Val, DAG.getVectorIdxConstant(0, DL));
641 
642   EVT ElementVT = PartVT.getVectorElementType();
643   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
644   // undef elements.
645   SmallVector<SDValue, 16> Ops;
646   DAG.ExtractVectorElements(Val, Ops);
647   SDValue EltUndef = DAG.getUNDEF(ElementVT);
648   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
649 
650   // FIXME: Use CONCAT for 2x -> 4x.
651   return DAG.getBuildVector(PartVT, DL, Ops);
652 }
653 
654 /// getCopyToPartsVector - Create a series of nodes that contain the specified
655 /// value split into legal parts.
656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
657                                  SDValue Val, SDValue *Parts, unsigned NumParts,
658                                  MVT PartVT, const Value *V,
659                                  Optional<CallingConv::ID> CallConv) {
660   EVT ValueVT = Val.getValueType();
661   assert(ValueVT.isVector() && "Not a vector");
662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
663   const bool IsABIRegCopy = CallConv.has_value();
664 
665   if (NumParts == 1) {
666     EVT PartEVT = PartVT;
667     if (PartEVT == ValueVT) {
668       // Nothing to do.
669     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
670       // Bitconvert vector->vector case.
671       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
672     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
673       Val = Widened;
674     } else if (PartVT.isVector() &&
675                PartEVT.getVectorElementType().bitsGE(
676                    ValueVT.getVectorElementType()) &&
677                PartEVT.getVectorElementCount() ==
678                    ValueVT.getVectorElementCount()) {
679 
680       // Promoted vector extract
681       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
682     } else if (PartEVT.isVector() &&
683                PartEVT.getVectorElementType() !=
684                    ValueVT.getVectorElementType() &&
685                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
686                    TargetLowering::TypeWidenVector) {
687       // Combination of widening and promotion.
688       EVT WidenVT =
689           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
690                            PartVT.getVectorElementCount());
691       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
692       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
693     } else {
694       // Don't extract an integer from a float vector. This can happen if the
695       // FP type gets softened to integer and then promoted. The promotion
696       // prevents it from being picked up by the earlier bitcast case.
697       if (ValueVT.getVectorElementCount().isScalar() &&
698           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
699         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
700                           DAG.getVectorIdxConstant(0, DL));
701       } else {
702         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
703         assert(PartVT.getFixedSizeInBits() > ValueSize &&
704                "lossy conversion of vector to scalar type");
705         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
706         Val = DAG.getBitcast(IntermediateType, Val);
707         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
708       }
709     }
710 
711     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
712     Parts[0] = Val;
713     return;
714   }
715 
716   // Handle a multi-element vector.
717   EVT IntermediateVT;
718   MVT RegisterVT;
719   unsigned NumIntermediates;
720   unsigned NumRegs;
721   if (IsABIRegCopy) {
722     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
723         *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT,
724         NumIntermediates, RegisterVT);
725   } else {
726     NumRegs =
727         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
728                                    NumIntermediates, RegisterVT);
729   }
730 
731   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
732   NumParts = NumRegs; // Silence a compiler warning.
733   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
734 
735   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
736          "Mixing scalable and fixed vectors when copying in parts");
737 
738   std::optional<ElementCount> DestEltCnt;
739 
740   if (IntermediateVT.isVector())
741     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
742   else
743     DestEltCnt = ElementCount::getFixed(NumIntermediates);
744 
745   EVT BuiltVectorTy = EVT::getVectorVT(
746       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
747 
748   if (ValueVT == BuiltVectorTy) {
749     // Nothing to do.
750   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
751     // Bitconvert vector->vector case.
752     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
753   } else {
754     if (BuiltVectorTy.getVectorElementType().bitsGT(
755             ValueVT.getVectorElementType())) {
756       // Integer promotion.
757       ValueVT = EVT::getVectorVT(*DAG.getContext(),
758                                  BuiltVectorTy.getVectorElementType(),
759                                  ValueVT.getVectorElementCount());
760       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
761     }
762 
763     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
764       Val = Widened;
765     }
766   }
767 
768   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
769 
770   // Split the vector into intermediate operands.
771   SmallVector<SDValue, 8> Ops(NumIntermediates);
772   for (unsigned i = 0; i != NumIntermediates; ++i) {
773     if (IntermediateVT.isVector()) {
774       // This does something sensible for scalable vectors - see the
775       // definition of EXTRACT_SUBVECTOR for further details.
776       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
777       Ops[i] =
778           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
779                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
780     } else {
781       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
782                            DAG.getVectorIdxConstant(i, DL));
783     }
784   }
785 
786   // Split the intermediate operands into legal parts.
787   if (NumParts == NumIntermediates) {
788     // If the register was not expanded, promote or copy the value,
789     // as appropriate.
790     for (unsigned i = 0; i != NumParts; ++i)
791       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
792   } else if (NumParts > 0) {
793     // If the intermediate type was expanded, split each the value into
794     // legal parts.
795     assert(NumIntermediates != 0 && "division by zero");
796     assert(NumParts % NumIntermediates == 0 &&
797            "Must expand into a divisible number of parts!");
798     unsigned Factor = NumParts / NumIntermediates;
799     for (unsigned i = 0; i != NumIntermediates; ++i)
800       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
801                      CallConv);
802   }
803 }
804 
805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
806                            EVT valuevt, Optional<CallingConv::ID> CC)
807     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
808       RegCount(1, regs.size()), CallConv(CC) {}
809 
810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
811                            const DataLayout &DL, unsigned Reg, Type *Ty,
812                            Optional<CallingConv::ID> CC) {
813   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
814 
815   CallConv = CC;
816 
817   for (EVT ValueVT : ValueVTs) {
818     unsigned NumRegs =
819         isABIMangled()
820             ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT)
821             : TLI.getNumRegisters(Context, ValueVT);
822     MVT RegisterVT =
823         isABIMangled()
824             ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT)
825             : TLI.getRegisterType(Context, ValueVT);
826     for (unsigned i = 0; i != NumRegs; ++i)
827       Regs.push_back(Reg + i);
828     RegVTs.push_back(RegisterVT);
829     RegCount.push_back(NumRegs);
830     Reg += NumRegs;
831   }
832 }
833 
834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
835                                       FunctionLoweringInfo &FuncInfo,
836                                       const SDLoc &dl, SDValue &Chain,
837                                       SDValue *Flag, const Value *V) const {
838   // A Value with type {} or [0 x %t] needs no registers.
839   if (ValueVTs.empty())
840     return SDValue();
841 
842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
843 
844   // Assemble the legal parts into the final values.
845   SmallVector<SDValue, 4> Values(ValueVTs.size());
846   SmallVector<SDValue, 8> Parts;
847   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
848     // Copy the legal parts from the registers.
849     EVT ValueVT = ValueVTs[Value];
850     unsigned NumRegs = RegCount[Value];
851     MVT RegisterVT =
852         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
853                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
854                        : RegVTs[Value];
855 
856     Parts.resize(NumRegs);
857     for (unsigned i = 0; i != NumRegs; ++i) {
858       SDValue P;
859       if (!Flag) {
860         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
861       } else {
862         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
863         *Flag = P.getValue(2);
864       }
865 
866       Chain = P.getValue(1);
867       Parts[i] = P;
868 
869       // If the source register was virtual and if we know something about it,
870       // add an assert node.
871       if (!Register::isVirtualRegister(Regs[Part + i]) ||
872           !RegisterVT.isInteger())
873         continue;
874 
875       const FunctionLoweringInfo::LiveOutInfo *LOI =
876         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
877       if (!LOI)
878         continue;
879 
880       unsigned RegSize = RegisterVT.getScalarSizeInBits();
881       unsigned NumSignBits = LOI->NumSignBits;
882       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
883 
884       if (NumZeroBits == RegSize) {
885         // The current value is a zero.
886         // Explicitly express that as it would be easier for
887         // optimizations to kick in.
888         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
889         continue;
890       }
891 
892       // FIXME: We capture more information than the dag can represent.  For
893       // now, just use the tightest assertzext/assertsext possible.
894       bool isSExt;
895       EVT FromVT(MVT::Other);
896       if (NumZeroBits) {
897         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
898         isSExt = false;
899       } else if (NumSignBits > 1) {
900         FromVT =
901             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
902         isSExt = true;
903       } else {
904         continue;
905       }
906       // Add an assertion node.
907       assert(FromVT != MVT::Other);
908       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
909                              RegisterVT, P, DAG.getValueType(FromVT));
910     }
911 
912     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
913                                      RegisterVT, ValueVT, V, CallConv);
914     Part += NumRegs;
915     Parts.clear();
916   }
917 
918   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
919 }
920 
921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
922                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
923                                  const Value *V,
924                                  ISD::NodeType PreferredExtendType) const {
925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926   ISD::NodeType ExtendKind = PreferredExtendType;
927 
928   // Get the list of the values's legal parts.
929   unsigned NumRegs = Regs.size();
930   SmallVector<SDValue, 8> Parts(NumRegs);
931   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
932     unsigned NumParts = RegCount[Value];
933 
934     MVT RegisterVT =
935         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
936                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
937                        : RegVTs[Value];
938 
939     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
940       ExtendKind = ISD::ZERO_EXTEND;
941 
942     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
943                    NumParts, RegisterVT, V, CallConv, ExtendKind);
944     Part += NumParts;
945   }
946 
947   // Copy the parts into the registers.
948   SmallVector<SDValue, 8> Chains(NumRegs);
949   for (unsigned i = 0; i != NumRegs; ++i) {
950     SDValue Part;
951     if (!Flag) {
952       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
953     } else {
954       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
955       *Flag = Part.getValue(1);
956     }
957 
958     Chains[i] = Part.getValue(0);
959   }
960 
961   if (NumRegs == 1 || Flag)
962     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
963     // flagged to it. That is the CopyToReg nodes and the user are considered
964     // a single scheduling unit. If we create a TokenFactor and return it as
965     // chain, then the TokenFactor is both a predecessor (operand) of the
966     // user as well as a successor (the TF operands are flagged to the user).
967     // c1, f1 = CopyToReg
968     // c2, f2 = CopyToReg
969     // c3     = TokenFactor c1, c2
970     // ...
971     //        = op c3, ..., f2
972     Chain = Chains[NumRegs-1];
973   else
974     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
975 }
976 
977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
978                                         unsigned MatchingIdx, const SDLoc &dl,
979                                         SelectionDAG &DAG,
980                                         std::vector<SDValue> &Ops) const {
981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
982 
983   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
984   if (HasMatching)
985     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
986   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
987     // Put the register class of the virtual registers in the flag word.  That
988     // way, later passes can recompute register class constraints for inline
989     // assembly as well as normal instructions.
990     // Don't do this for tied operands that can use the regclass information
991     // from the def.
992     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
993     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
994     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
995   }
996 
997   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
998   Ops.push_back(Res);
999 
1000   if (Code == InlineAsm::Kind_Clobber) {
1001     // Clobbers should always have a 1:1 mapping with registers, and may
1002     // reference registers that have illegal (e.g. vector) types. Hence, we
1003     // shouldn't try to apply any sort of splitting logic to them.
1004     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1005            "No 1:1 mapping from clobbers to regs?");
1006     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1007     (void)SP;
1008     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1009       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1010       assert(
1011           (Regs[I] != SP ||
1012            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1013           "If we clobbered the stack pointer, MFI should know about it.");
1014     }
1015     return;
1016   }
1017 
1018   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1019     MVT RegisterVT = RegVTs[Value];
1020     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1021                                            RegisterVT);
1022     for (unsigned i = 0; i != NumRegs; ++i) {
1023       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1024       unsigned TheReg = Regs[Reg++];
1025       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1026     }
1027   }
1028 }
1029 
1030 SmallVector<std::pair<unsigned, TypeSize>, 4>
1031 RegsForValue::getRegsAndSizes() const {
1032   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1033   unsigned I = 0;
1034   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1035     unsigned RegCount = std::get<0>(CountAndVT);
1036     MVT RegisterVT = std::get<1>(CountAndVT);
1037     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1038     for (unsigned E = I + RegCount; I != E; ++I)
1039       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1040   }
1041   return OutVec;
1042 }
1043 
1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1045                                AssumptionCache *ac,
1046                                const TargetLibraryInfo *li) {
1047   AA = aa;
1048   AC = ac;
1049   GFI = gfi;
1050   LibInfo = li;
1051   Context = DAG.getContext();
1052   LPadToCallSiteMap.clear();
1053   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1054 }
1055 
1056 void SelectionDAGBuilder::clear() {
1057   NodeMap.clear();
1058   UnusedArgNodeMap.clear();
1059   PendingLoads.clear();
1060   PendingExports.clear();
1061   PendingConstrainedFP.clear();
1062   PendingConstrainedFPStrict.clear();
1063   CurInst = nullptr;
1064   HasTailCall = false;
1065   SDNodeOrder = LowestSDNodeOrder;
1066   StatepointLowering.clear();
1067 }
1068 
1069 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1070   DanglingDebugInfoMap.clear();
1071 }
1072 
1073 // Update DAG root to include dependencies on Pending chains.
1074 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1075   SDValue Root = DAG.getRoot();
1076 
1077   if (Pending.empty())
1078     return Root;
1079 
1080   // Add current root to PendingChains, unless we already indirectly
1081   // depend on it.
1082   if (Root.getOpcode() != ISD::EntryToken) {
1083     unsigned i = 0, e = Pending.size();
1084     for (; i != e; ++i) {
1085       assert(Pending[i].getNode()->getNumOperands() > 1);
1086       if (Pending[i].getNode()->getOperand(0) == Root)
1087         break;  // Don't add the root if we already indirectly depend on it.
1088     }
1089 
1090     if (i == e)
1091       Pending.push_back(Root);
1092   }
1093 
1094   if (Pending.size() == 1)
1095     Root = Pending[0];
1096   else
1097     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1098 
1099   DAG.setRoot(Root);
1100   Pending.clear();
1101   return Root;
1102 }
1103 
1104 SDValue SelectionDAGBuilder::getMemoryRoot() {
1105   return updateRoot(PendingLoads);
1106 }
1107 
1108 SDValue SelectionDAGBuilder::getRoot() {
1109   // Chain up all pending constrained intrinsics together with all
1110   // pending loads, by simply appending them to PendingLoads and
1111   // then calling getMemoryRoot().
1112   PendingLoads.reserve(PendingLoads.size() +
1113                        PendingConstrainedFP.size() +
1114                        PendingConstrainedFPStrict.size());
1115   PendingLoads.append(PendingConstrainedFP.begin(),
1116                       PendingConstrainedFP.end());
1117   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1118                       PendingConstrainedFPStrict.end());
1119   PendingConstrainedFP.clear();
1120   PendingConstrainedFPStrict.clear();
1121   return getMemoryRoot();
1122 }
1123 
1124 SDValue SelectionDAGBuilder::getControlRoot() {
1125   // We need to emit pending fpexcept.strict constrained intrinsics,
1126   // so append them to the PendingExports list.
1127   PendingExports.append(PendingConstrainedFPStrict.begin(),
1128                         PendingConstrainedFPStrict.end());
1129   PendingConstrainedFPStrict.clear();
1130   return updateRoot(PendingExports);
1131 }
1132 
1133 void SelectionDAGBuilder::visit(const Instruction &I) {
1134   // Set up outgoing PHI node register values before emitting the terminator.
1135   if (I.isTerminator()) {
1136     HandlePHINodesInSuccessorBlocks(I.getParent());
1137   }
1138 
1139   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1140   if (!isa<DbgInfoIntrinsic>(I))
1141     ++SDNodeOrder;
1142 
1143   CurInst = &I;
1144 
1145   // Set inserted listener only if required.
1146   bool NodeInserted = false;
1147   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1148   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1149   if (PCSectionsMD) {
1150     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1151         DAG, [&](SDNode *) { NodeInserted = true; });
1152   }
1153 
1154   visit(I.getOpcode(), I);
1155 
1156   if (!I.isTerminator() && !HasTailCall &&
1157       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1158     CopyToExportRegsIfNeeded(&I);
1159 
1160   // Handle metadata.
1161   if (PCSectionsMD) {
1162     auto It = NodeMap.find(&I);
1163     if (It != NodeMap.end()) {
1164       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1165     } else if (NodeInserted) {
1166       // This should not happen; if it does, don't let it go unnoticed so we can
1167       // fix it. Relevant visit*() function is probably missing a setValue().
1168       errs() << "warning: loosing !pcsections metadata ["
1169              << I.getModule()->getName() << "]\n";
1170       LLVM_DEBUG(I.dump());
1171       assert(false);
1172     }
1173   }
1174 
1175   CurInst = nullptr;
1176 }
1177 
1178 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1179   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1180 }
1181 
1182 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1183   // Note: this doesn't use InstVisitor, because it has to work with
1184   // ConstantExpr's in addition to instructions.
1185   switch (Opcode) {
1186   default: llvm_unreachable("Unknown instruction type encountered!");
1187     // Build the switch statement using the Instruction.def file.
1188 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1189     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1190 #include "llvm/IR/Instruction.def"
1191   }
1192 }
1193 
1194 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1195                                                unsigned Order) {
1196   // We treat variadic dbg_values differently at this stage.
1197   if (DI->hasArgList()) {
1198     // For variadic dbg_values we will now insert an undef.
1199     // FIXME: We can potentially recover these!
1200     SmallVector<SDDbgOperand, 2> Locs;
1201     for (const Value *V : DI->getValues()) {
1202       auto Undef = UndefValue::get(V->getType());
1203       Locs.push_back(SDDbgOperand::fromConst(Undef));
1204     }
1205     SDDbgValue *SDV = DAG.getDbgValueList(
1206         DI->getVariable(), DI->getExpression(), Locs, {},
1207         /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true);
1208     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1209   } else {
1210     // TODO: Dangling debug info will eventually either be resolved or produce
1211     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1212     // between the original dbg.value location and its resolved DBG_VALUE,
1213     // which we should ideally fill with an extra Undef DBG_VALUE.
1214     assert(DI->getNumVariableLocationOps() == 1 &&
1215            "DbgValueInst without an ArgList should have a single location "
1216            "operand.");
1217     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1218   }
1219 }
1220 
1221 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1222                                                 const DIExpression *Expr) {
1223   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1224     DIVariable *DanglingVariable = DDI.getVariable();
1225     DIExpression *DanglingExpr = DDI.getExpression();
1226     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1227       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << DDI << "\n");
1228       return true;
1229     }
1230     return false;
1231   };
1232 
1233   for (auto &DDIMI : DanglingDebugInfoMap) {
1234     DanglingDebugInfoVector &DDIV = DDIMI.second;
1235 
1236     // If debug info is to be dropped, run it through final checks to see
1237     // whether it can be salvaged.
1238     for (auto &DDI : DDIV)
1239       if (isMatchingDbgValue(DDI))
1240         salvageUnresolvedDbgValue(DDI);
1241 
1242     erase_if(DDIV, isMatchingDbgValue);
1243   }
1244 }
1245 
1246 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1247 // generate the debug data structures now that we've seen its definition.
1248 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1249                                                    SDValue Val) {
1250   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1251   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1252     return;
1253 
1254   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1255   for (auto &DDI : DDIV) {
1256     DebugLoc DL = DDI.getDebugLoc();
1257     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1258     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1259     DILocalVariable *Variable = DDI.getVariable();
1260     DIExpression *Expr = DDI.getExpression();
1261     assert(Variable->isValidLocationForIntrinsic(DL) &&
1262            "Expected inlined-at fields to agree");
1263     SDDbgValue *SDV;
1264     if (Val.getNode()) {
1265       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1266       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1267       // we couldn't resolve it directly when examining the DbgValue intrinsic
1268       // in the first place we should not be more successful here). Unless we
1269       // have some test case that prove this to be correct we should avoid
1270       // calling EmitFuncArgumentDbgValue here.
1271       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1272                                     FuncArgumentDbgValueKind::Value, Val)) {
1273         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << DDI << "\n");
1274         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1275         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1276         // inserted after the definition of Val when emitting the instructions
1277         // after ISel. An alternative could be to teach
1278         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1279         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1280                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1281                    << ValSDNodeOrder << "\n");
1282         SDV = getDbgValue(Val, Variable, Expr, DL,
1283                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1284         DAG.AddDbgValue(SDV, false);
1285       } else
1286         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << DDI
1287                           << "in EmitFuncArgumentDbgValue\n");
1288     } else {
1289       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DDI << "\n");
1290       auto Undef = UndefValue::get(V->getType());
1291       auto SDV =
1292           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1293       DAG.AddDbgValue(SDV, false);
1294     }
1295   }
1296   DDIV.clear();
1297 }
1298 
1299 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1300   // TODO: For the variadic implementation, instead of only checking the fail
1301   // state of `handleDebugValue`, we need know specifically which values were
1302   // invalid, so that we attempt to salvage only those values when processing
1303   // a DIArgList.
1304   Value *V = DDI.getVariableLocationOp(0);
1305   Value *OrigV = V;
1306   DILocalVariable *Var = DDI.getVariable();
1307   DIExpression *Expr = DDI.getExpression();
1308   DebugLoc DL = DDI.getDebugLoc();
1309   unsigned SDOrder = DDI.getSDNodeOrder();
1310 
1311   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1312   // that DW_OP_stack_value is desired.
1313   bool StackValue = true;
1314 
1315   // Can this Value can be encoded without any further work?
1316   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1317     return;
1318 
1319   // Attempt to salvage back through as many instructions as possible. Bail if
1320   // a non-instruction is seen, such as a constant expression or global
1321   // variable. FIXME: Further work could recover those too.
1322   while (isa<Instruction>(V)) {
1323     Instruction &VAsInst = *cast<Instruction>(V);
1324     // Temporary "0", awaiting real implementation.
1325     SmallVector<uint64_t, 16> Ops;
1326     SmallVector<Value *, 4> AdditionalValues;
1327     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1328                              AdditionalValues);
1329     // If we cannot salvage any further, and haven't yet found a suitable debug
1330     // expression, bail out.
1331     if (!V)
1332       break;
1333 
1334     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1335     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1336     // here for variadic dbg_values, remove that condition.
1337     if (!AdditionalValues.empty())
1338       break;
1339 
1340     // New value and expr now represent this debuginfo.
1341     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1342 
1343     // Some kind of simplification occurred: check whether the operand of the
1344     // salvaged debug expression can be encoded in this DAG.
1345     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1346       LLVM_DEBUG(
1347           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1348                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1349       return;
1350     }
1351   }
1352 
1353   // This was the final opportunity to salvage this debug information, and it
1354   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1355   // any earlier variable location.
1356   assert(OrigV && "V shouldn't be null");
1357   auto *Undef = UndefValue::get(OrigV->getType());
1358   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1359   DAG.AddDbgValue(SDV, false);
1360   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI << "\n");
1361 }
1362 
1363 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1364                                            DILocalVariable *Var,
1365                                            DIExpression *Expr, DebugLoc DbgLoc,
1366                                            unsigned Order, bool IsVariadic) {
1367   if (Values.empty())
1368     return true;
1369   SmallVector<SDDbgOperand> LocationOps;
1370   SmallVector<SDNode *> Dependencies;
1371   for (const Value *V : Values) {
1372     // Constant value.
1373     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1374         isa<ConstantPointerNull>(V)) {
1375       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1376       continue;
1377     }
1378 
1379     // Look through IntToPtr constants.
1380     if (auto *CE = dyn_cast<ConstantExpr>(V))
1381       if (CE->getOpcode() == Instruction::IntToPtr) {
1382         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1383         continue;
1384       }
1385 
1386     // If the Value is a frame index, we can create a FrameIndex debug value
1387     // without relying on the DAG at all.
1388     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1389       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1390       if (SI != FuncInfo.StaticAllocaMap.end()) {
1391         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1392         continue;
1393       }
1394     }
1395 
1396     // Do not use getValue() in here; we don't want to generate code at
1397     // this point if it hasn't been done yet.
1398     SDValue N = NodeMap[V];
1399     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1400       N = UnusedArgNodeMap[V];
1401     if (N.getNode()) {
1402       // Only emit func arg dbg value for non-variadic dbg.values for now.
1403       if (!IsVariadic &&
1404           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1405                                    FuncArgumentDbgValueKind::Value, N))
1406         return true;
1407       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1408         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1409         // describe stack slot locations.
1410         //
1411         // Consider "int x = 0; int *px = &x;". There are two kinds of
1412         // interesting debug values here after optimization:
1413         //
1414         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1415         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1416         //
1417         // Both describe the direct values of their associated variables.
1418         Dependencies.push_back(N.getNode());
1419         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1420         continue;
1421       }
1422       LocationOps.emplace_back(
1423           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1424       continue;
1425     }
1426 
1427     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1428     // Special rules apply for the first dbg.values of parameter variables in a
1429     // function. Identify them by the fact they reference Argument Values, that
1430     // they're parameters, and they are parameters of the current function. We
1431     // need to let them dangle until they get an SDNode.
1432     bool IsParamOfFunc =
1433         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1434     if (IsParamOfFunc)
1435       return false;
1436 
1437     // The value is not used in this block yet (or it would have an SDNode).
1438     // We still want the value to appear for the user if possible -- if it has
1439     // an associated VReg, we can refer to that instead.
1440     auto VMI = FuncInfo.ValueMap.find(V);
1441     if (VMI != FuncInfo.ValueMap.end()) {
1442       unsigned Reg = VMI->second;
1443       // If this is a PHI node, it may be split up into several MI PHI nodes
1444       // (in FunctionLoweringInfo::set).
1445       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1446                        V->getType(), None);
1447       if (RFV.occupiesMultipleRegs()) {
1448         // FIXME: We could potentially support variadic dbg_values here.
1449         if (IsVariadic)
1450           return false;
1451         unsigned Offset = 0;
1452         unsigned BitsToDescribe = 0;
1453         if (auto VarSize = Var->getSizeInBits())
1454           BitsToDescribe = *VarSize;
1455         if (auto Fragment = Expr->getFragmentInfo())
1456           BitsToDescribe = Fragment->SizeInBits;
1457         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1458           // Bail out if all bits are described already.
1459           if (Offset >= BitsToDescribe)
1460             break;
1461           // TODO: handle scalable vectors.
1462           unsigned RegisterSize = RegAndSize.second;
1463           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1464                                       ? BitsToDescribe - Offset
1465                                       : RegisterSize;
1466           auto FragmentExpr = DIExpression::createFragmentExpression(
1467               Expr, Offset, FragmentSize);
1468           if (!FragmentExpr)
1469             continue;
1470           SDDbgValue *SDV = DAG.getVRegDbgValue(
1471               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1472           DAG.AddDbgValue(SDV, false);
1473           Offset += RegisterSize;
1474         }
1475         return true;
1476       }
1477       // We can use simple vreg locations for variadic dbg_values as well.
1478       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1479       continue;
1480     }
1481     // We failed to create a SDDbgOperand for V.
1482     return false;
1483   }
1484 
1485   // We have created a SDDbgOperand for each Value in Values.
1486   // Should use Order instead of SDNodeOrder?
1487   assert(!LocationOps.empty());
1488   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1489                                         /*IsIndirect=*/false, DbgLoc,
1490                                         SDNodeOrder, IsVariadic);
1491   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1492   return true;
1493 }
1494 
1495 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1496   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1497   for (auto &Pair : DanglingDebugInfoMap)
1498     for (auto &DDI : Pair.second)
1499       salvageUnresolvedDbgValue(DDI);
1500   clearDanglingDebugInfo();
1501 }
1502 
1503 /// getCopyFromRegs - If there was virtual register allocated for the value V
1504 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1505 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1506   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1507   SDValue Result;
1508 
1509   if (It != FuncInfo.ValueMap.end()) {
1510     Register InReg = It->second;
1511 
1512     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1513                      DAG.getDataLayout(), InReg, Ty,
1514                      None); // This is not an ABI copy.
1515     SDValue Chain = DAG.getEntryNode();
1516     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1517                                  V);
1518     resolveDanglingDebugInfo(V, Result);
1519   }
1520 
1521   return Result;
1522 }
1523 
1524 /// getValue - Return an SDValue for the given Value.
1525 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1526   // If we already have an SDValue for this value, use it. It's important
1527   // to do this first, so that we don't create a CopyFromReg if we already
1528   // have a regular SDValue.
1529   SDValue &N = NodeMap[V];
1530   if (N.getNode()) return N;
1531 
1532   // If there's a virtual register allocated and initialized for this
1533   // value, use it.
1534   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1535     return copyFromReg;
1536 
1537   // Otherwise create a new SDValue and remember it.
1538   SDValue Val = getValueImpl(V);
1539   NodeMap[V] = Val;
1540   resolveDanglingDebugInfo(V, Val);
1541   return Val;
1542 }
1543 
1544 /// getNonRegisterValue - Return an SDValue for the given Value, but
1545 /// don't look in FuncInfo.ValueMap for a virtual register.
1546 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1547   // If we already have an SDValue for this value, use it.
1548   SDValue &N = NodeMap[V];
1549   if (N.getNode()) {
1550     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1551       // Remove the debug location from the node as the node is about to be used
1552       // in a location which may differ from the original debug location.  This
1553       // is relevant to Constant and ConstantFP nodes because they can appear
1554       // as constant expressions inside PHI nodes.
1555       N->setDebugLoc(DebugLoc());
1556     }
1557     return N;
1558   }
1559 
1560   // Otherwise create a new SDValue and remember it.
1561   SDValue Val = getValueImpl(V);
1562   NodeMap[V] = Val;
1563   resolveDanglingDebugInfo(V, Val);
1564   return Val;
1565 }
1566 
1567 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1568 /// Create an SDValue for the given value.
1569 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1571 
1572   if (const Constant *C = dyn_cast<Constant>(V)) {
1573     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1574 
1575     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1576       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1577 
1578     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1579       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1580 
1581     if (isa<ConstantPointerNull>(C)) {
1582       unsigned AS = V->getType()->getPointerAddressSpace();
1583       return DAG.getConstant(0, getCurSDLoc(),
1584                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1585     }
1586 
1587     if (match(C, m_VScale(DAG.getDataLayout())))
1588       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1589 
1590     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1591       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1592 
1593     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1594       return DAG.getUNDEF(VT);
1595 
1596     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1597       visit(CE->getOpcode(), *CE);
1598       SDValue N1 = NodeMap[V];
1599       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1600       return N1;
1601     }
1602 
1603     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1604       SmallVector<SDValue, 4> Constants;
1605       for (const Use &U : C->operands()) {
1606         SDNode *Val = getValue(U).getNode();
1607         // If the operand is an empty aggregate, there are no values.
1608         if (!Val) continue;
1609         // Add each leaf value from the operand to the Constants list
1610         // to form a flattened list of all the values.
1611         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1612           Constants.push_back(SDValue(Val, i));
1613       }
1614 
1615       return DAG.getMergeValues(Constants, getCurSDLoc());
1616     }
1617 
1618     if (const ConstantDataSequential *CDS =
1619           dyn_cast<ConstantDataSequential>(C)) {
1620       SmallVector<SDValue, 4> Ops;
1621       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1622         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1623         // Add each leaf value from the operand to the Constants list
1624         // to form a flattened list of all the values.
1625         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1626           Ops.push_back(SDValue(Val, i));
1627       }
1628 
1629       if (isa<ArrayType>(CDS->getType()))
1630         return DAG.getMergeValues(Ops, getCurSDLoc());
1631       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1632     }
1633 
1634     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1635       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1636              "Unknown struct or array constant!");
1637 
1638       SmallVector<EVT, 4> ValueVTs;
1639       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1640       unsigned NumElts = ValueVTs.size();
1641       if (NumElts == 0)
1642         return SDValue(); // empty struct
1643       SmallVector<SDValue, 4> Constants(NumElts);
1644       for (unsigned i = 0; i != NumElts; ++i) {
1645         EVT EltVT = ValueVTs[i];
1646         if (isa<UndefValue>(C))
1647           Constants[i] = DAG.getUNDEF(EltVT);
1648         else if (EltVT.isFloatingPoint())
1649           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1650         else
1651           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1652       }
1653 
1654       return DAG.getMergeValues(Constants, getCurSDLoc());
1655     }
1656 
1657     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1658       return DAG.getBlockAddress(BA, VT);
1659 
1660     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1661       return getValue(Equiv->getGlobalValue());
1662 
1663     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1664       return getValue(NC->getGlobalValue());
1665 
1666     VectorType *VecTy = cast<VectorType>(V->getType());
1667 
1668     // Now that we know the number and type of the elements, get that number of
1669     // elements into the Ops array based on what kind of constant it is.
1670     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1671       SmallVector<SDValue, 16> Ops;
1672       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1673       for (unsigned i = 0; i != NumElements; ++i)
1674         Ops.push_back(getValue(CV->getOperand(i)));
1675 
1676       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1677     }
1678 
1679     if (isa<ConstantAggregateZero>(C)) {
1680       EVT EltVT =
1681           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1682 
1683       SDValue Op;
1684       if (EltVT.isFloatingPoint())
1685         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1686       else
1687         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1688 
1689       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1690     }
1691 
1692     llvm_unreachable("Unknown vector constant");
1693   }
1694 
1695   // If this is a static alloca, generate it as the frameindex instead of
1696   // computation.
1697   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1698     DenseMap<const AllocaInst*, int>::iterator SI =
1699       FuncInfo.StaticAllocaMap.find(AI);
1700     if (SI != FuncInfo.StaticAllocaMap.end())
1701       return DAG.getFrameIndex(
1702           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1703   }
1704 
1705   // If this is an instruction which fast-isel has deferred, select it now.
1706   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1707     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1708 
1709     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1710                      Inst->getType(), None);
1711     SDValue Chain = DAG.getEntryNode();
1712     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1713   }
1714 
1715   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1716     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1717 
1718   if (const auto *BB = dyn_cast<BasicBlock>(V))
1719     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1720 
1721   llvm_unreachable("Can't get register for value!");
1722 }
1723 
1724 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1725   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1726   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1727   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1728   bool IsSEH = isAsynchronousEHPersonality(Pers);
1729   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1730   if (!IsSEH)
1731     CatchPadMBB->setIsEHScopeEntry();
1732   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1733   if (IsMSVCCXX || IsCoreCLR)
1734     CatchPadMBB->setIsEHFuncletEntry();
1735 }
1736 
1737 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1738   // Update machine-CFG edge.
1739   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1740   FuncInfo.MBB->addSuccessor(TargetMBB);
1741   TargetMBB->setIsEHCatchretTarget(true);
1742   DAG.getMachineFunction().setHasEHCatchret(true);
1743 
1744   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1745   bool IsSEH = isAsynchronousEHPersonality(Pers);
1746   if (IsSEH) {
1747     // If this is not a fall-through branch or optimizations are switched off,
1748     // emit the branch.
1749     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1750         TM.getOptLevel() == CodeGenOpt::None)
1751       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1752                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1753     return;
1754   }
1755 
1756   // Figure out the funclet membership for the catchret's successor.
1757   // This will be used by the FuncletLayout pass to determine how to order the
1758   // BB's.
1759   // A 'catchret' returns to the outer scope's color.
1760   Value *ParentPad = I.getCatchSwitchParentPad();
1761   const BasicBlock *SuccessorColor;
1762   if (isa<ConstantTokenNone>(ParentPad))
1763     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1764   else
1765     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1766   assert(SuccessorColor && "No parent funclet for catchret!");
1767   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1768   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1769 
1770   // Create the terminator node.
1771   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1772                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1773                             DAG.getBasicBlock(SuccessorColorMBB));
1774   DAG.setRoot(Ret);
1775 }
1776 
1777 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1778   // Don't emit any special code for the cleanuppad instruction. It just marks
1779   // the start of an EH scope/funclet.
1780   FuncInfo.MBB->setIsEHScopeEntry();
1781   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1782   if (Pers != EHPersonality::Wasm_CXX) {
1783     FuncInfo.MBB->setIsEHFuncletEntry();
1784     FuncInfo.MBB->setIsCleanupFuncletEntry();
1785   }
1786 }
1787 
1788 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1789 // not match, it is OK to add only the first unwind destination catchpad to the
1790 // successors, because there will be at least one invoke instruction within the
1791 // catch scope that points to the next unwind destination, if one exists, so
1792 // CFGSort cannot mess up with BB sorting order.
1793 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1794 // call within them, and catchpads only consisting of 'catch (...)' have a
1795 // '__cxa_end_catch' call within them, both of which generate invokes in case
1796 // the next unwind destination exists, i.e., the next unwind destination is not
1797 // the caller.)
1798 //
1799 // Having at most one EH pad successor is also simpler and helps later
1800 // transformations.
1801 //
1802 // For example,
1803 // current:
1804 //   invoke void @foo to ... unwind label %catch.dispatch
1805 // catch.dispatch:
1806 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1807 // catch.start:
1808 //   ...
1809 //   ... in this BB or some other child BB dominated by this BB there will be an
1810 //   invoke that points to 'next' BB as an unwind destination
1811 //
1812 // next: ; We don't need to add this to 'current' BB's successor
1813 //   ...
1814 static void findWasmUnwindDestinations(
1815     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1816     BranchProbability Prob,
1817     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1818         &UnwindDests) {
1819   while (EHPadBB) {
1820     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1821     if (isa<CleanupPadInst>(Pad)) {
1822       // Stop on cleanup pads.
1823       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1824       UnwindDests.back().first->setIsEHScopeEntry();
1825       break;
1826     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1827       // Add the catchpad handlers to the possible destinations. We don't
1828       // continue to the unwind destination of the catchswitch for wasm.
1829       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1830         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1831         UnwindDests.back().first->setIsEHScopeEntry();
1832       }
1833       break;
1834     } else {
1835       continue;
1836     }
1837   }
1838 }
1839 
1840 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1841 /// many places it could ultimately go. In the IR, we have a single unwind
1842 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1843 /// This function skips over imaginary basic blocks that hold catchswitch
1844 /// instructions, and finds all the "real" machine
1845 /// basic block destinations. As those destinations may not be successors of
1846 /// EHPadBB, here we also calculate the edge probability to those destinations.
1847 /// The passed-in Prob is the edge probability to EHPadBB.
1848 static void findUnwindDestinations(
1849     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1850     BranchProbability Prob,
1851     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1852         &UnwindDests) {
1853   EHPersonality Personality =
1854     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1855   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1856   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1857   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1858   bool IsSEH = isAsynchronousEHPersonality(Personality);
1859 
1860   if (IsWasmCXX) {
1861     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1862     assert(UnwindDests.size() <= 1 &&
1863            "There should be at most one unwind destination for wasm");
1864     return;
1865   }
1866 
1867   while (EHPadBB) {
1868     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1869     BasicBlock *NewEHPadBB = nullptr;
1870     if (isa<LandingPadInst>(Pad)) {
1871       // Stop on landingpads. They are not funclets.
1872       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1873       break;
1874     } else if (isa<CleanupPadInst>(Pad)) {
1875       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1876       // personalities.
1877       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1878       UnwindDests.back().first->setIsEHScopeEntry();
1879       UnwindDests.back().first->setIsEHFuncletEntry();
1880       break;
1881     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1882       // Add the catchpad handlers to the possible destinations.
1883       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1884         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1885         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1886         if (IsMSVCCXX || IsCoreCLR)
1887           UnwindDests.back().first->setIsEHFuncletEntry();
1888         if (!IsSEH)
1889           UnwindDests.back().first->setIsEHScopeEntry();
1890       }
1891       NewEHPadBB = CatchSwitch->getUnwindDest();
1892     } else {
1893       continue;
1894     }
1895 
1896     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1897     if (BPI && NewEHPadBB)
1898       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1899     EHPadBB = NewEHPadBB;
1900   }
1901 }
1902 
1903 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1904   // Update successor info.
1905   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1906   auto UnwindDest = I.getUnwindDest();
1907   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1908   BranchProbability UnwindDestProb =
1909       (BPI && UnwindDest)
1910           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1911           : BranchProbability::getZero();
1912   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1913   for (auto &UnwindDest : UnwindDests) {
1914     UnwindDest.first->setIsEHPad();
1915     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1916   }
1917   FuncInfo.MBB->normalizeSuccProbs();
1918 
1919   // Create the terminator node.
1920   SDValue Ret =
1921       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1922   DAG.setRoot(Ret);
1923 }
1924 
1925 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1926   report_fatal_error("visitCatchSwitch not yet implemented!");
1927 }
1928 
1929 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1931   auto &DL = DAG.getDataLayout();
1932   SDValue Chain = getControlRoot();
1933   SmallVector<ISD::OutputArg, 8> Outs;
1934   SmallVector<SDValue, 8> OutVals;
1935 
1936   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1937   // lower
1938   //
1939   //   %val = call <ty> @llvm.experimental.deoptimize()
1940   //   ret <ty> %val
1941   //
1942   // differently.
1943   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1944     LowerDeoptimizingReturn();
1945     return;
1946   }
1947 
1948   if (!FuncInfo.CanLowerReturn) {
1949     unsigned DemoteReg = FuncInfo.DemoteRegister;
1950     const Function *F = I.getParent()->getParent();
1951 
1952     // Emit a store of the return value through the virtual register.
1953     // Leave Outs empty so that LowerReturn won't try to load return
1954     // registers the usual way.
1955     SmallVector<EVT, 1> PtrValueVTs;
1956     ComputeValueVTs(TLI, DL,
1957                     F->getReturnType()->getPointerTo(
1958                         DAG.getDataLayout().getAllocaAddrSpace()),
1959                     PtrValueVTs);
1960 
1961     SDValue RetPtr =
1962         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1963     SDValue RetOp = getValue(I.getOperand(0));
1964 
1965     SmallVector<EVT, 4> ValueVTs, MemVTs;
1966     SmallVector<uint64_t, 4> Offsets;
1967     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1968                     &Offsets);
1969     unsigned NumValues = ValueVTs.size();
1970 
1971     SmallVector<SDValue, 4> Chains(NumValues);
1972     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1973     for (unsigned i = 0; i != NumValues; ++i) {
1974       // An aggregate return value cannot wrap around the address space, so
1975       // offsets to its parts don't wrap either.
1976       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1977                                            TypeSize::Fixed(Offsets[i]));
1978 
1979       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1980       if (MemVTs[i] != ValueVTs[i])
1981         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1982       Chains[i] = DAG.getStore(
1983           Chain, getCurSDLoc(), Val,
1984           // FIXME: better loc info would be nice.
1985           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1986           commonAlignment(BaseAlign, Offsets[i]));
1987     }
1988 
1989     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1990                         MVT::Other, Chains);
1991   } else if (I.getNumOperands() != 0) {
1992     SmallVector<EVT, 4> ValueVTs;
1993     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1994     unsigned NumValues = ValueVTs.size();
1995     if (NumValues) {
1996       SDValue RetOp = getValue(I.getOperand(0));
1997 
1998       const Function *F = I.getParent()->getParent();
1999 
2000       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2001           I.getOperand(0)->getType(), F->getCallingConv(),
2002           /*IsVarArg*/ false, DL);
2003 
2004       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2005       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2006         ExtendKind = ISD::SIGN_EXTEND;
2007       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2008         ExtendKind = ISD::ZERO_EXTEND;
2009 
2010       LLVMContext &Context = F->getContext();
2011       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2012 
2013       for (unsigned j = 0; j != NumValues; ++j) {
2014         EVT VT = ValueVTs[j];
2015 
2016         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2017           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2018 
2019         CallingConv::ID CC = F->getCallingConv();
2020 
2021         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2022         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2023         SmallVector<SDValue, 4> Parts(NumParts);
2024         getCopyToParts(DAG, getCurSDLoc(),
2025                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2026                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2027 
2028         // 'inreg' on function refers to return value
2029         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2030         if (RetInReg)
2031           Flags.setInReg();
2032 
2033         if (I.getOperand(0)->getType()->isPointerTy()) {
2034           Flags.setPointer();
2035           Flags.setPointerAddrSpace(
2036               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2037         }
2038 
2039         if (NeedsRegBlock) {
2040           Flags.setInConsecutiveRegs();
2041           if (j == NumValues - 1)
2042             Flags.setInConsecutiveRegsLast();
2043         }
2044 
2045         // Propagate extension type if any
2046         if (ExtendKind == ISD::SIGN_EXTEND)
2047           Flags.setSExt();
2048         else if (ExtendKind == ISD::ZERO_EXTEND)
2049           Flags.setZExt();
2050 
2051         for (unsigned i = 0; i < NumParts; ++i) {
2052           Outs.push_back(ISD::OutputArg(Flags,
2053                                         Parts[i].getValueType().getSimpleVT(),
2054                                         VT, /*isfixed=*/true, 0, 0));
2055           OutVals.push_back(Parts[i]);
2056         }
2057       }
2058     }
2059   }
2060 
2061   // Push in swifterror virtual register as the last element of Outs. This makes
2062   // sure swifterror virtual register will be returned in the swifterror
2063   // physical register.
2064   const Function *F = I.getParent()->getParent();
2065   if (TLI.supportSwiftError() &&
2066       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2067     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2068     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2069     Flags.setSwiftError();
2070     Outs.push_back(ISD::OutputArg(
2071         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2072         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2073     // Create SDNode for the swifterror virtual register.
2074     OutVals.push_back(
2075         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2076                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2077                         EVT(TLI.getPointerTy(DL))));
2078   }
2079 
2080   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2081   CallingConv::ID CallConv =
2082     DAG.getMachineFunction().getFunction().getCallingConv();
2083   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2084       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2085 
2086   // Verify that the target's LowerReturn behaved as expected.
2087   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2088          "LowerReturn didn't return a valid chain!");
2089 
2090   // Update the DAG with the new chain value resulting from return lowering.
2091   DAG.setRoot(Chain);
2092 }
2093 
2094 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2095 /// created for it, emit nodes to copy the value into the virtual
2096 /// registers.
2097 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2098   // Skip empty types
2099   if (V->getType()->isEmptyTy())
2100     return;
2101 
2102   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2103   if (VMI != FuncInfo.ValueMap.end()) {
2104     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2105     CopyValueToVirtualRegister(V, VMI->second);
2106   }
2107 }
2108 
2109 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2110 /// the current basic block, add it to ValueMap now so that we'll get a
2111 /// CopyTo/FromReg.
2112 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2113   // No need to export constants.
2114   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2115 
2116   // Already exported?
2117   if (FuncInfo.isExportedInst(V)) return;
2118 
2119   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2120   CopyValueToVirtualRegister(V, Reg);
2121 }
2122 
2123 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2124                                                      const BasicBlock *FromBB) {
2125   // The operands of the setcc have to be in this block.  We don't know
2126   // how to export them from some other block.
2127   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2128     // Can export from current BB.
2129     if (VI->getParent() == FromBB)
2130       return true;
2131 
2132     // Is already exported, noop.
2133     return FuncInfo.isExportedInst(V);
2134   }
2135 
2136   // If this is an argument, we can export it if the BB is the entry block or
2137   // if it is already exported.
2138   if (isa<Argument>(V)) {
2139     if (FromBB->isEntryBlock())
2140       return true;
2141 
2142     // Otherwise, can only export this if it is already exported.
2143     return FuncInfo.isExportedInst(V);
2144   }
2145 
2146   // Otherwise, constants can always be exported.
2147   return true;
2148 }
2149 
2150 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2151 BranchProbability
2152 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2153                                         const MachineBasicBlock *Dst) const {
2154   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2155   const BasicBlock *SrcBB = Src->getBasicBlock();
2156   const BasicBlock *DstBB = Dst->getBasicBlock();
2157   if (!BPI) {
2158     // If BPI is not available, set the default probability as 1 / N, where N is
2159     // the number of successors.
2160     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2161     return BranchProbability(1, SuccSize);
2162   }
2163   return BPI->getEdgeProbability(SrcBB, DstBB);
2164 }
2165 
2166 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2167                                                MachineBasicBlock *Dst,
2168                                                BranchProbability Prob) {
2169   if (!FuncInfo.BPI)
2170     Src->addSuccessorWithoutProb(Dst);
2171   else {
2172     if (Prob.isUnknown())
2173       Prob = getEdgeProbability(Src, Dst);
2174     Src->addSuccessor(Dst, Prob);
2175   }
2176 }
2177 
2178 static bool InBlock(const Value *V, const BasicBlock *BB) {
2179   if (const Instruction *I = dyn_cast<Instruction>(V))
2180     return I->getParent() == BB;
2181   return true;
2182 }
2183 
2184 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2185 /// This function emits a branch and is used at the leaves of an OR or an
2186 /// AND operator tree.
2187 void
2188 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2189                                                   MachineBasicBlock *TBB,
2190                                                   MachineBasicBlock *FBB,
2191                                                   MachineBasicBlock *CurBB,
2192                                                   MachineBasicBlock *SwitchBB,
2193                                                   BranchProbability TProb,
2194                                                   BranchProbability FProb,
2195                                                   bool InvertCond) {
2196   const BasicBlock *BB = CurBB->getBasicBlock();
2197 
2198   // If the leaf of the tree is a comparison, merge the condition into
2199   // the caseblock.
2200   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2201     // The operands of the cmp have to be in this block.  We don't know
2202     // how to export them from some other block.  If this is the first block
2203     // of the sequence, no exporting is needed.
2204     if (CurBB == SwitchBB ||
2205         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2206          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2207       ISD::CondCode Condition;
2208       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2209         ICmpInst::Predicate Pred =
2210             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2211         Condition = getICmpCondCode(Pred);
2212       } else {
2213         const FCmpInst *FC = cast<FCmpInst>(Cond);
2214         FCmpInst::Predicate Pred =
2215             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2216         Condition = getFCmpCondCode(Pred);
2217         if (TM.Options.NoNaNsFPMath)
2218           Condition = getFCmpCodeWithoutNaN(Condition);
2219       }
2220 
2221       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2222                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2223       SL->SwitchCases.push_back(CB);
2224       return;
2225     }
2226   }
2227 
2228   // Create a CaseBlock record representing this branch.
2229   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2230   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2231                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2232   SL->SwitchCases.push_back(CB);
2233 }
2234 
2235 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2236                                                MachineBasicBlock *TBB,
2237                                                MachineBasicBlock *FBB,
2238                                                MachineBasicBlock *CurBB,
2239                                                MachineBasicBlock *SwitchBB,
2240                                                Instruction::BinaryOps Opc,
2241                                                BranchProbability TProb,
2242                                                BranchProbability FProb,
2243                                                bool InvertCond) {
2244   // Skip over not part of the tree and remember to invert op and operands at
2245   // next level.
2246   Value *NotCond;
2247   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2248       InBlock(NotCond, CurBB->getBasicBlock())) {
2249     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2250                          !InvertCond);
2251     return;
2252   }
2253 
2254   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2255   const Value *BOpOp0, *BOpOp1;
2256   // Compute the effective opcode for Cond, taking into account whether it needs
2257   // to be inverted, e.g.
2258   //   and (not (or A, B)), C
2259   // gets lowered as
2260   //   and (and (not A, not B), C)
2261   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2262   if (BOp) {
2263     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2264                ? Instruction::And
2265                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2266                       ? Instruction::Or
2267                       : (Instruction::BinaryOps)0);
2268     if (InvertCond) {
2269       if (BOpc == Instruction::And)
2270         BOpc = Instruction::Or;
2271       else if (BOpc == Instruction::Or)
2272         BOpc = Instruction::And;
2273     }
2274   }
2275 
2276   // If this node is not part of the or/and tree, emit it as a branch.
2277   // Note that all nodes in the tree should have same opcode.
2278   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2279   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2280       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2281       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2282     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2283                                  TProb, FProb, InvertCond);
2284     return;
2285   }
2286 
2287   //  Create TmpBB after CurBB.
2288   MachineFunction::iterator BBI(CurBB);
2289   MachineFunction &MF = DAG.getMachineFunction();
2290   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2291   CurBB->getParent()->insert(++BBI, TmpBB);
2292 
2293   if (Opc == Instruction::Or) {
2294     // Codegen X | Y as:
2295     // BB1:
2296     //   jmp_if_X TBB
2297     //   jmp TmpBB
2298     // TmpBB:
2299     //   jmp_if_Y TBB
2300     //   jmp FBB
2301     //
2302 
2303     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2304     // The requirement is that
2305     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2306     //     = TrueProb for original BB.
2307     // Assuming the original probabilities are A and B, one choice is to set
2308     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2309     // A/(1+B) and 2B/(1+B). This choice assumes that
2310     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2311     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2312     // TmpBB, but the math is more complicated.
2313 
2314     auto NewTrueProb = TProb / 2;
2315     auto NewFalseProb = TProb / 2 + FProb;
2316     // Emit the LHS condition.
2317     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2318                          NewFalseProb, InvertCond);
2319 
2320     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2321     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2322     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2323     // Emit the RHS condition into TmpBB.
2324     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2325                          Probs[1], InvertCond);
2326   } else {
2327     assert(Opc == Instruction::And && "Unknown merge op!");
2328     // Codegen X & Y as:
2329     // BB1:
2330     //   jmp_if_X TmpBB
2331     //   jmp FBB
2332     // TmpBB:
2333     //   jmp_if_Y TBB
2334     //   jmp FBB
2335     //
2336     //  This requires creation of TmpBB after CurBB.
2337 
2338     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2339     // The requirement is that
2340     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2341     //     = FalseProb for original BB.
2342     // Assuming the original probabilities are A and B, one choice is to set
2343     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2344     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2345     // TrueProb for BB1 * FalseProb for TmpBB.
2346 
2347     auto NewTrueProb = TProb + FProb / 2;
2348     auto NewFalseProb = FProb / 2;
2349     // Emit the LHS condition.
2350     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2351                          NewFalseProb, InvertCond);
2352 
2353     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2354     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2355     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2356     // Emit the RHS condition into TmpBB.
2357     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2358                          Probs[1], InvertCond);
2359   }
2360 }
2361 
2362 /// If the set of cases should be emitted as a series of branches, return true.
2363 /// If we should emit this as a bunch of and/or'd together conditions, return
2364 /// false.
2365 bool
2366 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2367   if (Cases.size() != 2) return true;
2368 
2369   // If this is two comparisons of the same values or'd or and'd together, they
2370   // will get folded into a single comparison, so don't emit two blocks.
2371   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2372        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2373       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2374        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2375     return false;
2376   }
2377 
2378   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2379   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2380   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2381       Cases[0].CC == Cases[1].CC &&
2382       isa<Constant>(Cases[0].CmpRHS) &&
2383       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2384     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2385       return false;
2386     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2387       return false;
2388   }
2389 
2390   return true;
2391 }
2392 
2393 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2394   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2395 
2396   // Update machine-CFG edges.
2397   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2398 
2399   if (I.isUnconditional()) {
2400     // Update machine-CFG edges.
2401     BrMBB->addSuccessor(Succ0MBB);
2402 
2403     // If this is not a fall-through branch or optimizations are switched off,
2404     // emit the branch.
2405     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2406       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2407                               MVT::Other, getControlRoot(),
2408                               DAG.getBasicBlock(Succ0MBB)));
2409 
2410     return;
2411   }
2412 
2413   // If this condition is one of the special cases we handle, do special stuff
2414   // now.
2415   const Value *CondVal = I.getCondition();
2416   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2417 
2418   // If this is a series of conditions that are or'd or and'd together, emit
2419   // this as a sequence of branches instead of setcc's with and/or operations.
2420   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2421   // unpredictable branches, and vector extracts because those jumps are likely
2422   // expensive for any target), this should improve performance.
2423   // For example, instead of something like:
2424   //     cmp A, B
2425   //     C = seteq
2426   //     cmp D, E
2427   //     F = setle
2428   //     or C, F
2429   //     jnz foo
2430   // Emit:
2431   //     cmp A, B
2432   //     je foo
2433   //     cmp D, E
2434   //     jle foo
2435   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2436   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2437       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2438     Value *Vec;
2439     const Value *BOp0, *BOp1;
2440     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2441     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2442       Opcode = Instruction::And;
2443     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2444       Opcode = Instruction::Or;
2445 
2446     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2447                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2448       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2449                            getEdgeProbability(BrMBB, Succ0MBB),
2450                            getEdgeProbability(BrMBB, Succ1MBB),
2451                            /*InvertCond=*/false);
2452       // If the compares in later blocks need to use values not currently
2453       // exported from this block, export them now.  This block should always
2454       // be the first entry.
2455       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2456 
2457       // Allow some cases to be rejected.
2458       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2459         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2460           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2461           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2462         }
2463 
2464         // Emit the branch for this block.
2465         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2466         SL->SwitchCases.erase(SL->SwitchCases.begin());
2467         return;
2468       }
2469 
2470       // Okay, we decided not to do this, remove any inserted MBB's and clear
2471       // SwitchCases.
2472       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2473         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2474 
2475       SL->SwitchCases.clear();
2476     }
2477   }
2478 
2479   // Create a CaseBlock record representing this branch.
2480   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2481                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2482 
2483   // Use visitSwitchCase to actually insert the fast branch sequence for this
2484   // cond branch.
2485   visitSwitchCase(CB, BrMBB);
2486 }
2487 
2488 /// visitSwitchCase - Emits the necessary code to represent a single node in
2489 /// the binary search tree resulting from lowering a switch instruction.
2490 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2491                                           MachineBasicBlock *SwitchBB) {
2492   SDValue Cond;
2493   SDValue CondLHS = getValue(CB.CmpLHS);
2494   SDLoc dl = CB.DL;
2495 
2496   if (CB.CC == ISD::SETTRUE) {
2497     // Branch or fall through to TrueBB.
2498     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2499     SwitchBB->normalizeSuccProbs();
2500     if (CB.TrueBB != NextBlock(SwitchBB)) {
2501       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2502                               DAG.getBasicBlock(CB.TrueBB)));
2503     }
2504     return;
2505   }
2506 
2507   auto &TLI = DAG.getTargetLoweringInfo();
2508   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2509 
2510   // Build the setcc now.
2511   if (!CB.CmpMHS) {
2512     // Fold "(X == true)" to X and "(X == false)" to !X to
2513     // handle common cases produced by branch lowering.
2514     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2515         CB.CC == ISD::SETEQ)
2516       Cond = CondLHS;
2517     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2518              CB.CC == ISD::SETEQ) {
2519       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2520       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2521     } else {
2522       SDValue CondRHS = getValue(CB.CmpRHS);
2523 
2524       // If a pointer's DAG type is larger than its memory type then the DAG
2525       // values are zero-extended. This breaks signed comparisons so truncate
2526       // back to the underlying type before doing the compare.
2527       if (CondLHS.getValueType() != MemVT) {
2528         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2529         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2530       }
2531       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2532     }
2533   } else {
2534     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2535 
2536     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2537     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2538 
2539     SDValue CmpOp = getValue(CB.CmpMHS);
2540     EVT VT = CmpOp.getValueType();
2541 
2542     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2543       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2544                           ISD::SETLE);
2545     } else {
2546       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2547                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2548       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2549                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2550     }
2551   }
2552 
2553   // Update successor info
2554   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2555   // TrueBB and FalseBB are always different unless the incoming IR is
2556   // degenerate. This only happens when running llc on weird IR.
2557   if (CB.TrueBB != CB.FalseBB)
2558     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2559   SwitchBB->normalizeSuccProbs();
2560 
2561   // If the lhs block is the next block, invert the condition so that we can
2562   // fall through to the lhs instead of the rhs block.
2563   if (CB.TrueBB == NextBlock(SwitchBB)) {
2564     std::swap(CB.TrueBB, CB.FalseBB);
2565     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2566     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2567   }
2568 
2569   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2570                                MVT::Other, getControlRoot(), Cond,
2571                                DAG.getBasicBlock(CB.TrueBB));
2572 
2573   setValue(CurInst, BrCond);
2574 
2575   // Insert the false branch. Do this even if it's a fall through branch,
2576   // this makes it easier to do DAG optimizations which require inverting
2577   // the branch condition.
2578   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2579                        DAG.getBasicBlock(CB.FalseBB));
2580 
2581   DAG.setRoot(BrCond);
2582 }
2583 
2584 /// visitJumpTable - Emit JumpTable node in the current MBB
2585 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2586   // Emit the code for the jump table
2587   assert(JT.Reg != -1U && "Should lower JT Header first!");
2588   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2589   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2590                                      JT.Reg, PTy);
2591   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2592   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2593                                     MVT::Other, Index.getValue(1),
2594                                     Table, Index);
2595   DAG.setRoot(BrJumpTable);
2596 }
2597 
2598 /// visitJumpTableHeader - This function emits necessary code to produce index
2599 /// in the JumpTable from switch case.
2600 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2601                                                JumpTableHeader &JTH,
2602                                                MachineBasicBlock *SwitchBB) {
2603   SDLoc dl = getCurSDLoc();
2604 
2605   // Subtract the lowest switch case value from the value being switched on.
2606   SDValue SwitchOp = getValue(JTH.SValue);
2607   EVT VT = SwitchOp.getValueType();
2608   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2609                             DAG.getConstant(JTH.First, dl, VT));
2610 
2611   // The SDNode we just created, which holds the value being switched on minus
2612   // the smallest case value, needs to be copied to a virtual register so it
2613   // can be used as an index into the jump table in a subsequent basic block.
2614   // This value may be smaller or larger than the target's pointer type, and
2615   // therefore require extension or truncating.
2616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2617   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2618 
2619   unsigned JumpTableReg =
2620       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2621   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2622                                     JumpTableReg, SwitchOp);
2623   JT.Reg = JumpTableReg;
2624 
2625   if (!JTH.FallthroughUnreachable) {
2626     // Emit the range check for the jump table, and branch to the default block
2627     // for the switch statement if the value being switched on exceeds the
2628     // largest case in the switch.
2629     SDValue CMP = DAG.getSetCC(
2630         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2631                                    Sub.getValueType()),
2632         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2633 
2634     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2635                                  MVT::Other, CopyTo, CMP,
2636                                  DAG.getBasicBlock(JT.Default));
2637 
2638     // Avoid emitting unnecessary branches to the next block.
2639     if (JT.MBB != NextBlock(SwitchBB))
2640       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2641                            DAG.getBasicBlock(JT.MBB));
2642 
2643     DAG.setRoot(BrCond);
2644   } else {
2645     // Avoid emitting unnecessary branches to the next block.
2646     if (JT.MBB != NextBlock(SwitchBB))
2647       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2648                               DAG.getBasicBlock(JT.MBB)));
2649     else
2650       DAG.setRoot(CopyTo);
2651   }
2652 }
2653 
2654 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2655 /// variable if there exists one.
2656 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2657                                  SDValue &Chain) {
2658   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2659   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2660   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2661   MachineFunction &MF = DAG.getMachineFunction();
2662   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2663   MachineSDNode *Node =
2664       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2665   if (Global) {
2666     MachinePointerInfo MPInfo(Global);
2667     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2668                  MachineMemOperand::MODereferenceable;
2669     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2670         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2671     DAG.setNodeMemRefs(Node, {MemRef});
2672   }
2673   if (PtrTy != PtrMemTy)
2674     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2675   return SDValue(Node, 0);
2676 }
2677 
2678 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2679 /// tail spliced into a stack protector check success bb.
2680 ///
2681 /// For a high level explanation of how this fits into the stack protector
2682 /// generation see the comment on the declaration of class
2683 /// StackProtectorDescriptor.
2684 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2685                                                   MachineBasicBlock *ParentBB) {
2686 
2687   // First create the loads to the guard/stack slot for the comparison.
2688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2689   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2690   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2691 
2692   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2693   int FI = MFI.getStackProtectorIndex();
2694 
2695   SDValue Guard;
2696   SDLoc dl = getCurSDLoc();
2697   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2698   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2699   Align Align =
2700       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2701 
2702   // Generate code to load the content of the guard slot.
2703   SDValue GuardVal = DAG.getLoad(
2704       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2705       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2706       MachineMemOperand::MOVolatile);
2707 
2708   if (TLI.useStackGuardXorFP())
2709     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2710 
2711   // Retrieve guard check function, nullptr if instrumentation is inlined.
2712   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2713     // The target provides a guard check function to validate the guard value.
2714     // Generate a call to that function with the content of the guard slot as
2715     // argument.
2716     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2717     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2718 
2719     TargetLowering::ArgListTy Args;
2720     TargetLowering::ArgListEntry Entry;
2721     Entry.Node = GuardVal;
2722     Entry.Ty = FnTy->getParamType(0);
2723     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2724       Entry.IsInReg = true;
2725     Args.push_back(Entry);
2726 
2727     TargetLowering::CallLoweringInfo CLI(DAG);
2728     CLI.setDebugLoc(getCurSDLoc())
2729         .setChain(DAG.getEntryNode())
2730         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2731                    getValue(GuardCheckFn), std::move(Args));
2732 
2733     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2734     DAG.setRoot(Result.second);
2735     return;
2736   }
2737 
2738   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2739   // Otherwise, emit a volatile load to retrieve the stack guard value.
2740   SDValue Chain = DAG.getEntryNode();
2741   if (TLI.useLoadStackGuardNode()) {
2742     Guard = getLoadStackGuard(DAG, dl, Chain);
2743   } else {
2744     const Value *IRGuard = TLI.getSDagStackGuard(M);
2745     SDValue GuardPtr = getValue(IRGuard);
2746 
2747     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2748                         MachinePointerInfo(IRGuard, 0), Align,
2749                         MachineMemOperand::MOVolatile);
2750   }
2751 
2752   // Perform the comparison via a getsetcc.
2753   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2754                                                         *DAG.getContext(),
2755                                                         Guard.getValueType()),
2756                              Guard, GuardVal, ISD::SETNE);
2757 
2758   // If the guard/stackslot do not equal, branch to failure MBB.
2759   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2760                                MVT::Other, GuardVal.getOperand(0),
2761                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2762   // Otherwise branch to success MBB.
2763   SDValue Br = DAG.getNode(ISD::BR, dl,
2764                            MVT::Other, BrCond,
2765                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2766 
2767   DAG.setRoot(Br);
2768 }
2769 
2770 /// Codegen the failure basic block for a stack protector check.
2771 ///
2772 /// A failure stack protector machine basic block consists simply of a call to
2773 /// __stack_chk_fail().
2774 ///
2775 /// For a high level explanation of how this fits into the stack protector
2776 /// generation see the comment on the declaration of class
2777 /// StackProtectorDescriptor.
2778 void
2779 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2781   TargetLowering::MakeLibCallOptions CallOptions;
2782   CallOptions.setDiscardResult(true);
2783   SDValue Chain =
2784       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2785                       None, CallOptions, getCurSDLoc()).second;
2786   // On PS4/PS5, the "return address" must still be within the calling
2787   // function, even if it's at the very end, so emit an explicit TRAP here.
2788   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2789   if (TM.getTargetTriple().isPS())
2790     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2791   // WebAssembly needs an unreachable instruction after a non-returning call,
2792   // because the function return type can be different from __stack_chk_fail's
2793   // return type (void).
2794   if (TM.getTargetTriple().isWasm())
2795     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2796 
2797   DAG.setRoot(Chain);
2798 }
2799 
2800 /// visitBitTestHeader - This function emits necessary code to produce value
2801 /// suitable for "bit tests"
2802 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2803                                              MachineBasicBlock *SwitchBB) {
2804   SDLoc dl = getCurSDLoc();
2805 
2806   // Subtract the minimum value.
2807   SDValue SwitchOp = getValue(B.SValue);
2808   EVT VT = SwitchOp.getValueType();
2809   SDValue RangeSub =
2810       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2811 
2812   // Determine the type of the test operands.
2813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2814   bool UsePtrType = false;
2815   if (!TLI.isTypeLegal(VT)) {
2816     UsePtrType = true;
2817   } else {
2818     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2819       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2820         // Switch table case range are encoded into series of masks.
2821         // Just use pointer type, it's guaranteed to fit.
2822         UsePtrType = true;
2823         break;
2824       }
2825   }
2826   SDValue Sub = RangeSub;
2827   if (UsePtrType) {
2828     VT = TLI.getPointerTy(DAG.getDataLayout());
2829     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2830   }
2831 
2832   B.RegVT = VT.getSimpleVT();
2833   B.Reg = FuncInfo.CreateReg(B.RegVT);
2834   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2835 
2836   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2837 
2838   if (!B.FallthroughUnreachable)
2839     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2840   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2841   SwitchBB->normalizeSuccProbs();
2842 
2843   SDValue Root = CopyTo;
2844   if (!B.FallthroughUnreachable) {
2845     // Conditional branch to the default block.
2846     SDValue RangeCmp = DAG.getSetCC(dl,
2847         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2848                                RangeSub.getValueType()),
2849         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2850         ISD::SETUGT);
2851 
2852     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2853                        DAG.getBasicBlock(B.Default));
2854   }
2855 
2856   // Avoid emitting unnecessary branches to the next block.
2857   if (MBB != NextBlock(SwitchBB))
2858     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2859 
2860   DAG.setRoot(Root);
2861 }
2862 
2863 /// visitBitTestCase - this function produces one "bit test"
2864 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2865                                            MachineBasicBlock* NextMBB,
2866                                            BranchProbability BranchProbToNext,
2867                                            unsigned Reg,
2868                                            BitTestCase &B,
2869                                            MachineBasicBlock *SwitchBB) {
2870   SDLoc dl = getCurSDLoc();
2871   MVT VT = BB.RegVT;
2872   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2873   SDValue Cmp;
2874   unsigned PopCount = countPopulation(B.Mask);
2875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2876   if (PopCount == 1) {
2877     // Testing for a single bit; just compare the shift count with what it
2878     // would need to be to shift a 1 bit in that position.
2879     Cmp = DAG.getSetCC(
2880         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2881         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2882         ISD::SETEQ);
2883   } else if (PopCount == BB.Range) {
2884     // There is only one zero bit in the range, test for it directly.
2885     Cmp = DAG.getSetCC(
2886         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2887         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2888         ISD::SETNE);
2889   } else {
2890     // Make desired shift
2891     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2892                                     DAG.getConstant(1, dl, VT), ShiftOp);
2893 
2894     // Emit bit tests and jumps
2895     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2896                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2897     Cmp = DAG.getSetCC(
2898         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2899         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2900   }
2901 
2902   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2903   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2904   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2905   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2906   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2907   // one as they are relative probabilities (and thus work more like weights),
2908   // and hence we need to normalize them to let the sum of them become one.
2909   SwitchBB->normalizeSuccProbs();
2910 
2911   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2912                               MVT::Other, getControlRoot(),
2913                               Cmp, DAG.getBasicBlock(B.TargetBB));
2914 
2915   // Avoid emitting unnecessary branches to the next block.
2916   if (NextMBB != NextBlock(SwitchBB))
2917     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2918                         DAG.getBasicBlock(NextMBB));
2919 
2920   DAG.setRoot(BrAnd);
2921 }
2922 
2923 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2924   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2925 
2926   // Retrieve successors. Look through artificial IR level blocks like
2927   // catchswitch for successors.
2928   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2929   const BasicBlock *EHPadBB = I.getSuccessor(1);
2930 
2931   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2932   // have to do anything here to lower funclet bundles.
2933   assert(!I.hasOperandBundlesOtherThan(
2934              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2935               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2936               LLVMContext::OB_cfguardtarget,
2937               LLVMContext::OB_clang_arc_attachedcall}) &&
2938          "Cannot lower invokes with arbitrary operand bundles yet!");
2939 
2940   const Value *Callee(I.getCalledOperand());
2941   const Function *Fn = dyn_cast<Function>(Callee);
2942   if (isa<InlineAsm>(Callee))
2943     visitInlineAsm(I, EHPadBB);
2944   else if (Fn && Fn->isIntrinsic()) {
2945     switch (Fn->getIntrinsicID()) {
2946     default:
2947       llvm_unreachable("Cannot invoke this intrinsic");
2948     case Intrinsic::donothing:
2949       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2950     case Intrinsic::seh_try_begin:
2951     case Intrinsic::seh_scope_begin:
2952     case Intrinsic::seh_try_end:
2953     case Intrinsic::seh_scope_end:
2954       break;
2955     case Intrinsic::experimental_patchpoint_void:
2956     case Intrinsic::experimental_patchpoint_i64:
2957       visitPatchpoint(I, EHPadBB);
2958       break;
2959     case Intrinsic::experimental_gc_statepoint:
2960       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2961       break;
2962     case Intrinsic::wasm_rethrow: {
2963       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2964       // special because it can be invoked, so we manually lower it to a DAG
2965       // node here.
2966       SmallVector<SDValue, 8> Ops;
2967       Ops.push_back(getRoot()); // inchain
2968       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2969       Ops.push_back(
2970           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2971                                 TLI.getPointerTy(DAG.getDataLayout())));
2972       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2973       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2974       break;
2975     }
2976     }
2977   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2978     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2979     // Eventually we will support lowering the @llvm.experimental.deoptimize
2980     // intrinsic, and right now there are no plans to support other intrinsics
2981     // with deopt state.
2982     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2983   } else {
2984     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2985   }
2986 
2987   // If the value of the invoke is used outside of its defining block, make it
2988   // available as a virtual register.
2989   // We already took care of the exported value for the statepoint instruction
2990   // during call to the LowerStatepoint.
2991   if (!isa<GCStatepointInst>(I)) {
2992     CopyToExportRegsIfNeeded(&I);
2993   }
2994 
2995   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2996   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2997   BranchProbability EHPadBBProb =
2998       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2999           : BranchProbability::getZero();
3000   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3001 
3002   // Update successor info.
3003   addSuccessorWithProb(InvokeMBB, Return);
3004   for (auto &UnwindDest : UnwindDests) {
3005     UnwindDest.first->setIsEHPad();
3006     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3007   }
3008   InvokeMBB->normalizeSuccProbs();
3009 
3010   // Drop into normal successor.
3011   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3012                           DAG.getBasicBlock(Return)));
3013 }
3014 
3015 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3016   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3017 
3018   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3019   // have to do anything here to lower funclet bundles.
3020   assert(!I.hasOperandBundlesOtherThan(
3021              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3022          "Cannot lower callbrs with arbitrary operand bundles yet!");
3023 
3024   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3025   visitInlineAsm(I);
3026   CopyToExportRegsIfNeeded(&I);
3027 
3028   // Retrieve successors.
3029   SmallPtrSet<BasicBlock *, 8> Dests;
3030   Dests.insert(I.getDefaultDest());
3031   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3032 
3033   // Update successor info.
3034   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3035   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3036     BasicBlock *Dest = I.getIndirectDest(i);
3037     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3038     Target->setIsInlineAsmBrIndirectTarget();
3039     Target->setMachineBlockAddressTaken();
3040     Target->setLabelMustBeEmitted();
3041     // Don't add duplicate machine successors.
3042     if (Dests.insert(Dest).second)
3043       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3044   }
3045   CallBrMBB->normalizeSuccProbs();
3046 
3047   // Drop into default successor.
3048   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3049                           MVT::Other, getControlRoot(),
3050                           DAG.getBasicBlock(Return)));
3051 }
3052 
3053 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3054   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3055 }
3056 
3057 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3058   assert(FuncInfo.MBB->isEHPad() &&
3059          "Call to landingpad not in landing pad!");
3060 
3061   // If there aren't registers to copy the values into (e.g., during SjLj
3062   // exceptions), then don't bother to create these DAG nodes.
3063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3064   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3065   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3066       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3067     return;
3068 
3069   // If landingpad's return type is token type, we don't create DAG nodes
3070   // for its exception pointer and selector value. The extraction of exception
3071   // pointer or selector value from token type landingpads is not currently
3072   // supported.
3073   if (LP.getType()->isTokenTy())
3074     return;
3075 
3076   SmallVector<EVT, 2> ValueVTs;
3077   SDLoc dl = getCurSDLoc();
3078   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3079   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3080 
3081   // Get the two live-in registers as SDValues. The physregs have already been
3082   // copied into virtual registers.
3083   SDValue Ops[2];
3084   if (FuncInfo.ExceptionPointerVirtReg) {
3085     Ops[0] = DAG.getZExtOrTrunc(
3086         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3087                            FuncInfo.ExceptionPointerVirtReg,
3088                            TLI.getPointerTy(DAG.getDataLayout())),
3089         dl, ValueVTs[0]);
3090   } else {
3091     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3092   }
3093   Ops[1] = DAG.getZExtOrTrunc(
3094       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3095                          FuncInfo.ExceptionSelectorVirtReg,
3096                          TLI.getPointerTy(DAG.getDataLayout())),
3097       dl, ValueVTs[1]);
3098 
3099   // Merge into one.
3100   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3101                             DAG.getVTList(ValueVTs), Ops);
3102   setValue(&LP, Res);
3103 }
3104 
3105 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3106                                            MachineBasicBlock *Last) {
3107   // Update JTCases.
3108   for (JumpTableBlock &JTB : SL->JTCases)
3109     if (JTB.first.HeaderBB == First)
3110       JTB.first.HeaderBB = Last;
3111 
3112   // Update BitTestCases.
3113   for (BitTestBlock &BTB : SL->BitTestCases)
3114     if (BTB.Parent == First)
3115       BTB.Parent = Last;
3116 }
3117 
3118 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3119   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3120 
3121   // Update machine-CFG edges with unique successors.
3122   SmallSet<BasicBlock*, 32> Done;
3123   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3124     BasicBlock *BB = I.getSuccessor(i);
3125     bool Inserted = Done.insert(BB).second;
3126     if (!Inserted)
3127         continue;
3128 
3129     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3130     addSuccessorWithProb(IndirectBrMBB, Succ);
3131   }
3132   IndirectBrMBB->normalizeSuccProbs();
3133 
3134   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3135                           MVT::Other, getControlRoot(),
3136                           getValue(I.getAddress())));
3137 }
3138 
3139 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3140   if (!DAG.getTarget().Options.TrapUnreachable)
3141     return;
3142 
3143   // We may be able to ignore unreachable behind a noreturn call.
3144   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3145     const BasicBlock &BB = *I.getParent();
3146     if (&I != &BB.front()) {
3147       BasicBlock::const_iterator PredI =
3148         std::prev(BasicBlock::const_iterator(&I));
3149       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3150         if (Call->doesNotReturn())
3151           return;
3152       }
3153     }
3154   }
3155 
3156   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3157 }
3158 
3159 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3160   SDNodeFlags Flags;
3161   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3162     Flags.copyFMF(*FPOp);
3163 
3164   SDValue Op = getValue(I.getOperand(0));
3165   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3166                                     Op, Flags);
3167   setValue(&I, UnNodeValue);
3168 }
3169 
3170 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3171   SDNodeFlags Flags;
3172   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3173     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3174     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3175   }
3176   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3177     Flags.setExact(ExactOp->isExact());
3178   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3179     Flags.copyFMF(*FPOp);
3180 
3181   SDValue Op1 = getValue(I.getOperand(0));
3182   SDValue Op2 = getValue(I.getOperand(1));
3183   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3184                                      Op1, Op2, Flags);
3185   setValue(&I, BinNodeValue);
3186 }
3187 
3188 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3189   SDValue Op1 = getValue(I.getOperand(0));
3190   SDValue Op2 = getValue(I.getOperand(1));
3191 
3192   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3193       Op1.getValueType(), DAG.getDataLayout());
3194 
3195   // Coerce the shift amount to the right type if we can. This exposes the
3196   // truncate or zext to optimization early.
3197   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3198     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3199            "Unexpected shift type");
3200     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3201   }
3202 
3203   bool nuw = false;
3204   bool nsw = false;
3205   bool exact = false;
3206 
3207   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3208 
3209     if (const OverflowingBinaryOperator *OFBinOp =
3210             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3211       nuw = OFBinOp->hasNoUnsignedWrap();
3212       nsw = OFBinOp->hasNoSignedWrap();
3213     }
3214     if (const PossiblyExactOperator *ExactOp =
3215             dyn_cast<const PossiblyExactOperator>(&I))
3216       exact = ExactOp->isExact();
3217   }
3218   SDNodeFlags Flags;
3219   Flags.setExact(exact);
3220   Flags.setNoSignedWrap(nsw);
3221   Flags.setNoUnsignedWrap(nuw);
3222   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3223                             Flags);
3224   setValue(&I, Res);
3225 }
3226 
3227 void SelectionDAGBuilder::visitSDiv(const User &I) {
3228   SDValue Op1 = getValue(I.getOperand(0));
3229   SDValue Op2 = getValue(I.getOperand(1));
3230 
3231   SDNodeFlags Flags;
3232   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3233                  cast<PossiblyExactOperator>(&I)->isExact());
3234   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3235                            Op2, Flags));
3236 }
3237 
3238 void SelectionDAGBuilder::visitICmp(const User &I) {
3239   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3240   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3241     predicate = IC->getPredicate();
3242   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3243     predicate = ICmpInst::Predicate(IC->getPredicate());
3244   SDValue Op1 = getValue(I.getOperand(0));
3245   SDValue Op2 = getValue(I.getOperand(1));
3246   ISD::CondCode Opcode = getICmpCondCode(predicate);
3247 
3248   auto &TLI = DAG.getTargetLoweringInfo();
3249   EVT MemVT =
3250       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3251 
3252   // If a pointer's DAG type is larger than its memory type then the DAG values
3253   // are zero-extended. This breaks signed comparisons so truncate back to the
3254   // underlying type before doing the compare.
3255   if (Op1.getValueType() != MemVT) {
3256     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3257     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3258   }
3259 
3260   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3261                                                         I.getType());
3262   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3263 }
3264 
3265 void SelectionDAGBuilder::visitFCmp(const User &I) {
3266   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3267   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3268     predicate = FC->getPredicate();
3269   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3270     predicate = FCmpInst::Predicate(FC->getPredicate());
3271   SDValue Op1 = getValue(I.getOperand(0));
3272   SDValue Op2 = getValue(I.getOperand(1));
3273 
3274   ISD::CondCode Condition = getFCmpCondCode(predicate);
3275   auto *FPMO = cast<FPMathOperator>(&I);
3276   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3277     Condition = getFCmpCodeWithoutNaN(Condition);
3278 
3279   SDNodeFlags Flags;
3280   Flags.copyFMF(*FPMO);
3281   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3282 
3283   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3284                                                         I.getType());
3285   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3286 }
3287 
3288 // Check if the condition of the select has one use or two users that are both
3289 // selects with the same condition.
3290 static bool hasOnlySelectUsers(const Value *Cond) {
3291   return llvm::all_of(Cond->users(), [](const Value *V) {
3292     return isa<SelectInst>(V);
3293   });
3294 }
3295 
3296 void SelectionDAGBuilder::visitSelect(const User &I) {
3297   SmallVector<EVT, 4> ValueVTs;
3298   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3299                   ValueVTs);
3300   unsigned NumValues = ValueVTs.size();
3301   if (NumValues == 0) return;
3302 
3303   SmallVector<SDValue, 4> Values(NumValues);
3304   SDValue Cond     = getValue(I.getOperand(0));
3305   SDValue LHSVal   = getValue(I.getOperand(1));
3306   SDValue RHSVal   = getValue(I.getOperand(2));
3307   SmallVector<SDValue, 1> BaseOps(1, Cond);
3308   ISD::NodeType OpCode =
3309       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3310 
3311   bool IsUnaryAbs = false;
3312   bool Negate = false;
3313 
3314   SDNodeFlags Flags;
3315   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3316     Flags.copyFMF(*FPOp);
3317 
3318   // Min/max matching is only viable if all output VTs are the same.
3319   if (all_equal(ValueVTs)) {
3320     EVT VT = ValueVTs[0];
3321     LLVMContext &Ctx = *DAG.getContext();
3322     auto &TLI = DAG.getTargetLoweringInfo();
3323 
3324     // We care about the legality of the operation after it has been type
3325     // legalized.
3326     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3327       VT = TLI.getTypeToTransformTo(Ctx, VT);
3328 
3329     // If the vselect is legal, assume we want to leave this as a vector setcc +
3330     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3331     // min/max is legal on the scalar type.
3332     bool UseScalarMinMax = VT.isVector() &&
3333       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3334 
3335     Value *LHS, *RHS;
3336     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3337     ISD::NodeType Opc = ISD::DELETED_NODE;
3338     switch (SPR.Flavor) {
3339     case SPF_UMAX:    Opc = ISD::UMAX; break;
3340     case SPF_UMIN:    Opc = ISD::UMIN; break;
3341     case SPF_SMAX:    Opc = ISD::SMAX; break;
3342     case SPF_SMIN:    Opc = ISD::SMIN; break;
3343     case SPF_FMINNUM:
3344       switch (SPR.NaNBehavior) {
3345       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3346       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3347       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3348       case SPNB_RETURNS_ANY: {
3349         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3350           Opc = ISD::FMINNUM;
3351         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3352           Opc = ISD::FMINIMUM;
3353         else if (UseScalarMinMax)
3354           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3355             ISD::FMINNUM : ISD::FMINIMUM;
3356         break;
3357       }
3358       }
3359       break;
3360     case SPF_FMAXNUM:
3361       switch (SPR.NaNBehavior) {
3362       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3363       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3364       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3365       case SPNB_RETURNS_ANY:
3366 
3367         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3368           Opc = ISD::FMAXNUM;
3369         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3370           Opc = ISD::FMAXIMUM;
3371         else if (UseScalarMinMax)
3372           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3373             ISD::FMAXNUM : ISD::FMAXIMUM;
3374         break;
3375       }
3376       break;
3377     case SPF_NABS:
3378       Negate = true;
3379       [[fallthrough]];
3380     case SPF_ABS:
3381       IsUnaryAbs = true;
3382       Opc = ISD::ABS;
3383       break;
3384     default: break;
3385     }
3386 
3387     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3388         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3389          (UseScalarMinMax &&
3390           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3391         // If the underlying comparison instruction is used by any other
3392         // instruction, the consumed instructions won't be destroyed, so it is
3393         // not profitable to convert to a min/max.
3394         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3395       OpCode = Opc;
3396       LHSVal = getValue(LHS);
3397       RHSVal = getValue(RHS);
3398       BaseOps.clear();
3399     }
3400 
3401     if (IsUnaryAbs) {
3402       OpCode = Opc;
3403       LHSVal = getValue(LHS);
3404       BaseOps.clear();
3405     }
3406   }
3407 
3408   if (IsUnaryAbs) {
3409     for (unsigned i = 0; i != NumValues; ++i) {
3410       SDLoc dl = getCurSDLoc();
3411       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3412       Values[i] =
3413           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3414       if (Negate)
3415         Values[i] = DAG.getNegative(Values[i], dl, VT);
3416     }
3417   } else {
3418     for (unsigned i = 0; i != NumValues; ++i) {
3419       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3420       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3421       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3422       Values[i] = DAG.getNode(
3423           OpCode, getCurSDLoc(),
3424           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3425     }
3426   }
3427 
3428   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3429                            DAG.getVTList(ValueVTs), Values));
3430 }
3431 
3432 void SelectionDAGBuilder::visitTrunc(const User &I) {
3433   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3434   SDValue N = getValue(I.getOperand(0));
3435   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3436                                                         I.getType());
3437   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3438 }
3439 
3440 void SelectionDAGBuilder::visitZExt(const User &I) {
3441   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3442   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3443   SDValue N = getValue(I.getOperand(0));
3444   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3445                                                         I.getType());
3446   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3447 }
3448 
3449 void SelectionDAGBuilder::visitSExt(const User &I) {
3450   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3451   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3452   SDValue N = getValue(I.getOperand(0));
3453   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3454                                                         I.getType());
3455   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3459   // FPTrunc is never a no-op cast, no need to check
3460   SDValue N = getValue(I.getOperand(0));
3461   SDLoc dl = getCurSDLoc();
3462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3463   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3464   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3465                            DAG.getTargetConstant(
3466                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3467 }
3468 
3469 void SelectionDAGBuilder::visitFPExt(const User &I) {
3470   // FPExt is never a no-op cast, no need to check
3471   SDValue N = getValue(I.getOperand(0));
3472   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3473                                                         I.getType());
3474   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3475 }
3476 
3477 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3478   // FPToUI is never a no-op cast, no need to check
3479   SDValue N = getValue(I.getOperand(0));
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3483 }
3484 
3485 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3486   // FPToSI is never a no-op cast, no need to check
3487   SDValue N = getValue(I.getOperand(0));
3488   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3489                                                         I.getType());
3490   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3491 }
3492 
3493 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3494   // UIToFP is never a no-op cast, no need to check
3495   SDValue N = getValue(I.getOperand(0));
3496   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3497                                                         I.getType());
3498   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3499 }
3500 
3501 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3502   // SIToFP is never a no-op cast, no need to check
3503   SDValue N = getValue(I.getOperand(0));
3504   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3505                                                         I.getType());
3506   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3507 }
3508 
3509 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3510   // What to do depends on the size of the integer and the size of the pointer.
3511   // We can either truncate, zero extend, or no-op, accordingly.
3512   SDValue N = getValue(I.getOperand(0));
3513   auto &TLI = DAG.getTargetLoweringInfo();
3514   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3515                                                         I.getType());
3516   EVT PtrMemVT =
3517       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3518   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3519   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3520   setValue(&I, N);
3521 }
3522 
3523 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3524   // What to do depends on the size of the integer and the size of the pointer.
3525   // We can either truncate, zero extend, or no-op, accordingly.
3526   SDValue N = getValue(I.getOperand(0));
3527   auto &TLI = DAG.getTargetLoweringInfo();
3528   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3529   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3530   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3531   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3532   setValue(&I, N);
3533 }
3534 
3535 void SelectionDAGBuilder::visitBitCast(const User &I) {
3536   SDValue N = getValue(I.getOperand(0));
3537   SDLoc dl = getCurSDLoc();
3538   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3539                                                         I.getType());
3540 
3541   // BitCast assures us that source and destination are the same size so this is
3542   // either a BITCAST or a no-op.
3543   if (DestVT != N.getValueType())
3544     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3545                              DestVT, N)); // convert types.
3546   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3547   // might fold any kind of constant expression to an integer constant and that
3548   // is not what we are looking for. Only recognize a bitcast of a genuine
3549   // constant integer as an opaque constant.
3550   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3551     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3552                                  /*isOpaque*/true));
3553   else
3554     setValue(&I, N);            // noop cast.
3555 }
3556 
3557 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3559   const Value *SV = I.getOperand(0);
3560   SDValue N = getValue(SV);
3561   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3562 
3563   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3564   unsigned DestAS = I.getType()->getPointerAddressSpace();
3565 
3566   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3567     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3568 
3569   setValue(&I, N);
3570 }
3571 
3572 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3574   SDValue InVec = getValue(I.getOperand(0));
3575   SDValue InVal = getValue(I.getOperand(1));
3576   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3577                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3578   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3579                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3580                            InVec, InVal, InIdx));
3581 }
3582 
3583 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3585   SDValue InVec = getValue(I.getOperand(0));
3586   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3587                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3588   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3589                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3590                            InVec, InIdx));
3591 }
3592 
3593 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3594   SDValue Src1 = getValue(I.getOperand(0));
3595   SDValue Src2 = getValue(I.getOperand(1));
3596   ArrayRef<int> Mask;
3597   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3598     Mask = SVI->getShuffleMask();
3599   else
3600     Mask = cast<ConstantExpr>(I).getShuffleMask();
3601   SDLoc DL = getCurSDLoc();
3602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3603   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3604   EVT SrcVT = Src1.getValueType();
3605 
3606   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3607       VT.isScalableVector()) {
3608     // Canonical splat form of first element of first input vector.
3609     SDValue FirstElt =
3610         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3611                     DAG.getVectorIdxConstant(0, DL));
3612     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3613     return;
3614   }
3615 
3616   // For now, we only handle splats for scalable vectors.
3617   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3618   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3619   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3620 
3621   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3622   unsigned MaskNumElts = Mask.size();
3623 
3624   if (SrcNumElts == MaskNumElts) {
3625     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3626     return;
3627   }
3628 
3629   // Normalize the shuffle vector since mask and vector length don't match.
3630   if (SrcNumElts < MaskNumElts) {
3631     // Mask is longer than the source vectors. We can use concatenate vector to
3632     // make the mask and vectors lengths match.
3633 
3634     if (MaskNumElts % SrcNumElts == 0) {
3635       // Mask length is a multiple of the source vector length.
3636       // Check if the shuffle is some kind of concatenation of the input
3637       // vectors.
3638       unsigned NumConcat = MaskNumElts / SrcNumElts;
3639       bool IsConcat = true;
3640       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3641       for (unsigned i = 0; i != MaskNumElts; ++i) {
3642         int Idx = Mask[i];
3643         if (Idx < 0)
3644           continue;
3645         // Ensure the indices in each SrcVT sized piece are sequential and that
3646         // the same source is used for the whole piece.
3647         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3648             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3649              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3650           IsConcat = false;
3651           break;
3652         }
3653         // Remember which source this index came from.
3654         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3655       }
3656 
3657       // The shuffle is concatenating multiple vectors together. Just emit
3658       // a CONCAT_VECTORS operation.
3659       if (IsConcat) {
3660         SmallVector<SDValue, 8> ConcatOps;
3661         for (auto Src : ConcatSrcs) {
3662           if (Src < 0)
3663             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3664           else if (Src == 0)
3665             ConcatOps.push_back(Src1);
3666           else
3667             ConcatOps.push_back(Src2);
3668         }
3669         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3670         return;
3671       }
3672     }
3673 
3674     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3675     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3676     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3677                                     PaddedMaskNumElts);
3678 
3679     // Pad both vectors with undefs to make them the same length as the mask.
3680     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3681 
3682     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3683     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3684     MOps1[0] = Src1;
3685     MOps2[0] = Src2;
3686 
3687     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3688     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3689 
3690     // Readjust mask for new input vector length.
3691     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3692     for (unsigned i = 0; i != MaskNumElts; ++i) {
3693       int Idx = Mask[i];
3694       if (Idx >= (int)SrcNumElts)
3695         Idx -= SrcNumElts - PaddedMaskNumElts;
3696       MappedOps[i] = Idx;
3697     }
3698 
3699     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3700 
3701     // If the concatenated vector was padded, extract a subvector with the
3702     // correct number of elements.
3703     if (MaskNumElts != PaddedMaskNumElts)
3704       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3705                            DAG.getVectorIdxConstant(0, DL));
3706 
3707     setValue(&I, Result);
3708     return;
3709   }
3710 
3711   if (SrcNumElts > MaskNumElts) {
3712     // Analyze the access pattern of the vector to see if we can extract
3713     // two subvectors and do the shuffle.
3714     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3715     bool CanExtract = true;
3716     for (int Idx : Mask) {
3717       unsigned Input = 0;
3718       if (Idx < 0)
3719         continue;
3720 
3721       if (Idx >= (int)SrcNumElts) {
3722         Input = 1;
3723         Idx -= SrcNumElts;
3724       }
3725 
3726       // If all the indices come from the same MaskNumElts sized portion of
3727       // the sources we can use extract. Also make sure the extract wouldn't
3728       // extract past the end of the source.
3729       int NewStartIdx = alignDown(Idx, MaskNumElts);
3730       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3731           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3732         CanExtract = false;
3733       // Make sure we always update StartIdx as we use it to track if all
3734       // elements are undef.
3735       StartIdx[Input] = NewStartIdx;
3736     }
3737 
3738     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3739       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3740       return;
3741     }
3742     if (CanExtract) {
3743       // Extract appropriate subvector and generate a vector shuffle
3744       for (unsigned Input = 0; Input < 2; ++Input) {
3745         SDValue &Src = Input == 0 ? Src1 : Src2;
3746         if (StartIdx[Input] < 0)
3747           Src = DAG.getUNDEF(VT);
3748         else {
3749           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3750                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3751         }
3752       }
3753 
3754       // Calculate new mask.
3755       SmallVector<int, 8> MappedOps(Mask);
3756       for (int &Idx : MappedOps) {
3757         if (Idx >= (int)SrcNumElts)
3758           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3759         else if (Idx >= 0)
3760           Idx -= StartIdx[0];
3761       }
3762 
3763       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3764       return;
3765     }
3766   }
3767 
3768   // We can't use either concat vectors or extract subvectors so fall back to
3769   // replacing the shuffle with extract and build vector.
3770   // to insert and build vector.
3771   EVT EltVT = VT.getVectorElementType();
3772   SmallVector<SDValue,8> Ops;
3773   for (int Idx : Mask) {
3774     SDValue Res;
3775 
3776     if (Idx < 0) {
3777       Res = DAG.getUNDEF(EltVT);
3778     } else {
3779       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3780       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3781 
3782       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3783                         DAG.getVectorIdxConstant(Idx, DL));
3784     }
3785 
3786     Ops.push_back(Res);
3787   }
3788 
3789   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3790 }
3791 
3792 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3793   ArrayRef<unsigned> Indices = I.getIndices();
3794   const Value *Op0 = I.getOperand(0);
3795   const Value *Op1 = I.getOperand(1);
3796   Type *AggTy = I.getType();
3797   Type *ValTy = Op1->getType();
3798   bool IntoUndef = isa<UndefValue>(Op0);
3799   bool FromUndef = isa<UndefValue>(Op1);
3800 
3801   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3802 
3803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3804   SmallVector<EVT, 4> AggValueVTs;
3805   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3806   SmallVector<EVT, 4> ValValueVTs;
3807   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3808 
3809   unsigned NumAggValues = AggValueVTs.size();
3810   unsigned NumValValues = ValValueVTs.size();
3811   SmallVector<SDValue, 4> Values(NumAggValues);
3812 
3813   // Ignore an insertvalue that produces an empty object
3814   if (!NumAggValues) {
3815     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3816     return;
3817   }
3818 
3819   SDValue Agg = getValue(Op0);
3820   unsigned i = 0;
3821   // Copy the beginning value(s) from the original aggregate.
3822   for (; i != LinearIndex; ++i)
3823     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3824                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3825   // Copy values from the inserted value(s).
3826   if (NumValValues) {
3827     SDValue Val = getValue(Op1);
3828     for (; i != LinearIndex + NumValValues; ++i)
3829       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3830                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3831   }
3832   // Copy remaining value(s) from the original aggregate.
3833   for (; i != NumAggValues; ++i)
3834     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3835                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3836 
3837   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3838                            DAG.getVTList(AggValueVTs), Values));
3839 }
3840 
3841 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3842   ArrayRef<unsigned> Indices = I.getIndices();
3843   const Value *Op0 = I.getOperand(0);
3844   Type *AggTy = Op0->getType();
3845   Type *ValTy = I.getType();
3846   bool OutOfUndef = isa<UndefValue>(Op0);
3847 
3848   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3849 
3850   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3851   SmallVector<EVT, 4> ValValueVTs;
3852   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3853 
3854   unsigned NumValValues = ValValueVTs.size();
3855 
3856   // Ignore a extractvalue that produces an empty object
3857   if (!NumValValues) {
3858     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3859     return;
3860   }
3861 
3862   SmallVector<SDValue, 4> Values(NumValValues);
3863 
3864   SDValue Agg = getValue(Op0);
3865   // Copy out the selected value(s).
3866   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3867     Values[i - LinearIndex] =
3868       OutOfUndef ?
3869         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3870         SDValue(Agg.getNode(), Agg.getResNo() + i);
3871 
3872   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3873                            DAG.getVTList(ValValueVTs), Values));
3874 }
3875 
3876 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3877   Value *Op0 = I.getOperand(0);
3878   // Note that the pointer operand may be a vector of pointers. Take the scalar
3879   // element which holds a pointer.
3880   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3881   SDValue N = getValue(Op0);
3882   SDLoc dl = getCurSDLoc();
3883   auto &TLI = DAG.getTargetLoweringInfo();
3884 
3885   // Normalize Vector GEP - all scalar operands should be converted to the
3886   // splat vector.
3887   bool IsVectorGEP = I.getType()->isVectorTy();
3888   ElementCount VectorElementCount =
3889       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3890                   : ElementCount::getFixed(0);
3891 
3892   if (IsVectorGEP && !N.getValueType().isVector()) {
3893     LLVMContext &Context = *DAG.getContext();
3894     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3895     N = DAG.getSplat(VT, dl, N);
3896   }
3897 
3898   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3899        GTI != E; ++GTI) {
3900     const Value *Idx = GTI.getOperand();
3901     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3902       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3903       if (Field) {
3904         // N = N + Offset
3905         uint64_t Offset =
3906             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3907 
3908         // In an inbounds GEP with an offset that is nonnegative even when
3909         // interpreted as signed, assume there is no unsigned overflow.
3910         SDNodeFlags Flags;
3911         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3912           Flags.setNoUnsignedWrap(true);
3913 
3914         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3915                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3916       }
3917     } else {
3918       // IdxSize is the width of the arithmetic according to IR semantics.
3919       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3920       // (and fix up the result later).
3921       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3922       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3923       TypeSize ElementSize =
3924           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3925       // We intentionally mask away the high bits here; ElementSize may not
3926       // fit in IdxTy.
3927       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3928       bool ElementScalable = ElementSize.isScalable();
3929 
3930       // If this is a scalar constant or a splat vector of constants,
3931       // handle it quickly.
3932       const auto *C = dyn_cast<Constant>(Idx);
3933       if (C && isa<VectorType>(C->getType()))
3934         C = C->getSplatValue();
3935 
3936       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3937       if (CI && CI->isZero())
3938         continue;
3939       if (CI && !ElementScalable) {
3940         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3941         LLVMContext &Context = *DAG.getContext();
3942         SDValue OffsVal;
3943         if (IsVectorGEP)
3944           OffsVal = DAG.getConstant(
3945               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3946         else
3947           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3948 
3949         // In an inbounds GEP with an offset that is nonnegative even when
3950         // interpreted as signed, assume there is no unsigned overflow.
3951         SDNodeFlags Flags;
3952         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3953           Flags.setNoUnsignedWrap(true);
3954 
3955         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3956 
3957         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3958         continue;
3959       }
3960 
3961       // N = N + Idx * ElementMul;
3962       SDValue IdxN = getValue(Idx);
3963 
3964       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3965         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3966                                   VectorElementCount);
3967         IdxN = DAG.getSplat(VT, dl, IdxN);
3968       }
3969 
3970       // If the index is smaller or larger than intptr_t, truncate or extend
3971       // it.
3972       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3973 
3974       if (ElementScalable) {
3975         EVT VScaleTy = N.getValueType().getScalarType();
3976         SDValue VScale = DAG.getNode(
3977             ISD::VSCALE, dl, VScaleTy,
3978             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3979         if (IsVectorGEP)
3980           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3981         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3982       } else {
3983         // If this is a multiply by a power of two, turn it into a shl
3984         // immediately.  This is a very common case.
3985         if (ElementMul != 1) {
3986           if (ElementMul.isPowerOf2()) {
3987             unsigned Amt = ElementMul.logBase2();
3988             IdxN = DAG.getNode(ISD::SHL, dl,
3989                                N.getValueType(), IdxN,
3990                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3991           } else {
3992             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3993                                             IdxN.getValueType());
3994             IdxN = DAG.getNode(ISD::MUL, dl,
3995                                N.getValueType(), IdxN, Scale);
3996           }
3997         }
3998       }
3999 
4000       N = DAG.getNode(ISD::ADD, dl,
4001                       N.getValueType(), N, IdxN);
4002     }
4003   }
4004 
4005   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4006   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4007   if (IsVectorGEP) {
4008     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4009     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4010   }
4011 
4012   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4013     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4014 
4015   setValue(&I, N);
4016 }
4017 
4018 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4019   // If this is a fixed sized alloca in the entry block of the function,
4020   // allocate it statically on the stack.
4021   if (FuncInfo.StaticAllocaMap.count(&I))
4022     return;   // getValue will auto-populate this.
4023 
4024   SDLoc dl = getCurSDLoc();
4025   Type *Ty = I.getAllocatedType();
4026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4027   auto &DL = DAG.getDataLayout();
4028   TypeSize TySize = DL.getTypeAllocSize(Ty);
4029   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4030 
4031   SDValue AllocSize = getValue(I.getArraySize());
4032 
4033   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4034   if (AllocSize.getValueType() != IntPtr)
4035     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4036 
4037   if (TySize.isScalable())
4038     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4039                             DAG.getVScale(dl, IntPtr,
4040                                           APInt(IntPtr.getScalarSizeInBits(),
4041                                                 TySize.getKnownMinValue())));
4042   else
4043     AllocSize =
4044         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4045                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4046 
4047   // Handle alignment.  If the requested alignment is less than or equal to
4048   // the stack alignment, ignore it.  If the size is greater than or equal to
4049   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4050   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4051   if (*Alignment <= StackAlign)
4052     Alignment = None;
4053 
4054   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4055   // Round the size of the allocation up to the stack alignment size
4056   // by add SA-1 to the size. This doesn't overflow because we're computing
4057   // an address inside an alloca.
4058   SDNodeFlags Flags;
4059   Flags.setNoUnsignedWrap(true);
4060   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4061                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4062 
4063   // Mask out the low bits for alignment purposes.
4064   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4065                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4066 
4067   SDValue Ops[] = {
4068       getRoot(), AllocSize,
4069       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4070   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4071   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4072   setValue(&I, DSA);
4073   DAG.setRoot(DSA.getValue(1));
4074 
4075   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4076 }
4077 
4078 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4079   if (I.isAtomic())
4080     return visitAtomicLoad(I);
4081 
4082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4083   const Value *SV = I.getOperand(0);
4084   if (TLI.supportSwiftError()) {
4085     // Swifterror values can come from either a function parameter with
4086     // swifterror attribute or an alloca with swifterror attribute.
4087     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4088       if (Arg->hasSwiftErrorAttr())
4089         return visitLoadFromSwiftError(I);
4090     }
4091 
4092     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4093       if (Alloca->isSwiftError())
4094         return visitLoadFromSwiftError(I);
4095     }
4096   }
4097 
4098   SDValue Ptr = getValue(SV);
4099 
4100   Type *Ty = I.getType();
4101   SmallVector<EVT, 4> ValueVTs, MemVTs;
4102   SmallVector<uint64_t, 4> Offsets;
4103   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4104   unsigned NumValues = ValueVTs.size();
4105   if (NumValues == 0)
4106     return;
4107 
4108   Align Alignment = I.getAlign();
4109   AAMDNodes AAInfo = I.getAAMetadata();
4110   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4111   bool isVolatile = I.isVolatile();
4112   MachineMemOperand::Flags MMOFlags =
4113       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4114 
4115   SDValue Root;
4116   bool ConstantMemory = false;
4117   if (isVolatile)
4118     // Serialize volatile loads with other side effects.
4119     Root = getRoot();
4120   else if (NumValues > MaxParallelChains)
4121     Root = getMemoryRoot();
4122   else if (AA &&
4123            AA->pointsToConstantMemory(MemoryLocation(
4124                SV,
4125                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4126                AAInfo))) {
4127     // Do not serialize (non-volatile) loads of constant memory with anything.
4128     Root = DAG.getEntryNode();
4129     ConstantMemory = true;
4130     MMOFlags |= MachineMemOperand::MOInvariant;
4131   } else {
4132     // Do not serialize non-volatile loads against each other.
4133     Root = DAG.getRoot();
4134   }
4135 
4136   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4137                                          &I, AC, nullptr, LibInfo))
4138     MMOFlags |= MachineMemOperand::MODereferenceable;
4139 
4140   SDLoc dl = getCurSDLoc();
4141 
4142   if (isVolatile)
4143     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4144 
4145   // An aggregate load cannot wrap around the address space, so offsets to its
4146   // parts don't wrap either.
4147   SDNodeFlags Flags;
4148   Flags.setNoUnsignedWrap(true);
4149 
4150   SmallVector<SDValue, 4> Values(NumValues);
4151   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4152   EVT PtrVT = Ptr.getValueType();
4153 
4154   unsigned ChainI = 0;
4155   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4156     // Serializing loads here may result in excessive register pressure, and
4157     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4158     // could recover a bit by hoisting nodes upward in the chain by recognizing
4159     // they are side-effect free or do not alias. The optimizer should really
4160     // avoid this case by converting large object/array copies to llvm.memcpy
4161     // (MaxParallelChains should always remain as failsafe).
4162     if (ChainI == MaxParallelChains) {
4163       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4164       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4165                                   makeArrayRef(Chains.data(), ChainI));
4166       Root = Chain;
4167       ChainI = 0;
4168     }
4169     SDValue A = DAG.getNode(ISD::ADD, dl,
4170                             PtrVT, Ptr,
4171                             DAG.getConstant(Offsets[i], dl, PtrVT),
4172                             Flags);
4173 
4174     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4175                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4176                             MMOFlags, AAInfo, Ranges);
4177     Chains[ChainI] = L.getValue(1);
4178 
4179     if (MemVTs[i] != ValueVTs[i])
4180       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4181 
4182     Values[i] = L;
4183   }
4184 
4185   if (!ConstantMemory) {
4186     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4187                                 makeArrayRef(Chains.data(), ChainI));
4188     if (isVolatile)
4189       DAG.setRoot(Chain);
4190     else
4191       PendingLoads.push_back(Chain);
4192   }
4193 
4194   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4195                            DAG.getVTList(ValueVTs), Values));
4196 }
4197 
4198 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4199   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4200          "call visitStoreToSwiftError when backend supports swifterror");
4201 
4202   SmallVector<EVT, 4> ValueVTs;
4203   SmallVector<uint64_t, 4> Offsets;
4204   const Value *SrcV = I.getOperand(0);
4205   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4206                   SrcV->getType(), ValueVTs, &Offsets);
4207   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4208          "expect a single EVT for swifterror");
4209 
4210   SDValue Src = getValue(SrcV);
4211   // Create a virtual register, then update the virtual register.
4212   Register VReg =
4213       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4214   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4215   // Chain can be getRoot or getControlRoot.
4216   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4217                                       SDValue(Src.getNode(), Src.getResNo()));
4218   DAG.setRoot(CopyNode);
4219 }
4220 
4221 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4222   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4223          "call visitLoadFromSwiftError when backend supports swifterror");
4224 
4225   assert(!I.isVolatile() &&
4226          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4227          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4228          "Support volatile, non temporal, invariant for load_from_swift_error");
4229 
4230   const Value *SV = I.getOperand(0);
4231   Type *Ty = I.getType();
4232   assert(
4233       (!AA ||
4234        !AA->pointsToConstantMemory(MemoryLocation(
4235            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4236            I.getAAMetadata()))) &&
4237       "load_from_swift_error should not be constant memory");
4238 
4239   SmallVector<EVT, 4> ValueVTs;
4240   SmallVector<uint64_t, 4> Offsets;
4241   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4242                   ValueVTs, &Offsets);
4243   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4244          "expect a single EVT for swifterror");
4245 
4246   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4247   SDValue L = DAG.getCopyFromReg(
4248       getRoot(), getCurSDLoc(),
4249       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4250 
4251   setValue(&I, L);
4252 }
4253 
4254 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4255   if (I.isAtomic())
4256     return visitAtomicStore(I);
4257 
4258   const Value *SrcV = I.getOperand(0);
4259   const Value *PtrV = I.getOperand(1);
4260 
4261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4262   if (TLI.supportSwiftError()) {
4263     // Swifterror values can come from either a function parameter with
4264     // swifterror attribute or an alloca with swifterror attribute.
4265     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4266       if (Arg->hasSwiftErrorAttr())
4267         return visitStoreToSwiftError(I);
4268     }
4269 
4270     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4271       if (Alloca->isSwiftError())
4272         return visitStoreToSwiftError(I);
4273     }
4274   }
4275 
4276   SmallVector<EVT, 4> ValueVTs, MemVTs;
4277   SmallVector<uint64_t, 4> Offsets;
4278   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4279                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4280   unsigned NumValues = ValueVTs.size();
4281   if (NumValues == 0)
4282     return;
4283 
4284   // Get the lowered operands. Note that we do this after
4285   // checking if NumResults is zero, because with zero results
4286   // the operands won't have values in the map.
4287   SDValue Src = getValue(SrcV);
4288   SDValue Ptr = getValue(PtrV);
4289 
4290   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4291   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4292   SDLoc dl = getCurSDLoc();
4293   Align Alignment = I.getAlign();
4294   AAMDNodes AAInfo = I.getAAMetadata();
4295 
4296   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4297 
4298   // An aggregate load cannot wrap around the address space, so offsets to its
4299   // parts don't wrap either.
4300   SDNodeFlags Flags;
4301   Flags.setNoUnsignedWrap(true);
4302 
4303   unsigned ChainI = 0;
4304   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4305     // See visitLoad comments.
4306     if (ChainI == MaxParallelChains) {
4307       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4308                                   makeArrayRef(Chains.data(), ChainI));
4309       Root = Chain;
4310       ChainI = 0;
4311     }
4312     SDValue Add =
4313         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4314     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4315     if (MemVTs[i] != ValueVTs[i])
4316       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4317     SDValue St =
4318         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4319                      Alignment, MMOFlags, AAInfo);
4320     Chains[ChainI] = St;
4321   }
4322 
4323   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4324                                   makeArrayRef(Chains.data(), ChainI));
4325   setValue(&I, StoreNode);
4326   DAG.setRoot(StoreNode);
4327 }
4328 
4329 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4330                                            bool IsCompressing) {
4331   SDLoc sdl = getCurSDLoc();
4332 
4333   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4334                                MaybeAlign &Alignment) {
4335     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4336     Src0 = I.getArgOperand(0);
4337     Ptr = I.getArgOperand(1);
4338     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4339     Mask = I.getArgOperand(3);
4340   };
4341   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4342                                     MaybeAlign &Alignment) {
4343     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4344     Src0 = I.getArgOperand(0);
4345     Ptr = I.getArgOperand(1);
4346     Mask = I.getArgOperand(2);
4347     Alignment = None;
4348   };
4349 
4350   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4351   MaybeAlign Alignment;
4352   if (IsCompressing)
4353     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4354   else
4355     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4356 
4357   SDValue Ptr = getValue(PtrOperand);
4358   SDValue Src0 = getValue(Src0Operand);
4359   SDValue Mask = getValue(MaskOperand);
4360   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4361 
4362   EVT VT = Src0.getValueType();
4363   if (!Alignment)
4364     Alignment = DAG.getEVTAlign(VT);
4365 
4366   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4367       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4368       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4369   SDValue StoreNode =
4370       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4371                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4372   DAG.setRoot(StoreNode);
4373   setValue(&I, StoreNode);
4374 }
4375 
4376 // Get a uniform base for the Gather/Scatter intrinsic.
4377 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4378 // We try to represent it as a base pointer + vector of indices.
4379 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4380 // The first operand of the GEP may be a single pointer or a vector of pointers
4381 // Example:
4382 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4383 //  or
4384 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4385 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4386 //
4387 // When the first GEP operand is a single pointer - it is the uniform base we
4388 // are looking for. If first operand of the GEP is a splat vector - we
4389 // extract the splat value and use it as a uniform base.
4390 // In all other cases the function returns 'false'.
4391 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4392                            ISD::MemIndexType &IndexType, SDValue &Scale,
4393                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4394                            uint64_t ElemSize) {
4395   SelectionDAG& DAG = SDB->DAG;
4396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4397   const DataLayout &DL = DAG.getDataLayout();
4398 
4399   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4400 
4401   // Handle splat constant pointer.
4402   if (auto *C = dyn_cast<Constant>(Ptr)) {
4403     C = C->getSplatValue();
4404     if (!C)
4405       return false;
4406 
4407     Base = SDB->getValue(C);
4408 
4409     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4410     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4411     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4412     IndexType = ISD::SIGNED_SCALED;
4413     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4414     return true;
4415   }
4416 
4417   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4418   if (!GEP || GEP->getParent() != CurBB)
4419     return false;
4420 
4421   if (GEP->getNumOperands() != 2)
4422     return false;
4423 
4424   const Value *BasePtr = GEP->getPointerOperand();
4425   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4426 
4427   // Make sure the base is scalar and the index is a vector.
4428   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4429     return false;
4430 
4431   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4432 
4433   // Target may not support the required addressing mode.
4434   if (ScaleVal != 1 &&
4435       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4436     return false;
4437 
4438   Base = SDB->getValue(BasePtr);
4439   Index = SDB->getValue(IndexVal);
4440   IndexType = ISD::SIGNED_SCALED;
4441 
4442   Scale =
4443       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4444   return true;
4445 }
4446 
4447 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4448   SDLoc sdl = getCurSDLoc();
4449 
4450   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4451   const Value *Ptr = I.getArgOperand(1);
4452   SDValue Src0 = getValue(I.getArgOperand(0));
4453   SDValue Mask = getValue(I.getArgOperand(3));
4454   EVT VT = Src0.getValueType();
4455   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4456                         ->getMaybeAlignValue()
4457                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4459 
4460   SDValue Base;
4461   SDValue Index;
4462   ISD::MemIndexType IndexType;
4463   SDValue Scale;
4464   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4465                                     I.getParent(), VT.getScalarStoreSize());
4466 
4467   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4468   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4469       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4470       // TODO: Make MachineMemOperands aware of scalable
4471       // vectors.
4472       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4473   if (!UniformBase) {
4474     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4475     Index = getValue(Ptr);
4476     IndexType = ISD::SIGNED_SCALED;
4477     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4478   }
4479 
4480   EVT IdxVT = Index.getValueType();
4481   EVT EltTy = IdxVT.getVectorElementType();
4482   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4483     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4484     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4485   }
4486 
4487   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4488   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4489                                          Ops, MMO, IndexType, false);
4490   DAG.setRoot(Scatter);
4491   setValue(&I, Scatter);
4492 }
4493 
4494 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4495   SDLoc sdl = getCurSDLoc();
4496 
4497   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4498                               MaybeAlign &Alignment) {
4499     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4500     Ptr = I.getArgOperand(0);
4501     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4502     Mask = I.getArgOperand(2);
4503     Src0 = I.getArgOperand(3);
4504   };
4505   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4506                                  MaybeAlign &Alignment) {
4507     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4508     Ptr = I.getArgOperand(0);
4509     Alignment = None;
4510     Mask = I.getArgOperand(1);
4511     Src0 = I.getArgOperand(2);
4512   };
4513 
4514   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4515   MaybeAlign Alignment;
4516   if (IsExpanding)
4517     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4518   else
4519     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4520 
4521   SDValue Ptr = getValue(PtrOperand);
4522   SDValue Src0 = getValue(Src0Operand);
4523   SDValue Mask = getValue(MaskOperand);
4524   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4525 
4526   EVT VT = Src0.getValueType();
4527   if (!Alignment)
4528     Alignment = DAG.getEVTAlign(VT);
4529 
4530   AAMDNodes AAInfo = I.getAAMetadata();
4531   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4532 
4533   // Do not serialize masked loads of constant memory with anything.
4534   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4535   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4536 
4537   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4538 
4539   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4540       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4541       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4542 
4543   SDValue Load =
4544       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4545                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4546   if (AddToChain)
4547     PendingLoads.push_back(Load.getValue(1));
4548   setValue(&I, Load);
4549 }
4550 
4551 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4552   SDLoc sdl = getCurSDLoc();
4553 
4554   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4555   const Value *Ptr = I.getArgOperand(0);
4556   SDValue Src0 = getValue(I.getArgOperand(3));
4557   SDValue Mask = getValue(I.getArgOperand(2));
4558 
4559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4560   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4561   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4562                         ->getMaybeAlignValue()
4563                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4564 
4565   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4566 
4567   SDValue Root = DAG.getRoot();
4568   SDValue Base;
4569   SDValue Index;
4570   ISD::MemIndexType IndexType;
4571   SDValue Scale;
4572   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4573                                     I.getParent(), VT.getScalarStoreSize());
4574   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4575   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4576       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4577       // TODO: Make MachineMemOperands aware of scalable
4578       // vectors.
4579       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4580 
4581   if (!UniformBase) {
4582     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4583     Index = getValue(Ptr);
4584     IndexType = ISD::SIGNED_SCALED;
4585     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4586   }
4587 
4588   EVT IdxVT = Index.getValueType();
4589   EVT EltTy = IdxVT.getVectorElementType();
4590   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4591     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4592     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4593   }
4594 
4595   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4596   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4597                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4598 
4599   PendingLoads.push_back(Gather.getValue(1));
4600   setValue(&I, Gather);
4601 }
4602 
4603 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4604   SDLoc dl = getCurSDLoc();
4605   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4606   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4607   SyncScope::ID SSID = I.getSyncScopeID();
4608 
4609   SDValue InChain = getRoot();
4610 
4611   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4612   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4613 
4614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4615   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4616 
4617   MachineFunction &MF = DAG.getMachineFunction();
4618   MachineMemOperand *MMO = MF.getMachineMemOperand(
4619       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4620       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4621       FailureOrdering);
4622 
4623   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4624                                    dl, MemVT, VTs, InChain,
4625                                    getValue(I.getPointerOperand()),
4626                                    getValue(I.getCompareOperand()),
4627                                    getValue(I.getNewValOperand()), MMO);
4628 
4629   SDValue OutChain = L.getValue(2);
4630 
4631   setValue(&I, L);
4632   DAG.setRoot(OutChain);
4633 }
4634 
4635 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4636   SDLoc dl = getCurSDLoc();
4637   ISD::NodeType NT;
4638   switch (I.getOperation()) {
4639   default: llvm_unreachable("Unknown atomicrmw operation");
4640   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4641   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4642   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4643   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4644   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4645   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4646   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4647   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4648   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4649   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4650   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4651   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4652   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4653   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4654   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4655   }
4656   AtomicOrdering Ordering = I.getOrdering();
4657   SyncScope::ID SSID = I.getSyncScopeID();
4658 
4659   SDValue InChain = getRoot();
4660 
4661   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4663   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4664 
4665   MachineFunction &MF = DAG.getMachineFunction();
4666   MachineMemOperand *MMO = MF.getMachineMemOperand(
4667       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4668       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4669 
4670   SDValue L =
4671     DAG.getAtomic(NT, dl, MemVT, InChain,
4672                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4673                   MMO);
4674 
4675   SDValue OutChain = L.getValue(1);
4676 
4677   setValue(&I, L);
4678   DAG.setRoot(OutChain);
4679 }
4680 
4681 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4682   SDLoc dl = getCurSDLoc();
4683   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4684   SDValue Ops[3];
4685   Ops[0] = getRoot();
4686   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4687                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4688   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4689                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4690   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4691   setValue(&I, N);
4692   DAG.setRoot(N);
4693 }
4694 
4695 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4696   SDLoc dl = getCurSDLoc();
4697   AtomicOrdering Order = I.getOrdering();
4698   SyncScope::ID SSID = I.getSyncScopeID();
4699 
4700   SDValue InChain = getRoot();
4701 
4702   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4703   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4704   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4705 
4706   if (!TLI.supportsUnalignedAtomics() &&
4707       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4708     report_fatal_error("Cannot generate unaligned atomic load");
4709 
4710   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4711 
4712   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4713       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4714       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4715 
4716   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4717 
4718   SDValue Ptr = getValue(I.getPointerOperand());
4719 
4720   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4721     // TODO: Once this is better exercised by tests, it should be merged with
4722     // the normal path for loads to prevent future divergence.
4723     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4724     if (MemVT != VT)
4725       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4726 
4727     setValue(&I, L);
4728     SDValue OutChain = L.getValue(1);
4729     if (!I.isUnordered())
4730       DAG.setRoot(OutChain);
4731     else
4732       PendingLoads.push_back(OutChain);
4733     return;
4734   }
4735 
4736   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4737                             Ptr, MMO);
4738 
4739   SDValue OutChain = L.getValue(1);
4740   if (MemVT != VT)
4741     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4742 
4743   setValue(&I, L);
4744   DAG.setRoot(OutChain);
4745 }
4746 
4747 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4748   SDLoc dl = getCurSDLoc();
4749 
4750   AtomicOrdering Ordering = I.getOrdering();
4751   SyncScope::ID SSID = I.getSyncScopeID();
4752 
4753   SDValue InChain = getRoot();
4754 
4755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4756   EVT MemVT =
4757       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4758 
4759   if (!TLI.supportsUnalignedAtomics() &&
4760       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4761     report_fatal_error("Cannot generate unaligned atomic store");
4762 
4763   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4764 
4765   MachineFunction &MF = DAG.getMachineFunction();
4766   MachineMemOperand *MMO = MF.getMachineMemOperand(
4767       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4768       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4769 
4770   SDValue Val = getValue(I.getValueOperand());
4771   if (Val.getValueType() != MemVT)
4772     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4773   SDValue Ptr = getValue(I.getPointerOperand());
4774 
4775   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4776     // TODO: Once this is better exercised by tests, it should be merged with
4777     // the normal path for stores to prevent future divergence.
4778     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4779     setValue(&I, S);
4780     DAG.setRoot(S);
4781     return;
4782   }
4783   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4784                                    Ptr, Val, MMO);
4785 
4786   setValue(&I, OutChain);
4787   DAG.setRoot(OutChain);
4788 }
4789 
4790 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4791 /// node.
4792 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4793                                                unsigned Intrinsic) {
4794   // Ignore the callsite's attributes. A specific call site may be marked with
4795   // readnone, but the lowering code will expect the chain based on the
4796   // definition.
4797   const Function *F = I.getCalledFunction();
4798   bool HasChain = !F->doesNotAccessMemory();
4799   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4800 
4801   // Build the operand list.
4802   SmallVector<SDValue, 8> Ops;
4803   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4804     if (OnlyLoad) {
4805       // We don't need to serialize loads against other loads.
4806       Ops.push_back(DAG.getRoot());
4807     } else {
4808       Ops.push_back(getRoot());
4809     }
4810   }
4811 
4812   // Info is set by getTgtMemIntrinsic
4813   TargetLowering::IntrinsicInfo Info;
4814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4815   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4816                                                DAG.getMachineFunction(),
4817                                                Intrinsic);
4818 
4819   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4820   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4821       Info.opc == ISD::INTRINSIC_W_CHAIN)
4822     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4823                                         TLI.getPointerTy(DAG.getDataLayout())));
4824 
4825   // Add all operands of the call to the operand list.
4826   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4827     const Value *Arg = I.getArgOperand(i);
4828     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4829       Ops.push_back(getValue(Arg));
4830       continue;
4831     }
4832 
4833     // Use TargetConstant instead of a regular constant for immarg.
4834     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4835     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4836       assert(CI->getBitWidth() <= 64 &&
4837              "large intrinsic immediates not handled");
4838       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4839     } else {
4840       Ops.push_back(
4841           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4842     }
4843   }
4844 
4845   SmallVector<EVT, 4> ValueVTs;
4846   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4847 
4848   if (HasChain)
4849     ValueVTs.push_back(MVT::Other);
4850 
4851   SDVTList VTs = DAG.getVTList(ValueVTs);
4852 
4853   // Propagate fast-math-flags from IR to node(s).
4854   SDNodeFlags Flags;
4855   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4856     Flags.copyFMF(*FPMO);
4857   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4858 
4859   // Create the node.
4860   SDValue Result;
4861   // In some cases, custom collection of operands from CallInst I may be needed.
4862   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4863   if (IsTgtIntrinsic) {
4864     // This is target intrinsic that touches memory
4865     //
4866     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4867     //       didn't yield anything useful.
4868     MachinePointerInfo MPI;
4869     if (Info.ptrVal)
4870       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4871     else if (Info.fallbackAddressSpace)
4872       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4873     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4874                                      Info.memVT, MPI, Info.align, Info.flags,
4875                                      Info.size, I.getAAMetadata());
4876   } else if (!HasChain) {
4877     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4878   } else if (!I.getType()->isVoidTy()) {
4879     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4880   } else {
4881     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4882   }
4883 
4884   if (HasChain) {
4885     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4886     if (OnlyLoad)
4887       PendingLoads.push_back(Chain);
4888     else
4889       DAG.setRoot(Chain);
4890   }
4891 
4892   if (!I.getType()->isVoidTy()) {
4893     if (!isa<VectorType>(I.getType()))
4894       Result = lowerRangeToAssertZExt(DAG, I, Result);
4895 
4896     MaybeAlign Alignment = I.getRetAlign();
4897     if (!Alignment)
4898       Alignment = F->getAttributes().getRetAlignment();
4899     // Insert `assertalign` node if there's an alignment.
4900     if (InsertAssertAlign && Alignment) {
4901       Result =
4902           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4903     }
4904 
4905     setValue(&I, Result);
4906   }
4907 }
4908 
4909 /// GetSignificand - Get the significand and build it into a floating-point
4910 /// number with exponent of 1:
4911 ///
4912 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4913 ///
4914 /// where Op is the hexadecimal representation of floating point value.
4915 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4916   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4917                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4918   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4919                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4920   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4921 }
4922 
4923 /// GetExponent - Get the exponent:
4924 ///
4925 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4926 ///
4927 /// where Op is the hexadecimal representation of floating point value.
4928 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4929                            const TargetLowering &TLI, const SDLoc &dl) {
4930   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4931                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4932   SDValue t1 = DAG.getNode(
4933       ISD::SRL, dl, MVT::i32, t0,
4934       DAG.getConstant(23, dl,
4935                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4936   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4937                            DAG.getConstant(127, dl, MVT::i32));
4938   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4939 }
4940 
4941 /// getF32Constant - Get 32-bit floating point constant.
4942 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4943                               const SDLoc &dl) {
4944   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4945                            MVT::f32);
4946 }
4947 
4948 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4949                                        SelectionDAG &DAG) {
4950   // TODO: What fast-math-flags should be set on the floating-point nodes?
4951 
4952   //   IntegerPartOfX = ((int32_t)(t0);
4953   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4954 
4955   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4956   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4957   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4958 
4959   //   IntegerPartOfX <<= 23;
4960   IntegerPartOfX =
4961       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4962                   DAG.getConstant(23, dl,
4963                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4964                                       MVT::i32, DAG.getDataLayout())));
4965 
4966   SDValue TwoToFractionalPartOfX;
4967   if (LimitFloatPrecision <= 6) {
4968     // For floating-point precision of 6:
4969     //
4970     //   TwoToFractionalPartOfX =
4971     //     0.997535578f +
4972     //       (0.735607626f + 0.252464424f * x) * x;
4973     //
4974     // error 0.0144103317, which is 6 bits
4975     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4976                              getF32Constant(DAG, 0x3e814304, dl));
4977     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4978                              getF32Constant(DAG, 0x3f3c50c8, dl));
4979     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4980     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4981                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4982   } else if (LimitFloatPrecision <= 12) {
4983     // For floating-point precision of 12:
4984     //
4985     //   TwoToFractionalPartOfX =
4986     //     0.999892986f +
4987     //       (0.696457318f +
4988     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4989     //
4990     // error 0.000107046256, which is 13 to 14 bits
4991     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4992                              getF32Constant(DAG, 0x3da235e3, dl));
4993     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4994                              getF32Constant(DAG, 0x3e65b8f3, dl));
4995     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4996     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4997                              getF32Constant(DAG, 0x3f324b07, dl));
4998     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4999     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5000                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5001   } else { // LimitFloatPrecision <= 18
5002     // For floating-point precision of 18:
5003     //
5004     //   TwoToFractionalPartOfX =
5005     //     0.999999982f +
5006     //       (0.693148872f +
5007     //         (0.240227044f +
5008     //           (0.554906021e-1f +
5009     //             (0.961591928e-2f +
5010     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5011     // error 2.47208000*10^(-7), which is better than 18 bits
5012     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5013                              getF32Constant(DAG, 0x3924b03e, dl));
5014     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5015                              getF32Constant(DAG, 0x3ab24b87, dl));
5016     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5017     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5018                              getF32Constant(DAG, 0x3c1d8c17, dl));
5019     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5020     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5021                              getF32Constant(DAG, 0x3d634a1d, dl));
5022     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5023     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5024                              getF32Constant(DAG, 0x3e75fe14, dl));
5025     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5026     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5027                               getF32Constant(DAG, 0x3f317234, dl));
5028     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5029     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5030                                          getF32Constant(DAG, 0x3f800000, dl));
5031   }
5032 
5033   // Add the exponent into the result in integer domain.
5034   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5035   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5036                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5037 }
5038 
5039 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5040 /// limited-precision mode.
5041 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5042                          const TargetLowering &TLI, SDNodeFlags Flags) {
5043   if (Op.getValueType() == MVT::f32 &&
5044       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5045 
5046     // Put the exponent in the right bit position for later addition to the
5047     // final result:
5048     //
5049     // t0 = Op * log2(e)
5050 
5051     // TODO: What fast-math-flags should be set here?
5052     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5053                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5054     return getLimitedPrecisionExp2(t0, dl, DAG);
5055   }
5056 
5057   // No special expansion.
5058   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5059 }
5060 
5061 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5062 /// limited-precision mode.
5063 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5064                          const TargetLowering &TLI, SDNodeFlags Flags) {
5065   // TODO: What fast-math-flags should be set on the floating-point nodes?
5066 
5067   if (Op.getValueType() == MVT::f32 &&
5068       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5069     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5070 
5071     // Scale the exponent by log(2).
5072     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5073     SDValue LogOfExponent =
5074         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5075                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5076 
5077     // Get the significand and build it into a floating-point number with
5078     // exponent of 1.
5079     SDValue X = GetSignificand(DAG, Op1, dl);
5080 
5081     SDValue LogOfMantissa;
5082     if (LimitFloatPrecision <= 6) {
5083       // For floating-point precision of 6:
5084       //
5085       //   LogofMantissa =
5086       //     -1.1609546f +
5087       //       (1.4034025f - 0.23903021f * x) * x;
5088       //
5089       // error 0.0034276066, which is better than 8 bits
5090       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5091                                getF32Constant(DAG, 0xbe74c456, dl));
5092       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5093                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5094       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5095       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5096                                   getF32Constant(DAG, 0x3f949a29, dl));
5097     } else if (LimitFloatPrecision <= 12) {
5098       // For floating-point precision of 12:
5099       //
5100       //   LogOfMantissa =
5101       //     -1.7417939f +
5102       //       (2.8212026f +
5103       //         (-1.4699568f +
5104       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5105       //
5106       // error 0.000061011436, which is 14 bits
5107       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5108                                getF32Constant(DAG, 0xbd67b6d6, dl));
5109       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5110                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5111       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5112       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5113                                getF32Constant(DAG, 0x3fbc278b, dl));
5114       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5115       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5116                                getF32Constant(DAG, 0x40348e95, dl));
5117       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5118       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5119                                   getF32Constant(DAG, 0x3fdef31a, dl));
5120     } else { // LimitFloatPrecision <= 18
5121       // For floating-point precision of 18:
5122       //
5123       //   LogOfMantissa =
5124       //     -2.1072184f +
5125       //       (4.2372794f +
5126       //         (-3.7029485f +
5127       //           (2.2781945f +
5128       //             (-0.87823314f +
5129       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5130       //
5131       // error 0.0000023660568, which is better than 18 bits
5132       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5133                                getF32Constant(DAG, 0xbc91e5ac, dl));
5134       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5135                                getF32Constant(DAG, 0x3e4350aa, dl));
5136       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5137       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5138                                getF32Constant(DAG, 0x3f60d3e3, dl));
5139       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5140       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5141                                getF32Constant(DAG, 0x4011cdf0, dl));
5142       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5143       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5144                                getF32Constant(DAG, 0x406cfd1c, dl));
5145       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5146       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5147                                getF32Constant(DAG, 0x408797cb, dl));
5148       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5149       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5150                                   getF32Constant(DAG, 0x4006dcab, dl));
5151     }
5152 
5153     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5154   }
5155 
5156   // No special expansion.
5157   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5158 }
5159 
5160 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5161 /// limited-precision mode.
5162 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5163                           const TargetLowering &TLI, SDNodeFlags Flags) {
5164   // TODO: What fast-math-flags should be set on the floating-point nodes?
5165 
5166   if (Op.getValueType() == MVT::f32 &&
5167       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5168     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5169 
5170     // Get the exponent.
5171     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5172 
5173     // Get the significand and build it into a floating-point number with
5174     // exponent of 1.
5175     SDValue X = GetSignificand(DAG, Op1, dl);
5176 
5177     // Different possible minimax approximations of significand in
5178     // floating-point for various degrees of accuracy over [1,2].
5179     SDValue Log2ofMantissa;
5180     if (LimitFloatPrecision <= 6) {
5181       // For floating-point precision of 6:
5182       //
5183       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5184       //
5185       // error 0.0049451742, which is more than 7 bits
5186       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5187                                getF32Constant(DAG, 0xbeb08fe0, dl));
5188       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5189                                getF32Constant(DAG, 0x40019463, dl));
5190       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5191       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5192                                    getF32Constant(DAG, 0x3fd6633d, dl));
5193     } else if (LimitFloatPrecision <= 12) {
5194       // For floating-point precision of 12:
5195       //
5196       //   Log2ofMantissa =
5197       //     -2.51285454f +
5198       //       (4.07009056f +
5199       //         (-2.12067489f +
5200       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5201       //
5202       // error 0.0000876136000, which is better than 13 bits
5203       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5204                                getF32Constant(DAG, 0xbda7262e, dl));
5205       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5206                                getF32Constant(DAG, 0x3f25280b, dl));
5207       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5208       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5209                                getF32Constant(DAG, 0x4007b923, dl));
5210       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5211       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5212                                getF32Constant(DAG, 0x40823e2f, dl));
5213       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5214       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5215                                    getF32Constant(DAG, 0x4020d29c, dl));
5216     } else { // LimitFloatPrecision <= 18
5217       // For floating-point precision of 18:
5218       //
5219       //   Log2ofMantissa =
5220       //     -3.0400495f +
5221       //       (6.1129976f +
5222       //         (-5.3420409f +
5223       //           (3.2865683f +
5224       //             (-1.2669343f +
5225       //               (0.27515199f -
5226       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5227       //
5228       // error 0.0000018516, which is better than 18 bits
5229       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5230                                getF32Constant(DAG, 0xbcd2769e, dl));
5231       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5232                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5233       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5234       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5235                                getF32Constant(DAG, 0x3fa22ae7, dl));
5236       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5237       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5238                                getF32Constant(DAG, 0x40525723, dl));
5239       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5240       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5241                                getF32Constant(DAG, 0x40aaf200, dl));
5242       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5243       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5244                                getF32Constant(DAG, 0x40c39dad, dl));
5245       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5246       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5247                                    getF32Constant(DAG, 0x4042902c, dl));
5248     }
5249 
5250     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5251   }
5252 
5253   // No special expansion.
5254   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5255 }
5256 
5257 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5258 /// limited-precision mode.
5259 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5260                            const TargetLowering &TLI, SDNodeFlags Flags) {
5261   // TODO: What fast-math-flags should be set on the floating-point nodes?
5262 
5263   if (Op.getValueType() == MVT::f32 &&
5264       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5265     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5266 
5267     // Scale the exponent by log10(2) [0.30102999f].
5268     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5269     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5270                                         getF32Constant(DAG, 0x3e9a209a, dl));
5271 
5272     // Get the significand and build it into a floating-point number with
5273     // exponent of 1.
5274     SDValue X = GetSignificand(DAG, Op1, dl);
5275 
5276     SDValue Log10ofMantissa;
5277     if (LimitFloatPrecision <= 6) {
5278       // For floating-point precision of 6:
5279       //
5280       //   Log10ofMantissa =
5281       //     -0.50419619f +
5282       //       (0.60948995f - 0.10380950f * x) * x;
5283       //
5284       // error 0.0014886165, which is 6 bits
5285       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5286                                getF32Constant(DAG, 0xbdd49a13, dl));
5287       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5288                                getF32Constant(DAG, 0x3f1c0789, dl));
5289       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5290       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5291                                     getF32Constant(DAG, 0x3f011300, dl));
5292     } else if (LimitFloatPrecision <= 12) {
5293       // For floating-point precision of 12:
5294       //
5295       //   Log10ofMantissa =
5296       //     -0.64831180f +
5297       //       (0.91751397f +
5298       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5299       //
5300       // error 0.00019228036, which is better than 12 bits
5301       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5302                                getF32Constant(DAG, 0x3d431f31, dl));
5303       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5304                                getF32Constant(DAG, 0x3ea21fb2, dl));
5305       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5306       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5307                                getF32Constant(DAG, 0x3f6ae232, dl));
5308       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5309       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5310                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5311     } else { // LimitFloatPrecision <= 18
5312       // For floating-point precision of 18:
5313       //
5314       //   Log10ofMantissa =
5315       //     -0.84299375f +
5316       //       (1.5327582f +
5317       //         (-1.0688956f +
5318       //           (0.49102474f +
5319       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5320       //
5321       // error 0.0000037995730, which is better than 18 bits
5322       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5323                                getF32Constant(DAG, 0x3c5d51ce, dl));
5324       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5325                                getF32Constant(DAG, 0x3e00685a, dl));
5326       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5327       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5328                                getF32Constant(DAG, 0x3efb6798, dl));
5329       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5330       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5331                                getF32Constant(DAG, 0x3f88d192, dl));
5332       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5333       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5334                                getF32Constant(DAG, 0x3fc4316c, dl));
5335       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5336       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5337                                     getF32Constant(DAG, 0x3f57ce70, dl));
5338     }
5339 
5340     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5341   }
5342 
5343   // No special expansion.
5344   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5345 }
5346 
5347 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5348 /// limited-precision mode.
5349 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5350                           const TargetLowering &TLI, SDNodeFlags Flags) {
5351   if (Op.getValueType() == MVT::f32 &&
5352       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5353     return getLimitedPrecisionExp2(Op, dl, DAG);
5354 
5355   // No special expansion.
5356   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5357 }
5358 
5359 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5360 /// limited-precision mode with x == 10.0f.
5361 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5362                          SelectionDAG &DAG, const TargetLowering &TLI,
5363                          SDNodeFlags Flags) {
5364   bool IsExp10 = false;
5365   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5366       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5367     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5368       APFloat Ten(10.0f);
5369       IsExp10 = LHSC->isExactlyValue(Ten);
5370     }
5371   }
5372 
5373   // TODO: What fast-math-flags should be set on the FMUL node?
5374   if (IsExp10) {
5375     // Put the exponent in the right bit position for later addition to the
5376     // final result:
5377     //
5378     //   #define LOG2OF10 3.3219281f
5379     //   t0 = Op * LOG2OF10;
5380     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5381                              getF32Constant(DAG, 0x40549a78, dl));
5382     return getLimitedPrecisionExp2(t0, dl, DAG);
5383   }
5384 
5385   // No special expansion.
5386   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5387 }
5388 
5389 /// ExpandPowI - Expand a llvm.powi intrinsic.
5390 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5391                           SelectionDAG &DAG) {
5392   // If RHS is a constant, we can expand this out to a multiplication tree if
5393   // it's beneficial on the target, otherwise we end up lowering to a call to
5394   // __powidf2 (for example).
5395   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5396     unsigned Val = RHSC->getSExtValue();
5397 
5398     // powi(x, 0) -> 1.0
5399     if (Val == 0)
5400       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5401 
5402     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5403             Val, DAG.shouldOptForSize())) {
5404       // Get the exponent as a positive value.
5405       if ((int)Val < 0)
5406         Val = -Val;
5407       // We use the simple binary decomposition method to generate the multiply
5408       // sequence.  There are more optimal ways to do this (for example,
5409       // powi(x,15) generates one more multiply than it should), but this has
5410       // the benefit of being both really simple and much better than a libcall.
5411       SDValue Res; // Logically starts equal to 1.0
5412       SDValue CurSquare = LHS;
5413       // TODO: Intrinsics should have fast-math-flags that propagate to these
5414       // nodes.
5415       while (Val) {
5416         if (Val & 1) {
5417           if (Res.getNode())
5418             Res =
5419                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5420           else
5421             Res = CurSquare; // 1.0*CurSquare.
5422         }
5423 
5424         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5425                                 CurSquare, CurSquare);
5426         Val >>= 1;
5427       }
5428 
5429       // If the original was negative, invert the result, producing 1/(x*x*x).
5430       if (RHSC->getSExtValue() < 0)
5431         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5432                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5433       return Res;
5434     }
5435   }
5436 
5437   // Otherwise, expand to a libcall.
5438   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5439 }
5440 
5441 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5442                             SDValue LHS, SDValue RHS, SDValue Scale,
5443                             SelectionDAG &DAG, const TargetLowering &TLI) {
5444   EVT VT = LHS.getValueType();
5445   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5446   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5447   LLVMContext &Ctx = *DAG.getContext();
5448 
5449   // If the type is legal but the operation isn't, this node might survive all
5450   // the way to operation legalization. If we end up there and we do not have
5451   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5452   // node.
5453 
5454   // Coax the legalizer into expanding the node during type legalization instead
5455   // by bumping the size by one bit. This will force it to Promote, enabling the
5456   // early expansion and avoiding the need to expand later.
5457 
5458   // We don't have to do this if Scale is 0; that can always be expanded, unless
5459   // it's a saturating signed operation. Those can experience true integer
5460   // division overflow, a case which we must avoid.
5461 
5462   // FIXME: We wouldn't have to do this (or any of the early
5463   // expansion/promotion) if it was possible to expand a libcall of an
5464   // illegal type during operation legalization. But it's not, so things
5465   // get a bit hacky.
5466   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5467   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5468       (TLI.isTypeLegal(VT) ||
5469        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5470     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5471         Opcode, VT, ScaleInt);
5472     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5473       EVT PromVT;
5474       if (VT.isScalarInteger())
5475         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5476       else if (VT.isVector()) {
5477         PromVT = VT.getVectorElementType();
5478         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5479         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5480       } else
5481         llvm_unreachable("Wrong VT for DIVFIX?");
5482       if (Signed) {
5483         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5484         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5485       } else {
5486         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5487         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5488       }
5489       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5490       // For saturating operations, we need to shift up the LHS to get the
5491       // proper saturation width, and then shift down again afterwards.
5492       if (Saturating)
5493         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5494                           DAG.getConstant(1, DL, ShiftTy));
5495       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5496       if (Saturating)
5497         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5498                           DAG.getConstant(1, DL, ShiftTy));
5499       return DAG.getZExtOrTrunc(Res, DL, VT);
5500     }
5501   }
5502 
5503   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5504 }
5505 
5506 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5507 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5508 static void
5509 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5510                      const SDValue &N) {
5511   switch (N.getOpcode()) {
5512   case ISD::CopyFromReg: {
5513     SDValue Op = N.getOperand(1);
5514     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5515                       Op.getValueType().getSizeInBits());
5516     return;
5517   }
5518   case ISD::BITCAST:
5519   case ISD::AssertZext:
5520   case ISD::AssertSext:
5521   case ISD::TRUNCATE:
5522     getUnderlyingArgRegs(Regs, N.getOperand(0));
5523     return;
5524   case ISD::BUILD_PAIR:
5525   case ISD::BUILD_VECTOR:
5526   case ISD::CONCAT_VECTORS:
5527     for (SDValue Op : N->op_values())
5528       getUnderlyingArgRegs(Regs, Op);
5529     return;
5530   default:
5531     return;
5532   }
5533 }
5534 
5535 /// If the DbgValueInst is a dbg_value of a function argument, create the
5536 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5537 /// instruction selection, they will be inserted to the entry BB.
5538 /// We don't currently support this for variadic dbg_values, as they shouldn't
5539 /// appear for function arguments or in the prologue.
5540 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5541     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5542     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5543   const Argument *Arg = dyn_cast<Argument>(V);
5544   if (!Arg)
5545     return false;
5546 
5547   MachineFunction &MF = DAG.getMachineFunction();
5548   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5549 
5550   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5551   // we've been asked to pursue.
5552   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5553                               bool Indirect) {
5554     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5555       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5556       // pointing at the VReg, which will be patched up later.
5557       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5558       auto MIB = BuildMI(MF, DL, Inst);
5559       MIB.addReg(Reg);
5560       MIB.addImm(0);
5561       MIB.addMetadata(Variable);
5562       auto *NewDIExpr = FragExpr;
5563       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5564       // the DIExpression.
5565       if (Indirect)
5566         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5567       MIB.addMetadata(NewDIExpr);
5568       return MIB;
5569     } else {
5570       // Create a completely standard DBG_VALUE.
5571       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5572       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5573     }
5574   };
5575 
5576   if (Kind == FuncArgumentDbgValueKind::Value) {
5577     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5578     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5579     // the entry block.
5580     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5581     if (!IsInEntryBlock)
5582       return false;
5583 
5584     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5585     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5586     // variable that also is a param.
5587     //
5588     // Although, if we are at the top of the entry block already, we can still
5589     // emit using ArgDbgValue. This might catch some situations when the
5590     // dbg.value refers to an argument that isn't used in the entry block, so
5591     // any CopyToReg node would be optimized out and the only way to express
5592     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5593     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5594     // we should only emit as ArgDbgValue if the Variable is an argument to the
5595     // current function, and the dbg.value intrinsic is found in the entry
5596     // block.
5597     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5598         !DL->getInlinedAt();
5599     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5600     if (!IsInPrologue && !VariableIsFunctionInputArg)
5601       return false;
5602 
5603     // Here we assume that a function argument on IR level only can be used to
5604     // describe one input parameter on source level. If we for example have
5605     // source code like this
5606     //
5607     //    struct A { long x, y; };
5608     //    void foo(struct A a, long b) {
5609     //      ...
5610     //      b = a.x;
5611     //      ...
5612     //    }
5613     //
5614     // and IR like this
5615     //
5616     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5617     //  entry:
5618     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5619     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5620     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5621     //    ...
5622     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5623     //    ...
5624     //
5625     // then the last dbg.value is describing a parameter "b" using a value that
5626     // is an argument. But since we already has used %a1 to describe a parameter
5627     // we should not handle that last dbg.value here (that would result in an
5628     // incorrect hoisting of the DBG_VALUE to the function entry).
5629     // Notice that we allow one dbg.value per IR level argument, to accommodate
5630     // for the situation with fragments above.
5631     if (VariableIsFunctionInputArg) {
5632       unsigned ArgNo = Arg->getArgNo();
5633       if (ArgNo >= FuncInfo.DescribedArgs.size())
5634         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5635       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5636         return false;
5637       FuncInfo.DescribedArgs.set(ArgNo);
5638     }
5639   }
5640 
5641   bool IsIndirect = false;
5642   std::optional<MachineOperand> Op;
5643   // Some arguments' frame index is recorded during argument lowering.
5644   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5645   if (FI != std::numeric_limits<int>::max())
5646     Op = MachineOperand::CreateFI(FI);
5647 
5648   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5649   if (!Op && N.getNode()) {
5650     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5651     Register Reg;
5652     if (ArgRegsAndSizes.size() == 1)
5653       Reg = ArgRegsAndSizes.front().first;
5654 
5655     if (Reg && Reg.isVirtual()) {
5656       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5657       Register PR = RegInfo.getLiveInPhysReg(Reg);
5658       if (PR)
5659         Reg = PR;
5660     }
5661     if (Reg) {
5662       Op = MachineOperand::CreateReg(Reg, false);
5663       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5664     }
5665   }
5666 
5667   if (!Op && N.getNode()) {
5668     // Check if frame index is available.
5669     SDValue LCandidate = peekThroughBitcasts(N);
5670     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5671       if (FrameIndexSDNode *FINode =
5672           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5673         Op = MachineOperand::CreateFI(FINode->getIndex());
5674   }
5675 
5676   if (!Op) {
5677     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5678     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5679                                          SplitRegs) {
5680       unsigned Offset = 0;
5681       for (const auto &RegAndSize : SplitRegs) {
5682         // If the expression is already a fragment, the current register
5683         // offset+size might extend beyond the fragment. In this case, only
5684         // the register bits that are inside the fragment are relevant.
5685         int RegFragmentSizeInBits = RegAndSize.second;
5686         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5687           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5688           // The register is entirely outside the expression fragment,
5689           // so is irrelevant for debug info.
5690           if (Offset >= ExprFragmentSizeInBits)
5691             break;
5692           // The register is partially outside the expression fragment, only
5693           // the low bits within the fragment are relevant for debug info.
5694           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5695             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5696           }
5697         }
5698 
5699         auto FragmentExpr = DIExpression::createFragmentExpression(
5700             Expr, Offset, RegFragmentSizeInBits);
5701         Offset += RegAndSize.second;
5702         // If a valid fragment expression cannot be created, the variable's
5703         // correct value cannot be determined and so it is set as Undef.
5704         if (!FragmentExpr) {
5705           SDDbgValue *SDV = DAG.getConstantDbgValue(
5706               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5707           DAG.AddDbgValue(SDV, false);
5708           continue;
5709         }
5710         MachineInstr *NewMI =
5711             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5712                              Kind != FuncArgumentDbgValueKind::Value);
5713         FuncInfo.ArgDbgValues.push_back(NewMI);
5714       }
5715     };
5716 
5717     // Check if ValueMap has reg number.
5718     DenseMap<const Value *, Register>::const_iterator
5719       VMI = FuncInfo.ValueMap.find(V);
5720     if (VMI != FuncInfo.ValueMap.end()) {
5721       const auto &TLI = DAG.getTargetLoweringInfo();
5722       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5723                        V->getType(), None);
5724       if (RFV.occupiesMultipleRegs()) {
5725         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5726         return true;
5727       }
5728 
5729       Op = MachineOperand::CreateReg(VMI->second, false);
5730       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5731     } else if (ArgRegsAndSizes.size() > 1) {
5732       // This was split due to the calling convention, and no virtual register
5733       // mapping exists for the value.
5734       splitMultiRegDbgValue(ArgRegsAndSizes);
5735       return true;
5736     }
5737   }
5738 
5739   if (!Op)
5740     return false;
5741 
5742   assert(Variable->isValidLocationForIntrinsic(DL) &&
5743          "Expected inlined-at fields to agree");
5744   MachineInstr *NewMI = nullptr;
5745 
5746   if (Op->isReg())
5747     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5748   else
5749     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5750                     Variable, Expr);
5751 
5752   // Otherwise, use ArgDbgValues.
5753   FuncInfo.ArgDbgValues.push_back(NewMI);
5754   return true;
5755 }
5756 
5757 /// Return the appropriate SDDbgValue based on N.
5758 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5759                                              DILocalVariable *Variable,
5760                                              DIExpression *Expr,
5761                                              const DebugLoc &dl,
5762                                              unsigned DbgSDNodeOrder) {
5763   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5764     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5765     // stack slot locations.
5766     //
5767     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5768     // debug values here after optimization:
5769     //
5770     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5771     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5772     //
5773     // Both describe the direct values of their associated variables.
5774     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5775                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5776   }
5777   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5778                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5779 }
5780 
5781 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5782   switch (Intrinsic) {
5783   case Intrinsic::smul_fix:
5784     return ISD::SMULFIX;
5785   case Intrinsic::umul_fix:
5786     return ISD::UMULFIX;
5787   case Intrinsic::smul_fix_sat:
5788     return ISD::SMULFIXSAT;
5789   case Intrinsic::umul_fix_sat:
5790     return ISD::UMULFIXSAT;
5791   case Intrinsic::sdiv_fix:
5792     return ISD::SDIVFIX;
5793   case Intrinsic::udiv_fix:
5794     return ISD::UDIVFIX;
5795   case Intrinsic::sdiv_fix_sat:
5796     return ISD::SDIVFIXSAT;
5797   case Intrinsic::udiv_fix_sat:
5798     return ISD::UDIVFIXSAT;
5799   default:
5800     llvm_unreachable("Unhandled fixed point intrinsic");
5801   }
5802 }
5803 
5804 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5805                                            const char *FunctionName) {
5806   assert(FunctionName && "FunctionName must not be nullptr");
5807   SDValue Callee = DAG.getExternalSymbol(
5808       FunctionName,
5809       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5810   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5811 }
5812 
5813 /// Given a @llvm.call.preallocated.setup, return the corresponding
5814 /// preallocated call.
5815 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5816   assert(cast<CallBase>(PreallocatedSetup)
5817                  ->getCalledFunction()
5818                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5819          "expected call_preallocated_setup Value");
5820   for (const auto *U : PreallocatedSetup->users()) {
5821     auto *UseCall = cast<CallBase>(U);
5822     const Function *Fn = UseCall->getCalledFunction();
5823     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5824       return UseCall;
5825     }
5826   }
5827   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5828 }
5829 
5830 /// Lower the call to the specified intrinsic function.
5831 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5832                                              unsigned Intrinsic) {
5833   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5834   SDLoc sdl = getCurSDLoc();
5835   DebugLoc dl = getCurDebugLoc();
5836   SDValue Res;
5837 
5838   SDNodeFlags Flags;
5839   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5840     Flags.copyFMF(*FPOp);
5841 
5842   switch (Intrinsic) {
5843   default:
5844     // By default, turn this into a target intrinsic node.
5845     visitTargetIntrinsic(I, Intrinsic);
5846     return;
5847   case Intrinsic::vscale: {
5848     match(&I, m_VScale(DAG.getDataLayout()));
5849     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5850     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5851     return;
5852   }
5853   case Intrinsic::vastart:  visitVAStart(I); return;
5854   case Intrinsic::vaend:    visitVAEnd(I); return;
5855   case Intrinsic::vacopy:   visitVACopy(I); return;
5856   case Intrinsic::returnaddress:
5857     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5858                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5859                              getValue(I.getArgOperand(0))));
5860     return;
5861   case Intrinsic::addressofreturnaddress:
5862     setValue(&I,
5863              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5864                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5865     return;
5866   case Intrinsic::sponentry:
5867     setValue(&I,
5868              DAG.getNode(ISD::SPONENTRY, sdl,
5869                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5870     return;
5871   case Intrinsic::frameaddress:
5872     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5873                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5874                              getValue(I.getArgOperand(0))));
5875     return;
5876   case Intrinsic::read_volatile_register:
5877   case Intrinsic::read_register: {
5878     Value *Reg = I.getArgOperand(0);
5879     SDValue Chain = getRoot();
5880     SDValue RegName =
5881         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5882     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5883     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5884       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5885     setValue(&I, Res);
5886     DAG.setRoot(Res.getValue(1));
5887     return;
5888   }
5889   case Intrinsic::write_register: {
5890     Value *Reg = I.getArgOperand(0);
5891     Value *RegValue = I.getArgOperand(1);
5892     SDValue Chain = getRoot();
5893     SDValue RegName =
5894         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5895     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5896                             RegName, getValue(RegValue)));
5897     return;
5898   }
5899   case Intrinsic::memcpy: {
5900     const auto &MCI = cast<MemCpyInst>(I);
5901     SDValue Op1 = getValue(I.getArgOperand(0));
5902     SDValue Op2 = getValue(I.getArgOperand(1));
5903     SDValue Op3 = getValue(I.getArgOperand(2));
5904     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5905     Align DstAlign = MCI.getDestAlign().valueOrOne();
5906     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5907     Align Alignment = std::min(DstAlign, SrcAlign);
5908     bool isVol = MCI.isVolatile();
5909     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5910     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5911     // node.
5912     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5913     SDValue MC = DAG.getMemcpy(
5914         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5915         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5916         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5917     updateDAGForMaybeTailCall(MC);
5918     return;
5919   }
5920   case Intrinsic::memcpy_inline: {
5921     const auto &MCI = cast<MemCpyInlineInst>(I);
5922     SDValue Dst = getValue(I.getArgOperand(0));
5923     SDValue Src = getValue(I.getArgOperand(1));
5924     SDValue Size = getValue(I.getArgOperand(2));
5925     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5926     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5927     Align DstAlign = MCI.getDestAlign().valueOrOne();
5928     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5929     Align Alignment = std::min(DstAlign, SrcAlign);
5930     bool isVol = MCI.isVolatile();
5931     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5932     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5933     // node.
5934     SDValue MC = DAG.getMemcpy(
5935         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5936         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5937         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5938     updateDAGForMaybeTailCall(MC);
5939     return;
5940   }
5941   case Intrinsic::memset: {
5942     const auto &MSI = cast<MemSetInst>(I);
5943     SDValue Op1 = getValue(I.getArgOperand(0));
5944     SDValue Op2 = getValue(I.getArgOperand(1));
5945     SDValue Op3 = getValue(I.getArgOperand(2));
5946     // @llvm.memset defines 0 and 1 to both mean no alignment.
5947     Align Alignment = MSI.getDestAlign().valueOrOne();
5948     bool isVol = MSI.isVolatile();
5949     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5950     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5951     SDValue MS = DAG.getMemset(
5952         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5953         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5954     updateDAGForMaybeTailCall(MS);
5955     return;
5956   }
5957   case Intrinsic::memset_inline: {
5958     const auto &MSII = cast<MemSetInlineInst>(I);
5959     SDValue Dst = getValue(I.getArgOperand(0));
5960     SDValue Value = getValue(I.getArgOperand(1));
5961     SDValue Size = getValue(I.getArgOperand(2));
5962     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5963     // @llvm.memset defines 0 and 1 to both mean no alignment.
5964     Align DstAlign = MSII.getDestAlign().valueOrOne();
5965     bool isVol = MSII.isVolatile();
5966     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5967     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5968     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5969                                /* AlwaysInline */ true, isTC,
5970                                MachinePointerInfo(I.getArgOperand(0)),
5971                                I.getAAMetadata());
5972     updateDAGForMaybeTailCall(MC);
5973     return;
5974   }
5975   case Intrinsic::memmove: {
5976     const auto &MMI = cast<MemMoveInst>(I);
5977     SDValue Op1 = getValue(I.getArgOperand(0));
5978     SDValue Op2 = getValue(I.getArgOperand(1));
5979     SDValue Op3 = getValue(I.getArgOperand(2));
5980     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5981     Align DstAlign = MMI.getDestAlign().valueOrOne();
5982     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5983     Align Alignment = std::min(DstAlign, SrcAlign);
5984     bool isVol = MMI.isVolatile();
5985     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5986     // FIXME: Support passing different dest/src alignments to the memmove DAG
5987     // node.
5988     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5989     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5990                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5991                                 MachinePointerInfo(I.getArgOperand(1)),
5992                                 I.getAAMetadata(), AA);
5993     updateDAGForMaybeTailCall(MM);
5994     return;
5995   }
5996   case Intrinsic::memcpy_element_unordered_atomic: {
5997     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5998     SDValue Dst = getValue(MI.getRawDest());
5999     SDValue Src = getValue(MI.getRawSource());
6000     SDValue Length = getValue(MI.getLength());
6001 
6002     Type *LengthTy = MI.getLength()->getType();
6003     unsigned ElemSz = MI.getElementSizeInBytes();
6004     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6005     SDValue MC =
6006         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6007                             isTC, MachinePointerInfo(MI.getRawDest()),
6008                             MachinePointerInfo(MI.getRawSource()));
6009     updateDAGForMaybeTailCall(MC);
6010     return;
6011   }
6012   case Intrinsic::memmove_element_unordered_atomic: {
6013     auto &MI = cast<AtomicMemMoveInst>(I);
6014     SDValue Dst = getValue(MI.getRawDest());
6015     SDValue Src = getValue(MI.getRawSource());
6016     SDValue Length = getValue(MI.getLength());
6017 
6018     Type *LengthTy = MI.getLength()->getType();
6019     unsigned ElemSz = MI.getElementSizeInBytes();
6020     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6021     SDValue MC =
6022         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6023                              isTC, MachinePointerInfo(MI.getRawDest()),
6024                              MachinePointerInfo(MI.getRawSource()));
6025     updateDAGForMaybeTailCall(MC);
6026     return;
6027   }
6028   case Intrinsic::memset_element_unordered_atomic: {
6029     auto &MI = cast<AtomicMemSetInst>(I);
6030     SDValue Dst = getValue(MI.getRawDest());
6031     SDValue Val = getValue(MI.getValue());
6032     SDValue Length = getValue(MI.getLength());
6033 
6034     Type *LengthTy = MI.getLength()->getType();
6035     unsigned ElemSz = MI.getElementSizeInBytes();
6036     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6037     SDValue MC =
6038         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6039                             isTC, MachinePointerInfo(MI.getRawDest()));
6040     updateDAGForMaybeTailCall(MC);
6041     return;
6042   }
6043   case Intrinsic::call_preallocated_setup: {
6044     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6045     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6046     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6047                               getRoot(), SrcValue);
6048     setValue(&I, Res);
6049     DAG.setRoot(Res);
6050     return;
6051   }
6052   case Intrinsic::call_preallocated_arg: {
6053     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6054     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6055     SDValue Ops[3];
6056     Ops[0] = getRoot();
6057     Ops[1] = SrcValue;
6058     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6059                                    MVT::i32); // arg index
6060     SDValue Res = DAG.getNode(
6061         ISD::PREALLOCATED_ARG, sdl,
6062         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6063     setValue(&I, Res);
6064     DAG.setRoot(Res.getValue(1));
6065     return;
6066   }
6067   case Intrinsic::dbg_addr:
6068   case Intrinsic::dbg_declare: {
6069     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6070     // they are non-variadic.
6071     const auto &DI = cast<DbgVariableIntrinsic>(I);
6072     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6073     DILocalVariable *Variable = DI.getVariable();
6074     DIExpression *Expression = DI.getExpression();
6075     dropDanglingDebugInfo(Variable, Expression);
6076     assert(Variable && "Missing variable");
6077     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6078                       << "\n");
6079     // Check if address has undef value.
6080     const Value *Address = DI.getVariableLocationOp(0);
6081     if (!Address || isa<UndefValue>(Address) ||
6082         (Address->use_empty() && !isa<Argument>(Address))) {
6083       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6084                         << " (bad/undef/unused-arg address)\n");
6085       return;
6086     }
6087 
6088     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6089 
6090     // Check if this variable can be described by a frame index, typically
6091     // either as a static alloca or a byval parameter.
6092     int FI = std::numeric_limits<int>::max();
6093     if (const auto *AI =
6094             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6095       if (AI->isStaticAlloca()) {
6096         auto I = FuncInfo.StaticAllocaMap.find(AI);
6097         if (I != FuncInfo.StaticAllocaMap.end())
6098           FI = I->second;
6099       }
6100     } else if (const auto *Arg = dyn_cast<Argument>(
6101                    Address->stripInBoundsConstantOffsets())) {
6102       FI = FuncInfo.getArgumentFrameIndex(Arg);
6103     }
6104 
6105     // llvm.dbg.addr is control dependent and always generates indirect
6106     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6107     // the MachineFunction variable table.
6108     if (FI != std::numeric_limits<int>::max()) {
6109       if (Intrinsic == Intrinsic::dbg_addr) {
6110         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6111             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6112             dl, SDNodeOrder);
6113         DAG.AddDbgValue(SDV, isParameter);
6114       } else {
6115         LLVM_DEBUG(dbgs() << "Skipping " << DI
6116                           << " (variable info stashed in MF side table)\n");
6117       }
6118       return;
6119     }
6120 
6121     SDValue &N = NodeMap[Address];
6122     if (!N.getNode() && isa<Argument>(Address))
6123       // Check unused arguments map.
6124       N = UnusedArgNodeMap[Address];
6125     SDDbgValue *SDV;
6126     if (N.getNode()) {
6127       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6128         Address = BCI->getOperand(0);
6129       // Parameters are handled specially.
6130       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6131       if (isParameter && FINode) {
6132         // Byval parameter. We have a frame index at this point.
6133         SDV =
6134             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6135                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6136       } else if (isa<Argument>(Address)) {
6137         // Address is an argument, so try to emit its dbg value using
6138         // virtual register info from the FuncInfo.ValueMap.
6139         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6140                                  FuncArgumentDbgValueKind::Declare, N);
6141         return;
6142       } else {
6143         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6144                               true, dl, SDNodeOrder);
6145       }
6146       DAG.AddDbgValue(SDV, isParameter);
6147     } else {
6148       // If Address is an argument then try to emit its dbg value using
6149       // virtual register info from the FuncInfo.ValueMap.
6150       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6151                                     FuncArgumentDbgValueKind::Declare, N)) {
6152         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6153                           << " (could not emit func-arg dbg_value)\n");
6154       }
6155     }
6156     return;
6157   }
6158   case Intrinsic::dbg_label: {
6159     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6160     DILabel *Label = DI.getLabel();
6161     assert(Label && "Missing label");
6162 
6163     SDDbgLabel *SDV;
6164     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6165     DAG.AddDbgLabel(SDV);
6166     return;
6167   }
6168   case Intrinsic::dbg_value: {
6169     const DbgValueInst &DI = cast<DbgValueInst>(I);
6170     assert(DI.getVariable() && "Missing variable");
6171 
6172     DILocalVariable *Variable = DI.getVariable();
6173     DIExpression *Expression = DI.getExpression();
6174     dropDanglingDebugInfo(Variable, Expression);
6175     SmallVector<Value *, 4> Values(DI.getValues());
6176     if (Values.empty())
6177       return;
6178 
6179     if (llvm::is_contained(Values, nullptr))
6180       return;
6181 
6182     bool IsVariadic = DI.hasArgList();
6183     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6184                           SDNodeOrder, IsVariadic))
6185       addDanglingDebugInfo(&DI, SDNodeOrder);
6186     return;
6187   }
6188 
6189   case Intrinsic::eh_typeid_for: {
6190     // Find the type id for the given typeinfo.
6191     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6192     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6193     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6194     setValue(&I, Res);
6195     return;
6196   }
6197 
6198   case Intrinsic::eh_return_i32:
6199   case Intrinsic::eh_return_i64:
6200     DAG.getMachineFunction().setCallsEHReturn(true);
6201     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6202                             MVT::Other,
6203                             getControlRoot(),
6204                             getValue(I.getArgOperand(0)),
6205                             getValue(I.getArgOperand(1))));
6206     return;
6207   case Intrinsic::eh_unwind_init:
6208     DAG.getMachineFunction().setCallsUnwindInit(true);
6209     return;
6210   case Intrinsic::eh_dwarf_cfa:
6211     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6212                              TLI.getPointerTy(DAG.getDataLayout()),
6213                              getValue(I.getArgOperand(0))));
6214     return;
6215   case Intrinsic::eh_sjlj_callsite: {
6216     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6217     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6218     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6219 
6220     MMI.setCurrentCallSite(CI->getZExtValue());
6221     return;
6222   }
6223   case Intrinsic::eh_sjlj_functioncontext: {
6224     // Get and store the index of the function context.
6225     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6226     AllocaInst *FnCtx =
6227       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6228     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6229     MFI.setFunctionContextIndex(FI);
6230     return;
6231   }
6232   case Intrinsic::eh_sjlj_setjmp: {
6233     SDValue Ops[2];
6234     Ops[0] = getRoot();
6235     Ops[1] = getValue(I.getArgOperand(0));
6236     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6237                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6238     setValue(&I, Op.getValue(0));
6239     DAG.setRoot(Op.getValue(1));
6240     return;
6241   }
6242   case Intrinsic::eh_sjlj_longjmp:
6243     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6244                             getRoot(), getValue(I.getArgOperand(0))));
6245     return;
6246   case Intrinsic::eh_sjlj_setup_dispatch:
6247     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6248                             getRoot()));
6249     return;
6250   case Intrinsic::masked_gather:
6251     visitMaskedGather(I);
6252     return;
6253   case Intrinsic::masked_load:
6254     visitMaskedLoad(I);
6255     return;
6256   case Intrinsic::masked_scatter:
6257     visitMaskedScatter(I);
6258     return;
6259   case Intrinsic::masked_store:
6260     visitMaskedStore(I);
6261     return;
6262   case Intrinsic::masked_expandload:
6263     visitMaskedLoad(I, true /* IsExpanding */);
6264     return;
6265   case Intrinsic::masked_compressstore:
6266     visitMaskedStore(I, true /* IsCompressing */);
6267     return;
6268   case Intrinsic::powi:
6269     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6270                             getValue(I.getArgOperand(1)), DAG));
6271     return;
6272   case Intrinsic::log:
6273     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6274     return;
6275   case Intrinsic::log2:
6276     setValue(&I,
6277              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6278     return;
6279   case Intrinsic::log10:
6280     setValue(&I,
6281              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6282     return;
6283   case Intrinsic::exp:
6284     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6285     return;
6286   case Intrinsic::exp2:
6287     setValue(&I,
6288              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6289     return;
6290   case Intrinsic::pow:
6291     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6292                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6293     return;
6294   case Intrinsic::sqrt:
6295   case Intrinsic::fabs:
6296   case Intrinsic::sin:
6297   case Intrinsic::cos:
6298   case Intrinsic::floor:
6299   case Intrinsic::ceil:
6300   case Intrinsic::trunc:
6301   case Intrinsic::rint:
6302   case Intrinsic::nearbyint:
6303   case Intrinsic::round:
6304   case Intrinsic::roundeven:
6305   case Intrinsic::canonicalize: {
6306     unsigned Opcode;
6307     switch (Intrinsic) {
6308     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6309     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6310     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6311     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6312     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6313     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6314     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6315     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6316     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6317     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6318     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6319     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6320     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6321     }
6322 
6323     setValue(&I, DAG.getNode(Opcode, sdl,
6324                              getValue(I.getArgOperand(0)).getValueType(),
6325                              getValue(I.getArgOperand(0)), Flags));
6326     return;
6327   }
6328   case Intrinsic::lround:
6329   case Intrinsic::llround:
6330   case Intrinsic::lrint:
6331   case Intrinsic::llrint: {
6332     unsigned Opcode;
6333     switch (Intrinsic) {
6334     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6335     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6336     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6337     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6338     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6339     }
6340 
6341     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6342     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6343                              getValue(I.getArgOperand(0))));
6344     return;
6345   }
6346   case Intrinsic::minnum:
6347     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6348                              getValue(I.getArgOperand(0)).getValueType(),
6349                              getValue(I.getArgOperand(0)),
6350                              getValue(I.getArgOperand(1)), Flags));
6351     return;
6352   case Intrinsic::maxnum:
6353     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6354                              getValue(I.getArgOperand(0)).getValueType(),
6355                              getValue(I.getArgOperand(0)),
6356                              getValue(I.getArgOperand(1)), Flags));
6357     return;
6358   case Intrinsic::minimum:
6359     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6360                              getValue(I.getArgOperand(0)).getValueType(),
6361                              getValue(I.getArgOperand(0)),
6362                              getValue(I.getArgOperand(1)), Flags));
6363     return;
6364   case Intrinsic::maximum:
6365     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6366                              getValue(I.getArgOperand(0)).getValueType(),
6367                              getValue(I.getArgOperand(0)),
6368                              getValue(I.getArgOperand(1)), Flags));
6369     return;
6370   case Intrinsic::copysign:
6371     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6372                              getValue(I.getArgOperand(0)).getValueType(),
6373                              getValue(I.getArgOperand(0)),
6374                              getValue(I.getArgOperand(1)), Flags));
6375     return;
6376   case Intrinsic::arithmetic_fence: {
6377     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6378                              getValue(I.getArgOperand(0)).getValueType(),
6379                              getValue(I.getArgOperand(0)), Flags));
6380     return;
6381   }
6382   case Intrinsic::fma:
6383     setValue(&I, DAG.getNode(
6384                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6385                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6386                      getValue(I.getArgOperand(2)), Flags));
6387     return;
6388 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6389   case Intrinsic::INTRINSIC:
6390 #include "llvm/IR/ConstrainedOps.def"
6391     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6392     return;
6393 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6394 #include "llvm/IR/VPIntrinsics.def"
6395     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6396     return;
6397   case Intrinsic::fptrunc_round: {
6398     // Get the last argument, the metadata and convert it to an integer in the
6399     // call
6400     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6401     Optional<RoundingMode> RoundMode =
6402         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6403 
6404     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6405 
6406     // Propagate fast-math-flags from IR to node(s).
6407     SDNodeFlags Flags;
6408     Flags.copyFMF(*cast<FPMathOperator>(&I));
6409     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6410 
6411     SDValue Result;
6412     Result = DAG.getNode(
6413         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6414         DAG.getTargetConstant((int)*RoundMode, sdl,
6415                               TLI.getPointerTy(DAG.getDataLayout())));
6416     setValue(&I, Result);
6417 
6418     return;
6419   }
6420   case Intrinsic::fmuladd: {
6421     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6422     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6423         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6424       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6425                                getValue(I.getArgOperand(0)).getValueType(),
6426                                getValue(I.getArgOperand(0)),
6427                                getValue(I.getArgOperand(1)),
6428                                getValue(I.getArgOperand(2)), Flags));
6429     } else {
6430       // TODO: Intrinsic calls should have fast-math-flags.
6431       SDValue Mul = DAG.getNode(
6432           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6433           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6434       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6435                                 getValue(I.getArgOperand(0)).getValueType(),
6436                                 Mul, getValue(I.getArgOperand(2)), Flags);
6437       setValue(&I, Add);
6438     }
6439     return;
6440   }
6441   case Intrinsic::convert_to_fp16:
6442     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6443                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6444                                          getValue(I.getArgOperand(0)),
6445                                          DAG.getTargetConstant(0, sdl,
6446                                                                MVT::i32))));
6447     return;
6448   case Intrinsic::convert_from_fp16:
6449     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6450                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6451                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6452                                          getValue(I.getArgOperand(0)))));
6453     return;
6454   case Intrinsic::fptosi_sat: {
6455     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6456     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6457                              getValue(I.getArgOperand(0)),
6458                              DAG.getValueType(VT.getScalarType())));
6459     return;
6460   }
6461   case Intrinsic::fptoui_sat: {
6462     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6463     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6464                              getValue(I.getArgOperand(0)),
6465                              DAG.getValueType(VT.getScalarType())));
6466     return;
6467   }
6468   case Intrinsic::set_rounding:
6469     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6470                       {getRoot(), getValue(I.getArgOperand(0))});
6471     setValue(&I, Res);
6472     DAG.setRoot(Res.getValue(0));
6473     return;
6474   case Intrinsic::is_fpclass: {
6475     const DataLayout DLayout = DAG.getDataLayout();
6476     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6477     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6478     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6479     MachineFunction &MF = DAG.getMachineFunction();
6480     const Function &F = MF.getFunction();
6481     SDValue Op = getValue(I.getArgOperand(0));
6482     SDNodeFlags Flags;
6483     Flags.setNoFPExcept(
6484         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6485     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6486     // expansion can use illegal types. Making expansion early allows
6487     // legalizing these types prior to selection.
6488     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6489       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6490       setValue(&I, Result);
6491       return;
6492     }
6493 
6494     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6495     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6496     setValue(&I, V);
6497     return;
6498   }
6499   case Intrinsic::pcmarker: {
6500     SDValue Tmp = getValue(I.getArgOperand(0));
6501     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6502     return;
6503   }
6504   case Intrinsic::readcyclecounter: {
6505     SDValue Op = getRoot();
6506     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6507                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6508     setValue(&I, Res);
6509     DAG.setRoot(Res.getValue(1));
6510     return;
6511   }
6512   case Intrinsic::bitreverse:
6513     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6514                              getValue(I.getArgOperand(0)).getValueType(),
6515                              getValue(I.getArgOperand(0))));
6516     return;
6517   case Intrinsic::bswap:
6518     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6519                              getValue(I.getArgOperand(0)).getValueType(),
6520                              getValue(I.getArgOperand(0))));
6521     return;
6522   case Intrinsic::cttz: {
6523     SDValue Arg = getValue(I.getArgOperand(0));
6524     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6525     EVT Ty = Arg.getValueType();
6526     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6527                              sdl, Ty, Arg));
6528     return;
6529   }
6530   case Intrinsic::ctlz: {
6531     SDValue Arg = getValue(I.getArgOperand(0));
6532     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6533     EVT Ty = Arg.getValueType();
6534     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6535                              sdl, Ty, Arg));
6536     return;
6537   }
6538   case Intrinsic::ctpop: {
6539     SDValue Arg = getValue(I.getArgOperand(0));
6540     EVT Ty = Arg.getValueType();
6541     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6542     return;
6543   }
6544   case Intrinsic::fshl:
6545   case Intrinsic::fshr: {
6546     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6547     SDValue X = getValue(I.getArgOperand(0));
6548     SDValue Y = getValue(I.getArgOperand(1));
6549     SDValue Z = getValue(I.getArgOperand(2));
6550     EVT VT = X.getValueType();
6551 
6552     if (X == Y) {
6553       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6554       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6555     } else {
6556       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6557       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6558     }
6559     return;
6560   }
6561   case Intrinsic::sadd_sat: {
6562     SDValue Op1 = getValue(I.getArgOperand(0));
6563     SDValue Op2 = getValue(I.getArgOperand(1));
6564     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6565     return;
6566   }
6567   case Intrinsic::uadd_sat: {
6568     SDValue Op1 = getValue(I.getArgOperand(0));
6569     SDValue Op2 = getValue(I.getArgOperand(1));
6570     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6571     return;
6572   }
6573   case Intrinsic::ssub_sat: {
6574     SDValue Op1 = getValue(I.getArgOperand(0));
6575     SDValue Op2 = getValue(I.getArgOperand(1));
6576     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6577     return;
6578   }
6579   case Intrinsic::usub_sat: {
6580     SDValue Op1 = getValue(I.getArgOperand(0));
6581     SDValue Op2 = getValue(I.getArgOperand(1));
6582     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6583     return;
6584   }
6585   case Intrinsic::sshl_sat: {
6586     SDValue Op1 = getValue(I.getArgOperand(0));
6587     SDValue Op2 = getValue(I.getArgOperand(1));
6588     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6589     return;
6590   }
6591   case Intrinsic::ushl_sat: {
6592     SDValue Op1 = getValue(I.getArgOperand(0));
6593     SDValue Op2 = getValue(I.getArgOperand(1));
6594     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6595     return;
6596   }
6597   case Intrinsic::smul_fix:
6598   case Intrinsic::umul_fix:
6599   case Intrinsic::smul_fix_sat:
6600   case Intrinsic::umul_fix_sat: {
6601     SDValue Op1 = getValue(I.getArgOperand(0));
6602     SDValue Op2 = getValue(I.getArgOperand(1));
6603     SDValue Op3 = getValue(I.getArgOperand(2));
6604     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6605                              Op1.getValueType(), Op1, Op2, Op3));
6606     return;
6607   }
6608   case Intrinsic::sdiv_fix:
6609   case Intrinsic::udiv_fix:
6610   case Intrinsic::sdiv_fix_sat:
6611   case Intrinsic::udiv_fix_sat: {
6612     SDValue Op1 = getValue(I.getArgOperand(0));
6613     SDValue Op2 = getValue(I.getArgOperand(1));
6614     SDValue Op3 = getValue(I.getArgOperand(2));
6615     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6616                               Op1, Op2, Op3, DAG, TLI));
6617     return;
6618   }
6619   case Intrinsic::smax: {
6620     SDValue Op1 = getValue(I.getArgOperand(0));
6621     SDValue Op2 = getValue(I.getArgOperand(1));
6622     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6623     return;
6624   }
6625   case Intrinsic::smin: {
6626     SDValue Op1 = getValue(I.getArgOperand(0));
6627     SDValue Op2 = getValue(I.getArgOperand(1));
6628     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6629     return;
6630   }
6631   case Intrinsic::umax: {
6632     SDValue Op1 = getValue(I.getArgOperand(0));
6633     SDValue Op2 = getValue(I.getArgOperand(1));
6634     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6635     return;
6636   }
6637   case Intrinsic::umin: {
6638     SDValue Op1 = getValue(I.getArgOperand(0));
6639     SDValue Op2 = getValue(I.getArgOperand(1));
6640     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6641     return;
6642   }
6643   case Intrinsic::abs: {
6644     // TODO: Preserve "int min is poison" arg in SDAG?
6645     SDValue Op1 = getValue(I.getArgOperand(0));
6646     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6647     return;
6648   }
6649   case Intrinsic::stacksave: {
6650     SDValue Op = getRoot();
6651     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6652     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6653     setValue(&I, Res);
6654     DAG.setRoot(Res.getValue(1));
6655     return;
6656   }
6657   case Intrinsic::stackrestore:
6658     Res = getValue(I.getArgOperand(0));
6659     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6660     return;
6661   case Intrinsic::get_dynamic_area_offset: {
6662     SDValue Op = getRoot();
6663     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6664     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6665     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6666     // target.
6667     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6668       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6669                          " intrinsic!");
6670     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6671                       Op);
6672     DAG.setRoot(Op);
6673     setValue(&I, Res);
6674     return;
6675   }
6676   case Intrinsic::stackguard: {
6677     MachineFunction &MF = DAG.getMachineFunction();
6678     const Module &M = *MF.getFunction().getParent();
6679     SDValue Chain = getRoot();
6680     if (TLI.useLoadStackGuardNode()) {
6681       Res = getLoadStackGuard(DAG, sdl, Chain);
6682     } else {
6683       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6684       const Value *Global = TLI.getSDagStackGuard(M);
6685       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6686       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6687                         MachinePointerInfo(Global, 0), Align,
6688                         MachineMemOperand::MOVolatile);
6689     }
6690     if (TLI.useStackGuardXorFP())
6691       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6692     DAG.setRoot(Chain);
6693     setValue(&I, Res);
6694     return;
6695   }
6696   case Intrinsic::stackprotector: {
6697     // Emit code into the DAG to store the stack guard onto the stack.
6698     MachineFunction &MF = DAG.getMachineFunction();
6699     MachineFrameInfo &MFI = MF.getFrameInfo();
6700     SDValue Src, Chain = getRoot();
6701 
6702     if (TLI.useLoadStackGuardNode())
6703       Src = getLoadStackGuard(DAG, sdl, Chain);
6704     else
6705       Src = getValue(I.getArgOperand(0));   // The guard's value.
6706 
6707     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6708 
6709     int FI = FuncInfo.StaticAllocaMap[Slot];
6710     MFI.setStackProtectorIndex(FI);
6711     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6712 
6713     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6714 
6715     // Store the stack protector onto the stack.
6716     Res = DAG.getStore(
6717         Chain, sdl, Src, FIN,
6718         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6719         MaybeAlign(), MachineMemOperand::MOVolatile);
6720     setValue(&I, Res);
6721     DAG.setRoot(Res);
6722     return;
6723   }
6724   case Intrinsic::objectsize:
6725     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6726 
6727   case Intrinsic::is_constant:
6728     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6729 
6730   case Intrinsic::annotation:
6731   case Intrinsic::ptr_annotation:
6732   case Intrinsic::launder_invariant_group:
6733   case Intrinsic::strip_invariant_group:
6734     // Drop the intrinsic, but forward the value
6735     setValue(&I, getValue(I.getOperand(0)));
6736     return;
6737 
6738   case Intrinsic::assume:
6739   case Intrinsic::experimental_noalias_scope_decl:
6740   case Intrinsic::var_annotation:
6741   case Intrinsic::sideeffect:
6742     // Discard annotate attributes, noalias scope declarations, assumptions, and
6743     // artificial side-effects.
6744     return;
6745 
6746   case Intrinsic::codeview_annotation: {
6747     // Emit a label associated with this metadata.
6748     MachineFunction &MF = DAG.getMachineFunction();
6749     MCSymbol *Label =
6750         MF.getMMI().getContext().createTempSymbol("annotation", true);
6751     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6752     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6753     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6754     DAG.setRoot(Res);
6755     return;
6756   }
6757 
6758   case Intrinsic::init_trampoline: {
6759     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6760 
6761     SDValue Ops[6];
6762     Ops[0] = getRoot();
6763     Ops[1] = getValue(I.getArgOperand(0));
6764     Ops[2] = getValue(I.getArgOperand(1));
6765     Ops[3] = getValue(I.getArgOperand(2));
6766     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6767     Ops[5] = DAG.getSrcValue(F);
6768 
6769     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6770 
6771     DAG.setRoot(Res);
6772     return;
6773   }
6774   case Intrinsic::adjust_trampoline:
6775     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6776                              TLI.getPointerTy(DAG.getDataLayout()),
6777                              getValue(I.getArgOperand(0))));
6778     return;
6779   case Intrinsic::gcroot: {
6780     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6781            "only valid in functions with gc specified, enforced by Verifier");
6782     assert(GFI && "implied by previous");
6783     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6784     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6785 
6786     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6787     GFI->addStackRoot(FI->getIndex(), TypeMap);
6788     return;
6789   }
6790   case Intrinsic::gcread:
6791   case Intrinsic::gcwrite:
6792     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6793   case Intrinsic::flt_rounds:
6794     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6795     setValue(&I, Res);
6796     DAG.setRoot(Res.getValue(1));
6797     return;
6798 
6799   case Intrinsic::expect:
6800     // Just replace __builtin_expect(exp, c) with EXP.
6801     setValue(&I, getValue(I.getArgOperand(0)));
6802     return;
6803 
6804   case Intrinsic::ubsantrap:
6805   case Intrinsic::debugtrap:
6806   case Intrinsic::trap: {
6807     StringRef TrapFuncName =
6808         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6809     if (TrapFuncName.empty()) {
6810       switch (Intrinsic) {
6811       case Intrinsic::trap:
6812         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6813         break;
6814       case Intrinsic::debugtrap:
6815         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6816         break;
6817       case Intrinsic::ubsantrap:
6818         DAG.setRoot(DAG.getNode(
6819             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6820             DAG.getTargetConstant(
6821                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6822                 MVT::i32)));
6823         break;
6824       default: llvm_unreachable("unknown trap intrinsic");
6825       }
6826       return;
6827     }
6828     TargetLowering::ArgListTy Args;
6829     if (Intrinsic == Intrinsic::ubsantrap) {
6830       Args.push_back(TargetLoweringBase::ArgListEntry());
6831       Args[0].Val = I.getArgOperand(0);
6832       Args[0].Node = getValue(Args[0].Val);
6833       Args[0].Ty = Args[0].Val->getType();
6834     }
6835 
6836     TargetLowering::CallLoweringInfo CLI(DAG);
6837     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6838         CallingConv::C, I.getType(),
6839         DAG.getExternalSymbol(TrapFuncName.data(),
6840                               TLI.getPointerTy(DAG.getDataLayout())),
6841         std::move(Args));
6842 
6843     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6844     DAG.setRoot(Result.second);
6845     return;
6846   }
6847 
6848   case Intrinsic::uadd_with_overflow:
6849   case Intrinsic::sadd_with_overflow:
6850   case Intrinsic::usub_with_overflow:
6851   case Intrinsic::ssub_with_overflow:
6852   case Intrinsic::umul_with_overflow:
6853   case Intrinsic::smul_with_overflow: {
6854     ISD::NodeType Op;
6855     switch (Intrinsic) {
6856     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6857     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6858     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6859     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6860     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6861     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6862     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6863     }
6864     SDValue Op1 = getValue(I.getArgOperand(0));
6865     SDValue Op2 = getValue(I.getArgOperand(1));
6866 
6867     EVT ResultVT = Op1.getValueType();
6868     EVT OverflowVT = MVT::i1;
6869     if (ResultVT.isVector())
6870       OverflowVT = EVT::getVectorVT(
6871           *Context, OverflowVT, ResultVT.getVectorElementCount());
6872 
6873     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6874     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6875     return;
6876   }
6877   case Intrinsic::prefetch: {
6878     SDValue Ops[5];
6879     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6880     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6881     Ops[0] = DAG.getRoot();
6882     Ops[1] = getValue(I.getArgOperand(0));
6883     Ops[2] = getValue(I.getArgOperand(1));
6884     Ops[3] = getValue(I.getArgOperand(2));
6885     Ops[4] = getValue(I.getArgOperand(3));
6886     SDValue Result = DAG.getMemIntrinsicNode(
6887         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6888         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6889         /* align */ None, Flags);
6890 
6891     // Chain the prefetch in parallell with any pending loads, to stay out of
6892     // the way of later optimizations.
6893     PendingLoads.push_back(Result);
6894     Result = getRoot();
6895     DAG.setRoot(Result);
6896     return;
6897   }
6898   case Intrinsic::lifetime_start:
6899   case Intrinsic::lifetime_end: {
6900     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6901     // Stack coloring is not enabled in O0, discard region information.
6902     if (TM.getOptLevel() == CodeGenOpt::None)
6903       return;
6904 
6905     const int64_t ObjectSize =
6906         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6907     Value *const ObjectPtr = I.getArgOperand(1);
6908     SmallVector<const Value *, 4> Allocas;
6909     getUnderlyingObjects(ObjectPtr, Allocas);
6910 
6911     for (const Value *Alloca : Allocas) {
6912       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6913 
6914       // Could not find an Alloca.
6915       if (!LifetimeObject)
6916         continue;
6917 
6918       // First check that the Alloca is static, otherwise it won't have a
6919       // valid frame index.
6920       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6921       if (SI == FuncInfo.StaticAllocaMap.end())
6922         return;
6923 
6924       const int FrameIndex = SI->second;
6925       int64_t Offset;
6926       if (GetPointerBaseWithConstantOffset(
6927               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6928         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6929       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6930                                 Offset);
6931       DAG.setRoot(Res);
6932     }
6933     return;
6934   }
6935   case Intrinsic::pseudoprobe: {
6936     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6937     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6938     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6939     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6940     DAG.setRoot(Res);
6941     return;
6942   }
6943   case Intrinsic::invariant_start:
6944     // Discard region information.
6945     setValue(&I,
6946              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6947     return;
6948   case Intrinsic::invariant_end:
6949     // Discard region information.
6950     return;
6951   case Intrinsic::clear_cache:
6952     /// FunctionName may be null.
6953     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6954       lowerCallToExternalSymbol(I, FunctionName);
6955     return;
6956   case Intrinsic::donothing:
6957   case Intrinsic::seh_try_begin:
6958   case Intrinsic::seh_scope_begin:
6959   case Intrinsic::seh_try_end:
6960   case Intrinsic::seh_scope_end:
6961     // ignore
6962     return;
6963   case Intrinsic::experimental_stackmap:
6964     visitStackmap(I);
6965     return;
6966   case Intrinsic::experimental_patchpoint_void:
6967   case Intrinsic::experimental_patchpoint_i64:
6968     visitPatchpoint(I);
6969     return;
6970   case Intrinsic::experimental_gc_statepoint:
6971     LowerStatepoint(cast<GCStatepointInst>(I));
6972     return;
6973   case Intrinsic::experimental_gc_result:
6974     visitGCResult(cast<GCResultInst>(I));
6975     return;
6976   case Intrinsic::experimental_gc_relocate:
6977     visitGCRelocate(cast<GCRelocateInst>(I));
6978     return;
6979   case Intrinsic::instrprof_cover:
6980     llvm_unreachable("instrprof failed to lower a cover");
6981   case Intrinsic::instrprof_increment:
6982     llvm_unreachable("instrprof failed to lower an increment");
6983   case Intrinsic::instrprof_value_profile:
6984     llvm_unreachable("instrprof failed to lower a value profiling call");
6985   case Intrinsic::localescape: {
6986     MachineFunction &MF = DAG.getMachineFunction();
6987     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6988 
6989     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6990     // is the same on all targets.
6991     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6992       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6993       if (isa<ConstantPointerNull>(Arg))
6994         continue; // Skip null pointers. They represent a hole in index space.
6995       AllocaInst *Slot = cast<AllocaInst>(Arg);
6996       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6997              "can only escape static allocas");
6998       int FI = FuncInfo.StaticAllocaMap[Slot];
6999       MCSymbol *FrameAllocSym =
7000           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7001               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7002       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7003               TII->get(TargetOpcode::LOCAL_ESCAPE))
7004           .addSym(FrameAllocSym)
7005           .addFrameIndex(FI);
7006     }
7007 
7008     return;
7009   }
7010 
7011   case Intrinsic::localrecover: {
7012     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7013     MachineFunction &MF = DAG.getMachineFunction();
7014 
7015     // Get the symbol that defines the frame offset.
7016     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7017     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7018     unsigned IdxVal =
7019         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7020     MCSymbol *FrameAllocSym =
7021         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7022             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7023 
7024     Value *FP = I.getArgOperand(1);
7025     SDValue FPVal = getValue(FP);
7026     EVT PtrVT = FPVal.getValueType();
7027 
7028     // Create a MCSymbol for the label to avoid any target lowering
7029     // that would make this PC relative.
7030     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7031     SDValue OffsetVal =
7032         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7033 
7034     // Add the offset to the FP.
7035     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7036     setValue(&I, Add);
7037 
7038     return;
7039   }
7040 
7041   case Intrinsic::eh_exceptionpointer:
7042   case Intrinsic::eh_exceptioncode: {
7043     // Get the exception pointer vreg, copy from it, and resize it to fit.
7044     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7045     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7046     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7047     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7048     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7049     if (Intrinsic == Intrinsic::eh_exceptioncode)
7050       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7051     setValue(&I, N);
7052     return;
7053   }
7054   case Intrinsic::xray_customevent: {
7055     // Here we want to make sure that the intrinsic behaves as if it has a
7056     // specific calling convention, and only for x86_64.
7057     // FIXME: Support other platforms later.
7058     const auto &Triple = DAG.getTarget().getTargetTriple();
7059     if (Triple.getArch() != Triple::x86_64)
7060       return;
7061 
7062     SmallVector<SDValue, 8> Ops;
7063 
7064     // We want to say that we always want the arguments in registers.
7065     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7066     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7067     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7068     SDValue Chain = getRoot();
7069     Ops.push_back(LogEntryVal);
7070     Ops.push_back(StrSizeVal);
7071     Ops.push_back(Chain);
7072 
7073     // We need to enforce the calling convention for the callsite, so that
7074     // argument ordering is enforced correctly, and that register allocation can
7075     // see that some registers may be assumed clobbered and have to preserve
7076     // them across calls to the intrinsic.
7077     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7078                                            sdl, NodeTys, Ops);
7079     SDValue patchableNode = SDValue(MN, 0);
7080     DAG.setRoot(patchableNode);
7081     setValue(&I, patchableNode);
7082     return;
7083   }
7084   case Intrinsic::xray_typedevent: {
7085     // Here we want to make sure that the intrinsic behaves as if it has a
7086     // specific calling convention, and only for x86_64.
7087     // FIXME: Support other platforms later.
7088     const auto &Triple = DAG.getTarget().getTargetTriple();
7089     if (Triple.getArch() != Triple::x86_64)
7090       return;
7091 
7092     SmallVector<SDValue, 8> Ops;
7093 
7094     // We want to say that we always want the arguments in registers.
7095     // It's unclear to me how manipulating the selection DAG here forces callers
7096     // to provide arguments in registers instead of on the stack.
7097     SDValue LogTypeId = getValue(I.getArgOperand(0));
7098     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7099     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7100     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7101     SDValue Chain = getRoot();
7102     Ops.push_back(LogTypeId);
7103     Ops.push_back(LogEntryVal);
7104     Ops.push_back(StrSizeVal);
7105     Ops.push_back(Chain);
7106 
7107     // We need to enforce the calling convention for the callsite, so that
7108     // argument ordering is enforced correctly, and that register allocation can
7109     // see that some registers may be assumed clobbered and have to preserve
7110     // them across calls to the intrinsic.
7111     MachineSDNode *MN = DAG.getMachineNode(
7112         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7113     SDValue patchableNode = SDValue(MN, 0);
7114     DAG.setRoot(patchableNode);
7115     setValue(&I, patchableNode);
7116     return;
7117   }
7118   case Intrinsic::experimental_deoptimize:
7119     LowerDeoptimizeCall(&I);
7120     return;
7121   case Intrinsic::experimental_stepvector:
7122     visitStepVector(I);
7123     return;
7124   case Intrinsic::vector_reduce_fadd:
7125   case Intrinsic::vector_reduce_fmul:
7126   case Intrinsic::vector_reduce_add:
7127   case Intrinsic::vector_reduce_mul:
7128   case Intrinsic::vector_reduce_and:
7129   case Intrinsic::vector_reduce_or:
7130   case Intrinsic::vector_reduce_xor:
7131   case Intrinsic::vector_reduce_smax:
7132   case Intrinsic::vector_reduce_smin:
7133   case Intrinsic::vector_reduce_umax:
7134   case Intrinsic::vector_reduce_umin:
7135   case Intrinsic::vector_reduce_fmax:
7136   case Intrinsic::vector_reduce_fmin:
7137     visitVectorReduce(I, Intrinsic);
7138     return;
7139 
7140   case Intrinsic::icall_branch_funnel: {
7141     SmallVector<SDValue, 16> Ops;
7142     Ops.push_back(getValue(I.getArgOperand(0)));
7143 
7144     int64_t Offset;
7145     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7146         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7147     if (!Base)
7148       report_fatal_error(
7149           "llvm.icall.branch.funnel operand must be a GlobalValue");
7150     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7151 
7152     struct BranchFunnelTarget {
7153       int64_t Offset;
7154       SDValue Target;
7155     };
7156     SmallVector<BranchFunnelTarget, 8> Targets;
7157 
7158     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7159       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7160           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7161       if (ElemBase != Base)
7162         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7163                            "to the same GlobalValue");
7164 
7165       SDValue Val = getValue(I.getArgOperand(Op + 1));
7166       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7167       if (!GA)
7168         report_fatal_error(
7169             "llvm.icall.branch.funnel operand must be a GlobalValue");
7170       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7171                                      GA->getGlobal(), sdl, Val.getValueType(),
7172                                      GA->getOffset())});
7173     }
7174     llvm::sort(Targets,
7175                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7176                  return T1.Offset < T2.Offset;
7177                });
7178 
7179     for (auto &T : Targets) {
7180       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7181       Ops.push_back(T.Target);
7182     }
7183 
7184     Ops.push_back(DAG.getRoot()); // Chain
7185     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7186                                  MVT::Other, Ops),
7187               0);
7188     DAG.setRoot(N);
7189     setValue(&I, N);
7190     HasTailCall = true;
7191     return;
7192   }
7193 
7194   case Intrinsic::wasm_landingpad_index:
7195     // Information this intrinsic contained has been transferred to
7196     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7197     // delete it now.
7198     return;
7199 
7200   case Intrinsic::aarch64_settag:
7201   case Intrinsic::aarch64_settag_zero: {
7202     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7203     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7204     SDValue Val = TSI.EmitTargetCodeForSetTag(
7205         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7206         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7207         ZeroMemory);
7208     DAG.setRoot(Val);
7209     setValue(&I, Val);
7210     return;
7211   }
7212   case Intrinsic::ptrmask: {
7213     SDValue Ptr = getValue(I.getOperand(0));
7214     SDValue Const = getValue(I.getOperand(1));
7215 
7216     EVT PtrVT = Ptr.getValueType();
7217     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7218                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7219     return;
7220   }
7221   case Intrinsic::threadlocal_address: {
7222     setValue(&I, getValue(I.getOperand(0)));
7223     return;
7224   }
7225   case Intrinsic::get_active_lane_mask: {
7226     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7227     SDValue Index = getValue(I.getOperand(0));
7228     EVT ElementVT = Index.getValueType();
7229 
7230     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7231       visitTargetIntrinsic(I, Intrinsic);
7232       return;
7233     }
7234 
7235     SDValue TripCount = getValue(I.getOperand(1));
7236     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7237 
7238     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7239     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7240     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7241     SDValue VectorInduction = DAG.getNode(
7242         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7243     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7244                                  VectorTripCount, ISD::CondCode::SETULT);
7245     setValue(&I, SetCC);
7246     return;
7247   }
7248   case Intrinsic::vector_insert: {
7249     SDValue Vec = getValue(I.getOperand(0));
7250     SDValue SubVec = getValue(I.getOperand(1));
7251     SDValue Index = getValue(I.getOperand(2));
7252 
7253     // The intrinsic's index type is i64, but the SDNode requires an index type
7254     // suitable for the target. Convert the index as required.
7255     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7256     if (Index.getValueType() != VectorIdxTy)
7257       Index = DAG.getVectorIdxConstant(
7258           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7259 
7260     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7261     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7262                              Index));
7263     return;
7264   }
7265   case Intrinsic::vector_extract: {
7266     SDValue Vec = getValue(I.getOperand(0));
7267     SDValue Index = getValue(I.getOperand(1));
7268     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7269 
7270     // The intrinsic's index type is i64, but the SDNode requires an index type
7271     // suitable for the target. Convert the index as required.
7272     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7273     if (Index.getValueType() != VectorIdxTy)
7274       Index = DAG.getVectorIdxConstant(
7275           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7276 
7277     setValue(&I,
7278              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7279     return;
7280   }
7281   case Intrinsic::experimental_vector_reverse:
7282     visitVectorReverse(I);
7283     return;
7284   case Intrinsic::experimental_vector_splice:
7285     visitVectorSplice(I);
7286     return;
7287   }
7288 }
7289 
7290 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7291     const ConstrainedFPIntrinsic &FPI) {
7292   SDLoc sdl = getCurSDLoc();
7293 
7294   // We do not need to serialize constrained FP intrinsics against
7295   // each other or against (nonvolatile) loads, so they can be
7296   // chained like loads.
7297   SDValue Chain = DAG.getRoot();
7298   SmallVector<SDValue, 4> Opers;
7299   Opers.push_back(Chain);
7300   if (FPI.isUnaryOp()) {
7301     Opers.push_back(getValue(FPI.getArgOperand(0)));
7302   } else if (FPI.isTernaryOp()) {
7303     Opers.push_back(getValue(FPI.getArgOperand(0)));
7304     Opers.push_back(getValue(FPI.getArgOperand(1)));
7305     Opers.push_back(getValue(FPI.getArgOperand(2)));
7306   } else {
7307     Opers.push_back(getValue(FPI.getArgOperand(0)));
7308     Opers.push_back(getValue(FPI.getArgOperand(1)));
7309   }
7310 
7311   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7312     assert(Result.getNode()->getNumValues() == 2);
7313 
7314     // Push node to the appropriate list so that future instructions can be
7315     // chained up correctly.
7316     SDValue OutChain = Result.getValue(1);
7317     switch (EB) {
7318     case fp::ExceptionBehavior::ebIgnore:
7319       // The only reason why ebIgnore nodes still need to be chained is that
7320       // they might depend on the current rounding mode, and therefore must
7321       // not be moved across instruction that may change that mode.
7322       [[fallthrough]];
7323     case fp::ExceptionBehavior::ebMayTrap:
7324       // These must not be moved across calls or instructions that may change
7325       // floating-point exception masks.
7326       PendingConstrainedFP.push_back(OutChain);
7327       break;
7328     case fp::ExceptionBehavior::ebStrict:
7329       // These must not be moved across calls or instructions that may change
7330       // floating-point exception masks or read floating-point exception flags.
7331       // In addition, they cannot be optimized out even if unused.
7332       PendingConstrainedFPStrict.push_back(OutChain);
7333       break;
7334     }
7335   };
7336 
7337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7338   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7339   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7340   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7341 
7342   SDNodeFlags Flags;
7343   if (EB == fp::ExceptionBehavior::ebIgnore)
7344     Flags.setNoFPExcept(true);
7345 
7346   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7347     Flags.copyFMF(*FPOp);
7348 
7349   unsigned Opcode;
7350   switch (FPI.getIntrinsicID()) {
7351   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7352 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7353   case Intrinsic::INTRINSIC:                                                   \
7354     Opcode = ISD::STRICT_##DAGN;                                               \
7355     break;
7356 #include "llvm/IR/ConstrainedOps.def"
7357   case Intrinsic::experimental_constrained_fmuladd: {
7358     Opcode = ISD::STRICT_FMA;
7359     // Break fmuladd into fmul and fadd.
7360     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7361         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7362       Opers.pop_back();
7363       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7364       pushOutChain(Mul, EB);
7365       Opcode = ISD::STRICT_FADD;
7366       Opers.clear();
7367       Opers.push_back(Mul.getValue(1));
7368       Opers.push_back(Mul.getValue(0));
7369       Opers.push_back(getValue(FPI.getArgOperand(2)));
7370     }
7371     break;
7372   }
7373   }
7374 
7375   // A few strict DAG nodes carry additional operands that are not
7376   // set up by the default code above.
7377   switch (Opcode) {
7378   default: break;
7379   case ISD::STRICT_FP_ROUND:
7380     Opers.push_back(
7381         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7382     break;
7383   case ISD::STRICT_FSETCC:
7384   case ISD::STRICT_FSETCCS: {
7385     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7386     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7387     if (TM.Options.NoNaNsFPMath)
7388       Condition = getFCmpCodeWithoutNaN(Condition);
7389     Opers.push_back(DAG.getCondCode(Condition));
7390     break;
7391   }
7392   }
7393 
7394   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7395   pushOutChain(Result, EB);
7396 
7397   SDValue FPResult = Result.getValue(0);
7398   setValue(&FPI, FPResult);
7399 }
7400 
7401 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7402   std::optional<unsigned> ResOPC;
7403   switch (VPIntrin.getIntrinsicID()) {
7404 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7405   case Intrinsic::VPID:                                                        \
7406     ResOPC = ISD::VPSD;                                                        \
7407     break;
7408 #include "llvm/IR/VPIntrinsics.def"
7409   }
7410 
7411   if (!ResOPC)
7412     llvm_unreachable(
7413         "Inconsistency: no SDNode available for this VPIntrinsic!");
7414 
7415   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7416       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7417     if (VPIntrin.getFastMathFlags().allowReassoc())
7418       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7419                                                 : ISD::VP_REDUCE_FMUL;
7420   }
7421 
7422   return *ResOPC;
7423 }
7424 
7425 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7426                                       SmallVector<SDValue, 7> &OpValues) {
7427   SDLoc DL = getCurSDLoc();
7428   Value *PtrOperand = VPIntrin.getArgOperand(0);
7429   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7430   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7431   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7432   SDValue LD;
7433   bool AddToChain = true;
7434   // Do not serialize variable-length loads of constant memory with
7435   // anything.
7436   if (!Alignment)
7437     Alignment = DAG.getEVTAlign(VT);
7438   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7439   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7440   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7441   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7442       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7443       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7444   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7445                      MMO, false /*IsExpanding */);
7446   if (AddToChain)
7447     PendingLoads.push_back(LD.getValue(1));
7448   setValue(&VPIntrin, LD);
7449 }
7450 
7451 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7452                                         SmallVector<SDValue, 7> &OpValues) {
7453   SDLoc DL = getCurSDLoc();
7454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7455   Value *PtrOperand = VPIntrin.getArgOperand(0);
7456   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7457   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7458   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7459   SDValue LD;
7460   if (!Alignment)
7461     Alignment = DAG.getEVTAlign(VT.getScalarType());
7462   unsigned AS =
7463     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7464   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7465      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7466      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7467   SDValue Base, Index, Scale;
7468   ISD::MemIndexType IndexType;
7469   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7470                                     this, VPIntrin.getParent(),
7471                                     VT.getScalarStoreSize());
7472   if (!UniformBase) {
7473     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7474     Index = getValue(PtrOperand);
7475     IndexType = ISD::SIGNED_SCALED;
7476     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7477   }
7478   EVT IdxVT = Index.getValueType();
7479   EVT EltTy = IdxVT.getVectorElementType();
7480   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7481     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7482     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7483   }
7484   LD = DAG.getGatherVP(
7485       DAG.getVTList(VT, MVT::Other), VT, DL,
7486       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7487       IndexType);
7488   PendingLoads.push_back(LD.getValue(1));
7489   setValue(&VPIntrin, LD);
7490 }
7491 
7492 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7493                                        SmallVector<SDValue, 7> &OpValues) {
7494   SDLoc DL = getCurSDLoc();
7495   Value *PtrOperand = VPIntrin.getArgOperand(1);
7496   EVT VT = OpValues[0].getValueType();
7497   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7498   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7499   SDValue ST;
7500   if (!Alignment)
7501     Alignment = DAG.getEVTAlign(VT);
7502   SDValue Ptr = OpValues[1];
7503   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7504   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7505       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7506       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7507   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7508                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7509                       /* IsTruncating */ false, /*IsCompressing*/ false);
7510   DAG.setRoot(ST);
7511   setValue(&VPIntrin, ST);
7512 }
7513 
7514 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7515                                               SmallVector<SDValue, 7> &OpValues) {
7516   SDLoc DL = getCurSDLoc();
7517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7518   Value *PtrOperand = VPIntrin.getArgOperand(1);
7519   EVT VT = OpValues[0].getValueType();
7520   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7521   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7522   SDValue ST;
7523   if (!Alignment)
7524     Alignment = DAG.getEVTAlign(VT.getScalarType());
7525   unsigned AS =
7526       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7527   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7528       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7529       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7530   SDValue Base, Index, Scale;
7531   ISD::MemIndexType IndexType;
7532   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7533                                     this, VPIntrin.getParent(),
7534                                     VT.getScalarStoreSize());
7535   if (!UniformBase) {
7536     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7537     Index = getValue(PtrOperand);
7538     IndexType = ISD::SIGNED_SCALED;
7539     Scale =
7540       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7541   }
7542   EVT IdxVT = Index.getValueType();
7543   EVT EltTy = IdxVT.getVectorElementType();
7544   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7545     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7546     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7547   }
7548   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7549                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7550                          OpValues[2], OpValues[3]},
7551                         MMO, IndexType);
7552   DAG.setRoot(ST);
7553   setValue(&VPIntrin, ST);
7554 }
7555 
7556 void SelectionDAGBuilder::visitVPStridedLoad(
7557     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7558   SDLoc DL = getCurSDLoc();
7559   Value *PtrOperand = VPIntrin.getArgOperand(0);
7560   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7561   if (!Alignment)
7562     Alignment = DAG.getEVTAlign(VT.getScalarType());
7563   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7564   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7565   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7566   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7567   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7568   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7569       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7570       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7571 
7572   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7573                                     OpValues[2], OpValues[3], MMO,
7574                                     false /*IsExpanding*/);
7575 
7576   if (AddToChain)
7577     PendingLoads.push_back(LD.getValue(1));
7578   setValue(&VPIntrin, LD);
7579 }
7580 
7581 void SelectionDAGBuilder::visitVPStridedStore(
7582     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7583   SDLoc DL = getCurSDLoc();
7584   Value *PtrOperand = VPIntrin.getArgOperand(1);
7585   EVT VT = OpValues[0].getValueType();
7586   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7587   if (!Alignment)
7588     Alignment = DAG.getEVTAlign(VT.getScalarType());
7589   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7590   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7591       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7592       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7593 
7594   SDValue ST = DAG.getStridedStoreVP(
7595       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7596       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7597       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7598       /*IsCompressing*/ false);
7599 
7600   DAG.setRoot(ST);
7601   setValue(&VPIntrin, ST);
7602 }
7603 
7604 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7606   SDLoc DL = getCurSDLoc();
7607 
7608   ISD::CondCode Condition;
7609   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7610   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7611   if (IsFP) {
7612     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7613     // flags, but calls that don't return floating-point types can't be
7614     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7615     Condition = getFCmpCondCode(CondCode);
7616     if (TM.Options.NoNaNsFPMath)
7617       Condition = getFCmpCodeWithoutNaN(Condition);
7618   } else {
7619     Condition = getICmpCondCode(CondCode);
7620   }
7621 
7622   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7623   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7624   // #2 is the condition code
7625   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7626   SDValue EVL = getValue(VPIntrin.getOperand(4));
7627   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7628   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7629          "Unexpected target EVL type");
7630   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7631 
7632   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7633                                                         VPIntrin.getType());
7634   setValue(&VPIntrin,
7635            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7636 }
7637 
7638 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7639     const VPIntrinsic &VPIntrin) {
7640   SDLoc DL = getCurSDLoc();
7641   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7642 
7643   auto IID = VPIntrin.getIntrinsicID();
7644 
7645   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7646     return visitVPCmp(*CmpI);
7647 
7648   SmallVector<EVT, 4> ValueVTs;
7649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7650   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7651   SDVTList VTs = DAG.getVTList(ValueVTs);
7652 
7653   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7654 
7655   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7656   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7657          "Unexpected target EVL type");
7658 
7659   // Request operands.
7660   SmallVector<SDValue, 7> OpValues;
7661   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7662     auto Op = getValue(VPIntrin.getArgOperand(I));
7663     if (I == EVLParamPos)
7664       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7665     OpValues.push_back(Op);
7666   }
7667 
7668   switch (Opcode) {
7669   default: {
7670     SDNodeFlags SDFlags;
7671     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7672       SDFlags.copyFMF(*FPMO);
7673     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7674     setValue(&VPIntrin, Result);
7675     break;
7676   }
7677   case ISD::VP_LOAD:
7678     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7679     break;
7680   case ISD::VP_GATHER:
7681     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7682     break;
7683   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7684     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7685     break;
7686   case ISD::VP_STORE:
7687     visitVPStore(VPIntrin, OpValues);
7688     break;
7689   case ISD::VP_SCATTER:
7690     visitVPScatter(VPIntrin, OpValues);
7691     break;
7692   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7693     visitVPStridedStore(VPIntrin, OpValues);
7694     break;
7695   case ISD::VP_FMULADD: {
7696     assert(OpValues.size() == 5 && "Unexpected number of operands");
7697     SDNodeFlags SDFlags;
7698     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7699       SDFlags.copyFMF(*FPMO);
7700     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7701         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7702       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7703     } else {
7704       SDValue Mul = DAG.getNode(
7705           ISD::VP_FMUL, DL, VTs,
7706           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7707       SDValue Add =
7708           DAG.getNode(ISD::VP_FADD, DL, VTs,
7709                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7710       setValue(&VPIntrin, Add);
7711     }
7712     break;
7713   }
7714   case ISD::VP_INTTOPTR: {
7715     SDValue N = OpValues[0];
7716     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7717     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7718     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7719                                OpValues[2]);
7720     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7721                              OpValues[2]);
7722     setValue(&VPIntrin, N);
7723     break;
7724   }
7725   case ISD::VP_PTRTOINT: {
7726     SDValue N = OpValues[0];
7727     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7728                                                           VPIntrin.getType());
7729     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7730                                        VPIntrin.getOperand(0)->getType());
7731     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7732                                OpValues[2]);
7733     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7734                              OpValues[2]);
7735     setValue(&VPIntrin, N);
7736     break;
7737   }
7738   }
7739 }
7740 
7741 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7742                                           const BasicBlock *EHPadBB,
7743                                           MCSymbol *&BeginLabel) {
7744   MachineFunction &MF = DAG.getMachineFunction();
7745   MachineModuleInfo &MMI = MF.getMMI();
7746 
7747   // Insert a label before the invoke call to mark the try range.  This can be
7748   // used to detect deletion of the invoke via the MachineModuleInfo.
7749   BeginLabel = MMI.getContext().createTempSymbol();
7750 
7751   // For SjLj, keep track of which landing pads go with which invokes
7752   // so as to maintain the ordering of pads in the LSDA.
7753   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7754   if (CallSiteIndex) {
7755     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7756     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7757 
7758     // Now that the call site is handled, stop tracking it.
7759     MMI.setCurrentCallSite(0);
7760   }
7761 
7762   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7763 }
7764 
7765 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7766                                         const BasicBlock *EHPadBB,
7767                                         MCSymbol *BeginLabel) {
7768   assert(BeginLabel && "BeginLabel should've been set");
7769 
7770   MachineFunction &MF = DAG.getMachineFunction();
7771   MachineModuleInfo &MMI = MF.getMMI();
7772 
7773   // Insert a label at the end of the invoke call to mark the try range.  This
7774   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7775   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7776   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7777 
7778   // Inform MachineModuleInfo of range.
7779   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7780   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7781   // actually use outlined funclets and their LSDA info style.
7782   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7783     assert(II && "II should've been set");
7784     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7785     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7786   } else if (!isScopedEHPersonality(Pers)) {
7787     assert(EHPadBB);
7788     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7789   }
7790 
7791   return Chain;
7792 }
7793 
7794 std::pair<SDValue, SDValue>
7795 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7796                                     const BasicBlock *EHPadBB) {
7797   MCSymbol *BeginLabel = nullptr;
7798 
7799   if (EHPadBB) {
7800     // Both PendingLoads and PendingExports must be flushed here;
7801     // this call might not return.
7802     (void)getRoot();
7803     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7804     CLI.setChain(getRoot());
7805   }
7806 
7807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7808   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7809 
7810   assert((CLI.IsTailCall || Result.second.getNode()) &&
7811          "Non-null chain expected with non-tail call!");
7812   assert((Result.second.getNode() || !Result.first.getNode()) &&
7813          "Null value expected with tail call!");
7814 
7815   if (!Result.second.getNode()) {
7816     // As a special case, a null chain means that a tail call has been emitted
7817     // and the DAG root is already updated.
7818     HasTailCall = true;
7819 
7820     // Since there's no actual continuation from this block, nothing can be
7821     // relying on us setting vregs for them.
7822     PendingExports.clear();
7823   } else {
7824     DAG.setRoot(Result.second);
7825   }
7826 
7827   if (EHPadBB) {
7828     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7829                            BeginLabel));
7830   }
7831 
7832   return Result;
7833 }
7834 
7835 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7836                                       bool isTailCall,
7837                                       bool isMustTailCall,
7838                                       const BasicBlock *EHPadBB) {
7839   auto &DL = DAG.getDataLayout();
7840   FunctionType *FTy = CB.getFunctionType();
7841   Type *RetTy = CB.getType();
7842 
7843   TargetLowering::ArgListTy Args;
7844   Args.reserve(CB.arg_size());
7845 
7846   const Value *SwiftErrorVal = nullptr;
7847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7848 
7849   if (isTailCall) {
7850     // Avoid emitting tail calls in functions with the disable-tail-calls
7851     // attribute.
7852     auto *Caller = CB.getParent()->getParent();
7853     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7854         "true" && !isMustTailCall)
7855       isTailCall = false;
7856 
7857     // We can't tail call inside a function with a swifterror argument. Lowering
7858     // does not support this yet. It would have to move into the swifterror
7859     // register before the call.
7860     if (TLI.supportSwiftError() &&
7861         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7862       isTailCall = false;
7863   }
7864 
7865   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7866     TargetLowering::ArgListEntry Entry;
7867     const Value *V = *I;
7868 
7869     // Skip empty types
7870     if (V->getType()->isEmptyTy())
7871       continue;
7872 
7873     SDValue ArgNode = getValue(V);
7874     Entry.Node = ArgNode; Entry.Ty = V->getType();
7875 
7876     Entry.setAttributes(&CB, I - CB.arg_begin());
7877 
7878     // Use swifterror virtual register as input to the call.
7879     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7880       SwiftErrorVal = V;
7881       // We find the virtual register for the actual swifterror argument.
7882       // Instead of using the Value, we use the virtual register instead.
7883       Entry.Node =
7884           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7885                           EVT(TLI.getPointerTy(DL)));
7886     }
7887 
7888     Args.push_back(Entry);
7889 
7890     // If we have an explicit sret argument that is an Instruction, (i.e., it
7891     // might point to function-local memory), we can't meaningfully tail-call.
7892     if (Entry.IsSRet && isa<Instruction>(V))
7893       isTailCall = false;
7894   }
7895 
7896   // If call site has a cfguardtarget operand bundle, create and add an
7897   // additional ArgListEntry.
7898   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7899     TargetLowering::ArgListEntry Entry;
7900     Value *V = Bundle->Inputs[0];
7901     SDValue ArgNode = getValue(V);
7902     Entry.Node = ArgNode;
7903     Entry.Ty = V->getType();
7904     Entry.IsCFGuardTarget = true;
7905     Args.push_back(Entry);
7906   }
7907 
7908   // Check if target-independent constraints permit a tail call here.
7909   // Target-dependent constraints are checked within TLI->LowerCallTo.
7910   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7911     isTailCall = false;
7912 
7913   // Disable tail calls if there is an swifterror argument. Targets have not
7914   // been updated to support tail calls.
7915   if (TLI.supportSwiftError() && SwiftErrorVal)
7916     isTailCall = false;
7917 
7918   ConstantInt *CFIType = nullptr;
7919   if (CB.isIndirectCall()) {
7920     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7921       if (!TLI.supportKCFIBundles())
7922         report_fatal_error(
7923             "Target doesn't support calls with kcfi operand bundles.");
7924       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7925       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7926     }
7927   }
7928 
7929   TargetLowering::CallLoweringInfo CLI(DAG);
7930   CLI.setDebugLoc(getCurSDLoc())
7931       .setChain(getRoot())
7932       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7933       .setTailCall(isTailCall)
7934       .setConvergent(CB.isConvergent())
7935       .setIsPreallocated(
7936           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7937       .setCFIType(CFIType);
7938   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7939 
7940   if (Result.first.getNode()) {
7941     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7942     setValue(&CB, Result.first);
7943   }
7944 
7945   // The last element of CLI.InVals has the SDValue for swifterror return.
7946   // Here we copy it to a virtual register and update SwiftErrorMap for
7947   // book-keeping.
7948   if (SwiftErrorVal && TLI.supportSwiftError()) {
7949     // Get the last element of InVals.
7950     SDValue Src = CLI.InVals.back();
7951     Register VReg =
7952         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7953     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7954     DAG.setRoot(CopyNode);
7955   }
7956 }
7957 
7958 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7959                              SelectionDAGBuilder &Builder) {
7960   // Check to see if this load can be trivially constant folded, e.g. if the
7961   // input is from a string literal.
7962   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7963     // Cast pointer to the type we really want to load.
7964     Type *LoadTy =
7965         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7966     if (LoadVT.isVector())
7967       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7968 
7969     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7970                                          PointerType::getUnqual(LoadTy));
7971 
7972     if (const Constant *LoadCst =
7973             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7974                                          LoadTy, Builder.DAG.getDataLayout()))
7975       return Builder.getValue(LoadCst);
7976   }
7977 
7978   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7979   // still constant memory, the input chain can be the entry node.
7980   SDValue Root;
7981   bool ConstantMemory = false;
7982 
7983   // Do not serialize (non-volatile) loads of constant memory with anything.
7984   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7985     Root = Builder.DAG.getEntryNode();
7986     ConstantMemory = true;
7987   } else {
7988     // Do not serialize non-volatile loads against each other.
7989     Root = Builder.DAG.getRoot();
7990   }
7991 
7992   SDValue Ptr = Builder.getValue(PtrVal);
7993   SDValue LoadVal =
7994       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7995                           MachinePointerInfo(PtrVal), Align(1));
7996 
7997   if (!ConstantMemory)
7998     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7999   return LoadVal;
8000 }
8001 
8002 /// Record the value for an instruction that produces an integer result,
8003 /// converting the type where necessary.
8004 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8005                                                   SDValue Value,
8006                                                   bool IsSigned) {
8007   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8008                                                     I.getType(), true);
8009   if (IsSigned)
8010     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8011   else
8012     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8013   setValue(&I, Value);
8014 }
8015 
8016 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8017 /// true and lower it. Otherwise return false, and it will be lowered like a
8018 /// normal call.
8019 /// The caller already checked that \p I calls the appropriate LibFunc with a
8020 /// correct prototype.
8021 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8022   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8023   const Value *Size = I.getArgOperand(2);
8024   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8025   if (CSize && CSize->getZExtValue() == 0) {
8026     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8027                                                           I.getType(), true);
8028     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8029     return true;
8030   }
8031 
8032   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8033   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8034       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8035       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8036   if (Res.first.getNode()) {
8037     processIntegerCallValue(I, Res.first, true);
8038     PendingLoads.push_back(Res.second);
8039     return true;
8040   }
8041 
8042   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8043   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8044   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8045     return false;
8046 
8047   // If the target has a fast compare for the given size, it will return a
8048   // preferred load type for that size. Require that the load VT is legal and
8049   // that the target supports unaligned loads of that type. Otherwise, return
8050   // INVALID.
8051   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8052     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8053     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8054     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8055       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8056       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8057       // TODO: Check alignment of src and dest ptrs.
8058       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8059       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8060       if (!TLI.isTypeLegal(LVT) ||
8061           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8062           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8063         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8064     }
8065 
8066     return LVT;
8067   };
8068 
8069   // This turns into unaligned loads. We only do this if the target natively
8070   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8071   // we'll only produce a small number of byte loads.
8072   MVT LoadVT;
8073   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8074   switch (NumBitsToCompare) {
8075   default:
8076     return false;
8077   case 16:
8078     LoadVT = MVT::i16;
8079     break;
8080   case 32:
8081     LoadVT = MVT::i32;
8082     break;
8083   case 64:
8084   case 128:
8085   case 256:
8086     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8087     break;
8088   }
8089 
8090   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8091     return false;
8092 
8093   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8094   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8095 
8096   // Bitcast to a wide integer type if the loads are vectors.
8097   if (LoadVT.isVector()) {
8098     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8099     LoadL = DAG.getBitcast(CmpVT, LoadL);
8100     LoadR = DAG.getBitcast(CmpVT, LoadR);
8101   }
8102 
8103   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8104   processIntegerCallValue(I, Cmp, false);
8105   return true;
8106 }
8107 
8108 /// See if we can lower a memchr call into an optimized form. If so, return
8109 /// true and lower it. Otherwise return false, and it will be lowered like a
8110 /// normal call.
8111 /// The caller already checked that \p I calls the appropriate LibFunc with a
8112 /// correct prototype.
8113 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8114   const Value *Src = I.getArgOperand(0);
8115   const Value *Char = I.getArgOperand(1);
8116   const Value *Length = I.getArgOperand(2);
8117 
8118   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8119   std::pair<SDValue, SDValue> Res =
8120     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8121                                 getValue(Src), getValue(Char), getValue(Length),
8122                                 MachinePointerInfo(Src));
8123   if (Res.first.getNode()) {
8124     setValue(&I, Res.first);
8125     PendingLoads.push_back(Res.second);
8126     return true;
8127   }
8128 
8129   return false;
8130 }
8131 
8132 /// See if we can lower a mempcpy call into an optimized form. If so, return
8133 /// true and lower it. Otherwise return false, and it will be lowered like a
8134 /// normal call.
8135 /// The caller already checked that \p I calls the appropriate LibFunc with a
8136 /// correct prototype.
8137 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8138   SDValue Dst = getValue(I.getArgOperand(0));
8139   SDValue Src = getValue(I.getArgOperand(1));
8140   SDValue Size = getValue(I.getArgOperand(2));
8141 
8142   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8143   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8144   // DAG::getMemcpy needs Alignment to be defined.
8145   Align Alignment = std::min(DstAlign, SrcAlign);
8146 
8147   bool isVol = false;
8148   SDLoc sdl = getCurSDLoc();
8149 
8150   // In the mempcpy context we need to pass in a false value for isTailCall
8151   // because the return pointer needs to be adjusted by the size of
8152   // the copied memory.
8153   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8154   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8155                              /*isTailCall=*/false,
8156                              MachinePointerInfo(I.getArgOperand(0)),
8157                              MachinePointerInfo(I.getArgOperand(1)),
8158                              I.getAAMetadata());
8159   assert(MC.getNode() != nullptr &&
8160          "** memcpy should not be lowered as TailCall in mempcpy context **");
8161   DAG.setRoot(MC);
8162 
8163   // Check if Size needs to be truncated or extended.
8164   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8165 
8166   // Adjust return pointer to point just past the last dst byte.
8167   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8168                                     Dst, Size);
8169   setValue(&I, DstPlusSize);
8170   return true;
8171 }
8172 
8173 /// See if we can lower a strcpy call into an optimized form.  If so, return
8174 /// true and lower it, otherwise return false and it will be lowered like a
8175 /// normal call.
8176 /// The caller already checked that \p I calls the appropriate LibFunc with a
8177 /// correct prototype.
8178 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8179   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8180 
8181   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8182   std::pair<SDValue, SDValue> Res =
8183     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8184                                 getValue(Arg0), getValue(Arg1),
8185                                 MachinePointerInfo(Arg0),
8186                                 MachinePointerInfo(Arg1), isStpcpy);
8187   if (Res.first.getNode()) {
8188     setValue(&I, Res.first);
8189     DAG.setRoot(Res.second);
8190     return true;
8191   }
8192 
8193   return false;
8194 }
8195 
8196 /// See if we can lower a strcmp call into an optimized form.  If so, return
8197 /// true and lower it, otherwise return false and it will be lowered like a
8198 /// normal call.
8199 /// The caller already checked that \p I calls the appropriate LibFunc with a
8200 /// correct prototype.
8201 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8202   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8203 
8204   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8205   std::pair<SDValue, SDValue> Res =
8206     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8207                                 getValue(Arg0), getValue(Arg1),
8208                                 MachinePointerInfo(Arg0),
8209                                 MachinePointerInfo(Arg1));
8210   if (Res.first.getNode()) {
8211     processIntegerCallValue(I, Res.first, true);
8212     PendingLoads.push_back(Res.second);
8213     return true;
8214   }
8215 
8216   return false;
8217 }
8218 
8219 /// See if we can lower a strlen call into an optimized form.  If so, return
8220 /// true and lower it, otherwise return false and it will be lowered like a
8221 /// normal call.
8222 /// The caller already checked that \p I calls the appropriate LibFunc with a
8223 /// correct prototype.
8224 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8225   const Value *Arg0 = I.getArgOperand(0);
8226 
8227   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8228   std::pair<SDValue, SDValue> Res =
8229     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8230                                 getValue(Arg0), MachinePointerInfo(Arg0));
8231   if (Res.first.getNode()) {
8232     processIntegerCallValue(I, Res.first, false);
8233     PendingLoads.push_back(Res.second);
8234     return true;
8235   }
8236 
8237   return false;
8238 }
8239 
8240 /// See if we can lower a strnlen call into an optimized form.  If so, return
8241 /// true and lower it, otherwise return false and it will be lowered like a
8242 /// normal call.
8243 /// The caller already checked that \p I calls the appropriate LibFunc with a
8244 /// correct prototype.
8245 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8246   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8247 
8248   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8249   std::pair<SDValue, SDValue> Res =
8250     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8251                                  getValue(Arg0), getValue(Arg1),
8252                                  MachinePointerInfo(Arg0));
8253   if (Res.first.getNode()) {
8254     processIntegerCallValue(I, Res.first, false);
8255     PendingLoads.push_back(Res.second);
8256     return true;
8257   }
8258 
8259   return false;
8260 }
8261 
8262 /// See if we can lower a unary floating-point operation into an SDNode with
8263 /// the specified Opcode.  If so, return true and lower it, otherwise return
8264 /// false and it will be lowered like a normal call.
8265 /// The caller already checked that \p I calls the appropriate LibFunc with a
8266 /// correct prototype.
8267 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8268                                               unsigned Opcode) {
8269   // We already checked this call's prototype; verify it doesn't modify errno.
8270   if (!I.onlyReadsMemory())
8271     return false;
8272 
8273   SDNodeFlags Flags;
8274   Flags.copyFMF(cast<FPMathOperator>(I));
8275 
8276   SDValue Tmp = getValue(I.getArgOperand(0));
8277   setValue(&I,
8278            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8279   return true;
8280 }
8281 
8282 /// See if we can lower a binary floating-point operation into an SDNode with
8283 /// the specified Opcode. If so, return true and lower it. Otherwise return
8284 /// false, and it will be lowered like a normal call.
8285 /// The caller already checked that \p I calls the appropriate LibFunc with a
8286 /// correct prototype.
8287 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8288                                                unsigned Opcode) {
8289   // We already checked this call's prototype; verify it doesn't modify errno.
8290   if (!I.onlyReadsMemory())
8291     return false;
8292 
8293   SDNodeFlags Flags;
8294   Flags.copyFMF(cast<FPMathOperator>(I));
8295 
8296   SDValue Tmp0 = getValue(I.getArgOperand(0));
8297   SDValue Tmp1 = getValue(I.getArgOperand(1));
8298   EVT VT = Tmp0.getValueType();
8299   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8300   return true;
8301 }
8302 
8303 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8304   // Handle inline assembly differently.
8305   if (I.isInlineAsm()) {
8306     visitInlineAsm(I);
8307     return;
8308   }
8309 
8310   if (Function *F = I.getCalledFunction()) {
8311     diagnoseDontCall(I);
8312 
8313     if (F->isDeclaration()) {
8314       // Is this an LLVM intrinsic or a target-specific intrinsic?
8315       unsigned IID = F->getIntrinsicID();
8316       if (!IID)
8317         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8318           IID = II->getIntrinsicID(F);
8319 
8320       if (IID) {
8321         visitIntrinsicCall(I, IID);
8322         return;
8323       }
8324     }
8325 
8326     // Check for well-known libc/libm calls.  If the function is internal, it
8327     // can't be a library call.  Don't do the check if marked as nobuiltin for
8328     // some reason or the call site requires strict floating point semantics.
8329     LibFunc Func;
8330     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8331         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8332         LibInfo->hasOptimizedCodeGen(Func)) {
8333       switch (Func) {
8334       default: break;
8335       case LibFunc_bcmp:
8336         if (visitMemCmpBCmpCall(I))
8337           return;
8338         break;
8339       case LibFunc_copysign:
8340       case LibFunc_copysignf:
8341       case LibFunc_copysignl:
8342         // We already checked this call's prototype; verify it doesn't modify
8343         // errno.
8344         if (I.onlyReadsMemory()) {
8345           SDValue LHS = getValue(I.getArgOperand(0));
8346           SDValue RHS = getValue(I.getArgOperand(1));
8347           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8348                                    LHS.getValueType(), LHS, RHS));
8349           return;
8350         }
8351         break;
8352       case LibFunc_fabs:
8353       case LibFunc_fabsf:
8354       case LibFunc_fabsl:
8355         if (visitUnaryFloatCall(I, ISD::FABS))
8356           return;
8357         break;
8358       case LibFunc_fmin:
8359       case LibFunc_fminf:
8360       case LibFunc_fminl:
8361         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8362           return;
8363         break;
8364       case LibFunc_fmax:
8365       case LibFunc_fmaxf:
8366       case LibFunc_fmaxl:
8367         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8368           return;
8369         break;
8370       case LibFunc_sin:
8371       case LibFunc_sinf:
8372       case LibFunc_sinl:
8373         if (visitUnaryFloatCall(I, ISD::FSIN))
8374           return;
8375         break;
8376       case LibFunc_cos:
8377       case LibFunc_cosf:
8378       case LibFunc_cosl:
8379         if (visitUnaryFloatCall(I, ISD::FCOS))
8380           return;
8381         break;
8382       case LibFunc_sqrt:
8383       case LibFunc_sqrtf:
8384       case LibFunc_sqrtl:
8385       case LibFunc_sqrt_finite:
8386       case LibFunc_sqrtf_finite:
8387       case LibFunc_sqrtl_finite:
8388         if (visitUnaryFloatCall(I, ISD::FSQRT))
8389           return;
8390         break;
8391       case LibFunc_floor:
8392       case LibFunc_floorf:
8393       case LibFunc_floorl:
8394         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8395           return;
8396         break;
8397       case LibFunc_nearbyint:
8398       case LibFunc_nearbyintf:
8399       case LibFunc_nearbyintl:
8400         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8401           return;
8402         break;
8403       case LibFunc_ceil:
8404       case LibFunc_ceilf:
8405       case LibFunc_ceill:
8406         if (visitUnaryFloatCall(I, ISD::FCEIL))
8407           return;
8408         break;
8409       case LibFunc_rint:
8410       case LibFunc_rintf:
8411       case LibFunc_rintl:
8412         if (visitUnaryFloatCall(I, ISD::FRINT))
8413           return;
8414         break;
8415       case LibFunc_round:
8416       case LibFunc_roundf:
8417       case LibFunc_roundl:
8418         if (visitUnaryFloatCall(I, ISD::FROUND))
8419           return;
8420         break;
8421       case LibFunc_trunc:
8422       case LibFunc_truncf:
8423       case LibFunc_truncl:
8424         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8425           return;
8426         break;
8427       case LibFunc_log2:
8428       case LibFunc_log2f:
8429       case LibFunc_log2l:
8430         if (visitUnaryFloatCall(I, ISD::FLOG2))
8431           return;
8432         break;
8433       case LibFunc_exp2:
8434       case LibFunc_exp2f:
8435       case LibFunc_exp2l:
8436         if (visitUnaryFloatCall(I, ISD::FEXP2))
8437           return;
8438         break;
8439       case LibFunc_memcmp:
8440         if (visitMemCmpBCmpCall(I))
8441           return;
8442         break;
8443       case LibFunc_mempcpy:
8444         if (visitMemPCpyCall(I))
8445           return;
8446         break;
8447       case LibFunc_memchr:
8448         if (visitMemChrCall(I))
8449           return;
8450         break;
8451       case LibFunc_strcpy:
8452         if (visitStrCpyCall(I, false))
8453           return;
8454         break;
8455       case LibFunc_stpcpy:
8456         if (visitStrCpyCall(I, true))
8457           return;
8458         break;
8459       case LibFunc_strcmp:
8460         if (visitStrCmpCall(I))
8461           return;
8462         break;
8463       case LibFunc_strlen:
8464         if (visitStrLenCall(I))
8465           return;
8466         break;
8467       case LibFunc_strnlen:
8468         if (visitStrNLenCall(I))
8469           return;
8470         break;
8471       }
8472     }
8473   }
8474 
8475   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8476   // have to do anything here to lower funclet bundles.
8477   // CFGuardTarget bundles are lowered in LowerCallTo.
8478   assert(!I.hasOperandBundlesOtherThan(
8479              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8480               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8481               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8482          "Cannot lower calls with arbitrary operand bundles!");
8483 
8484   SDValue Callee = getValue(I.getCalledOperand());
8485 
8486   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8487     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8488   else
8489     // Check if we can potentially perform a tail call. More detailed checking
8490     // is be done within LowerCallTo, after more information about the call is
8491     // known.
8492     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8493 }
8494 
8495 namespace {
8496 
8497 /// AsmOperandInfo - This contains information for each constraint that we are
8498 /// lowering.
8499 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8500 public:
8501   /// CallOperand - If this is the result output operand or a clobber
8502   /// this is null, otherwise it is the incoming operand to the CallInst.
8503   /// This gets modified as the asm is processed.
8504   SDValue CallOperand;
8505 
8506   /// AssignedRegs - If this is a register or register class operand, this
8507   /// contains the set of register corresponding to the operand.
8508   RegsForValue AssignedRegs;
8509 
8510   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8511     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8512   }
8513 
8514   /// Whether or not this operand accesses memory
8515   bool hasMemory(const TargetLowering &TLI) const {
8516     // Indirect operand accesses access memory.
8517     if (isIndirect)
8518       return true;
8519 
8520     for (const auto &Code : Codes)
8521       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8522         return true;
8523 
8524     return false;
8525   }
8526 };
8527 
8528 
8529 } // end anonymous namespace
8530 
8531 /// Make sure that the output operand \p OpInfo and its corresponding input
8532 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8533 /// out).
8534 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8535                                SDISelAsmOperandInfo &MatchingOpInfo,
8536                                SelectionDAG &DAG) {
8537   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8538     return;
8539 
8540   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8541   const auto &TLI = DAG.getTargetLoweringInfo();
8542 
8543   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8544       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8545                                        OpInfo.ConstraintVT);
8546   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8547       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8548                                        MatchingOpInfo.ConstraintVT);
8549   if ((OpInfo.ConstraintVT.isInteger() !=
8550        MatchingOpInfo.ConstraintVT.isInteger()) ||
8551       (MatchRC.second != InputRC.second)) {
8552     // FIXME: error out in a more elegant fashion
8553     report_fatal_error("Unsupported asm: input constraint"
8554                        " with a matching output constraint of"
8555                        " incompatible type!");
8556   }
8557   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8558 }
8559 
8560 /// Get a direct memory input to behave well as an indirect operand.
8561 /// This may introduce stores, hence the need for a \p Chain.
8562 /// \return The (possibly updated) chain.
8563 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8564                                         SDISelAsmOperandInfo &OpInfo,
8565                                         SelectionDAG &DAG) {
8566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8567 
8568   // If we don't have an indirect input, put it in the constpool if we can,
8569   // otherwise spill it to a stack slot.
8570   // TODO: This isn't quite right. We need to handle these according to
8571   // the addressing mode that the constraint wants. Also, this may take
8572   // an additional register for the computation and we don't want that
8573   // either.
8574 
8575   // If the operand is a float, integer, or vector constant, spill to a
8576   // constant pool entry to get its address.
8577   const Value *OpVal = OpInfo.CallOperandVal;
8578   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8579       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8580     OpInfo.CallOperand = DAG.getConstantPool(
8581         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8582     return Chain;
8583   }
8584 
8585   // Otherwise, create a stack slot and emit a store to it before the asm.
8586   Type *Ty = OpVal->getType();
8587   auto &DL = DAG.getDataLayout();
8588   uint64_t TySize = DL.getTypeAllocSize(Ty);
8589   MachineFunction &MF = DAG.getMachineFunction();
8590   int SSFI = MF.getFrameInfo().CreateStackObject(
8591       TySize, DL.getPrefTypeAlign(Ty), false);
8592   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8593   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8594                             MachinePointerInfo::getFixedStack(MF, SSFI),
8595                             TLI.getMemValueType(DL, Ty));
8596   OpInfo.CallOperand = StackSlot;
8597 
8598   return Chain;
8599 }
8600 
8601 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8602 /// specified operand.  We prefer to assign virtual registers, to allow the
8603 /// register allocator to handle the assignment process.  However, if the asm
8604 /// uses features that we can't model on machineinstrs, we have SDISel do the
8605 /// allocation.  This produces generally horrible, but correct, code.
8606 ///
8607 ///   OpInfo describes the operand
8608 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8609 static std::optional<unsigned>
8610 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8611                      SDISelAsmOperandInfo &OpInfo,
8612                      SDISelAsmOperandInfo &RefOpInfo) {
8613   LLVMContext &Context = *DAG.getContext();
8614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8615 
8616   MachineFunction &MF = DAG.getMachineFunction();
8617   SmallVector<unsigned, 4> Regs;
8618   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8619 
8620   // No work to do for memory/address operands.
8621   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8622       OpInfo.ConstraintType == TargetLowering::C_Address)
8623     return std::nullopt;
8624 
8625   // If this is a constraint for a single physreg, or a constraint for a
8626   // register class, find it.
8627   unsigned AssignedReg;
8628   const TargetRegisterClass *RC;
8629   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8630       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8631   // RC is unset only on failure. Return immediately.
8632   if (!RC)
8633     return std::nullopt;
8634 
8635   // Get the actual register value type.  This is important, because the user
8636   // may have asked for (e.g.) the AX register in i32 type.  We need to
8637   // remember that AX is actually i16 to get the right extension.
8638   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8639 
8640   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8641     // If this is an FP operand in an integer register (or visa versa), or more
8642     // generally if the operand value disagrees with the register class we plan
8643     // to stick it in, fix the operand type.
8644     //
8645     // If this is an input value, the bitcast to the new type is done now.
8646     // Bitcast for output value is done at the end of visitInlineAsm().
8647     if ((OpInfo.Type == InlineAsm::isOutput ||
8648          OpInfo.Type == InlineAsm::isInput) &&
8649         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8650       // Try to convert to the first EVT that the reg class contains.  If the
8651       // types are identical size, use a bitcast to convert (e.g. two differing
8652       // vector types).  Note: output bitcast is done at the end of
8653       // visitInlineAsm().
8654       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8655         // Exclude indirect inputs while they are unsupported because the code
8656         // to perform the load is missing and thus OpInfo.CallOperand still
8657         // refers to the input address rather than the pointed-to value.
8658         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8659           OpInfo.CallOperand =
8660               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8661         OpInfo.ConstraintVT = RegVT;
8662         // If the operand is an FP value and we want it in integer registers,
8663         // use the corresponding integer type. This turns an f64 value into
8664         // i64, which can be passed with two i32 values on a 32-bit machine.
8665       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8666         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8667         if (OpInfo.Type == InlineAsm::isInput)
8668           OpInfo.CallOperand =
8669               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8670         OpInfo.ConstraintVT = VT;
8671       }
8672     }
8673   }
8674 
8675   // No need to allocate a matching input constraint since the constraint it's
8676   // matching to has already been allocated.
8677   if (OpInfo.isMatchingInputConstraint())
8678     return std::nullopt;
8679 
8680   EVT ValueVT = OpInfo.ConstraintVT;
8681   if (OpInfo.ConstraintVT == MVT::Other)
8682     ValueVT = RegVT;
8683 
8684   // Initialize NumRegs.
8685   unsigned NumRegs = 1;
8686   if (OpInfo.ConstraintVT != MVT::Other)
8687     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8688 
8689   // If this is a constraint for a specific physical register, like {r17},
8690   // assign it now.
8691 
8692   // If this associated to a specific register, initialize iterator to correct
8693   // place. If virtual, make sure we have enough registers
8694 
8695   // Initialize iterator if necessary
8696   TargetRegisterClass::iterator I = RC->begin();
8697   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8698 
8699   // Do not check for single registers.
8700   if (AssignedReg) {
8701     I = std::find(I, RC->end(), AssignedReg);
8702     if (I == RC->end()) {
8703       // RC does not contain the selected register, which indicates a
8704       // mismatch between the register and the required type/bitwidth.
8705       return {AssignedReg};
8706     }
8707   }
8708 
8709   for (; NumRegs; --NumRegs, ++I) {
8710     assert(I != RC->end() && "Ran out of registers to allocate!");
8711     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8712     Regs.push_back(R);
8713   }
8714 
8715   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8716   return std::nullopt;
8717 }
8718 
8719 static unsigned
8720 findMatchingInlineAsmOperand(unsigned OperandNo,
8721                              const std::vector<SDValue> &AsmNodeOperands) {
8722   // Scan until we find the definition we already emitted of this operand.
8723   unsigned CurOp = InlineAsm::Op_FirstOperand;
8724   for (; OperandNo; --OperandNo) {
8725     // Advance to the next operand.
8726     unsigned OpFlag =
8727         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8728     assert((InlineAsm::isRegDefKind(OpFlag) ||
8729             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8730             InlineAsm::isMemKind(OpFlag)) &&
8731            "Skipped past definitions?");
8732     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8733   }
8734   return CurOp;
8735 }
8736 
8737 namespace {
8738 
8739 class ExtraFlags {
8740   unsigned Flags = 0;
8741 
8742 public:
8743   explicit ExtraFlags(const CallBase &Call) {
8744     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8745     if (IA->hasSideEffects())
8746       Flags |= InlineAsm::Extra_HasSideEffects;
8747     if (IA->isAlignStack())
8748       Flags |= InlineAsm::Extra_IsAlignStack;
8749     if (Call.isConvergent())
8750       Flags |= InlineAsm::Extra_IsConvergent;
8751     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8752   }
8753 
8754   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8755     // Ideally, we would only check against memory constraints.  However, the
8756     // meaning of an Other constraint can be target-specific and we can't easily
8757     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8758     // for Other constraints as well.
8759     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8760         OpInfo.ConstraintType == TargetLowering::C_Other) {
8761       if (OpInfo.Type == InlineAsm::isInput)
8762         Flags |= InlineAsm::Extra_MayLoad;
8763       else if (OpInfo.Type == InlineAsm::isOutput)
8764         Flags |= InlineAsm::Extra_MayStore;
8765       else if (OpInfo.Type == InlineAsm::isClobber)
8766         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8767     }
8768   }
8769 
8770   unsigned get() const { return Flags; }
8771 };
8772 
8773 } // end anonymous namespace
8774 
8775 static bool isFunction(SDValue Op) {
8776   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8777     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8778       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8779 
8780       // In normal "call dllimport func" instruction (non-inlineasm) it force
8781       // indirect access by specifing call opcode. And usually specially print
8782       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8783       // not do in this way now. (In fact, this is similar with "Data Access"
8784       // action). So here we ignore dllimport function.
8785       if (Fn && !Fn->hasDLLImportStorageClass())
8786         return true;
8787     }
8788   }
8789   return false;
8790 }
8791 
8792 /// visitInlineAsm - Handle a call to an InlineAsm object.
8793 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8794                                          const BasicBlock *EHPadBB) {
8795   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8796 
8797   /// ConstraintOperands - Information about all of the constraints.
8798   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8799 
8800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8801   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8802       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8803 
8804   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8805   // AsmDialect, MayLoad, MayStore).
8806   bool HasSideEffect = IA->hasSideEffects();
8807   ExtraFlags ExtraInfo(Call);
8808 
8809   for (auto &T : TargetConstraints) {
8810     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8811     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8812 
8813     if (OpInfo.CallOperandVal)
8814       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8815 
8816     if (!HasSideEffect)
8817       HasSideEffect = OpInfo.hasMemory(TLI);
8818 
8819     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8820     // FIXME: Could we compute this on OpInfo rather than T?
8821 
8822     // Compute the constraint code and ConstraintType to use.
8823     TLI.ComputeConstraintToUse(T, SDValue());
8824 
8825     if (T.ConstraintType == TargetLowering::C_Immediate &&
8826         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8827       // We've delayed emitting a diagnostic like the "n" constraint because
8828       // inlining could cause an integer showing up.
8829       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8830                                           "' expects an integer constant "
8831                                           "expression");
8832 
8833     ExtraInfo.update(T);
8834   }
8835 
8836   // We won't need to flush pending loads if this asm doesn't touch
8837   // memory and is nonvolatile.
8838   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8839 
8840   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8841   if (EmitEHLabels) {
8842     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8843   }
8844   bool IsCallBr = isa<CallBrInst>(Call);
8845 
8846   if (IsCallBr || EmitEHLabels) {
8847     // If this is a callbr or invoke we need to flush pending exports since
8848     // inlineasm_br and invoke are terminators.
8849     // We need to do this before nodes are glued to the inlineasm_br node.
8850     Chain = getControlRoot();
8851   }
8852 
8853   MCSymbol *BeginLabel = nullptr;
8854   if (EmitEHLabels) {
8855     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8856   }
8857 
8858   int OpNo = -1;
8859   SmallVector<StringRef> AsmStrs;
8860   IA->collectAsmStrs(AsmStrs);
8861 
8862   // Second pass over the constraints: compute which constraint option to use.
8863   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8864     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8865       OpNo++;
8866 
8867     // If this is an output operand with a matching input operand, look up the
8868     // matching input. If their types mismatch, e.g. one is an integer, the
8869     // other is floating point, or their sizes are different, flag it as an
8870     // error.
8871     if (OpInfo.hasMatchingInput()) {
8872       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8873       patchMatchingInput(OpInfo, Input, DAG);
8874     }
8875 
8876     // Compute the constraint code and ConstraintType to use.
8877     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8878 
8879     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8880          OpInfo.Type == InlineAsm::isClobber) ||
8881         OpInfo.ConstraintType == TargetLowering::C_Address)
8882       continue;
8883 
8884     // In Linux PIC model, there are 4 cases about value/label addressing:
8885     //
8886     // 1: Function call or Label jmp inside the module.
8887     // 2: Data access (such as global variable, static variable) inside module.
8888     // 3: Function call or Label jmp outside the module.
8889     // 4: Data access (such as global variable) outside the module.
8890     //
8891     // Due to current llvm inline asm architecture designed to not "recognize"
8892     // the asm code, there are quite troubles for us to treat mem addressing
8893     // differently for same value/adress used in different instuctions.
8894     // For example, in pic model, call a func may in plt way or direclty
8895     // pc-related, but lea/mov a function adress may use got.
8896     //
8897     // Here we try to "recognize" function call for the case 1 and case 3 in
8898     // inline asm. And try to adjust the constraint for them.
8899     //
8900     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8901     // label, so here we don't handle jmp function label now, but we need to
8902     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8903     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8904         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8905         TM.getCodeModel() != CodeModel::Large) {
8906       OpInfo.isIndirect = false;
8907       OpInfo.ConstraintType = TargetLowering::C_Address;
8908     }
8909 
8910     // If this is a memory input, and if the operand is not indirect, do what we
8911     // need to provide an address for the memory input.
8912     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8913         !OpInfo.isIndirect) {
8914       assert((OpInfo.isMultipleAlternative ||
8915               (OpInfo.Type == InlineAsm::isInput)) &&
8916              "Can only indirectify direct input operands!");
8917 
8918       // Memory operands really want the address of the value.
8919       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8920 
8921       // There is no longer a Value* corresponding to this operand.
8922       OpInfo.CallOperandVal = nullptr;
8923 
8924       // It is now an indirect operand.
8925       OpInfo.isIndirect = true;
8926     }
8927 
8928   }
8929 
8930   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8931   std::vector<SDValue> AsmNodeOperands;
8932   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8933   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8934       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8935 
8936   // If we have a !srcloc metadata node associated with it, we want to attach
8937   // this to the ultimately generated inline asm machineinstr.  To do this, we
8938   // pass in the third operand as this (potentially null) inline asm MDNode.
8939   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8940   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8941 
8942   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8943   // bits as operand 3.
8944   AsmNodeOperands.push_back(DAG.getTargetConstant(
8945       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8946 
8947   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8948   // this, assign virtual and physical registers for inputs and otput.
8949   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8950     // Assign Registers.
8951     SDISelAsmOperandInfo &RefOpInfo =
8952         OpInfo.isMatchingInputConstraint()
8953             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8954             : OpInfo;
8955     const auto RegError =
8956         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8957     if (RegError) {
8958       const MachineFunction &MF = DAG.getMachineFunction();
8959       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8960       const char *RegName = TRI.getName(RegError.value());
8961       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8962                                    "' allocated for constraint '" +
8963                                    Twine(OpInfo.ConstraintCode) +
8964                                    "' does not match required type");
8965       return;
8966     }
8967 
8968     auto DetectWriteToReservedRegister = [&]() {
8969       const MachineFunction &MF = DAG.getMachineFunction();
8970       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8971       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8972         if (Register::isPhysicalRegister(Reg) &&
8973             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8974           const char *RegName = TRI.getName(Reg);
8975           emitInlineAsmError(Call, "write to reserved register '" +
8976                                        Twine(RegName) + "'");
8977           return true;
8978         }
8979       }
8980       return false;
8981     };
8982     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8983             (OpInfo.Type == InlineAsm::isInput &&
8984              !OpInfo.isMatchingInputConstraint())) &&
8985            "Only address as input operand is allowed.");
8986 
8987     switch (OpInfo.Type) {
8988     case InlineAsm::isOutput:
8989       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8990         unsigned ConstraintID =
8991             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8992         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8993                "Failed to convert memory constraint code to constraint id.");
8994 
8995         // Add information to the INLINEASM node to know about this output.
8996         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8997         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8998         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8999                                                         MVT::i32));
9000         AsmNodeOperands.push_back(OpInfo.CallOperand);
9001       } else {
9002         // Otherwise, this outputs to a register (directly for C_Register /
9003         // C_RegisterClass, and a target-defined fashion for
9004         // C_Immediate/C_Other). Find a register that we can use.
9005         if (OpInfo.AssignedRegs.Regs.empty()) {
9006           emitInlineAsmError(
9007               Call, "couldn't allocate output register for constraint '" +
9008                         Twine(OpInfo.ConstraintCode) + "'");
9009           return;
9010         }
9011 
9012         if (DetectWriteToReservedRegister())
9013           return;
9014 
9015         // Add information to the INLINEASM node to know that this register is
9016         // set.
9017         OpInfo.AssignedRegs.AddInlineAsmOperands(
9018             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9019                                   : InlineAsm::Kind_RegDef,
9020             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9021       }
9022       break;
9023 
9024     case InlineAsm::isInput:
9025     case InlineAsm::isLabel: {
9026       SDValue InOperandVal = OpInfo.CallOperand;
9027 
9028       if (OpInfo.isMatchingInputConstraint()) {
9029         // If this is required to match an output register we have already set,
9030         // just use its register.
9031         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9032                                                   AsmNodeOperands);
9033         unsigned OpFlag =
9034           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9035         if (InlineAsm::isRegDefKind(OpFlag) ||
9036             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9037           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9038           if (OpInfo.isIndirect) {
9039             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9040             emitInlineAsmError(Call, "inline asm not supported yet: "
9041                                      "don't know how to handle tied "
9042                                      "indirect register inputs");
9043             return;
9044           }
9045 
9046           SmallVector<unsigned, 4> Regs;
9047           MachineFunction &MF = DAG.getMachineFunction();
9048           MachineRegisterInfo &MRI = MF.getRegInfo();
9049           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9050           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9051           Register TiedReg = R->getReg();
9052           MVT RegVT = R->getSimpleValueType(0);
9053           const TargetRegisterClass *RC =
9054               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9055               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9056                                       : TRI.getMinimalPhysRegClass(TiedReg);
9057           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9058           for (unsigned i = 0; i != NumRegs; ++i)
9059             Regs.push_back(MRI.createVirtualRegister(RC));
9060 
9061           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9062 
9063           SDLoc dl = getCurSDLoc();
9064           // Use the produced MatchedRegs object to
9065           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9066           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9067                                            true, OpInfo.getMatchedOperand(), dl,
9068                                            DAG, AsmNodeOperands);
9069           break;
9070         }
9071 
9072         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9073         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9074                "Unexpected number of operands");
9075         // Add information to the INLINEASM node to know about this input.
9076         // See InlineAsm.h isUseOperandTiedToDef.
9077         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9078         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9079                                                     OpInfo.getMatchedOperand());
9080         AsmNodeOperands.push_back(DAG.getTargetConstant(
9081             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9082         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9083         break;
9084       }
9085 
9086       // Treat indirect 'X' constraint as memory.
9087       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9088           OpInfo.isIndirect)
9089         OpInfo.ConstraintType = TargetLowering::C_Memory;
9090 
9091       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9092           OpInfo.ConstraintType == TargetLowering::C_Other) {
9093         std::vector<SDValue> Ops;
9094         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9095                                           Ops, DAG);
9096         if (Ops.empty()) {
9097           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9098             if (isa<ConstantSDNode>(InOperandVal)) {
9099               emitInlineAsmError(Call, "value out of range for constraint '" +
9100                                            Twine(OpInfo.ConstraintCode) + "'");
9101               return;
9102             }
9103 
9104           emitInlineAsmError(Call,
9105                              "invalid operand for inline asm constraint '" +
9106                                  Twine(OpInfo.ConstraintCode) + "'");
9107           return;
9108         }
9109 
9110         // Add information to the INLINEASM node to know about this input.
9111         unsigned ResOpType =
9112           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9113         AsmNodeOperands.push_back(DAG.getTargetConstant(
9114             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9115         llvm::append_range(AsmNodeOperands, Ops);
9116         break;
9117       }
9118 
9119       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9120         assert((OpInfo.isIndirect ||
9121                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9122                "Operand must be indirect to be a mem!");
9123         assert(InOperandVal.getValueType() ==
9124                    TLI.getPointerTy(DAG.getDataLayout()) &&
9125                "Memory operands expect pointer values");
9126 
9127         unsigned ConstraintID =
9128             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9129         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9130                "Failed to convert memory constraint code to constraint id.");
9131 
9132         // Add information to the INLINEASM node to know about this input.
9133         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9134         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9135         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9136                                                         getCurSDLoc(),
9137                                                         MVT::i32));
9138         AsmNodeOperands.push_back(InOperandVal);
9139         break;
9140       }
9141 
9142       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9143         assert(InOperandVal.getValueType() ==
9144                    TLI.getPointerTy(DAG.getDataLayout()) &&
9145                "Address operands expect pointer values");
9146 
9147         unsigned ConstraintID =
9148             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9149         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9150                "Failed to convert memory constraint code to constraint id.");
9151 
9152         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9153 
9154         SDValue AsmOp = InOperandVal;
9155         if (isFunction(InOperandVal)) {
9156           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9157           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9158           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9159                                              InOperandVal.getValueType(),
9160                                              GA->getOffset());
9161         }
9162 
9163         // Add information to the INLINEASM node to know about this input.
9164         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9165 
9166         AsmNodeOperands.push_back(
9167             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9168 
9169         AsmNodeOperands.push_back(AsmOp);
9170         break;
9171       }
9172 
9173       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9174               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9175              "Unknown constraint type!");
9176 
9177       // TODO: Support this.
9178       if (OpInfo.isIndirect) {
9179         emitInlineAsmError(
9180             Call, "Don't know how to handle indirect register inputs yet "
9181                   "for constraint '" +
9182                       Twine(OpInfo.ConstraintCode) + "'");
9183         return;
9184       }
9185 
9186       // Copy the input into the appropriate registers.
9187       if (OpInfo.AssignedRegs.Regs.empty()) {
9188         emitInlineAsmError(Call,
9189                            "couldn't allocate input reg for constraint '" +
9190                                Twine(OpInfo.ConstraintCode) + "'");
9191         return;
9192       }
9193 
9194       if (DetectWriteToReservedRegister())
9195         return;
9196 
9197       SDLoc dl = getCurSDLoc();
9198 
9199       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9200                                         &Call);
9201 
9202       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9203                                                dl, DAG, AsmNodeOperands);
9204       break;
9205     }
9206     case InlineAsm::isClobber:
9207       // Add the clobbered value to the operand list, so that the register
9208       // allocator is aware that the physreg got clobbered.
9209       if (!OpInfo.AssignedRegs.Regs.empty())
9210         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9211                                                  false, 0, getCurSDLoc(), DAG,
9212                                                  AsmNodeOperands);
9213       break;
9214     }
9215   }
9216 
9217   // Finish up input operands.  Set the input chain and add the flag last.
9218   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9219   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9220 
9221   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9222   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9223                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9224   Flag = Chain.getValue(1);
9225 
9226   // Do additional work to generate outputs.
9227 
9228   SmallVector<EVT, 1> ResultVTs;
9229   SmallVector<SDValue, 1> ResultValues;
9230   SmallVector<SDValue, 8> OutChains;
9231 
9232   llvm::Type *CallResultType = Call.getType();
9233   ArrayRef<Type *> ResultTypes;
9234   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9235     ResultTypes = StructResult->elements();
9236   else if (!CallResultType->isVoidTy())
9237     ResultTypes = makeArrayRef(CallResultType);
9238 
9239   auto CurResultType = ResultTypes.begin();
9240   auto handleRegAssign = [&](SDValue V) {
9241     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9242     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9243     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9244     ++CurResultType;
9245     // If the type of the inline asm call site return value is different but has
9246     // same size as the type of the asm output bitcast it.  One example of this
9247     // is for vectors with different width / number of elements.  This can
9248     // happen for register classes that can contain multiple different value
9249     // types.  The preg or vreg allocated may not have the same VT as was
9250     // expected.
9251     //
9252     // This can also happen for a return value that disagrees with the register
9253     // class it is put in, eg. a double in a general-purpose register on a
9254     // 32-bit machine.
9255     if (ResultVT != V.getValueType() &&
9256         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9257       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9258     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9259              V.getValueType().isInteger()) {
9260       // If a result value was tied to an input value, the computed result
9261       // may have a wider width than the expected result.  Extract the
9262       // relevant portion.
9263       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9264     }
9265     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9266     ResultVTs.push_back(ResultVT);
9267     ResultValues.push_back(V);
9268   };
9269 
9270   // Deal with output operands.
9271   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9272     if (OpInfo.Type == InlineAsm::isOutput) {
9273       SDValue Val;
9274       // Skip trivial output operands.
9275       if (OpInfo.AssignedRegs.Regs.empty())
9276         continue;
9277 
9278       switch (OpInfo.ConstraintType) {
9279       case TargetLowering::C_Register:
9280       case TargetLowering::C_RegisterClass:
9281         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9282                                                   Chain, &Flag, &Call);
9283         break;
9284       case TargetLowering::C_Immediate:
9285       case TargetLowering::C_Other:
9286         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9287                                               OpInfo, DAG);
9288         break;
9289       case TargetLowering::C_Memory:
9290         break; // Already handled.
9291       case TargetLowering::C_Address:
9292         break; // Silence warning.
9293       case TargetLowering::C_Unknown:
9294         assert(false && "Unexpected unknown constraint");
9295       }
9296 
9297       // Indirect output manifest as stores. Record output chains.
9298       if (OpInfo.isIndirect) {
9299         const Value *Ptr = OpInfo.CallOperandVal;
9300         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9301         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9302                                      MachinePointerInfo(Ptr));
9303         OutChains.push_back(Store);
9304       } else {
9305         // generate CopyFromRegs to associated registers.
9306         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9307         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9308           for (const SDValue &V : Val->op_values())
9309             handleRegAssign(V);
9310         } else
9311           handleRegAssign(Val);
9312       }
9313     }
9314   }
9315 
9316   // Set results.
9317   if (!ResultValues.empty()) {
9318     assert(CurResultType == ResultTypes.end() &&
9319            "Mismatch in number of ResultTypes");
9320     assert(ResultValues.size() == ResultTypes.size() &&
9321            "Mismatch in number of output operands in asm result");
9322 
9323     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9324                             DAG.getVTList(ResultVTs), ResultValues);
9325     setValue(&Call, V);
9326   }
9327 
9328   // Collect store chains.
9329   if (!OutChains.empty())
9330     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9331 
9332   if (EmitEHLabels) {
9333     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9334   }
9335 
9336   // Only Update Root if inline assembly has a memory effect.
9337   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9338       EmitEHLabels)
9339     DAG.setRoot(Chain);
9340 }
9341 
9342 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9343                                              const Twine &Message) {
9344   LLVMContext &Ctx = *DAG.getContext();
9345   Ctx.emitError(&Call, Message);
9346 
9347   // Make sure we leave the DAG in a valid state
9348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9349   SmallVector<EVT, 1> ValueVTs;
9350   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9351 
9352   if (ValueVTs.empty())
9353     return;
9354 
9355   SmallVector<SDValue, 1> Ops;
9356   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9357     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9358 
9359   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9360 }
9361 
9362 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9363   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9364                           MVT::Other, getRoot(),
9365                           getValue(I.getArgOperand(0)),
9366                           DAG.getSrcValue(I.getArgOperand(0))));
9367 }
9368 
9369 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9370   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9371   const DataLayout &DL = DAG.getDataLayout();
9372   SDValue V = DAG.getVAArg(
9373       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9374       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9375       DL.getABITypeAlign(I.getType()).value());
9376   DAG.setRoot(V.getValue(1));
9377 
9378   if (I.getType()->isPointerTy())
9379     V = DAG.getPtrExtOrTrunc(
9380         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9381   setValue(&I, V);
9382 }
9383 
9384 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9385   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9386                           MVT::Other, getRoot(),
9387                           getValue(I.getArgOperand(0)),
9388                           DAG.getSrcValue(I.getArgOperand(0))));
9389 }
9390 
9391 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9392   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9393                           MVT::Other, getRoot(),
9394                           getValue(I.getArgOperand(0)),
9395                           getValue(I.getArgOperand(1)),
9396                           DAG.getSrcValue(I.getArgOperand(0)),
9397                           DAG.getSrcValue(I.getArgOperand(1))));
9398 }
9399 
9400 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9401                                                     const Instruction &I,
9402                                                     SDValue Op) {
9403   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9404   if (!Range)
9405     return Op;
9406 
9407   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9408   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9409     return Op;
9410 
9411   APInt Lo = CR.getUnsignedMin();
9412   if (!Lo.isMinValue())
9413     return Op;
9414 
9415   APInt Hi = CR.getUnsignedMax();
9416   unsigned Bits = std::max(Hi.getActiveBits(),
9417                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9418 
9419   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9420 
9421   SDLoc SL = getCurSDLoc();
9422 
9423   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9424                              DAG.getValueType(SmallVT));
9425   unsigned NumVals = Op.getNode()->getNumValues();
9426   if (NumVals == 1)
9427     return ZExt;
9428 
9429   SmallVector<SDValue, 4> Ops;
9430 
9431   Ops.push_back(ZExt);
9432   for (unsigned I = 1; I != NumVals; ++I)
9433     Ops.push_back(Op.getValue(I));
9434 
9435   return DAG.getMergeValues(Ops, SL);
9436 }
9437 
9438 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9439 /// the call being lowered.
9440 ///
9441 /// This is a helper for lowering intrinsics that follow a target calling
9442 /// convention or require stack pointer adjustment. Only a subset of the
9443 /// intrinsic's operands need to participate in the calling convention.
9444 void SelectionDAGBuilder::populateCallLoweringInfo(
9445     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9446     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9447     bool IsPatchPoint) {
9448   TargetLowering::ArgListTy Args;
9449   Args.reserve(NumArgs);
9450 
9451   // Populate the argument list.
9452   // Attributes for args start at offset 1, after the return attribute.
9453   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9454        ArgI != ArgE; ++ArgI) {
9455     const Value *V = Call->getOperand(ArgI);
9456 
9457     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9458 
9459     TargetLowering::ArgListEntry Entry;
9460     Entry.Node = getValue(V);
9461     Entry.Ty = V->getType();
9462     Entry.setAttributes(Call, ArgI);
9463     Args.push_back(Entry);
9464   }
9465 
9466   CLI.setDebugLoc(getCurSDLoc())
9467       .setChain(getRoot())
9468       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9469       .setDiscardResult(Call->use_empty())
9470       .setIsPatchPoint(IsPatchPoint)
9471       .setIsPreallocated(
9472           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9473 }
9474 
9475 /// Add a stack map intrinsic call's live variable operands to a stackmap
9476 /// or patchpoint target node's operand list.
9477 ///
9478 /// Constants are converted to TargetConstants purely as an optimization to
9479 /// avoid constant materialization and register allocation.
9480 ///
9481 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9482 /// generate addess computation nodes, and so FinalizeISel can convert the
9483 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9484 /// address materialization and register allocation, but may also be required
9485 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9486 /// alloca in the entry block, then the runtime may assume that the alloca's
9487 /// StackMap location can be read immediately after compilation and that the
9488 /// location is valid at any point during execution (this is similar to the
9489 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9490 /// only available in a register, then the runtime would need to trap when
9491 /// execution reaches the StackMap in order to read the alloca's location.
9492 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9493                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9494                                 SelectionDAGBuilder &Builder) {
9495   SelectionDAG &DAG = Builder.DAG;
9496   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9497     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9498 
9499     // Things on the stack are pointer-typed, meaning that they are already
9500     // legal and can be emitted directly to target nodes.
9501     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9502       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9503     } else {
9504       // Otherwise emit a target independent node to be legalised.
9505       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9506     }
9507   }
9508 }
9509 
9510 /// Lower llvm.experimental.stackmap.
9511 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9512   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9513   //                                  [live variables...])
9514 
9515   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9516 
9517   SDValue Chain, InFlag, Callee;
9518   SmallVector<SDValue, 32> Ops;
9519 
9520   SDLoc DL = getCurSDLoc();
9521   Callee = getValue(CI.getCalledOperand());
9522 
9523   // The stackmap intrinsic only records the live variables (the arguments
9524   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9525   // intrinsic, this won't be lowered to a function call. This means we don't
9526   // have to worry about calling conventions and target specific lowering code.
9527   // Instead we perform the call lowering right here.
9528   //
9529   // chain, flag = CALLSEQ_START(chain, 0, 0)
9530   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9531   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9532   //
9533   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9534   InFlag = Chain.getValue(1);
9535 
9536   // Add the STACKMAP operands, starting with DAG house-keeping.
9537   Ops.push_back(Chain);
9538   Ops.push_back(InFlag);
9539 
9540   // Add the <id>, <numShadowBytes> operands.
9541   //
9542   // These do not require legalisation, and can be emitted directly to target
9543   // constant nodes.
9544   SDValue ID = getValue(CI.getArgOperand(0));
9545   assert(ID.getValueType() == MVT::i64);
9546   SDValue IDConst = DAG.getTargetConstant(
9547       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9548   Ops.push_back(IDConst);
9549 
9550   SDValue Shad = getValue(CI.getArgOperand(1));
9551   assert(Shad.getValueType() == MVT::i32);
9552   SDValue ShadConst = DAG.getTargetConstant(
9553       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9554   Ops.push_back(ShadConst);
9555 
9556   // Add the live variables.
9557   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9558 
9559   // Create the STACKMAP node.
9560   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9561   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9562   InFlag = Chain.getValue(1);
9563 
9564   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9565 
9566   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9567 
9568   // Set the root to the target-lowered call chain.
9569   DAG.setRoot(Chain);
9570 
9571   // Inform the Frame Information that we have a stackmap in this function.
9572   FuncInfo.MF->getFrameInfo().setHasStackMap();
9573 }
9574 
9575 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9576 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9577                                           const BasicBlock *EHPadBB) {
9578   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9579   //                                                 i32 <numBytes>,
9580   //                                                 i8* <target>,
9581   //                                                 i32 <numArgs>,
9582   //                                                 [Args...],
9583   //                                                 [live variables...])
9584 
9585   CallingConv::ID CC = CB.getCallingConv();
9586   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9587   bool HasDef = !CB.getType()->isVoidTy();
9588   SDLoc dl = getCurSDLoc();
9589   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9590 
9591   // Handle immediate and symbolic callees.
9592   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9593     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9594                                    /*isTarget=*/true);
9595   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9596     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9597                                          SDLoc(SymbolicCallee),
9598                                          SymbolicCallee->getValueType(0));
9599 
9600   // Get the real number of arguments participating in the call <numArgs>
9601   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9602   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9603 
9604   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9605   // Intrinsics include all meta-operands up to but not including CC.
9606   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9607   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9608          "Not enough arguments provided to the patchpoint intrinsic");
9609 
9610   // For AnyRegCC the arguments are lowered later on manually.
9611   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9612   Type *ReturnTy =
9613       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9614 
9615   TargetLowering::CallLoweringInfo CLI(DAG);
9616   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9617                            ReturnTy, true);
9618   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9619 
9620   SDNode *CallEnd = Result.second.getNode();
9621   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9622     CallEnd = CallEnd->getOperand(0).getNode();
9623 
9624   /// Get a call instruction from the call sequence chain.
9625   /// Tail calls are not allowed.
9626   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9627          "Expected a callseq node.");
9628   SDNode *Call = CallEnd->getOperand(0).getNode();
9629   bool HasGlue = Call->getGluedNode();
9630 
9631   // Replace the target specific call node with the patchable intrinsic.
9632   SmallVector<SDValue, 8> Ops;
9633 
9634   // Push the chain.
9635   Ops.push_back(*(Call->op_begin()));
9636 
9637   // Optionally, push the glue (if any).
9638   if (HasGlue)
9639     Ops.push_back(*(Call->op_end() - 1));
9640 
9641   // Push the register mask info.
9642   if (HasGlue)
9643     Ops.push_back(*(Call->op_end() - 2));
9644   else
9645     Ops.push_back(*(Call->op_end() - 1));
9646 
9647   // Add the <id> and <numBytes> constants.
9648   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9649   Ops.push_back(DAG.getTargetConstant(
9650                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9651   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9652   Ops.push_back(DAG.getTargetConstant(
9653                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9654                   MVT::i32));
9655 
9656   // Add the callee.
9657   Ops.push_back(Callee);
9658 
9659   // Adjust <numArgs> to account for any arguments that have been passed on the
9660   // stack instead.
9661   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9662   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9663   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9664   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9665 
9666   // Add the calling convention
9667   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9668 
9669   // Add the arguments we omitted previously. The register allocator should
9670   // place these in any free register.
9671   if (IsAnyRegCC)
9672     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9673       Ops.push_back(getValue(CB.getArgOperand(i)));
9674 
9675   // Push the arguments from the call instruction.
9676   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9677   Ops.append(Call->op_begin() + 2, e);
9678 
9679   // Push live variables for the stack map.
9680   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9681 
9682   SDVTList NodeTys;
9683   if (IsAnyRegCC && HasDef) {
9684     // Create the return types based on the intrinsic definition
9685     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9686     SmallVector<EVT, 3> ValueVTs;
9687     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9688     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9689 
9690     // There is always a chain and a glue type at the end
9691     ValueVTs.push_back(MVT::Other);
9692     ValueVTs.push_back(MVT::Glue);
9693     NodeTys = DAG.getVTList(ValueVTs);
9694   } else
9695     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9696 
9697   // Replace the target specific call node with a PATCHPOINT node.
9698   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9699 
9700   // Update the NodeMap.
9701   if (HasDef) {
9702     if (IsAnyRegCC)
9703       setValue(&CB, SDValue(PPV.getNode(), 0));
9704     else
9705       setValue(&CB, Result.first);
9706   }
9707 
9708   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9709   // call sequence. Furthermore the location of the chain and glue can change
9710   // when the AnyReg calling convention is used and the intrinsic returns a
9711   // value.
9712   if (IsAnyRegCC && HasDef) {
9713     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9714     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9715     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9716   } else
9717     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9718   DAG.DeleteNode(Call);
9719 
9720   // Inform the Frame Information that we have a patchpoint in this function.
9721   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9722 }
9723 
9724 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9725                                             unsigned Intrinsic) {
9726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9727   SDValue Op1 = getValue(I.getArgOperand(0));
9728   SDValue Op2;
9729   if (I.arg_size() > 1)
9730     Op2 = getValue(I.getArgOperand(1));
9731   SDLoc dl = getCurSDLoc();
9732   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9733   SDValue Res;
9734   SDNodeFlags SDFlags;
9735   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9736     SDFlags.copyFMF(*FPMO);
9737 
9738   switch (Intrinsic) {
9739   case Intrinsic::vector_reduce_fadd:
9740     if (SDFlags.hasAllowReassociation())
9741       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9742                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9743                         SDFlags);
9744     else
9745       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9746     break;
9747   case Intrinsic::vector_reduce_fmul:
9748     if (SDFlags.hasAllowReassociation())
9749       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9750                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9751                         SDFlags);
9752     else
9753       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9754     break;
9755   case Intrinsic::vector_reduce_add:
9756     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9757     break;
9758   case Intrinsic::vector_reduce_mul:
9759     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9760     break;
9761   case Intrinsic::vector_reduce_and:
9762     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9763     break;
9764   case Intrinsic::vector_reduce_or:
9765     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9766     break;
9767   case Intrinsic::vector_reduce_xor:
9768     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9769     break;
9770   case Intrinsic::vector_reduce_smax:
9771     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9772     break;
9773   case Intrinsic::vector_reduce_smin:
9774     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9775     break;
9776   case Intrinsic::vector_reduce_umax:
9777     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9778     break;
9779   case Intrinsic::vector_reduce_umin:
9780     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9781     break;
9782   case Intrinsic::vector_reduce_fmax:
9783     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9784     break;
9785   case Intrinsic::vector_reduce_fmin:
9786     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9787     break;
9788   default:
9789     llvm_unreachable("Unhandled vector reduce intrinsic");
9790   }
9791   setValue(&I, Res);
9792 }
9793 
9794 /// Returns an AttributeList representing the attributes applied to the return
9795 /// value of the given call.
9796 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9797   SmallVector<Attribute::AttrKind, 2> Attrs;
9798   if (CLI.RetSExt)
9799     Attrs.push_back(Attribute::SExt);
9800   if (CLI.RetZExt)
9801     Attrs.push_back(Attribute::ZExt);
9802   if (CLI.IsInReg)
9803     Attrs.push_back(Attribute::InReg);
9804 
9805   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9806                             Attrs);
9807 }
9808 
9809 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9810 /// implementation, which just calls LowerCall.
9811 /// FIXME: When all targets are
9812 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9813 std::pair<SDValue, SDValue>
9814 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9815   // Handle the incoming return values from the call.
9816   CLI.Ins.clear();
9817   Type *OrigRetTy = CLI.RetTy;
9818   SmallVector<EVT, 4> RetTys;
9819   SmallVector<uint64_t, 4> Offsets;
9820   auto &DL = CLI.DAG.getDataLayout();
9821   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9822 
9823   if (CLI.IsPostTypeLegalization) {
9824     // If we are lowering a libcall after legalization, split the return type.
9825     SmallVector<EVT, 4> OldRetTys;
9826     SmallVector<uint64_t, 4> OldOffsets;
9827     RetTys.swap(OldRetTys);
9828     Offsets.swap(OldOffsets);
9829 
9830     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9831       EVT RetVT = OldRetTys[i];
9832       uint64_t Offset = OldOffsets[i];
9833       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9834       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9835       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9836       RetTys.append(NumRegs, RegisterVT);
9837       for (unsigned j = 0; j != NumRegs; ++j)
9838         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9839     }
9840   }
9841 
9842   SmallVector<ISD::OutputArg, 4> Outs;
9843   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9844 
9845   bool CanLowerReturn =
9846       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9847                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9848 
9849   SDValue DemoteStackSlot;
9850   int DemoteStackIdx = -100;
9851   if (!CanLowerReturn) {
9852     // FIXME: equivalent assert?
9853     // assert(!CS.hasInAllocaArgument() &&
9854     //        "sret demotion is incompatible with inalloca");
9855     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9856     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9857     MachineFunction &MF = CLI.DAG.getMachineFunction();
9858     DemoteStackIdx =
9859         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9860     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9861                                               DL.getAllocaAddrSpace());
9862 
9863     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9864     ArgListEntry Entry;
9865     Entry.Node = DemoteStackSlot;
9866     Entry.Ty = StackSlotPtrType;
9867     Entry.IsSExt = false;
9868     Entry.IsZExt = false;
9869     Entry.IsInReg = false;
9870     Entry.IsSRet = true;
9871     Entry.IsNest = false;
9872     Entry.IsByVal = false;
9873     Entry.IsByRef = false;
9874     Entry.IsReturned = false;
9875     Entry.IsSwiftSelf = false;
9876     Entry.IsSwiftAsync = false;
9877     Entry.IsSwiftError = false;
9878     Entry.IsCFGuardTarget = false;
9879     Entry.Alignment = Alignment;
9880     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9881     CLI.NumFixedArgs += 1;
9882     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9883     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9884 
9885     // sret demotion isn't compatible with tail-calls, since the sret argument
9886     // points into the callers stack frame.
9887     CLI.IsTailCall = false;
9888   } else {
9889     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9890         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9891     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9892       ISD::ArgFlagsTy Flags;
9893       if (NeedsRegBlock) {
9894         Flags.setInConsecutiveRegs();
9895         if (I == RetTys.size() - 1)
9896           Flags.setInConsecutiveRegsLast();
9897       }
9898       EVT VT = RetTys[I];
9899       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9900                                                      CLI.CallConv, VT);
9901       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9902                                                        CLI.CallConv, VT);
9903       for (unsigned i = 0; i != NumRegs; ++i) {
9904         ISD::InputArg MyFlags;
9905         MyFlags.Flags = Flags;
9906         MyFlags.VT = RegisterVT;
9907         MyFlags.ArgVT = VT;
9908         MyFlags.Used = CLI.IsReturnValueUsed;
9909         if (CLI.RetTy->isPointerTy()) {
9910           MyFlags.Flags.setPointer();
9911           MyFlags.Flags.setPointerAddrSpace(
9912               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9913         }
9914         if (CLI.RetSExt)
9915           MyFlags.Flags.setSExt();
9916         if (CLI.RetZExt)
9917           MyFlags.Flags.setZExt();
9918         if (CLI.IsInReg)
9919           MyFlags.Flags.setInReg();
9920         CLI.Ins.push_back(MyFlags);
9921       }
9922     }
9923   }
9924 
9925   // We push in swifterror return as the last element of CLI.Ins.
9926   ArgListTy &Args = CLI.getArgs();
9927   if (supportSwiftError()) {
9928     for (const ArgListEntry &Arg : Args) {
9929       if (Arg.IsSwiftError) {
9930         ISD::InputArg MyFlags;
9931         MyFlags.VT = getPointerTy(DL);
9932         MyFlags.ArgVT = EVT(getPointerTy(DL));
9933         MyFlags.Flags.setSwiftError();
9934         CLI.Ins.push_back(MyFlags);
9935       }
9936     }
9937   }
9938 
9939   // Handle all of the outgoing arguments.
9940   CLI.Outs.clear();
9941   CLI.OutVals.clear();
9942   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9943     SmallVector<EVT, 4> ValueVTs;
9944     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9945     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9946     Type *FinalType = Args[i].Ty;
9947     if (Args[i].IsByVal)
9948       FinalType = Args[i].IndirectType;
9949     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9950         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9951     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9952          ++Value) {
9953       EVT VT = ValueVTs[Value];
9954       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9955       SDValue Op = SDValue(Args[i].Node.getNode(),
9956                            Args[i].Node.getResNo() + Value);
9957       ISD::ArgFlagsTy Flags;
9958 
9959       // Certain targets (such as MIPS), may have a different ABI alignment
9960       // for a type depending on the context. Give the target a chance to
9961       // specify the alignment it wants.
9962       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9963       Flags.setOrigAlign(OriginalAlignment);
9964 
9965       if (Args[i].Ty->isPointerTy()) {
9966         Flags.setPointer();
9967         Flags.setPointerAddrSpace(
9968             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9969       }
9970       if (Args[i].IsZExt)
9971         Flags.setZExt();
9972       if (Args[i].IsSExt)
9973         Flags.setSExt();
9974       if (Args[i].IsInReg) {
9975         // If we are using vectorcall calling convention, a structure that is
9976         // passed InReg - is surely an HVA
9977         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9978             isa<StructType>(FinalType)) {
9979           // The first value of a structure is marked
9980           if (0 == Value)
9981             Flags.setHvaStart();
9982           Flags.setHva();
9983         }
9984         // Set InReg Flag
9985         Flags.setInReg();
9986       }
9987       if (Args[i].IsSRet)
9988         Flags.setSRet();
9989       if (Args[i].IsSwiftSelf)
9990         Flags.setSwiftSelf();
9991       if (Args[i].IsSwiftAsync)
9992         Flags.setSwiftAsync();
9993       if (Args[i].IsSwiftError)
9994         Flags.setSwiftError();
9995       if (Args[i].IsCFGuardTarget)
9996         Flags.setCFGuardTarget();
9997       if (Args[i].IsByVal)
9998         Flags.setByVal();
9999       if (Args[i].IsByRef)
10000         Flags.setByRef();
10001       if (Args[i].IsPreallocated) {
10002         Flags.setPreallocated();
10003         // Set the byval flag for CCAssignFn callbacks that don't know about
10004         // preallocated.  This way we can know how many bytes we should've
10005         // allocated and how many bytes a callee cleanup function will pop.  If
10006         // we port preallocated to more targets, we'll have to add custom
10007         // preallocated handling in the various CC lowering callbacks.
10008         Flags.setByVal();
10009       }
10010       if (Args[i].IsInAlloca) {
10011         Flags.setInAlloca();
10012         // Set the byval flag for CCAssignFn callbacks that don't know about
10013         // inalloca.  This way we can know how many bytes we should've allocated
10014         // and how many bytes a callee cleanup function will pop.  If we port
10015         // inalloca to more targets, we'll have to add custom inalloca handling
10016         // in the various CC lowering callbacks.
10017         Flags.setByVal();
10018       }
10019       Align MemAlign;
10020       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10021         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10022         Flags.setByValSize(FrameSize);
10023 
10024         // info is not there but there are cases it cannot get right.
10025         if (auto MA = Args[i].Alignment)
10026           MemAlign = *MA;
10027         else
10028           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10029       } else if (auto MA = Args[i].Alignment) {
10030         MemAlign = *MA;
10031       } else {
10032         MemAlign = OriginalAlignment;
10033       }
10034       Flags.setMemAlign(MemAlign);
10035       if (Args[i].IsNest)
10036         Flags.setNest();
10037       if (NeedsRegBlock)
10038         Flags.setInConsecutiveRegs();
10039 
10040       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10041                                                  CLI.CallConv, VT);
10042       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10043                                                         CLI.CallConv, VT);
10044       SmallVector<SDValue, 4> Parts(NumParts);
10045       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10046 
10047       if (Args[i].IsSExt)
10048         ExtendKind = ISD::SIGN_EXTEND;
10049       else if (Args[i].IsZExt)
10050         ExtendKind = ISD::ZERO_EXTEND;
10051 
10052       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10053       // for now.
10054       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10055           CanLowerReturn) {
10056         assert((CLI.RetTy == Args[i].Ty ||
10057                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10058                  CLI.RetTy->getPointerAddressSpace() ==
10059                      Args[i].Ty->getPointerAddressSpace())) &&
10060                RetTys.size() == NumValues && "unexpected use of 'returned'");
10061         // Before passing 'returned' to the target lowering code, ensure that
10062         // either the register MVT and the actual EVT are the same size or that
10063         // the return value and argument are extended in the same way; in these
10064         // cases it's safe to pass the argument register value unchanged as the
10065         // return register value (although it's at the target's option whether
10066         // to do so)
10067         // TODO: allow code generation to take advantage of partially preserved
10068         // registers rather than clobbering the entire register when the
10069         // parameter extension method is not compatible with the return
10070         // extension method
10071         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10072             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10073              CLI.RetZExt == Args[i].IsZExt))
10074           Flags.setReturned();
10075       }
10076 
10077       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10078                      CLI.CallConv, ExtendKind);
10079 
10080       for (unsigned j = 0; j != NumParts; ++j) {
10081         // if it isn't first piece, alignment must be 1
10082         // For scalable vectors the scalable part is currently handled
10083         // by individual targets, so we just use the known minimum size here.
10084         ISD::OutputArg MyFlags(
10085             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10086             i < CLI.NumFixedArgs, i,
10087             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
10088         if (NumParts > 1 && j == 0)
10089           MyFlags.Flags.setSplit();
10090         else if (j != 0) {
10091           MyFlags.Flags.setOrigAlign(Align(1));
10092           if (j == NumParts - 1)
10093             MyFlags.Flags.setSplitEnd();
10094         }
10095 
10096         CLI.Outs.push_back(MyFlags);
10097         CLI.OutVals.push_back(Parts[j]);
10098       }
10099 
10100       if (NeedsRegBlock && Value == NumValues - 1)
10101         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10102     }
10103   }
10104 
10105   SmallVector<SDValue, 4> InVals;
10106   CLI.Chain = LowerCall(CLI, InVals);
10107 
10108   // Update CLI.InVals to use outside of this function.
10109   CLI.InVals = InVals;
10110 
10111   // Verify that the target's LowerCall behaved as expected.
10112   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10113          "LowerCall didn't return a valid chain!");
10114   assert((!CLI.IsTailCall || InVals.empty()) &&
10115          "LowerCall emitted a return value for a tail call!");
10116   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10117          "LowerCall didn't emit the correct number of values!");
10118 
10119   // For a tail call, the return value is merely live-out and there aren't
10120   // any nodes in the DAG representing it. Return a special value to
10121   // indicate that a tail call has been emitted and no more Instructions
10122   // should be processed in the current block.
10123   if (CLI.IsTailCall) {
10124     CLI.DAG.setRoot(CLI.Chain);
10125     return std::make_pair(SDValue(), SDValue());
10126   }
10127 
10128 #ifndef NDEBUG
10129   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10130     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10131     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10132            "LowerCall emitted a value with the wrong type!");
10133   }
10134 #endif
10135 
10136   SmallVector<SDValue, 4> ReturnValues;
10137   if (!CanLowerReturn) {
10138     // The instruction result is the result of loading from the
10139     // hidden sret parameter.
10140     SmallVector<EVT, 1> PVTs;
10141     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10142 
10143     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10144     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10145     EVT PtrVT = PVTs[0];
10146 
10147     unsigned NumValues = RetTys.size();
10148     ReturnValues.resize(NumValues);
10149     SmallVector<SDValue, 4> Chains(NumValues);
10150 
10151     // An aggregate return value cannot wrap around the address space, so
10152     // offsets to its parts don't wrap either.
10153     SDNodeFlags Flags;
10154     Flags.setNoUnsignedWrap(true);
10155 
10156     MachineFunction &MF = CLI.DAG.getMachineFunction();
10157     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10158     for (unsigned i = 0; i < NumValues; ++i) {
10159       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10160                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10161                                                         PtrVT), Flags);
10162       SDValue L = CLI.DAG.getLoad(
10163           RetTys[i], CLI.DL, CLI.Chain, Add,
10164           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10165                                             DemoteStackIdx, Offsets[i]),
10166           HiddenSRetAlign);
10167       ReturnValues[i] = L;
10168       Chains[i] = L.getValue(1);
10169     }
10170 
10171     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10172   } else {
10173     // Collect the legal value parts into potentially illegal values
10174     // that correspond to the original function's return values.
10175     Optional<ISD::NodeType> AssertOp;
10176     if (CLI.RetSExt)
10177       AssertOp = ISD::AssertSext;
10178     else if (CLI.RetZExt)
10179       AssertOp = ISD::AssertZext;
10180     unsigned CurReg = 0;
10181     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10182       EVT VT = RetTys[I];
10183       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10184                                                      CLI.CallConv, VT);
10185       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10186                                                        CLI.CallConv, VT);
10187 
10188       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10189                                               NumRegs, RegisterVT, VT, nullptr,
10190                                               CLI.CallConv, AssertOp));
10191       CurReg += NumRegs;
10192     }
10193 
10194     // For a function returning void, there is no return value. We can't create
10195     // such a node, so we just return a null return value in that case. In
10196     // that case, nothing will actually look at the value.
10197     if (ReturnValues.empty())
10198       return std::make_pair(SDValue(), CLI.Chain);
10199   }
10200 
10201   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10202                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10203   return std::make_pair(Res, CLI.Chain);
10204 }
10205 
10206 /// Places new result values for the node in Results (their number
10207 /// and types must exactly match those of the original return values of
10208 /// the node), or leaves Results empty, which indicates that the node is not
10209 /// to be custom lowered after all.
10210 void TargetLowering::LowerOperationWrapper(SDNode *N,
10211                                            SmallVectorImpl<SDValue> &Results,
10212                                            SelectionDAG &DAG) const {
10213   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10214 
10215   if (!Res.getNode())
10216     return;
10217 
10218   // If the original node has one result, take the return value from
10219   // LowerOperation as is. It might not be result number 0.
10220   if (N->getNumValues() == 1) {
10221     Results.push_back(Res);
10222     return;
10223   }
10224 
10225   // If the original node has multiple results, then the return node should
10226   // have the same number of results.
10227   assert((N->getNumValues() == Res->getNumValues()) &&
10228       "Lowering returned the wrong number of results!");
10229 
10230   // Places new result values base on N result number.
10231   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10232     Results.push_back(Res.getValue(I));
10233 }
10234 
10235 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10236   llvm_unreachable("LowerOperation not implemented for this target!");
10237 }
10238 
10239 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10240                                                      unsigned Reg,
10241                                                      ISD::NodeType ExtendType) {
10242   SDValue Op = getNonRegisterValue(V);
10243   assert((Op.getOpcode() != ISD::CopyFromReg ||
10244           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10245          "Copy from a reg to the same reg!");
10246   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10247 
10248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10249   // If this is an InlineAsm we have to match the registers required, not the
10250   // notional registers required by the type.
10251 
10252   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10253                    None); // This is not an ABI copy.
10254   SDValue Chain = DAG.getEntryNode();
10255 
10256   if (ExtendType == ISD::ANY_EXTEND) {
10257     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10258     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10259       ExtendType = PreferredExtendIt->second;
10260   }
10261   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10262   PendingExports.push_back(Chain);
10263 }
10264 
10265 #include "llvm/CodeGen/SelectionDAGISel.h"
10266 
10267 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10268 /// entry block, return true.  This includes arguments used by switches, since
10269 /// the switch may expand into multiple basic blocks.
10270 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10271   // With FastISel active, we may be splitting blocks, so force creation
10272   // of virtual registers for all non-dead arguments.
10273   if (FastISel)
10274     return A->use_empty();
10275 
10276   const BasicBlock &Entry = A->getParent()->front();
10277   for (const User *U : A->users())
10278     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10279       return false;  // Use not in entry block.
10280 
10281   return true;
10282 }
10283 
10284 using ArgCopyElisionMapTy =
10285     DenseMap<const Argument *,
10286              std::pair<const AllocaInst *, const StoreInst *>>;
10287 
10288 /// Scan the entry block of the function in FuncInfo for arguments that look
10289 /// like copies into a local alloca. Record any copied arguments in
10290 /// ArgCopyElisionCandidates.
10291 static void
10292 findArgumentCopyElisionCandidates(const DataLayout &DL,
10293                                   FunctionLoweringInfo *FuncInfo,
10294                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10295   // Record the state of every static alloca used in the entry block. Argument
10296   // allocas are all used in the entry block, so we need approximately as many
10297   // entries as we have arguments.
10298   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10299   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10300   unsigned NumArgs = FuncInfo->Fn->arg_size();
10301   StaticAllocas.reserve(NumArgs * 2);
10302 
10303   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10304     if (!V)
10305       return nullptr;
10306     V = V->stripPointerCasts();
10307     const auto *AI = dyn_cast<AllocaInst>(V);
10308     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10309       return nullptr;
10310     auto Iter = StaticAllocas.insert({AI, Unknown});
10311     return &Iter.first->second;
10312   };
10313 
10314   // Look for stores of arguments to static allocas. Look through bitcasts and
10315   // GEPs to handle type coercions, as long as the alloca is fully initialized
10316   // by the store. Any non-store use of an alloca escapes it and any subsequent
10317   // unanalyzed store might write it.
10318   // FIXME: Handle structs initialized with multiple stores.
10319   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10320     // Look for stores, and handle non-store uses conservatively.
10321     const auto *SI = dyn_cast<StoreInst>(&I);
10322     if (!SI) {
10323       // We will look through cast uses, so ignore them completely.
10324       if (I.isCast())
10325         continue;
10326       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10327       // to allocas.
10328       if (I.isDebugOrPseudoInst())
10329         continue;
10330       // This is an unknown instruction. Assume it escapes or writes to all
10331       // static alloca operands.
10332       for (const Use &U : I.operands()) {
10333         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10334           *Info = StaticAllocaInfo::Clobbered;
10335       }
10336       continue;
10337     }
10338 
10339     // If the stored value is a static alloca, mark it as escaped.
10340     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10341       *Info = StaticAllocaInfo::Clobbered;
10342 
10343     // Check if the destination is a static alloca.
10344     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10345     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10346     if (!Info)
10347       continue;
10348     const AllocaInst *AI = cast<AllocaInst>(Dst);
10349 
10350     // Skip allocas that have been initialized or clobbered.
10351     if (*Info != StaticAllocaInfo::Unknown)
10352       continue;
10353 
10354     // Check if the stored value is an argument, and that this store fully
10355     // initializes the alloca.
10356     // If the argument type has padding bits we can't directly forward a pointer
10357     // as the upper bits may contain garbage.
10358     // Don't elide copies from the same argument twice.
10359     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10360     const auto *Arg = dyn_cast<Argument>(Val);
10361     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10362         Arg->getType()->isEmptyTy() ||
10363         DL.getTypeStoreSize(Arg->getType()) !=
10364             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10365         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10366         ArgCopyElisionCandidates.count(Arg)) {
10367       *Info = StaticAllocaInfo::Clobbered;
10368       continue;
10369     }
10370 
10371     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10372                       << '\n');
10373 
10374     // Mark this alloca and store for argument copy elision.
10375     *Info = StaticAllocaInfo::Elidable;
10376     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10377 
10378     // Stop scanning if we've seen all arguments. This will happen early in -O0
10379     // builds, which is useful, because -O0 builds have large entry blocks and
10380     // many allocas.
10381     if (ArgCopyElisionCandidates.size() == NumArgs)
10382       break;
10383   }
10384 }
10385 
10386 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10387 /// ArgVal is a load from a suitable fixed stack object.
10388 static void tryToElideArgumentCopy(
10389     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10390     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10391     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10392     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10393     SDValue ArgVal, bool &ArgHasUses) {
10394   // Check if this is a load from a fixed stack object.
10395   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10396   if (!LNode)
10397     return;
10398   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10399   if (!FINode)
10400     return;
10401 
10402   // Check that the fixed stack object is the right size and alignment.
10403   // Look at the alignment that the user wrote on the alloca instead of looking
10404   // at the stack object.
10405   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10406   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10407   const AllocaInst *AI = ArgCopyIter->second.first;
10408   int FixedIndex = FINode->getIndex();
10409   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10410   int OldIndex = AllocaIndex;
10411   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10412   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10413     LLVM_DEBUG(
10414         dbgs() << "  argument copy elision failed due to bad fixed stack "
10415                   "object size\n");
10416     return;
10417   }
10418   Align RequiredAlignment = AI->getAlign();
10419   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10420     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10421                          "greater than stack argument alignment ("
10422                       << DebugStr(RequiredAlignment) << " vs "
10423                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10424     return;
10425   }
10426 
10427   // Perform the elision. Delete the old stack object and replace its only use
10428   // in the variable info map. Mark the stack object as mutable.
10429   LLVM_DEBUG({
10430     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10431            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10432            << '\n';
10433   });
10434   MFI.RemoveStackObject(OldIndex);
10435   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10436   AllocaIndex = FixedIndex;
10437   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10438   Chains.push_back(ArgVal.getValue(1));
10439 
10440   // Avoid emitting code for the store implementing the copy.
10441   const StoreInst *SI = ArgCopyIter->second.second;
10442   ElidedArgCopyInstrs.insert(SI);
10443 
10444   // Check for uses of the argument again so that we can avoid exporting ArgVal
10445   // if it is't used by anything other than the store.
10446   for (const Value *U : Arg.users()) {
10447     if (U != SI) {
10448       ArgHasUses = true;
10449       break;
10450     }
10451   }
10452 }
10453 
10454 void SelectionDAGISel::LowerArguments(const Function &F) {
10455   SelectionDAG &DAG = SDB->DAG;
10456   SDLoc dl = SDB->getCurSDLoc();
10457   const DataLayout &DL = DAG.getDataLayout();
10458   SmallVector<ISD::InputArg, 16> Ins;
10459 
10460   // In Naked functions we aren't going to save any registers.
10461   if (F.hasFnAttribute(Attribute::Naked))
10462     return;
10463 
10464   if (!FuncInfo->CanLowerReturn) {
10465     // Put in an sret pointer parameter before all the other parameters.
10466     SmallVector<EVT, 1> ValueVTs;
10467     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10468                     F.getReturnType()->getPointerTo(
10469                         DAG.getDataLayout().getAllocaAddrSpace()),
10470                     ValueVTs);
10471 
10472     // NOTE: Assuming that a pointer will never break down to more than one VT
10473     // or one register.
10474     ISD::ArgFlagsTy Flags;
10475     Flags.setSRet();
10476     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10477     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10478                          ISD::InputArg::NoArgIndex, 0);
10479     Ins.push_back(RetArg);
10480   }
10481 
10482   // Look for stores of arguments to static allocas. Mark such arguments with a
10483   // flag to ask the target to give us the memory location of that argument if
10484   // available.
10485   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10486   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10487                                     ArgCopyElisionCandidates);
10488 
10489   // Set up the incoming argument description vector.
10490   for (const Argument &Arg : F.args()) {
10491     unsigned ArgNo = Arg.getArgNo();
10492     SmallVector<EVT, 4> ValueVTs;
10493     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10494     bool isArgValueUsed = !Arg.use_empty();
10495     unsigned PartBase = 0;
10496     Type *FinalType = Arg.getType();
10497     if (Arg.hasAttribute(Attribute::ByVal))
10498       FinalType = Arg.getParamByValType();
10499     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10500         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10501     for (unsigned Value = 0, NumValues = ValueVTs.size();
10502          Value != NumValues; ++Value) {
10503       EVT VT = ValueVTs[Value];
10504       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10505       ISD::ArgFlagsTy Flags;
10506 
10507 
10508       if (Arg.getType()->isPointerTy()) {
10509         Flags.setPointer();
10510         Flags.setPointerAddrSpace(
10511             cast<PointerType>(Arg.getType())->getAddressSpace());
10512       }
10513       if (Arg.hasAttribute(Attribute::ZExt))
10514         Flags.setZExt();
10515       if (Arg.hasAttribute(Attribute::SExt))
10516         Flags.setSExt();
10517       if (Arg.hasAttribute(Attribute::InReg)) {
10518         // If we are using vectorcall calling convention, a structure that is
10519         // passed InReg - is surely an HVA
10520         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10521             isa<StructType>(Arg.getType())) {
10522           // The first value of a structure is marked
10523           if (0 == Value)
10524             Flags.setHvaStart();
10525           Flags.setHva();
10526         }
10527         // Set InReg Flag
10528         Flags.setInReg();
10529       }
10530       if (Arg.hasAttribute(Attribute::StructRet))
10531         Flags.setSRet();
10532       if (Arg.hasAttribute(Attribute::SwiftSelf))
10533         Flags.setSwiftSelf();
10534       if (Arg.hasAttribute(Attribute::SwiftAsync))
10535         Flags.setSwiftAsync();
10536       if (Arg.hasAttribute(Attribute::SwiftError))
10537         Flags.setSwiftError();
10538       if (Arg.hasAttribute(Attribute::ByVal))
10539         Flags.setByVal();
10540       if (Arg.hasAttribute(Attribute::ByRef))
10541         Flags.setByRef();
10542       if (Arg.hasAttribute(Attribute::InAlloca)) {
10543         Flags.setInAlloca();
10544         // Set the byval flag for CCAssignFn callbacks that don't know about
10545         // inalloca.  This way we can know how many bytes we should've allocated
10546         // and how many bytes a callee cleanup function will pop.  If we port
10547         // inalloca to more targets, we'll have to add custom inalloca handling
10548         // in the various CC lowering callbacks.
10549         Flags.setByVal();
10550       }
10551       if (Arg.hasAttribute(Attribute::Preallocated)) {
10552         Flags.setPreallocated();
10553         // Set the byval flag for CCAssignFn callbacks that don't know about
10554         // preallocated.  This way we can know how many bytes we should've
10555         // allocated and how many bytes a callee cleanup function will pop.  If
10556         // we port preallocated to more targets, we'll have to add custom
10557         // preallocated handling in the various CC lowering callbacks.
10558         Flags.setByVal();
10559       }
10560 
10561       // Certain targets (such as MIPS), may have a different ABI alignment
10562       // for a type depending on the context. Give the target a chance to
10563       // specify the alignment it wants.
10564       const Align OriginalAlignment(
10565           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10566       Flags.setOrigAlign(OriginalAlignment);
10567 
10568       Align MemAlign;
10569       Type *ArgMemTy = nullptr;
10570       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10571           Flags.isByRef()) {
10572         if (!ArgMemTy)
10573           ArgMemTy = Arg.getPointeeInMemoryValueType();
10574 
10575         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10576 
10577         // For in-memory arguments, size and alignment should be passed from FE.
10578         // BE will guess if this info is not there but there are cases it cannot
10579         // get right.
10580         if (auto ParamAlign = Arg.getParamStackAlign())
10581           MemAlign = *ParamAlign;
10582         else if ((ParamAlign = Arg.getParamAlign()))
10583           MemAlign = *ParamAlign;
10584         else
10585           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10586         if (Flags.isByRef())
10587           Flags.setByRefSize(MemSize);
10588         else
10589           Flags.setByValSize(MemSize);
10590       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10591         MemAlign = *ParamAlign;
10592       } else {
10593         MemAlign = OriginalAlignment;
10594       }
10595       Flags.setMemAlign(MemAlign);
10596 
10597       if (Arg.hasAttribute(Attribute::Nest))
10598         Flags.setNest();
10599       if (NeedsRegBlock)
10600         Flags.setInConsecutiveRegs();
10601       if (ArgCopyElisionCandidates.count(&Arg))
10602         Flags.setCopyElisionCandidate();
10603       if (Arg.hasAttribute(Attribute::Returned))
10604         Flags.setReturned();
10605 
10606       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10607           *CurDAG->getContext(), F.getCallingConv(), VT);
10608       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10609           *CurDAG->getContext(), F.getCallingConv(), VT);
10610       for (unsigned i = 0; i != NumRegs; ++i) {
10611         // For scalable vectors, use the minimum size; individual targets
10612         // are responsible for handling scalable vector arguments and
10613         // return values.
10614         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10615                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10616         if (NumRegs > 1 && i == 0)
10617           MyFlags.Flags.setSplit();
10618         // if it isn't first piece, alignment must be 1
10619         else if (i > 0) {
10620           MyFlags.Flags.setOrigAlign(Align(1));
10621           if (i == NumRegs - 1)
10622             MyFlags.Flags.setSplitEnd();
10623         }
10624         Ins.push_back(MyFlags);
10625       }
10626       if (NeedsRegBlock && Value == NumValues - 1)
10627         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10628       PartBase += VT.getStoreSize().getKnownMinSize();
10629     }
10630   }
10631 
10632   // Call the target to set up the argument values.
10633   SmallVector<SDValue, 8> InVals;
10634   SDValue NewRoot = TLI->LowerFormalArguments(
10635       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10636 
10637   // Verify that the target's LowerFormalArguments behaved as expected.
10638   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10639          "LowerFormalArguments didn't return a valid chain!");
10640   assert(InVals.size() == Ins.size() &&
10641          "LowerFormalArguments didn't emit the correct number of values!");
10642   LLVM_DEBUG({
10643     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10644       assert(InVals[i].getNode() &&
10645              "LowerFormalArguments emitted a null value!");
10646       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10647              "LowerFormalArguments emitted a value with the wrong type!");
10648     }
10649   });
10650 
10651   // Update the DAG with the new chain value resulting from argument lowering.
10652   DAG.setRoot(NewRoot);
10653 
10654   // Set up the argument values.
10655   unsigned i = 0;
10656   if (!FuncInfo->CanLowerReturn) {
10657     // Create a virtual register for the sret pointer, and put in a copy
10658     // from the sret argument into it.
10659     SmallVector<EVT, 1> ValueVTs;
10660     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10661                     F.getReturnType()->getPointerTo(
10662                         DAG.getDataLayout().getAllocaAddrSpace()),
10663                     ValueVTs);
10664     MVT VT = ValueVTs[0].getSimpleVT();
10665     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10666     Optional<ISD::NodeType> AssertOp;
10667     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10668                                         nullptr, F.getCallingConv(), AssertOp);
10669 
10670     MachineFunction& MF = SDB->DAG.getMachineFunction();
10671     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10672     Register SRetReg =
10673         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10674     FuncInfo->DemoteRegister = SRetReg;
10675     NewRoot =
10676         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10677     DAG.setRoot(NewRoot);
10678 
10679     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10680     ++i;
10681   }
10682 
10683   SmallVector<SDValue, 4> Chains;
10684   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10685   for (const Argument &Arg : F.args()) {
10686     SmallVector<SDValue, 4> ArgValues;
10687     SmallVector<EVT, 4> ValueVTs;
10688     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10689     unsigned NumValues = ValueVTs.size();
10690     if (NumValues == 0)
10691       continue;
10692 
10693     bool ArgHasUses = !Arg.use_empty();
10694 
10695     // Elide the copying store if the target loaded this argument from a
10696     // suitable fixed stack object.
10697     if (Ins[i].Flags.isCopyElisionCandidate()) {
10698       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10699                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10700                              InVals[i], ArgHasUses);
10701     }
10702 
10703     // If this argument is unused then remember its value. It is used to generate
10704     // debugging information.
10705     bool isSwiftErrorArg =
10706         TLI->supportSwiftError() &&
10707         Arg.hasAttribute(Attribute::SwiftError);
10708     if (!ArgHasUses && !isSwiftErrorArg) {
10709       SDB->setUnusedArgValue(&Arg, InVals[i]);
10710 
10711       // Also remember any frame index for use in FastISel.
10712       if (FrameIndexSDNode *FI =
10713           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10714         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10715     }
10716 
10717     for (unsigned Val = 0; Val != NumValues; ++Val) {
10718       EVT VT = ValueVTs[Val];
10719       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10720                                                       F.getCallingConv(), VT);
10721       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10722           *CurDAG->getContext(), F.getCallingConv(), VT);
10723 
10724       // Even an apparent 'unused' swifterror argument needs to be returned. So
10725       // we do generate a copy for it that can be used on return from the
10726       // function.
10727       if (ArgHasUses || isSwiftErrorArg) {
10728         Optional<ISD::NodeType> AssertOp;
10729         if (Arg.hasAttribute(Attribute::SExt))
10730           AssertOp = ISD::AssertSext;
10731         else if (Arg.hasAttribute(Attribute::ZExt))
10732           AssertOp = ISD::AssertZext;
10733 
10734         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10735                                              PartVT, VT, nullptr,
10736                                              F.getCallingConv(), AssertOp));
10737       }
10738 
10739       i += NumParts;
10740     }
10741 
10742     // We don't need to do anything else for unused arguments.
10743     if (ArgValues.empty())
10744       continue;
10745 
10746     // Note down frame index.
10747     if (FrameIndexSDNode *FI =
10748         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10749       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10750 
10751     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10752                                      SDB->getCurSDLoc());
10753 
10754     SDB->setValue(&Arg, Res);
10755     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10756       // We want to associate the argument with the frame index, among
10757       // involved operands, that correspond to the lowest address. The
10758       // getCopyFromParts function, called earlier, is swapping the order of
10759       // the operands to BUILD_PAIR depending on endianness. The result of
10760       // that swapping is that the least significant bits of the argument will
10761       // be in the first operand of the BUILD_PAIR node, and the most
10762       // significant bits will be in the second operand.
10763       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10764       if (LoadSDNode *LNode =
10765           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10766         if (FrameIndexSDNode *FI =
10767             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10768           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10769     }
10770 
10771     // Analyses past this point are naive and don't expect an assertion.
10772     if (Res.getOpcode() == ISD::AssertZext)
10773       Res = Res.getOperand(0);
10774 
10775     // Update the SwiftErrorVRegDefMap.
10776     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10777       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10778       if (Register::isVirtualRegister(Reg))
10779         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10780                                    Reg);
10781     }
10782 
10783     // If this argument is live outside of the entry block, insert a copy from
10784     // wherever we got it to the vreg that other BB's will reference it as.
10785     if (Res.getOpcode() == ISD::CopyFromReg) {
10786       // If we can, though, try to skip creating an unnecessary vreg.
10787       // FIXME: This isn't very clean... it would be nice to make this more
10788       // general.
10789       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10790       if (Register::isVirtualRegister(Reg)) {
10791         FuncInfo->ValueMap[&Arg] = Reg;
10792         continue;
10793       }
10794     }
10795     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10796       FuncInfo->InitializeRegForValue(&Arg);
10797       SDB->CopyToExportRegsIfNeeded(&Arg);
10798     }
10799   }
10800 
10801   if (!Chains.empty()) {
10802     Chains.push_back(NewRoot);
10803     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10804   }
10805 
10806   DAG.setRoot(NewRoot);
10807 
10808   assert(i == InVals.size() && "Argument register count mismatch!");
10809 
10810   // If any argument copy elisions occurred and we have debug info, update the
10811   // stale frame indices used in the dbg.declare variable info table.
10812   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10813   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10814     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10815       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10816       if (I != ArgCopyElisionFrameIndexMap.end())
10817         VI.Slot = I->second;
10818     }
10819   }
10820 
10821   // Finally, if the target has anything special to do, allow it to do so.
10822   emitFunctionEntryCode();
10823 }
10824 
10825 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10826 /// ensure constants are generated when needed.  Remember the virtual registers
10827 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10828 /// directly add them, because expansion might result in multiple MBB's for one
10829 /// BB.  As such, the start of the BB might correspond to a different MBB than
10830 /// the end.
10831 void
10832 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10833   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10834 
10835   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10836 
10837   // Check PHI nodes in successors that expect a value to be available from this
10838   // block.
10839   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10840     if (!isa<PHINode>(SuccBB->begin())) continue;
10841     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10842 
10843     // If this terminator has multiple identical successors (common for
10844     // switches), only handle each succ once.
10845     if (!SuccsHandled.insert(SuccMBB).second)
10846       continue;
10847 
10848     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10849 
10850     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10851     // nodes and Machine PHI nodes, but the incoming operands have not been
10852     // emitted yet.
10853     for (const PHINode &PN : SuccBB->phis()) {
10854       // Ignore dead phi's.
10855       if (PN.use_empty())
10856         continue;
10857 
10858       // Skip empty types
10859       if (PN.getType()->isEmptyTy())
10860         continue;
10861 
10862       unsigned Reg;
10863       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10864 
10865       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10866         unsigned &RegOut = ConstantsOut[C];
10867         if (RegOut == 0) {
10868           RegOut = FuncInfo.CreateRegs(C);
10869           // We need to zero/sign extend ConstantInt phi operands to match
10870           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10871           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10872           if (auto *CI = dyn_cast<ConstantInt>(C))
10873             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10874                                                     : ISD::ZERO_EXTEND;
10875           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10876         }
10877         Reg = RegOut;
10878       } else {
10879         DenseMap<const Value *, Register>::iterator I =
10880           FuncInfo.ValueMap.find(PHIOp);
10881         if (I != FuncInfo.ValueMap.end())
10882           Reg = I->second;
10883         else {
10884           assert(isa<AllocaInst>(PHIOp) &&
10885                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10886                  "Didn't codegen value into a register!??");
10887           Reg = FuncInfo.CreateRegs(PHIOp);
10888           CopyValueToVirtualRegister(PHIOp, Reg);
10889         }
10890       }
10891 
10892       // Remember that this register needs to added to the machine PHI node as
10893       // the input for this MBB.
10894       SmallVector<EVT, 4> ValueVTs;
10895       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10896       for (EVT VT : ValueVTs) {
10897         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10898         for (unsigned i = 0; i != NumRegisters; ++i)
10899           FuncInfo.PHINodesToUpdate.push_back(
10900               std::make_pair(&*MBBI++, Reg + i));
10901         Reg += NumRegisters;
10902       }
10903     }
10904   }
10905 
10906   ConstantsOut.clear();
10907 }
10908 
10909 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10910   MachineFunction::iterator I(MBB);
10911   if (++I == FuncInfo.MF->end())
10912     return nullptr;
10913   return &*I;
10914 }
10915 
10916 /// During lowering new call nodes can be created (such as memset, etc.).
10917 /// Those will become new roots of the current DAG, but complications arise
10918 /// when they are tail calls. In such cases, the call lowering will update
10919 /// the root, but the builder still needs to know that a tail call has been
10920 /// lowered in order to avoid generating an additional return.
10921 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10922   // If the node is null, we do have a tail call.
10923   if (MaybeTC.getNode() != nullptr)
10924     DAG.setRoot(MaybeTC);
10925   else
10926     HasTailCall = true;
10927 }
10928 
10929 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10930                                         MachineBasicBlock *SwitchMBB,
10931                                         MachineBasicBlock *DefaultMBB) {
10932   MachineFunction *CurMF = FuncInfo.MF;
10933   MachineBasicBlock *NextMBB = nullptr;
10934   MachineFunction::iterator BBI(W.MBB);
10935   if (++BBI != FuncInfo.MF->end())
10936     NextMBB = &*BBI;
10937 
10938   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10939 
10940   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10941 
10942   if (Size == 2 && W.MBB == SwitchMBB) {
10943     // If any two of the cases has the same destination, and if one value
10944     // is the same as the other, but has one bit unset that the other has set,
10945     // use bit manipulation to do two compares at once.  For example:
10946     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10947     // TODO: This could be extended to merge any 2 cases in switches with 3
10948     // cases.
10949     // TODO: Handle cases where W.CaseBB != SwitchBB.
10950     CaseCluster &Small = *W.FirstCluster;
10951     CaseCluster &Big = *W.LastCluster;
10952 
10953     if (Small.Low == Small.High && Big.Low == Big.High &&
10954         Small.MBB == Big.MBB) {
10955       const APInt &SmallValue = Small.Low->getValue();
10956       const APInt &BigValue = Big.Low->getValue();
10957 
10958       // Check that there is only one bit different.
10959       APInt CommonBit = BigValue ^ SmallValue;
10960       if (CommonBit.isPowerOf2()) {
10961         SDValue CondLHS = getValue(Cond);
10962         EVT VT = CondLHS.getValueType();
10963         SDLoc DL = getCurSDLoc();
10964 
10965         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10966                                  DAG.getConstant(CommonBit, DL, VT));
10967         SDValue Cond = DAG.getSetCC(
10968             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10969             ISD::SETEQ);
10970 
10971         // Update successor info.
10972         // Both Small and Big will jump to Small.BB, so we sum up the
10973         // probabilities.
10974         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10975         if (BPI)
10976           addSuccessorWithProb(
10977               SwitchMBB, DefaultMBB,
10978               // The default destination is the first successor in IR.
10979               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10980         else
10981           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10982 
10983         // Insert the true branch.
10984         SDValue BrCond =
10985             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10986                         DAG.getBasicBlock(Small.MBB));
10987         // Insert the false branch.
10988         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10989                              DAG.getBasicBlock(DefaultMBB));
10990 
10991         DAG.setRoot(BrCond);
10992         return;
10993       }
10994     }
10995   }
10996 
10997   if (TM.getOptLevel() != CodeGenOpt::None) {
10998     // Here, we order cases by probability so the most likely case will be
10999     // checked first. However, two clusters can have the same probability in
11000     // which case their relative ordering is non-deterministic. So we use Low
11001     // as a tie-breaker as clusters are guaranteed to never overlap.
11002     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11003                [](const CaseCluster &a, const CaseCluster &b) {
11004       return a.Prob != b.Prob ?
11005              a.Prob > b.Prob :
11006              a.Low->getValue().slt(b.Low->getValue());
11007     });
11008 
11009     // Rearrange the case blocks so that the last one falls through if possible
11010     // without changing the order of probabilities.
11011     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11012       --I;
11013       if (I->Prob > W.LastCluster->Prob)
11014         break;
11015       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11016         std::swap(*I, *W.LastCluster);
11017         break;
11018       }
11019     }
11020   }
11021 
11022   // Compute total probability.
11023   BranchProbability DefaultProb = W.DefaultProb;
11024   BranchProbability UnhandledProbs = DefaultProb;
11025   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11026     UnhandledProbs += I->Prob;
11027 
11028   MachineBasicBlock *CurMBB = W.MBB;
11029   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11030     bool FallthroughUnreachable = false;
11031     MachineBasicBlock *Fallthrough;
11032     if (I == W.LastCluster) {
11033       // For the last cluster, fall through to the default destination.
11034       Fallthrough = DefaultMBB;
11035       FallthroughUnreachable = isa<UnreachableInst>(
11036           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11037     } else {
11038       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11039       CurMF->insert(BBI, Fallthrough);
11040       // Put Cond in a virtual register to make it available from the new blocks.
11041       ExportFromCurrentBlock(Cond);
11042     }
11043     UnhandledProbs -= I->Prob;
11044 
11045     switch (I->Kind) {
11046       case CC_JumpTable: {
11047         // FIXME: Optimize away range check based on pivot comparisons.
11048         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11049         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11050 
11051         // The jump block hasn't been inserted yet; insert it here.
11052         MachineBasicBlock *JumpMBB = JT->MBB;
11053         CurMF->insert(BBI, JumpMBB);
11054 
11055         auto JumpProb = I->Prob;
11056         auto FallthroughProb = UnhandledProbs;
11057 
11058         // If the default statement is a target of the jump table, we evenly
11059         // distribute the default probability to successors of CurMBB. Also
11060         // update the probability on the edge from JumpMBB to Fallthrough.
11061         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11062                                               SE = JumpMBB->succ_end();
11063              SI != SE; ++SI) {
11064           if (*SI == DefaultMBB) {
11065             JumpProb += DefaultProb / 2;
11066             FallthroughProb -= DefaultProb / 2;
11067             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11068             JumpMBB->normalizeSuccProbs();
11069             break;
11070           }
11071         }
11072 
11073         if (FallthroughUnreachable)
11074           JTH->FallthroughUnreachable = true;
11075 
11076         if (!JTH->FallthroughUnreachable)
11077           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11078         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11079         CurMBB->normalizeSuccProbs();
11080 
11081         // The jump table header will be inserted in our current block, do the
11082         // range check, and fall through to our fallthrough block.
11083         JTH->HeaderBB = CurMBB;
11084         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11085 
11086         // If we're in the right place, emit the jump table header right now.
11087         if (CurMBB == SwitchMBB) {
11088           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11089           JTH->Emitted = true;
11090         }
11091         break;
11092       }
11093       case CC_BitTests: {
11094         // FIXME: Optimize away range check based on pivot comparisons.
11095         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11096 
11097         // The bit test blocks haven't been inserted yet; insert them here.
11098         for (BitTestCase &BTC : BTB->Cases)
11099           CurMF->insert(BBI, BTC.ThisBB);
11100 
11101         // Fill in fields of the BitTestBlock.
11102         BTB->Parent = CurMBB;
11103         BTB->Default = Fallthrough;
11104 
11105         BTB->DefaultProb = UnhandledProbs;
11106         // If the cases in bit test don't form a contiguous range, we evenly
11107         // distribute the probability on the edge to Fallthrough to two
11108         // successors of CurMBB.
11109         if (!BTB->ContiguousRange) {
11110           BTB->Prob += DefaultProb / 2;
11111           BTB->DefaultProb -= DefaultProb / 2;
11112         }
11113 
11114         if (FallthroughUnreachable)
11115           BTB->FallthroughUnreachable = true;
11116 
11117         // If we're in the right place, emit the bit test header right now.
11118         if (CurMBB == SwitchMBB) {
11119           visitBitTestHeader(*BTB, SwitchMBB);
11120           BTB->Emitted = true;
11121         }
11122         break;
11123       }
11124       case CC_Range: {
11125         const Value *RHS, *LHS, *MHS;
11126         ISD::CondCode CC;
11127         if (I->Low == I->High) {
11128           // Check Cond == I->Low.
11129           CC = ISD::SETEQ;
11130           LHS = Cond;
11131           RHS=I->Low;
11132           MHS = nullptr;
11133         } else {
11134           // Check I->Low <= Cond <= I->High.
11135           CC = ISD::SETLE;
11136           LHS = I->Low;
11137           MHS = Cond;
11138           RHS = I->High;
11139         }
11140 
11141         // If Fallthrough is unreachable, fold away the comparison.
11142         if (FallthroughUnreachable)
11143           CC = ISD::SETTRUE;
11144 
11145         // The false probability is the sum of all unhandled cases.
11146         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11147                      getCurSDLoc(), I->Prob, UnhandledProbs);
11148 
11149         if (CurMBB == SwitchMBB)
11150           visitSwitchCase(CB, SwitchMBB);
11151         else
11152           SL->SwitchCases.push_back(CB);
11153 
11154         break;
11155       }
11156     }
11157     CurMBB = Fallthrough;
11158   }
11159 }
11160 
11161 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11162                                               CaseClusterIt First,
11163                                               CaseClusterIt Last) {
11164   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11165     if (X.Prob != CC.Prob)
11166       return X.Prob > CC.Prob;
11167 
11168     // Ties are broken by comparing the case value.
11169     return X.Low->getValue().slt(CC.Low->getValue());
11170   });
11171 }
11172 
11173 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11174                                         const SwitchWorkListItem &W,
11175                                         Value *Cond,
11176                                         MachineBasicBlock *SwitchMBB) {
11177   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11178          "Clusters not sorted?");
11179 
11180   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11181 
11182   // Balance the tree based on branch probabilities to create a near-optimal (in
11183   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11184   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11185   CaseClusterIt LastLeft = W.FirstCluster;
11186   CaseClusterIt FirstRight = W.LastCluster;
11187   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11188   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11189 
11190   // Move LastLeft and FirstRight towards each other from opposite directions to
11191   // find a partitioning of the clusters which balances the probability on both
11192   // sides. If LeftProb and RightProb are equal, alternate which side is
11193   // taken to ensure 0-probability nodes are distributed evenly.
11194   unsigned I = 0;
11195   while (LastLeft + 1 < FirstRight) {
11196     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11197       LeftProb += (++LastLeft)->Prob;
11198     else
11199       RightProb += (--FirstRight)->Prob;
11200     I++;
11201   }
11202 
11203   while (true) {
11204     // Our binary search tree differs from a typical BST in that ours can have up
11205     // to three values in each leaf. The pivot selection above doesn't take that
11206     // into account, which means the tree might require more nodes and be less
11207     // efficient. We compensate for this here.
11208 
11209     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11210     unsigned NumRight = W.LastCluster - FirstRight + 1;
11211 
11212     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11213       // If one side has less than 3 clusters, and the other has more than 3,
11214       // consider taking a cluster from the other side.
11215 
11216       if (NumLeft < NumRight) {
11217         // Consider moving the first cluster on the right to the left side.
11218         CaseCluster &CC = *FirstRight;
11219         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11220         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11221         if (LeftSideRank <= RightSideRank) {
11222           // Moving the cluster to the left does not demote it.
11223           ++LastLeft;
11224           ++FirstRight;
11225           continue;
11226         }
11227       } else {
11228         assert(NumRight < NumLeft);
11229         // Consider moving the last element on the left to the right side.
11230         CaseCluster &CC = *LastLeft;
11231         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11232         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11233         if (RightSideRank <= LeftSideRank) {
11234           // Moving the cluster to the right does not demot it.
11235           --LastLeft;
11236           --FirstRight;
11237           continue;
11238         }
11239       }
11240     }
11241     break;
11242   }
11243 
11244   assert(LastLeft + 1 == FirstRight);
11245   assert(LastLeft >= W.FirstCluster);
11246   assert(FirstRight <= W.LastCluster);
11247 
11248   // Use the first element on the right as pivot since we will make less-than
11249   // comparisons against it.
11250   CaseClusterIt PivotCluster = FirstRight;
11251   assert(PivotCluster > W.FirstCluster);
11252   assert(PivotCluster <= W.LastCluster);
11253 
11254   CaseClusterIt FirstLeft = W.FirstCluster;
11255   CaseClusterIt LastRight = W.LastCluster;
11256 
11257   const ConstantInt *Pivot = PivotCluster->Low;
11258 
11259   // New blocks will be inserted immediately after the current one.
11260   MachineFunction::iterator BBI(W.MBB);
11261   ++BBI;
11262 
11263   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11264   // we can branch to its destination directly if it's squeezed exactly in
11265   // between the known lower bound and Pivot - 1.
11266   MachineBasicBlock *LeftMBB;
11267   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11268       FirstLeft->Low == W.GE &&
11269       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11270     LeftMBB = FirstLeft->MBB;
11271   } else {
11272     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11273     FuncInfo.MF->insert(BBI, LeftMBB);
11274     WorkList.push_back(
11275         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11276     // Put Cond in a virtual register to make it available from the new blocks.
11277     ExportFromCurrentBlock(Cond);
11278   }
11279 
11280   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11281   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11282   // directly if RHS.High equals the current upper bound.
11283   MachineBasicBlock *RightMBB;
11284   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11285       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11286     RightMBB = FirstRight->MBB;
11287   } else {
11288     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11289     FuncInfo.MF->insert(BBI, RightMBB);
11290     WorkList.push_back(
11291         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11292     // Put Cond in a virtual register to make it available from the new blocks.
11293     ExportFromCurrentBlock(Cond);
11294   }
11295 
11296   // Create the CaseBlock record that will be used to lower the branch.
11297   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11298                getCurSDLoc(), LeftProb, RightProb);
11299 
11300   if (W.MBB == SwitchMBB)
11301     visitSwitchCase(CB, SwitchMBB);
11302   else
11303     SL->SwitchCases.push_back(CB);
11304 }
11305 
11306 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11307 // from the swith statement.
11308 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11309                                             BranchProbability PeeledCaseProb) {
11310   if (PeeledCaseProb == BranchProbability::getOne())
11311     return BranchProbability::getZero();
11312   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11313 
11314   uint32_t Numerator = CaseProb.getNumerator();
11315   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11316   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11317 }
11318 
11319 // Try to peel the top probability case if it exceeds the threshold.
11320 // Return current MachineBasicBlock for the switch statement if the peeling
11321 // does not occur.
11322 // If the peeling is performed, return the newly created MachineBasicBlock
11323 // for the peeled switch statement. Also update Clusters to remove the peeled
11324 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11325 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11326     const SwitchInst &SI, CaseClusterVector &Clusters,
11327     BranchProbability &PeeledCaseProb) {
11328   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11329   // Don't perform if there is only one cluster or optimizing for size.
11330   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11331       TM.getOptLevel() == CodeGenOpt::None ||
11332       SwitchMBB->getParent()->getFunction().hasMinSize())
11333     return SwitchMBB;
11334 
11335   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11336   unsigned PeeledCaseIndex = 0;
11337   bool SwitchPeeled = false;
11338   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11339     CaseCluster &CC = Clusters[Index];
11340     if (CC.Prob < TopCaseProb)
11341       continue;
11342     TopCaseProb = CC.Prob;
11343     PeeledCaseIndex = Index;
11344     SwitchPeeled = true;
11345   }
11346   if (!SwitchPeeled)
11347     return SwitchMBB;
11348 
11349   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11350                     << TopCaseProb << "\n");
11351 
11352   // Record the MBB for the peeled switch statement.
11353   MachineFunction::iterator BBI(SwitchMBB);
11354   ++BBI;
11355   MachineBasicBlock *PeeledSwitchMBB =
11356       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11357   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11358 
11359   ExportFromCurrentBlock(SI.getCondition());
11360   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11361   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11362                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11363   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11364 
11365   Clusters.erase(PeeledCaseIt);
11366   for (CaseCluster &CC : Clusters) {
11367     LLVM_DEBUG(
11368         dbgs() << "Scale the probablity for one cluster, before scaling: "
11369                << CC.Prob << "\n");
11370     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11371     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11372   }
11373   PeeledCaseProb = TopCaseProb;
11374   return PeeledSwitchMBB;
11375 }
11376 
11377 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11378   // Extract cases from the switch.
11379   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11380   CaseClusterVector Clusters;
11381   Clusters.reserve(SI.getNumCases());
11382   for (auto I : SI.cases()) {
11383     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11384     const ConstantInt *CaseVal = I.getCaseValue();
11385     BranchProbability Prob =
11386         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11387             : BranchProbability(1, SI.getNumCases() + 1);
11388     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11389   }
11390 
11391   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11392 
11393   // Cluster adjacent cases with the same destination. We do this at all
11394   // optimization levels because it's cheap to do and will make codegen faster
11395   // if there are many clusters.
11396   sortAndRangeify(Clusters);
11397 
11398   // The branch probablity of the peeled case.
11399   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11400   MachineBasicBlock *PeeledSwitchMBB =
11401       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11402 
11403   // If there is only the default destination, jump there directly.
11404   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11405   if (Clusters.empty()) {
11406     assert(PeeledSwitchMBB == SwitchMBB);
11407     SwitchMBB->addSuccessor(DefaultMBB);
11408     if (DefaultMBB != NextBlock(SwitchMBB)) {
11409       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11410                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11411     }
11412     return;
11413   }
11414 
11415   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11416   SL->findBitTestClusters(Clusters, &SI);
11417 
11418   LLVM_DEBUG({
11419     dbgs() << "Case clusters: ";
11420     for (const CaseCluster &C : Clusters) {
11421       if (C.Kind == CC_JumpTable)
11422         dbgs() << "JT:";
11423       if (C.Kind == CC_BitTests)
11424         dbgs() << "BT:";
11425 
11426       C.Low->getValue().print(dbgs(), true);
11427       if (C.Low != C.High) {
11428         dbgs() << '-';
11429         C.High->getValue().print(dbgs(), true);
11430       }
11431       dbgs() << ' ';
11432     }
11433     dbgs() << '\n';
11434   });
11435 
11436   assert(!Clusters.empty());
11437   SwitchWorkList WorkList;
11438   CaseClusterIt First = Clusters.begin();
11439   CaseClusterIt Last = Clusters.end() - 1;
11440   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11441   // Scale the branchprobability for DefaultMBB if the peel occurs and
11442   // DefaultMBB is not replaced.
11443   if (PeeledCaseProb != BranchProbability::getZero() &&
11444       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11445     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11446   WorkList.push_back(
11447       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11448 
11449   while (!WorkList.empty()) {
11450     SwitchWorkListItem W = WorkList.pop_back_val();
11451     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11452 
11453     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11454         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11455       // For optimized builds, lower large range as a balanced binary tree.
11456       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11457       continue;
11458     }
11459 
11460     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11461   }
11462 }
11463 
11464 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11466   auto DL = getCurSDLoc();
11467   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11468   setValue(&I, DAG.getStepVector(DL, ResultVT));
11469 }
11470 
11471 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11473   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11474 
11475   SDLoc DL = getCurSDLoc();
11476   SDValue V = getValue(I.getOperand(0));
11477   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11478 
11479   if (VT.isScalableVector()) {
11480     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11481     return;
11482   }
11483 
11484   // Use VECTOR_SHUFFLE for the fixed-length vector
11485   // to maintain existing behavior.
11486   SmallVector<int, 8> Mask;
11487   unsigned NumElts = VT.getVectorMinNumElements();
11488   for (unsigned i = 0; i != NumElts; ++i)
11489     Mask.push_back(NumElts - 1 - i);
11490 
11491   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11492 }
11493 
11494 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11495   SmallVector<EVT, 4> ValueVTs;
11496   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11497                   ValueVTs);
11498   unsigned NumValues = ValueVTs.size();
11499   if (NumValues == 0) return;
11500 
11501   SmallVector<SDValue, 4> Values(NumValues);
11502   SDValue Op = getValue(I.getOperand(0));
11503 
11504   for (unsigned i = 0; i != NumValues; ++i)
11505     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11506                             SDValue(Op.getNode(), Op.getResNo() + i));
11507 
11508   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11509                            DAG.getVTList(ValueVTs), Values));
11510 }
11511 
11512 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11514   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11515 
11516   SDLoc DL = getCurSDLoc();
11517   SDValue V1 = getValue(I.getOperand(0));
11518   SDValue V2 = getValue(I.getOperand(1));
11519   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11520 
11521   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11522   if (VT.isScalableVector()) {
11523     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11524     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11525                              DAG.getConstant(Imm, DL, IdxVT)));
11526     return;
11527   }
11528 
11529   unsigned NumElts = VT.getVectorNumElements();
11530 
11531   uint64_t Idx = (NumElts + Imm) % NumElts;
11532 
11533   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11534   SmallVector<int, 8> Mask;
11535   for (unsigned i = 0; i < NumElts; ++i)
11536     Mask.push_back(Idx + i);
11537   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11538 }
11539