xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 21f97fdc9788fdc294659055f16290688c11e540)
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 <tuple>
104 
105 using namespace llvm;
106 using namespace PatternMatch;
107 using namespace SwitchCG;
108 
109 #define DEBUG_TYPE "isel"
110 
111 /// LimitFloatPrecision - Generate low-precision inline sequences for
112 /// some float libcalls (6, 8 or 12 bits).
113 static unsigned LimitFloatPrecision;
114 
115 static cl::opt<bool>
116     InsertAssertAlign("insert-assert-align", cl::init(true),
117                       cl::desc("Insert the experimental `assertalign` node."),
118                       cl::ReallyHidden);
119 
120 static cl::opt<unsigned, true>
121     LimitFPPrecision("limit-float-precision",
122                      cl::desc("Generate low-precision inline sequences "
123                               "for some float libcalls"),
124                      cl::location(LimitFloatPrecision), cl::Hidden,
125                      cl::init(0));
126 
127 static cl::opt<unsigned> SwitchPeelThreshold(
128     "switch-peel-threshold", cl::Hidden, cl::init(66),
129     cl::desc("Set the case probability threshold for peeling the case from a "
130              "switch statement. A value greater than 100 will void this "
131              "optimization"));
132 
133 // Limit the width of DAG chains. This is important in general to prevent
134 // DAG-based analysis from blowing up. For example, alias analysis and
135 // load clustering may not complete in reasonable time. It is difficult to
136 // recognize and avoid this situation within each individual analysis, and
137 // future analyses are likely to have the same behavior. Limiting DAG width is
138 // the safe approach and will be especially important with global DAGs.
139 //
140 // MaxParallelChains default is arbitrarily high to avoid affecting
141 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
142 // sequence over this should have been converted to llvm.memcpy by the
143 // frontend. It is easy to induce this behavior with .ll code such as:
144 // %buffer = alloca [4096 x i8]
145 // %data = load [4096 x i8]* %argPtr
146 // store [4096 x i8] %data, [4096 x i8]* %buffer
147 static const unsigned MaxParallelChains = 64;
148 
149 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
150                                       const SDValue *Parts, unsigned NumParts,
151                                       MVT PartVT, EVT ValueVT, const Value *V,
152                                       Optional<CallingConv::ID> CC);
153 
154 /// getCopyFromParts - Create a value that contains the specified legal parts
155 /// combined into the value they represent.  If the parts combine to a type
156 /// larger than ValueVT then AssertOp can be used to specify whether the extra
157 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
158 /// (ISD::AssertSext).
159 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
160                                 const SDValue *Parts, unsigned NumParts,
161                                 MVT PartVT, EVT ValueVT, const Value *V,
162                                 Optional<CallingConv::ID> CC = None,
163                                 Optional<ISD::NodeType> AssertOp = None) {
164   // Let the target assemble the parts if it wants to
165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
166   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
167                                                    PartVT, ValueVT, CC))
168     return Val;
169 
170   if (ValueVT.isVector())
171     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
172                                   CC);
173 
174   assert(NumParts > 0 && "No parts to assemble!");
175   SDValue Val = Parts[0];
176 
177   if (NumParts > 1) {
178     // Assemble the value from multiple parts.
179     if (ValueVT.isInteger()) {
180       unsigned PartBits = PartVT.getSizeInBits();
181       unsigned ValueBits = ValueVT.getSizeInBits();
182 
183       // Assemble the power of 2 part.
184       unsigned RoundParts =
185           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
186       unsigned RoundBits = PartBits * RoundParts;
187       EVT RoundVT = RoundBits == ValueBits ?
188         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
189       SDValue Lo, Hi;
190 
191       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
192 
193       if (RoundParts > 2) {
194         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
195                               PartVT, HalfVT, V);
196         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
197                               RoundParts / 2, PartVT, HalfVT, V);
198       } else {
199         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
200         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
201       }
202 
203       if (DAG.getDataLayout().isBigEndian())
204         std::swap(Lo, Hi);
205 
206       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
207 
208       if (RoundParts < NumParts) {
209         // Assemble the trailing non-power-of-2 part.
210         unsigned OddParts = NumParts - RoundParts;
211         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
212         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
213                               OddVT, V, CC);
214 
215         // Combine the round and odd parts.
216         Lo = Val;
217         if (DAG.getDataLayout().isBigEndian())
218           std::swap(Lo, Hi);
219         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
220         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
221         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
222                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
223                                          TLI.getShiftAmountTy(
224                                              TotalVT, DAG.getDataLayout())));
225         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
226         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
227       }
228     } else if (PartVT.isFloatingPoint()) {
229       // FP split into multiple FP parts (for ppcf128)
230       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
231              "Unexpected split");
232       SDValue Lo, Hi;
233       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
234       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
235       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
236         std::swap(Lo, Hi);
237       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
238     } else {
239       // FP split into integer parts (soft fp)
240       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
241              !PartVT.isVector() && "Unexpected split");
242       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
243       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
244     }
245   }
246 
247   // There is now one part, held in Val.  Correct it to match ValueVT.
248   // PartEVT is the type of the register class that holds the value.
249   // ValueVT is the type of the inline asm operation.
250   EVT PartEVT = Val.getValueType();
251 
252   if (PartEVT == ValueVT)
253     return Val;
254 
255   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
256       ValueVT.bitsLT(PartEVT)) {
257     // For an FP value in an integer part, we need to truncate to the right
258     // width first.
259     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
260     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
261   }
262 
263   // Handle types that have the same size.
264   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
265     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
266 
267   // Handle types with different sizes.
268   if (PartEVT.isInteger() && ValueVT.isInteger()) {
269     if (ValueVT.bitsLT(PartEVT)) {
270       // For a truncate, see if we have any information to
271       // indicate whether the truncated bits will always be
272       // zero or sign-extension.
273       if (AssertOp)
274         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
275                           DAG.getValueType(ValueVT));
276       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
277     }
278     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
279   }
280 
281   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
282     // FP_ROUND's are always exact here.
283     if (ValueVT.bitsLT(Val.getValueType()))
284       return DAG.getNode(
285           ISD::FP_ROUND, DL, ValueVT, Val,
286           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
287 
288     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
289   }
290 
291   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
292   // then truncating.
293   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
294       ValueVT.bitsLT(PartEVT)) {
295     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
296     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
297   }
298 
299   report_fatal_error("Unknown mismatch in getCopyFromParts!");
300 }
301 
302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
303                                               const Twine &ErrMsg) {
304   const Instruction *I = dyn_cast_or_null<Instruction>(V);
305   if (!V)
306     return Ctx.emitError(ErrMsg);
307 
308   const char *AsmError = ", possible invalid constraint for vector type";
309   if (const CallInst *CI = dyn_cast<CallInst>(I))
310     if (CI->isInlineAsm())
311       return Ctx.emitError(I, ErrMsg + AsmError);
312 
313   return Ctx.emitError(I, ErrMsg);
314 }
315 
316 /// getCopyFromPartsVector - Create a value that contains the specified legal
317 /// parts combined into the value they represent.  If the parts combine to a
318 /// type larger than ValueVT then AssertOp can be used to specify whether the
319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
320 /// ValueVT (ISD::AssertSext).
321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
322                                       const SDValue *Parts, unsigned NumParts,
323                                       MVT PartVT, EVT ValueVT, const Value *V,
324                                       Optional<CallingConv::ID> CallConv) {
325   assert(ValueVT.isVector() && "Not a vector value");
326   assert(NumParts > 0 && "No parts to assemble!");
327   const bool IsABIRegCopy = CallConv.has_value();
328 
329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
330   SDValue Val = Parts[0];
331 
332   // Handle a multi-element vector.
333   if (NumParts > 1) {
334     EVT IntermediateVT;
335     MVT RegisterVT;
336     unsigned NumIntermediates;
337     unsigned NumRegs;
338 
339     if (IsABIRegCopy) {
340       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
341           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
342           NumIntermediates, RegisterVT);
343     } else {
344       NumRegs =
345           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
346                                      NumIntermediates, RegisterVT);
347     }
348 
349     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
350     NumParts = NumRegs; // Silence a compiler warning.
351     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
352     assert(RegisterVT.getSizeInBits() ==
353            Parts[0].getSimpleValueType().getSizeInBits() &&
354            "Part type sizes don't match!");
355 
356     // Assemble the parts into intermediate operands.
357     SmallVector<SDValue, 8> Ops(NumIntermediates);
358     if (NumIntermediates == NumParts) {
359       // If the register was not expanded, truncate or copy the value,
360       // as appropriate.
361       for (unsigned i = 0; i != NumParts; ++i)
362         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
363                                   PartVT, IntermediateVT, V, CallConv);
364     } else if (NumParts > 0) {
365       // If the intermediate type was expanded, build the intermediate
366       // operands from the parts.
367       assert(NumParts % NumIntermediates == 0 &&
368              "Must expand into a divisible number of parts!");
369       unsigned Factor = NumParts / NumIntermediates;
370       for (unsigned i = 0; i != NumIntermediates; ++i)
371         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
372                                   PartVT, IntermediateVT, V, CallConv);
373     }
374 
375     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
376     // intermediate operands.
377     EVT BuiltVectorTy =
378         IntermediateVT.isVector()
379             ? EVT::getVectorVT(
380                   *DAG.getContext(), IntermediateVT.getScalarType(),
381                   IntermediateVT.getVectorElementCount() * NumParts)
382             : EVT::getVectorVT(*DAG.getContext(),
383                                IntermediateVT.getScalarType(),
384                                NumIntermediates);
385     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
386                                                 : ISD::BUILD_VECTOR,
387                       DL, BuiltVectorTy, Ops);
388   }
389 
390   // There is now one part, held in Val.  Correct it to match ValueVT.
391   EVT PartEVT = Val.getValueType();
392 
393   if (PartEVT == ValueVT)
394     return Val;
395 
396   if (PartEVT.isVector()) {
397     // Vector/Vector bitcast.
398     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
399       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
400 
401     // If the element type of the source/dest vectors are the same, but the
402     // parts vector has more elements than the value vector, then we have a
403     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
404     // 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     }
419 
420     // Promoted vector extract
421     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
422   }
423 
424   // Trivial bitcast if the types are the same size and the destination
425   // vector type is legal.
426   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
427       TLI.isTypeLegal(ValueVT))
428     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
429 
430   if (ValueVT.getVectorNumElements() != 1) {
431      // Certain ABIs require that vectors are passed as integers. For vectors
432      // are the same size, this is an obvious bitcast.
433      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
434        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435      } else if (ValueVT.bitsLT(PartEVT)) {
436        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
437        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
438        // Drop the extra bits.
439        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
440        return DAG.getBitcast(ValueVT, Val);
441      }
442 
443      diagnosePossiblyInvalidConstraint(
444          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
445      return DAG.getUNDEF(ValueVT);
446   }
447 
448   // Handle cases such as i8 -> <1 x i1>
449   EVT ValueSVT = ValueVT.getVectorElementType();
450   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
451     unsigned ValueSize = ValueSVT.getSizeInBits();
452     if (ValueSize == PartEVT.getSizeInBits()) {
453       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
454     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
455       // It's possible a scalar floating point type gets softened to integer and
456       // then promoted to a larger integer. If PartEVT is the larger integer
457       // we need to truncate it and then bitcast to the FP type.
458       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
459       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
460       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
461       Val = DAG.getBitcast(ValueSVT, Val);
462     } else {
463       Val = ValueVT.isFloatingPoint()
464                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
465                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
466     }
467   }
468 
469   return DAG.getBuildVector(ValueVT, DL, Val);
470 }
471 
472 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
473                                  SDValue Val, SDValue *Parts, unsigned NumParts,
474                                  MVT PartVT, const Value *V,
475                                  Optional<CallingConv::ID> CallConv);
476 
477 /// getCopyToParts - Create a series of nodes that contain the specified value
478 /// split into legal parts.  If the parts contain more bits than Val, then, for
479 /// integers, ExtendKind can be used to specify how to generate the extra bits.
480 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
481                            SDValue *Parts, unsigned NumParts, MVT PartVT,
482                            const Value *V,
483                            Optional<CallingConv::ID> CallConv = None,
484                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
485   // Let the target split the parts if it wants to
486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
487   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
488                                       CallConv))
489     return;
490   EVT ValueVT = Val.getValueType();
491 
492   // Handle the vector case separately.
493   if (ValueVT.isVector())
494     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
495                                 CallConv);
496 
497   unsigned PartBits = PartVT.getSizeInBits();
498   unsigned OrigNumParts = NumParts;
499   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
500          "Copying to an illegal type!");
501 
502   if (NumParts == 0)
503     return;
504 
505   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
506   EVT PartEVT = PartVT;
507   if (PartEVT == ValueVT) {
508     assert(NumParts == 1 && "No-op copy with multiple parts!");
509     Parts[0] = Val;
510     return;
511   }
512 
513   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
514     // If the parts cover more bits than the value has, promote the value.
515     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
516       assert(NumParts == 1 && "Do not know what to promote to!");
517       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
518     } else {
519       if (ValueVT.isFloatingPoint()) {
520         // FP values need to be bitcast, then extended if they are being put
521         // into a larger container.
522         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
523         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
524       }
525       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
526              ValueVT.isInteger() &&
527              "Unknown mismatch!");
528       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
529       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
530       if (PartVT == MVT::x86mmx)
531         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
532     }
533   } else if (PartBits == ValueVT.getSizeInBits()) {
534     // Different types of the same size.
535     assert(NumParts == 1 && PartEVT != ValueVT);
536     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
537   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
538     // If the parts cover less bits than value has, truncate the value.
539     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
540            ValueVT.isInteger() &&
541            "Unknown mismatch!");
542     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
543     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
544     if (PartVT == MVT::x86mmx)
545       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
546   }
547 
548   // The value may have changed - recompute ValueVT.
549   ValueVT = Val.getValueType();
550   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
551          "Failed to tile the value with PartVT!");
552 
553   if (NumParts == 1) {
554     if (PartEVT != ValueVT) {
555       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
556                                         "scalar-to-vector conversion failed");
557       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559 
560     Parts[0] = Val;
561     return;
562   }
563 
564   // Expand the value into multiple parts.
565   if (NumParts & (NumParts - 1)) {
566     // The number of parts is not a power of 2.  Split off and copy the tail.
567     assert(PartVT.isInteger() && ValueVT.isInteger() &&
568            "Do not know what to expand to!");
569     unsigned RoundParts = 1 << Log2_32(NumParts);
570     unsigned RoundBits = RoundParts * PartBits;
571     unsigned OddParts = NumParts - RoundParts;
572     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
573       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
574 
575     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
576                    CallConv);
577 
578     if (DAG.getDataLayout().isBigEndian())
579       // The odd parts were reversed by getCopyToParts - unreverse them.
580       std::reverse(Parts + RoundParts, Parts + NumParts);
581 
582     NumParts = RoundParts;
583     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
584     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
585   }
586 
587   // The number of parts is a power of 2.  Repeatedly bisect the value using
588   // EXTRACT_ELEMENT.
589   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
590                          EVT::getIntegerVT(*DAG.getContext(),
591                                            ValueVT.getSizeInBits()),
592                          Val);
593 
594   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
595     for (unsigned i = 0; i < NumParts; i += StepSize) {
596       unsigned ThisBits = StepSize * PartBits / 2;
597       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
598       SDValue &Part0 = Parts[i];
599       SDValue &Part1 = Parts[i+StepSize/2];
600 
601       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
602                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
603       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
605 
606       if (ThisBits == PartBits && ThisVT != PartVT) {
607         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
608         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
609       }
610     }
611   }
612 
613   if (DAG.getDataLayout().isBigEndian())
614     std::reverse(Parts, Parts + OrigNumParts);
615 }
616 
617 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
618                                      const SDLoc &DL, EVT PartVT) {
619   if (!PartVT.isVector())
620     return SDValue();
621 
622   EVT ValueVT = Val.getValueType();
623   ElementCount PartNumElts = PartVT.getVectorElementCount();
624   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
625 
626   // We only support widening vectors with equivalent element types and
627   // fixed/scalable properties. If a target needs to widen a fixed-length type
628   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
629   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
630       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
631       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
632     return SDValue();
633 
634   // Widening a scalable vector to another scalable vector is done by inserting
635   // the vector into a larger undef one.
636   if (PartNumElts.isScalable())
637     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
638                        Val, DAG.getVectorIdxConstant(0, DL));
639 
640   EVT ElementVT = PartVT.getVectorElementType();
641   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
642   // undef elements.
643   SmallVector<SDValue, 16> Ops;
644   DAG.ExtractVectorElements(Val, Ops);
645   SDValue EltUndef = DAG.getUNDEF(ElementVT);
646   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
647 
648   // FIXME: Use CONCAT for 2x -> 4x.
649   return DAG.getBuildVector(PartVT, DL, Ops);
650 }
651 
652 /// getCopyToPartsVector - Create a series of nodes that contain the specified
653 /// value split into legal parts.
654 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
655                                  SDValue Val, SDValue *Parts, unsigned NumParts,
656                                  MVT PartVT, const Value *V,
657                                  Optional<CallingConv::ID> CallConv) {
658   EVT ValueVT = Val.getValueType();
659   assert(ValueVT.isVector() && "Not a vector");
660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
661   const bool IsABIRegCopy = CallConv.has_value();
662 
663   if (NumParts == 1) {
664     EVT PartEVT = PartVT;
665     if (PartEVT == ValueVT) {
666       // Nothing to do.
667     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
668       // Bitconvert vector->vector case.
669       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
670     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
671       Val = Widened;
672     } else if (PartVT.isVector() &&
673                PartEVT.getVectorElementType().bitsGE(
674                    ValueVT.getVectorElementType()) &&
675                PartEVT.getVectorElementCount() ==
676                    ValueVT.getVectorElementCount()) {
677 
678       // Promoted vector extract
679       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
680     } else if (PartEVT.isVector() &&
681                PartEVT.getVectorElementType() !=
682                    ValueVT.getVectorElementType() &&
683                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
684                    TargetLowering::TypeWidenVector) {
685       // Combination of widening and promotion.
686       EVT WidenVT =
687           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
688                            PartVT.getVectorElementCount());
689       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
690       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
691     } else {
692       // Don't extract an integer from a float vector. This can happen if the
693       // FP type gets softened to integer and then promoted. The promotion
694       // prevents it from being picked up by the earlier bitcast case.
695       if (ValueVT.getVectorElementCount().isScalar() &&
696           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
697         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
698                           DAG.getVectorIdxConstant(0, DL));
699       } else {
700         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
701         assert(PartVT.getFixedSizeInBits() > ValueSize &&
702                "lossy conversion of vector to scalar type");
703         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
704         Val = DAG.getBitcast(IntermediateType, Val);
705         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
706       }
707     }
708 
709     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
710     Parts[0] = Val;
711     return;
712   }
713 
714   // Handle a multi-element vector.
715   EVT IntermediateVT;
716   MVT RegisterVT;
717   unsigned NumIntermediates;
718   unsigned NumRegs;
719   if (IsABIRegCopy) {
720     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
721         *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT,
722         NumIntermediates, RegisterVT);
723   } else {
724     NumRegs =
725         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
726                                    NumIntermediates, RegisterVT);
727   }
728 
729   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
730   NumParts = NumRegs; // Silence a compiler warning.
731   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
732 
733   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
734          "Mixing scalable and fixed vectors when copying in parts");
735 
736   Optional<ElementCount> DestEltCnt;
737 
738   if (IntermediateVT.isVector())
739     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
740   else
741     DestEltCnt = ElementCount::getFixed(NumIntermediates);
742 
743   EVT BuiltVectorTy = EVT::getVectorVT(
744       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
745 
746   if (ValueVT == BuiltVectorTy) {
747     // Nothing to do.
748   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
749     // Bitconvert vector->vector case.
750     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
751   } else {
752     if (BuiltVectorTy.getVectorElementType().bitsGT(
753             ValueVT.getVectorElementType())) {
754       // Integer promotion.
755       ValueVT = EVT::getVectorVT(*DAG.getContext(),
756                                  BuiltVectorTy.getVectorElementType(),
757                                  ValueVT.getVectorElementCount());
758       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
759     }
760 
761     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
762       Val = Widened;
763     }
764   }
765 
766   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
767 
768   // Split the vector into intermediate operands.
769   SmallVector<SDValue, 8> Ops(NumIntermediates);
770   for (unsigned i = 0; i != NumIntermediates; ++i) {
771     if (IntermediateVT.isVector()) {
772       // This does something sensible for scalable vectors - see the
773       // definition of EXTRACT_SUBVECTOR for further details.
774       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
775       Ops[i] =
776           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
777                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
778     } else {
779       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
780                            DAG.getVectorIdxConstant(i, DL));
781     }
782   }
783 
784   // Split the intermediate operands into legal parts.
785   if (NumParts == NumIntermediates) {
786     // If the register was not expanded, promote or copy the value,
787     // as appropriate.
788     for (unsigned i = 0; i != NumParts; ++i)
789       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
790   } else if (NumParts > 0) {
791     // If the intermediate type was expanded, split each the value into
792     // legal parts.
793     assert(NumIntermediates != 0 && "division by zero");
794     assert(NumParts % NumIntermediates == 0 &&
795            "Must expand into a divisible number of parts!");
796     unsigned Factor = NumParts / NumIntermediates;
797     for (unsigned i = 0; i != NumIntermediates; ++i)
798       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
799                      CallConv);
800   }
801 }
802 
803 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
804                            EVT valuevt, Optional<CallingConv::ID> CC)
805     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
806       RegCount(1, regs.size()), CallConv(CC) {}
807 
808 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
809                            const DataLayout &DL, unsigned Reg, Type *Ty,
810                            Optional<CallingConv::ID> CC) {
811   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
812 
813   CallConv = CC;
814 
815   for (EVT ValueVT : ValueVTs) {
816     unsigned NumRegs =
817         isABIMangled()
818             ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT)
819             : TLI.getNumRegisters(Context, ValueVT);
820     MVT RegisterVT =
821         isABIMangled()
822             ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT)
823             : TLI.getRegisterType(Context, ValueVT);
824     for (unsigned i = 0; i != NumRegs; ++i)
825       Regs.push_back(Reg + i);
826     RegVTs.push_back(RegisterVT);
827     RegCount.push_back(NumRegs);
828     Reg += NumRegs;
829   }
830 }
831 
832 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
833                                       FunctionLoweringInfo &FuncInfo,
834                                       const SDLoc &dl, SDValue &Chain,
835                                       SDValue *Flag, const Value *V) const {
836   // A Value with type {} or [0 x %t] needs no registers.
837   if (ValueVTs.empty())
838     return SDValue();
839 
840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
841 
842   // Assemble the legal parts into the final values.
843   SmallVector<SDValue, 4> Values(ValueVTs.size());
844   SmallVector<SDValue, 8> Parts;
845   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
846     // Copy the legal parts from the registers.
847     EVT ValueVT = ValueVTs[Value];
848     unsigned NumRegs = RegCount[Value];
849     MVT RegisterVT =
850         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
851                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
852                        : RegVTs[Value];
853 
854     Parts.resize(NumRegs);
855     for (unsigned i = 0; i != NumRegs; ++i) {
856       SDValue P;
857       if (!Flag) {
858         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
859       } else {
860         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
861         *Flag = P.getValue(2);
862       }
863 
864       Chain = P.getValue(1);
865       Parts[i] = P;
866 
867       // If the source register was virtual and if we know something about it,
868       // add an assert node.
869       if (!Register::isVirtualRegister(Regs[Part + i]) ||
870           !RegisterVT.isInteger())
871         continue;
872 
873       const FunctionLoweringInfo::LiveOutInfo *LOI =
874         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
875       if (!LOI)
876         continue;
877 
878       unsigned RegSize = RegisterVT.getScalarSizeInBits();
879       unsigned NumSignBits = LOI->NumSignBits;
880       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
881 
882       if (NumZeroBits == RegSize) {
883         // The current value is a zero.
884         // Explicitly express that as it would be easier for
885         // optimizations to kick in.
886         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
887         continue;
888       }
889 
890       // FIXME: We capture more information than the dag can represent.  For
891       // now, just use the tightest assertzext/assertsext possible.
892       bool isSExt;
893       EVT FromVT(MVT::Other);
894       if (NumZeroBits) {
895         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
896         isSExt = false;
897       } else if (NumSignBits > 1) {
898         FromVT =
899             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
900         isSExt = true;
901       } else {
902         continue;
903       }
904       // Add an assertion node.
905       assert(FromVT != MVT::Other);
906       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
907                              RegisterVT, P, DAG.getValueType(FromVT));
908     }
909 
910     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
911                                      RegisterVT, ValueVT, V, CallConv);
912     Part += NumRegs;
913     Parts.clear();
914   }
915 
916   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
917 }
918 
919 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
920                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
921                                  const Value *V,
922                                  ISD::NodeType PreferredExtendType) const {
923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
924   ISD::NodeType ExtendKind = PreferredExtendType;
925 
926   // Get the list of the values's legal parts.
927   unsigned NumRegs = Regs.size();
928   SmallVector<SDValue, 8> Parts(NumRegs);
929   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
930     unsigned NumParts = RegCount[Value];
931 
932     MVT RegisterVT =
933         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
934                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
935                        : RegVTs[Value];
936 
937     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
938       ExtendKind = ISD::ZERO_EXTEND;
939 
940     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
941                    NumParts, RegisterVT, V, CallConv, ExtendKind);
942     Part += NumParts;
943   }
944 
945   // Copy the parts into the registers.
946   SmallVector<SDValue, 8> Chains(NumRegs);
947   for (unsigned i = 0; i != NumRegs; ++i) {
948     SDValue Part;
949     if (!Flag) {
950       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
951     } else {
952       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
953       *Flag = Part.getValue(1);
954     }
955 
956     Chains[i] = Part.getValue(0);
957   }
958 
959   if (NumRegs == 1 || Flag)
960     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
961     // flagged to it. That is the CopyToReg nodes and the user are considered
962     // a single scheduling unit. If we create a TokenFactor and return it as
963     // chain, then the TokenFactor is both a predecessor (operand) of the
964     // user as well as a successor (the TF operands are flagged to the user).
965     // c1, f1 = CopyToReg
966     // c2, f2 = CopyToReg
967     // c3     = TokenFactor c1, c2
968     // ...
969     //        = op c3, ..., f2
970     Chain = Chains[NumRegs-1];
971   else
972     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
973 }
974 
975 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
976                                         unsigned MatchingIdx, const SDLoc &dl,
977                                         SelectionDAG &DAG,
978                                         std::vector<SDValue> &Ops) const {
979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
980 
981   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
982   if (HasMatching)
983     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
984   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
985     // Put the register class of the virtual registers in the flag word.  That
986     // way, later passes can recompute register class constraints for inline
987     // assembly as well as normal instructions.
988     // Don't do this for tied operands that can use the regclass information
989     // from the def.
990     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
991     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
992     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
993   }
994 
995   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
996   Ops.push_back(Res);
997 
998   if (Code == InlineAsm::Kind_Clobber) {
999     // Clobbers should always have a 1:1 mapping with registers, and may
1000     // reference registers that have illegal (e.g. vector) types. Hence, we
1001     // shouldn't try to apply any sort of splitting logic to them.
1002     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1003            "No 1:1 mapping from clobbers to regs?");
1004     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1005     (void)SP;
1006     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1007       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1008       assert(
1009           (Regs[I] != SP ||
1010            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1011           "If we clobbered the stack pointer, MFI should know about it.");
1012     }
1013     return;
1014   }
1015 
1016   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1017     MVT RegisterVT = RegVTs[Value];
1018     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1019                                            RegisterVT);
1020     for (unsigned i = 0; i != NumRegs; ++i) {
1021       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1022       unsigned TheReg = Regs[Reg++];
1023       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1024     }
1025   }
1026 }
1027 
1028 SmallVector<std::pair<unsigned, TypeSize>, 4>
1029 RegsForValue::getRegsAndSizes() const {
1030   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1031   unsigned I = 0;
1032   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1033     unsigned RegCount = std::get<0>(CountAndVT);
1034     MVT RegisterVT = std::get<1>(CountAndVT);
1035     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1036     for (unsigned E = I + RegCount; I != E; ++I)
1037       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1038   }
1039   return OutVec;
1040 }
1041 
1042 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1043                                AssumptionCache *ac,
1044                                const TargetLibraryInfo *li) {
1045   AA = aa;
1046   AC = ac;
1047   GFI = gfi;
1048   LibInfo = li;
1049   Context = DAG.getContext();
1050   LPadToCallSiteMap.clear();
1051   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1052 }
1053 
1054 void SelectionDAGBuilder::clear() {
1055   NodeMap.clear();
1056   UnusedArgNodeMap.clear();
1057   PendingLoads.clear();
1058   PendingExports.clear();
1059   PendingConstrainedFP.clear();
1060   PendingConstrainedFPStrict.clear();
1061   CurInst = nullptr;
1062   HasTailCall = false;
1063   SDNodeOrder = LowestSDNodeOrder;
1064   StatepointLowering.clear();
1065 }
1066 
1067 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1068   DanglingDebugInfoMap.clear();
1069 }
1070 
1071 // Update DAG root to include dependencies on Pending chains.
1072 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1073   SDValue Root = DAG.getRoot();
1074 
1075   if (Pending.empty())
1076     return Root;
1077 
1078   // Add current root to PendingChains, unless we already indirectly
1079   // depend on it.
1080   if (Root.getOpcode() != ISD::EntryToken) {
1081     unsigned i = 0, e = Pending.size();
1082     for (; i != e; ++i) {
1083       assert(Pending[i].getNode()->getNumOperands() > 1);
1084       if (Pending[i].getNode()->getOperand(0) == Root)
1085         break;  // Don't add the root if we already indirectly depend on it.
1086     }
1087 
1088     if (i == e)
1089       Pending.push_back(Root);
1090   }
1091 
1092   if (Pending.size() == 1)
1093     Root = Pending[0];
1094   else
1095     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1096 
1097   DAG.setRoot(Root);
1098   Pending.clear();
1099   return Root;
1100 }
1101 
1102 SDValue SelectionDAGBuilder::getMemoryRoot() {
1103   return updateRoot(PendingLoads);
1104 }
1105 
1106 SDValue SelectionDAGBuilder::getRoot() {
1107   // Chain up all pending constrained intrinsics together with all
1108   // pending loads, by simply appending them to PendingLoads and
1109   // then calling getMemoryRoot().
1110   PendingLoads.reserve(PendingLoads.size() +
1111                        PendingConstrainedFP.size() +
1112                        PendingConstrainedFPStrict.size());
1113   PendingLoads.append(PendingConstrainedFP.begin(),
1114                       PendingConstrainedFP.end());
1115   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1116                       PendingConstrainedFPStrict.end());
1117   PendingConstrainedFP.clear();
1118   PendingConstrainedFPStrict.clear();
1119   return getMemoryRoot();
1120 }
1121 
1122 SDValue SelectionDAGBuilder::getControlRoot() {
1123   // We need to emit pending fpexcept.strict constrained intrinsics,
1124   // so append them to the PendingExports list.
1125   PendingExports.append(PendingConstrainedFPStrict.begin(),
1126                         PendingConstrainedFPStrict.end());
1127   PendingConstrainedFPStrict.clear();
1128   return updateRoot(PendingExports);
1129 }
1130 
1131 void SelectionDAGBuilder::visit(const Instruction &I) {
1132   // Set up outgoing PHI node register values before emitting the terminator.
1133   if (I.isTerminator()) {
1134     HandlePHINodesInSuccessorBlocks(I.getParent());
1135   }
1136 
1137   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1138   if (!isa<DbgInfoIntrinsic>(I))
1139     ++SDNodeOrder;
1140 
1141   CurInst = &I;
1142 
1143   // Set inserted listener only if required.
1144   bool NodeInserted = false;
1145   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1146   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1147   if (PCSectionsMD) {
1148     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1149         DAG, [&](SDNode *) { NodeInserted = true; });
1150   }
1151 
1152   visit(I.getOpcode(), I);
1153 
1154   if (!I.isTerminator() && !HasTailCall &&
1155       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1156     CopyToExportRegsIfNeeded(&I);
1157 
1158   // Handle metadata.
1159   if (PCSectionsMD) {
1160     auto It = NodeMap.find(&I);
1161     if (It != NodeMap.end()) {
1162       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1163     } else if (NodeInserted) {
1164       // This should not happen; if it does, don't let it go unnoticed so we can
1165       // fix it. Relevant visit*() function is probably missing a setValue().
1166       errs() << "warning: loosing !pcsections metadata ["
1167              << I.getModule()->getName() << "]\n";
1168       LLVM_DEBUG(I.dump());
1169       assert(false);
1170     }
1171   }
1172 
1173   CurInst = nullptr;
1174 }
1175 
1176 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1177   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1178 }
1179 
1180 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1181   // Note: this doesn't use InstVisitor, because it has to work with
1182   // ConstantExpr's in addition to instructions.
1183   switch (Opcode) {
1184   default: llvm_unreachable("Unknown instruction type encountered!");
1185     // Build the switch statement using the Instruction.def file.
1186 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1187     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1188 #include "llvm/IR/Instruction.def"
1189   }
1190 }
1191 
1192 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1193                                                DebugLoc DL, unsigned Order) {
1194   // We treat variadic dbg_values differently at this stage.
1195   if (DI->hasArgList()) {
1196     // For variadic dbg_values we will now insert an undef.
1197     // FIXME: We can potentially recover these!
1198     SmallVector<SDDbgOperand, 2> Locs;
1199     for (const Value *V : DI->getValues()) {
1200       auto Undef = UndefValue::get(V->getType());
1201       Locs.push_back(SDDbgOperand::fromConst(Undef));
1202     }
1203     SDDbgValue *SDV = DAG.getDbgValueList(
1204         DI->getVariable(), DI->getExpression(), Locs, {},
1205         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1206     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1207   } else {
1208     // TODO: Dangling debug info will eventually either be resolved or produce
1209     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1210     // between the original dbg.value location and its resolved DBG_VALUE,
1211     // which we should ideally fill with an extra Undef DBG_VALUE.
1212     assert(DI->getNumVariableLocationOps() == 1 &&
1213            "DbgValueInst without an ArgList should have a single location "
1214            "operand.");
1215     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1216   }
1217 }
1218 
1219 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1220                                                 const DIExpression *Expr) {
1221   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1222     const DbgValueInst *DI = DDI.getDI();
1223     DIVariable *DanglingVariable = DI->getVariable();
1224     DIExpression *DanglingExpr = DI->getExpression();
1225     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1226       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1227       return true;
1228     }
1229     return false;
1230   };
1231 
1232   for (auto &DDIMI : DanglingDebugInfoMap) {
1233     DanglingDebugInfoVector &DDIV = DDIMI.second;
1234 
1235     // If debug info is to be dropped, run it through final checks to see
1236     // whether it can be salvaged.
1237     for (auto &DDI : DDIV)
1238       if (isMatchingDbgValue(DDI))
1239         salvageUnresolvedDbgValue(DDI);
1240 
1241     erase_if(DDIV, isMatchingDbgValue);
1242   }
1243 }
1244 
1245 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1246 // generate the debug data structures now that we've seen its definition.
1247 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1248                                                    SDValue Val) {
1249   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1250   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1251     return;
1252 
1253   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1254   for (auto &DDI : DDIV) {
1255     const DbgValueInst *DI = DDI.getDI();
1256     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1257     assert(DI && "Ill-formed DanglingDebugInfo");
1258     DebugLoc dl = DDI.getdl();
1259     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1260     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1261     DILocalVariable *Variable = DI->getVariable();
1262     DIExpression *Expr = DI->getExpression();
1263     assert(Variable->isValidLocationForIntrinsic(dl) &&
1264            "Expected inlined-at fields to agree");
1265     SDDbgValue *SDV;
1266     if (Val.getNode()) {
1267       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1268       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1269       // we couldn't resolve it directly when examining the DbgValue intrinsic
1270       // in the first place we should not be more successful here). Unless we
1271       // have some test case that prove this to be correct we should avoid
1272       // calling EmitFuncArgumentDbgValue here.
1273       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl,
1274                                     FuncArgumentDbgValueKind::Value, Val)) {
1275         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1276                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1277         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1278         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1279         // inserted after the definition of Val when emitting the instructions
1280         // after ISel. An alternative could be to teach
1281         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1282         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1283                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1284                    << ValSDNodeOrder << "\n");
1285         SDV = getDbgValue(Val, Variable, Expr, dl,
1286                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1287         DAG.AddDbgValue(SDV, false);
1288       } else
1289         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1290                           << "in EmitFuncArgumentDbgValue\n");
1291     } else {
1292       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1293       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1294       auto SDV =
1295           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1296       DAG.AddDbgValue(SDV, false);
1297     }
1298   }
1299   DDIV.clear();
1300 }
1301 
1302 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1303   // TODO: For the variadic implementation, instead of only checking the fail
1304   // state of `handleDebugValue`, we need know specifically which values were
1305   // invalid, so that we attempt to salvage only those values when processing
1306   // a DIArgList.
1307   assert(!DDI.getDI()->hasArgList() &&
1308          "Not implemented for variadic dbg_values");
1309   Value *V = DDI.getDI()->getValue(0);
1310   DILocalVariable *Var = DDI.getDI()->getVariable();
1311   DIExpression *Expr = DDI.getDI()->getExpression();
1312   DebugLoc DL = DDI.getdl();
1313   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1314   unsigned SDOrder = DDI.getSDNodeOrder();
1315   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1316   // that DW_OP_stack_value is desired.
1317   assert(isa<DbgValueInst>(DDI.getDI()));
1318   bool StackValue = true;
1319 
1320   // Can this Value can be encoded without any further work?
1321   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1322     return;
1323 
1324   // Attempt to salvage back through as many instructions as possible. Bail if
1325   // a non-instruction is seen, such as a constant expression or global
1326   // variable. FIXME: Further work could recover those too.
1327   while (isa<Instruction>(V)) {
1328     Instruction &VAsInst = *cast<Instruction>(V);
1329     // Temporary "0", awaiting real implementation.
1330     SmallVector<uint64_t, 16> Ops;
1331     SmallVector<Value *, 4> AdditionalValues;
1332     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1333                              AdditionalValues);
1334     // If we cannot salvage any further, and haven't yet found a suitable debug
1335     // expression, bail out.
1336     if (!V)
1337       break;
1338 
1339     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1340     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1341     // here for variadic dbg_values, remove that condition.
1342     if (!AdditionalValues.empty())
1343       break;
1344 
1345     // New value and expr now represent this debuginfo.
1346     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1347 
1348     // Some kind of simplification occurred: check whether the operand of the
1349     // salvaged debug expression can be encoded in this DAG.
1350     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1351                          /*IsVariadic=*/false)) {
1352       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1353                         << *DDI.getDI() << "\nBy stripping back to:\n  " << *V);
1354       return;
1355     }
1356   }
1357 
1358   // This was the final opportunity to salvage this debug information, and it
1359   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1360   // any earlier variable location.
1361   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1362   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1363   DAG.AddDbgValue(SDV, false);
1364 
1365   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << *DDI.getDI()
1366                     << "\n");
1367   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1368                     << "\n");
1369 }
1370 
1371 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1372                                            DILocalVariable *Var,
1373                                            DIExpression *Expr, DebugLoc dl,
1374                                            DebugLoc InstDL, unsigned Order,
1375                                            bool IsVariadic) {
1376   if (Values.empty())
1377     return true;
1378   SmallVector<SDDbgOperand> LocationOps;
1379   SmallVector<SDNode *> Dependencies;
1380   for (const Value *V : Values) {
1381     // Constant value.
1382     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1383         isa<ConstantPointerNull>(V)) {
1384       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1385       continue;
1386     }
1387 
1388     // Look through IntToPtr constants.
1389     if (auto *CE = dyn_cast<ConstantExpr>(V))
1390       if (CE->getOpcode() == Instruction::IntToPtr) {
1391         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1392         continue;
1393       }
1394 
1395     // If the Value is a frame index, we can create a FrameIndex debug value
1396     // without relying on the DAG at all.
1397     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1398       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1399       if (SI != FuncInfo.StaticAllocaMap.end()) {
1400         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1401         continue;
1402       }
1403     }
1404 
1405     // Do not use getValue() in here; we don't want to generate code at
1406     // this point if it hasn't been done yet.
1407     SDValue N = NodeMap[V];
1408     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1409       N = UnusedArgNodeMap[V];
1410     if (N.getNode()) {
1411       // Only emit func arg dbg value for non-variadic dbg.values for now.
1412       if (!IsVariadic &&
1413           EmitFuncArgumentDbgValue(V, Var, Expr, dl,
1414                                    FuncArgumentDbgValueKind::Value, N))
1415         return true;
1416       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1417         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1418         // describe stack slot locations.
1419         //
1420         // Consider "int x = 0; int *px = &x;". There are two kinds of
1421         // interesting debug values here after optimization:
1422         //
1423         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1424         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1425         //
1426         // Both describe the direct values of their associated variables.
1427         Dependencies.push_back(N.getNode());
1428         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1429         continue;
1430       }
1431       LocationOps.emplace_back(
1432           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1433       continue;
1434     }
1435 
1436     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1437     // Special rules apply for the first dbg.values of parameter variables in a
1438     // function. Identify them by the fact they reference Argument Values, that
1439     // they're parameters, and they are parameters of the current function. We
1440     // need to let them dangle until they get an SDNode.
1441     bool IsParamOfFunc =
1442         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1443     if (IsParamOfFunc)
1444       return false;
1445 
1446     // The value is not used in this block yet (or it would have an SDNode).
1447     // We still want the value to appear for the user if possible -- if it has
1448     // an associated VReg, we can refer to that instead.
1449     auto VMI = FuncInfo.ValueMap.find(V);
1450     if (VMI != FuncInfo.ValueMap.end()) {
1451       unsigned Reg = VMI->second;
1452       // If this is a PHI node, it may be split up into several MI PHI nodes
1453       // (in FunctionLoweringInfo::set).
1454       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1455                        V->getType(), None);
1456       if (RFV.occupiesMultipleRegs()) {
1457         // FIXME: We could potentially support variadic dbg_values here.
1458         if (IsVariadic)
1459           return false;
1460         unsigned Offset = 0;
1461         unsigned BitsToDescribe = 0;
1462         if (auto VarSize = Var->getSizeInBits())
1463           BitsToDescribe = *VarSize;
1464         if (auto Fragment = Expr->getFragmentInfo())
1465           BitsToDescribe = Fragment->SizeInBits;
1466         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1467           // Bail out if all bits are described already.
1468           if (Offset >= BitsToDescribe)
1469             break;
1470           // TODO: handle scalable vectors.
1471           unsigned RegisterSize = RegAndSize.second;
1472           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1473                                       ? BitsToDescribe - Offset
1474                                       : RegisterSize;
1475           auto FragmentExpr = DIExpression::createFragmentExpression(
1476               Expr, Offset, FragmentSize);
1477           if (!FragmentExpr)
1478             continue;
1479           SDDbgValue *SDV = DAG.getVRegDbgValue(
1480               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1481           DAG.AddDbgValue(SDV, false);
1482           Offset += RegisterSize;
1483         }
1484         return true;
1485       }
1486       // We can use simple vreg locations for variadic dbg_values as well.
1487       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1488       continue;
1489     }
1490     // We failed to create a SDDbgOperand for V.
1491     return false;
1492   }
1493 
1494   // We have created a SDDbgOperand for each Value in Values.
1495   // Should use Order instead of SDNodeOrder?
1496   assert(!LocationOps.empty());
1497   SDDbgValue *SDV =
1498       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1499                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1500   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1501   return true;
1502 }
1503 
1504 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1505   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1506   for (auto &Pair : DanglingDebugInfoMap)
1507     for (auto &DDI : Pair.second)
1508       salvageUnresolvedDbgValue(DDI);
1509   clearDanglingDebugInfo();
1510 }
1511 
1512 /// getCopyFromRegs - If there was virtual register allocated for the value V
1513 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1514 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1515   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1516   SDValue Result;
1517 
1518   if (It != FuncInfo.ValueMap.end()) {
1519     Register InReg = It->second;
1520 
1521     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1522                      DAG.getDataLayout(), InReg, Ty,
1523                      None); // This is not an ABI copy.
1524     SDValue Chain = DAG.getEntryNode();
1525     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1526                                  V);
1527     resolveDanglingDebugInfo(V, Result);
1528   }
1529 
1530   return Result;
1531 }
1532 
1533 /// getValue - Return an SDValue for the given Value.
1534 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1535   // If we already have an SDValue for this value, use it. It's important
1536   // to do this first, so that we don't create a CopyFromReg if we already
1537   // have a regular SDValue.
1538   SDValue &N = NodeMap[V];
1539   if (N.getNode()) return N;
1540 
1541   // If there's a virtual register allocated and initialized for this
1542   // value, use it.
1543   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1544     return copyFromReg;
1545 
1546   // Otherwise create a new SDValue and remember it.
1547   SDValue Val = getValueImpl(V);
1548   NodeMap[V] = Val;
1549   resolveDanglingDebugInfo(V, Val);
1550   return Val;
1551 }
1552 
1553 /// getNonRegisterValue - Return an SDValue for the given Value, but
1554 /// don't look in FuncInfo.ValueMap for a virtual register.
1555 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1556   // If we already have an SDValue for this value, use it.
1557   SDValue &N = NodeMap[V];
1558   if (N.getNode()) {
1559     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1560       // Remove the debug location from the node as the node is about to be used
1561       // in a location which may differ from the original debug location.  This
1562       // is relevant to Constant and ConstantFP nodes because they can appear
1563       // as constant expressions inside PHI nodes.
1564       N->setDebugLoc(DebugLoc());
1565     }
1566     return N;
1567   }
1568 
1569   // Otherwise create a new SDValue and remember it.
1570   SDValue Val = getValueImpl(V);
1571   NodeMap[V] = Val;
1572   resolveDanglingDebugInfo(V, Val);
1573   return Val;
1574 }
1575 
1576 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1577 /// Create an SDValue for the given value.
1578 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1579   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1580 
1581   if (const Constant *C = dyn_cast<Constant>(V)) {
1582     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1583 
1584     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1585       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1586 
1587     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1588       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1589 
1590     if (isa<ConstantPointerNull>(C)) {
1591       unsigned AS = V->getType()->getPointerAddressSpace();
1592       return DAG.getConstant(0, getCurSDLoc(),
1593                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1594     }
1595 
1596     if (match(C, m_VScale(DAG.getDataLayout())))
1597       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1598 
1599     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1600       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1601 
1602     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1603       return DAG.getUNDEF(VT);
1604 
1605     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1606       visit(CE->getOpcode(), *CE);
1607       SDValue N1 = NodeMap[V];
1608       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1609       return N1;
1610     }
1611 
1612     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1613       SmallVector<SDValue, 4> Constants;
1614       for (const Use &U : C->operands()) {
1615         SDNode *Val = getValue(U).getNode();
1616         // If the operand is an empty aggregate, there are no values.
1617         if (!Val) continue;
1618         // Add each leaf value from the operand to the Constants list
1619         // to form a flattened list of all the values.
1620         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1621           Constants.push_back(SDValue(Val, i));
1622       }
1623 
1624       return DAG.getMergeValues(Constants, getCurSDLoc());
1625     }
1626 
1627     if (const ConstantDataSequential *CDS =
1628           dyn_cast<ConstantDataSequential>(C)) {
1629       SmallVector<SDValue, 4> Ops;
1630       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1631         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1632         // Add each leaf value from the operand to the Constants list
1633         // to form a flattened list of all the values.
1634         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1635           Ops.push_back(SDValue(Val, i));
1636       }
1637 
1638       if (isa<ArrayType>(CDS->getType()))
1639         return DAG.getMergeValues(Ops, getCurSDLoc());
1640       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1641     }
1642 
1643     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1644       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1645              "Unknown struct or array constant!");
1646 
1647       SmallVector<EVT, 4> ValueVTs;
1648       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1649       unsigned NumElts = ValueVTs.size();
1650       if (NumElts == 0)
1651         return SDValue(); // empty struct
1652       SmallVector<SDValue, 4> Constants(NumElts);
1653       for (unsigned i = 0; i != NumElts; ++i) {
1654         EVT EltVT = ValueVTs[i];
1655         if (isa<UndefValue>(C))
1656           Constants[i] = DAG.getUNDEF(EltVT);
1657         else if (EltVT.isFloatingPoint())
1658           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1659         else
1660           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1661       }
1662 
1663       return DAG.getMergeValues(Constants, getCurSDLoc());
1664     }
1665 
1666     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1667       return DAG.getBlockAddress(BA, VT);
1668 
1669     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1670       return getValue(Equiv->getGlobalValue());
1671 
1672     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1673       return getValue(NC->getGlobalValue());
1674 
1675     VectorType *VecTy = cast<VectorType>(V->getType());
1676 
1677     // Now that we know the number and type of the elements, get that number of
1678     // elements into the Ops array based on what kind of constant it is.
1679     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1680       SmallVector<SDValue, 16> Ops;
1681       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1682       for (unsigned i = 0; i != NumElements; ++i)
1683         Ops.push_back(getValue(CV->getOperand(i)));
1684 
1685       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1686     }
1687 
1688     if (isa<ConstantAggregateZero>(C)) {
1689       EVT EltVT =
1690           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1691 
1692       SDValue Op;
1693       if (EltVT.isFloatingPoint())
1694         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1695       else
1696         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1697 
1698       if (isa<ScalableVectorType>(VecTy))
1699         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1700       return NodeMap[V] = DAG.getSplatBuildVector(VT, getCurSDLoc(), Op);
1701     }
1702 
1703     llvm_unreachable("Unknown vector constant");
1704   }
1705 
1706   // If this is a static alloca, generate it as the frameindex instead of
1707   // computation.
1708   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1709     DenseMap<const AllocaInst*, int>::iterator SI =
1710       FuncInfo.StaticAllocaMap.find(AI);
1711     if (SI != FuncInfo.StaticAllocaMap.end())
1712       return DAG.getFrameIndex(SI->second,
1713                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1714   }
1715 
1716   // If this is an instruction which fast-isel has deferred, select it now.
1717   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1718     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1719 
1720     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1721                      Inst->getType(), None);
1722     SDValue Chain = DAG.getEntryNode();
1723     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1724   }
1725 
1726   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1727     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1728 
1729   if (const auto *BB = dyn_cast<BasicBlock>(V))
1730     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1731 
1732   llvm_unreachable("Can't get register for value!");
1733 }
1734 
1735 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1736   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1737   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1738   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1739   bool IsSEH = isAsynchronousEHPersonality(Pers);
1740   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1741   if (!IsSEH)
1742     CatchPadMBB->setIsEHScopeEntry();
1743   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1744   if (IsMSVCCXX || IsCoreCLR)
1745     CatchPadMBB->setIsEHFuncletEntry();
1746 }
1747 
1748 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1749   // Update machine-CFG edge.
1750   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1751   FuncInfo.MBB->addSuccessor(TargetMBB);
1752   TargetMBB->setIsEHCatchretTarget(true);
1753   DAG.getMachineFunction().setHasEHCatchret(true);
1754 
1755   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1756   bool IsSEH = isAsynchronousEHPersonality(Pers);
1757   if (IsSEH) {
1758     // If this is not a fall-through branch or optimizations are switched off,
1759     // emit the branch.
1760     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1761         TM.getOptLevel() == CodeGenOpt::None)
1762       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1763                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1764     return;
1765   }
1766 
1767   // Figure out the funclet membership for the catchret's successor.
1768   // This will be used by the FuncletLayout pass to determine how to order the
1769   // BB's.
1770   // A 'catchret' returns to the outer scope's color.
1771   Value *ParentPad = I.getCatchSwitchParentPad();
1772   const BasicBlock *SuccessorColor;
1773   if (isa<ConstantTokenNone>(ParentPad))
1774     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1775   else
1776     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1777   assert(SuccessorColor && "No parent funclet for catchret!");
1778   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1779   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1780 
1781   // Create the terminator node.
1782   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1783                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1784                             DAG.getBasicBlock(SuccessorColorMBB));
1785   DAG.setRoot(Ret);
1786 }
1787 
1788 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1789   // Don't emit any special code for the cleanuppad instruction. It just marks
1790   // the start of an EH scope/funclet.
1791   FuncInfo.MBB->setIsEHScopeEntry();
1792   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1793   if (Pers != EHPersonality::Wasm_CXX) {
1794     FuncInfo.MBB->setIsEHFuncletEntry();
1795     FuncInfo.MBB->setIsCleanupFuncletEntry();
1796   }
1797 }
1798 
1799 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1800 // not match, it is OK to add only the first unwind destination catchpad to the
1801 // successors, because there will be at least one invoke instruction within the
1802 // catch scope that points to the next unwind destination, if one exists, so
1803 // CFGSort cannot mess up with BB sorting order.
1804 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1805 // call within them, and catchpads only consisting of 'catch (...)' have a
1806 // '__cxa_end_catch' call within them, both of which generate invokes in case
1807 // the next unwind destination exists, i.e., the next unwind destination is not
1808 // the caller.)
1809 //
1810 // Having at most one EH pad successor is also simpler and helps later
1811 // transformations.
1812 //
1813 // For example,
1814 // current:
1815 //   invoke void @foo to ... unwind label %catch.dispatch
1816 // catch.dispatch:
1817 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1818 // catch.start:
1819 //   ...
1820 //   ... in this BB or some other child BB dominated by this BB there will be an
1821 //   invoke that points to 'next' BB as an unwind destination
1822 //
1823 // next: ; We don't need to add this to 'current' BB's successor
1824 //   ...
1825 static void findWasmUnwindDestinations(
1826     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1827     BranchProbability Prob,
1828     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1829         &UnwindDests) {
1830   while (EHPadBB) {
1831     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1832     if (isa<CleanupPadInst>(Pad)) {
1833       // Stop on cleanup pads.
1834       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1835       UnwindDests.back().first->setIsEHScopeEntry();
1836       break;
1837     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1838       // Add the catchpad handlers to the possible destinations. We don't
1839       // continue to the unwind destination of the catchswitch for wasm.
1840       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1841         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1842         UnwindDests.back().first->setIsEHScopeEntry();
1843       }
1844       break;
1845     } else {
1846       continue;
1847     }
1848   }
1849 }
1850 
1851 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1852 /// many places it could ultimately go. In the IR, we have a single unwind
1853 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1854 /// This function skips over imaginary basic blocks that hold catchswitch
1855 /// instructions, and finds all the "real" machine
1856 /// basic block destinations. As those destinations may not be successors of
1857 /// EHPadBB, here we also calculate the edge probability to those destinations.
1858 /// The passed-in Prob is the edge probability to EHPadBB.
1859 static void findUnwindDestinations(
1860     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1861     BranchProbability Prob,
1862     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1863         &UnwindDests) {
1864   EHPersonality Personality =
1865     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1866   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1867   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1868   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1869   bool IsSEH = isAsynchronousEHPersonality(Personality);
1870 
1871   if (IsWasmCXX) {
1872     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1873     assert(UnwindDests.size() <= 1 &&
1874            "There should be at most one unwind destination for wasm");
1875     return;
1876   }
1877 
1878   while (EHPadBB) {
1879     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1880     BasicBlock *NewEHPadBB = nullptr;
1881     if (isa<LandingPadInst>(Pad)) {
1882       // Stop on landingpads. They are not funclets.
1883       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1884       break;
1885     } else if (isa<CleanupPadInst>(Pad)) {
1886       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1887       // personalities.
1888       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1889       UnwindDests.back().first->setIsEHScopeEntry();
1890       UnwindDests.back().first->setIsEHFuncletEntry();
1891       break;
1892     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1893       // Add the catchpad handlers to the possible destinations.
1894       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1895         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1896         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1897         if (IsMSVCCXX || IsCoreCLR)
1898           UnwindDests.back().first->setIsEHFuncletEntry();
1899         if (!IsSEH)
1900           UnwindDests.back().first->setIsEHScopeEntry();
1901       }
1902       NewEHPadBB = CatchSwitch->getUnwindDest();
1903     } else {
1904       continue;
1905     }
1906 
1907     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1908     if (BPI && NewEHPadBB)
1909       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1910     EHPadBB = NewEHPadBB;
1911   }
1912 }
1913 
1914 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1915   // Update successor info.
1916   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1917   auto UnwindDest = I.getUnwindDest();
1918   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1919   BranchProbability UnwindDestProb =
1920       (BPI && UnwindDest)
1921           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1922           : BranchProbability::getZero();
1923   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1924   for (auto &UnwindDest : UnwindDests) {
1925     UnwindDest.first->setIsEHPad();
1926     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1927   }
1928   FuncInfo.MBB->normalizeSuccProbs();
1929 
1930   // Create the terminator node.
1931   SDValue Ret =
1932       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1933   DAG.setRoot(Ret);
1934 }
1935 
1936 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1937   report_fatal_error("visitCatchSwitch not yet implemented!");
1938 }
1939 
1940 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1942   auto &DL = DAG.getDataLayout();
1943   SDValue Chain = getControlRoot();
1944   SmallVector<ISD::OutputArg, 8> Outs;
1945   SmallVector<SDValue, 8> OutVals;
1946 
1947   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1948   // lower
1949   //
1950   //   %val = call <ty> @llvm.experimental.deoptimize()
1951   //   ret <ty> %val
1952   //
1953   // differently.
1954   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1955     LowerDeoptimizingReturn();
1956     return;
1957   }
1958 
1959   if (!FuncInfo.CanLowerReturn) {
1960     unsigned DemoteReg = FuncInfo.DemoteRegister;
1961     const Function *F = I.getParent()->getParent();
1962 
1963     // Emit a store of the return value through the virtual register.
1964     // Leave Outs empty so that LowerReturn won't try to load return
1965     // registers the usual way.
1966     SmallVector<EVT, 1> PtrValueVTs;
1967     ComputeValueVTs(TLI, DL,
1968                     F->getReturnType()->getPointerTo(
1969                         DAG.getDataLayout().getAllocaAddrSpace()),
1970                     PtrValueVTs);
1971 
1972     SDValue RetPtr =
1973         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1974     SDValue RetOp = getValue(I.getOperand(0));
1975 
1976     SmallVector<EVT, 4> ValueVTs, MemVTs;
1977     SmallVector<uint64_t, 4> Offsets;
1978     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1979                     &Offsets);
1980     unsigned NumValues = ValueVTs.size();
1981 
1982     SmallVector<SDValue, 4> Chains(NumValues);
1983     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1984     for (unsigned i = 0; i != NumValues; ++i) {
1985       // An aggregate return value cannot wrap around the address space, so
1986       // offsets to its parts don't wrap either.
1987       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1988                                            TypeSize::Fixed(Offsets[i]));
1989 
1990       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1991       if (MemVTs[i] != ValueVTs[i])
1992         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1993       Chains[i] = DAG.getStore(
1994           Chain, getCurSDLoc(), Val,
1995           // FIXME: better loc info would be nice.
1996           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1997           commonAlignment(BaseAlign, Offsets[i]));
1998     }
1999 
2000     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2001                         MVT::Other, Chains);
2002   } else if (I.getNumOperands() != 0) {
2003     SmallVector<EVT, 4> ValueVTs;
2004     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2005     unsigned NumValues = ValueVTs.size();
2006     if (NumValues) {
2007       SDValue RetOp = getValue(I.getOperand(0));
2008 
2009       const Function *F = I.getParent()->getParent();
2010 
2011       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2012           I.getOperand(0)->getType(), F->getCallingConv(),
2013           /*IsVarArg*/ false, DL);
2014 
2015       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2016       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2017         ExtendKind = ISD::SIGN_EXTEND;
2018       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2019         ExtendKind = ISD::ZERO_EXTEND;
2020 
2021       LLVMContext &Context = F->getContext();
2022       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2023 
2024       for (unsigned j = 0; j != NumValues; ++j) {
2025         EVT VT = ValueVTs[j];
2026 
2027         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2028           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2029 
2030         CallingConv::ID CC = F->getCallingConv();
2031 
2032         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2033         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2034         SmallVector<SDValue, 4> Parts(NumParts);
2035         getCopyToParts(DAG, getCurSDLoc(),
2036                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2037                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2038 
2039         // 'inreg' on function refers to return value
2040         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2041         if (RetInReg)
2042           Flags.setInReg();
2043 
2044         if (I.getOperand(0)->getType()->isPointerTy()) {
2045           Flags.setPointer();
2046           Flags.setPointerAddrSpace(
2047               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2048         }
2049 
2050         if (NeedsRegBlock) {
2051           Flags.setInConsecutiveRegs();
2052           if (j == NumValues - 1)
2053             Flags.setInConsecutiveRegsLast();
2054         }
2055 
2056         // Propagate extension type if any
2057         if (ExtendKind == ISD::SIGN_EXTEND)
2058           Flags.setSExt();
2059         else if (ExtendKind == ISD::ZERO_EXTEND)
2060           Flags.setZExt();
2061 
2062         for (unsigned i = 0; i < NumParts; ++i) {
2063           Outs.push_back(ISD::OutputArg(Flags,
2064                                         Parts[i].getValueType().getSimpleVT(),
2065                                         VT, /*isfixed=*/true, 0, 0));
2066           OutVals.push_back(Parts[i]);
2067         }
2068       }
2069     }
2070   }
2071 
2072   // Push in swifterror virtual register as the last element of Outs. This makes
2073   // sure swifterror virtual register will be returned in the swifterror
2074   // physical register.
2075   const Function *F = I.getParent()->getParent();
2076   if (TLI.supportSwiftError() &&
2077       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2078     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2079     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2080     Flags.setSwiftError();
2081     Outs.push_back(ISD::OutputArg(
2082         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2083         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2084     // Create SDNode for the swifterror virtual register.
2085     OutVals.push_back(
2086         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2087                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2088                         EVT(TLI.getPointerTy(DL))));
2089   }
2090 
2091   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2092   CallingConv::ID CallConv =
2093     DAG.getMachineFunction().getFunction().getCallingConv();
2094   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2095       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2096 
2097   // Verify that the target's LowerReturn behaved as expected.
2098   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2099          "LowerReturn didn't return a valid chain!");
2100 
2101   // Update the DAG with the new chain value resulting from return lowering.
2102   DAG.setRoot(Chain);
2103 }
2104 
2105 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2106 /// created for it, emit nodes to copy the value into the virtual
2107 /// registers.
2108 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2109   // Skip empty types
2110   if (V->getType()->isEmptyTy())
2111     return;
2112 
2113   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2114   if (VMI != FuncInfo.ValueMap.end()) {
2115     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2116     CopyValueToVirtualRegister(V, VMI->second);
2117   }
2118 }
2119 
2120 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2121 /// the current basic block, add it to ValueMap now so that we'll get a
2122 /// CopyTo/FromReg.
2123 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2124   // No need to export constants.
2125   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2126 
2127   // Already exported?
2128   if (FuncInfo.isExportedInst(V)) return;
2129 
2130   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2131   CopyValueToVirtualRegister(V, Reg);
2132 }
2133 
2134 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2135                                                      const BasicBlock *FromBB) {
2136   // The operands of the setcc have to be in this block.  We don't know
2137   // how to export them from some other block.
2138   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2139     // Can export from current BB.
2140     if (VI->getParent() == FromBB)
2141       return true;
2142 
2143     // Is already exported, noop.
2144     return FuncInfo.isExportedInst(V);
2145   }
2146 
2147   // If this is an argument, we can export it if the BB is the entry block or
2148   // if it is already exported.
2149   if (isa<Argument>(V)) {
2150     if (FromBB->isEntryBlock())
2151       return true;
2152 
2153     // Otherwise, can only export this if it is already exported.
2154     return FuncInfo.isExportedInst(V);
2155   }
2156 
2157   // Otherwise, constants can always be exported.
2158   return true;
2159 }
2160 
2161 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2162 BranchProbability
2163 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2164                                         const MachineBasicBlock *Dst) const {
2165   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2166   const BasicBlock *SrcBB = Src->getBasicBlock();
2167   const BasicBlock *DstBB = Dst->getBasicBlock();
2168   if (!BPI) {
2169     // If BPI is not available, set the default probability as 1 / N, where N is
2170     // the number of successors.
2171     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2172     return BranchProbability(1, SuccSize);
2173   }
2174   return BPI->getEdgeProbability(SrcBB, DstBB);
2175 }
2176 
2177 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2178                                                MachineBasicBlock *Dst,
2179                                                BranchProbability Prob) {
2180   if (!FuncInfo.BPI)
2181     Src->addSuccessorWithoutProb(Dst);
2182   else {
2183     if (Prob.isUnknown())
2184       Prob = getEdgeProbability(Src, Dst);
2185     Src->addSuccessor(Dst, Prob);
2186   }
2187 }
2188 
2189 static bool InBlock(const Value *V, const BasicBlock *BB) {
2190   if (const Instruction *I = dyn_cast<Instruction>(V))
2191     return I->getParent() == BB;
2192   return true;
2193 }
2194 
2195 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2196 /// This function emits a branch and is used at the leaves of an OR or an
2197 /// AND operator tree.
2198 void
2199 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2200                                                   MachineBasicBlock *TBB,
2201                                                   MachineBasicBlock *FBB,
2202                                                   MachineBasicBlock *CurBB,
2203                                                   MachineBasicBlock *SwitchBB,
2204                                                   BranchProbability TProb,
2205                                                   BranchProbability FProb,
2206                                                   bool InvertCond) {
2207   const BasicBlock *BB = CurBB->getBasicBlock();
2208 
2209   // If the leaf of the tree is a comparison, merge the condition into
2210   // the caseblock.
2211   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2212     // The operands of the cmp have to be in this block.  We don't know
2213     // how to export them from some other block.  If this is the first block
2214     // of the sequence, no exporting is needed.
2215     if (CurBB == SwitchBB ||
2216         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2217          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2218       ISD::CondCode Condition;
2219       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2220         ICmpInst::Predicate Pred =
2221             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2222         Condition = getICmpCondCode(Pred);
2223       } else {
2224         const FCmpInst *FC = cast<FCmpInst>(Cond);
2225         FCmpInst::Predicate Pred =
2226             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2227         Condition = getFCmpCondCode(Pred);
2228         if (TM.Options.NoNaNsFPMath)
2229           Condition = getFCmpCodeWithoutNaN(Condition);
2230       }
2231 
2232       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2233                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2234       SL->SwitchCases.push_back(CB);
2235       return;
2236     }
2237   }
2238 
2239   // Create a CaseBlock record representing this branch.
2240   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2241   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2242                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2243   SL->SwitchCases.push_back(CB);
2244 }
2245 
2246 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2247                                                MachineBasicBlock *TBB,
2248                                                MachineBasicBlock *FBB,
2249                                                MachineBasicBlock *CurBB,
2250                                                MachineBasicBlock *SwitchBB,
2251                                                Instruction::BinaryOps Opc,
2252                                                BranchProbability TProb,
2253                                                BranchProbability FProb,
2254                                                bool InvertCond) {
2255   // Skip over not part of the tree and remember to invert op and operands at
2256   // next level.
2257   Value *NotCond;
2258   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2259       InBlock(NotCond, CurBB->getBasicBlock())) {
2260     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2261                          !InvertCond);
2262     return;
2263   }
2264 
2265   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2266   const Value *BOpOp0, *BOpOp1;
2267   // Compute the effective opcode for Cond, taking into account whether it needs
2268   // to be inverted, e.g.
2269   //   and (not (or A, B)), C
2270   // gets lowered as
2271   //   and (and (not A, not B), C)
2272   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2273   if (BOp) {
2274     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2275                ? Instruction::And
2276                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2277                       ? Instruction::Or
2278                       : (Instruction::BinaryOps)0);
2279     if (InvertCond) {
2280       if (BOpc == Instruction::And)
2281         BOpc = Instruction::Or;
2282       else if (BOpc == Instruction::Or)
2283         BOpc = Instruction::And;
2284     }
2285   }
2286 
2287   // If this node is not part of the or/and tree, emit it as a branch.
2288   // Note that all nodes in the tree should have same opcode.
2289   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2290   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2291       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2292       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2293     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2294                                  TProb, FProb, InvertCond);
2295     return;
2296   }
2297 
2298   //  Create TmpBB after CurBB.
2299   MachineFunction::iterator BBI(CurBB);
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2302   CurBB->getParent()->insert(++BBI, TmpBB);
2303 
2304   if (Opc == Instruction::Or) {
2305     // Codegen X | Y as:
2306     // BB1:
2307     //   jmp_if_X TBB
2308     //   jmp TmpBB
2309     // TmpBB:
2310     //   jmp_if_Y TBB
2311     //   jmp FBB
2312     //
2313 
2314     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2315     // The requirement is that
2316     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2317     //     = TrueProb for original BB.
2318     // Assuming the original probabilities are A and B, one choice is to set
2319     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2320     // A/(1+B) and 2B/(1+B). This choice assumes that
2321     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2322     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2323     // TmpBB, but the math is more complicated.
2324 
2325     auto NewTrueProb = TProb / 2;
2326     auto NewFalseProb = TProb / 2 + FProb;
2327     // Emit the LHS condition.
2328     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2329                          NewFalseProb, InvertCond);
2330 
2331     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2332     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2333     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2334     // Emit the RHS condition into TmpBB.
2335     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2336                          Probs[1], InvertCond);
2337   } else {
2338     assert(Opc == Instruction::And && "Unknown merge op!");
2339     // Codegen X & Y as:
2340     // BB1:
2341     //   jmp_if_X TmpBB
2342     //   jmp FBB
2343     // TmpBB:
2344     //   jmp_if_Y TBB
2345     //   jmp FBB
2346     //
2347     //  This requires creation of TmpBB after CurBB.
2348 
2349     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2350     // The requirement is that
2351     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2352     //     = FalseProb for original BB.
2353     // Assuming the original probabilities are A and B, one choice is to set
2354     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2355     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2356     // TrueProb for BB1 * FalseProb for TmpBB.
2357 
2358     auto NewTrueProb = TProb + FProb / 2;
2359     auto NewFalseProb = FProb / 2;
2360     // Emit the LHS condition.
2361     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2362                          NewFalseProb, InvertCond);
2363 
2364     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2365     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2366     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2367     // Emit the RHS condition into TmpBB.
2368     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2369                          Probs[1], InvertCond);
2370   }
2371 }
2372 
2373 /// If the set of cases should be emitted as a series of branches, return true.
2374 /// If we should emit this as a bunch of and/or'd together conditions, return
2375 /// false.
2376 bool
2377 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2378   if (Cases.size() != 2) return true;
2379 
2380   // If this is two comparisons of the same values or'd or and'd together, they
2381   // will get folded into a single comparison, so don't emit two blocks.
2382   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2383        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2384       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2385        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2386     return false;
2387   }
2388 
2389   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2390   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2391   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2392       Cases[0].CC == Cases[1].CC &&
2393       isa<Constant>(Cases[0].CmpRHS) &&
2394       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2395     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2396       return false;
2397     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2398       return false;
2399   }
2400 
2401   return true;
2402 }
2403 
2404 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2405   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2406 
2407   // Update machine-CFG edges.
2408   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2409 
2410   if (I.isUnconditional()) {
2411     // Update machine-CFG edges.
2412     BrMBB->addSuccessor(Succ0MBB);
2413 
2414     // If this is not a fall-through branch or optimizations are switched off,
2415     // emit the branch.
2416     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2417       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2418                               MVT::Other, getControlRoot(),
2419                               DAG.getBasicBlock(Succ0MBB)));
2420 
2421     return;
2422   }
2423 
2424   // If this condition is one of the special cases we handle, do special stuff
2425   // now.
2426   const Value *CondVal = I.getCondition();
2427   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2428 
2429   // If this is a series of conditions that are or'd or and'd together, emit
2430   // this as a sequence of branches instead of setcc's with and/or operations.
2431   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2432   // unpredictable branches, and vector extracts because those jumps are likely
2433   // expensive for any target), this should improve performance.
2434   // For example, instead of something like:
2435   //     cmp A, B
2436   //     C = seteq
2437   //     cmp D, E
2438   //     F = setle
2439   //     or C, F
2440   //     jnz foo
2441   // Emit:
2442   //     cmp A, B
2443   //     je foo
2444   //     cmp D, E
2445   //     jle foo
2446   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2447   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2448       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2449     Value *Vec;
2450     const Value *BOp0, *BOp1;
2451     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2452     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2453       Opcode = Instruction::And;
2454     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2455       Opcode = Instruction::Or;
2456 
2457     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2458                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2459       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2460                            getEdgeProbability(BrMBB, Succ0MBB),
2461                            getEdgeProbability(BrMBB, Succ1MBB),
2462                            /*InvertCond=*/false);
2463       // If the compares in later blocks need to use values not currently
2464       // exported from this block, export them now.  This block should always
2465       // be the first entry.
2466       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2467 
2468       // Allow some cases to be rejected.
2469       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2470         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2471           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2472           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2473         }
2474 
2475         // Emit the branch for this block.
2476         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2477         SL->SwitchCases.erase(SL->SwitchCases.begin());
2478         return;
2479       }
2480 
2481       // Okay, we decided not to do this, remove any inserted MBB's and clear
2482       // SwitchCases.
2483       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2484         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2485 
2486       SL->SwitchCases.clear();
2487     }
2488   }
2489 
2490   // Create a CaseBlock record representing this branch.
2491   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2492                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2493 
2494   // Use visitSwitchCase to actually insert the fast branch sequence for this
2495   // cond branch.
2496   visitSwitchCase(CB, BrMBB);
2497 }
2498 
2499 /// visitSwitchCase - Emits the necessary code to represent a single node in
2500 /// the binary search tree resulting from lowering a switch instruction.
2501 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2502                                           MachineBasicBlock *SwitchBB) {
2503   SDValue Cond;
2504   SDValue CondLHS = getValue(CB.CmpLHS);
2505   SDLoc dl = CB.DL;
2506 
2507   if (CB.CC == ISD::SETTRUE) {
2508     // Branch or fall through to TrueBB.
2509     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2510     SwitchBB->normalizeSuccProbs();
2511     if (CB.TrueBB != NextBlock(SwitchBB)) {
2512       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2513                               DAG.getBasicBlock(CB.TrueBB)));
2514     }
2515     return;
2516   }
2517 
2518   auto &TLI = DAG.getTargetLoweringInfo();
2519   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2520 
2521   // Build the setcc now.
2522   if (!CB.CmpMHS) {
2523     // Fold "(X == true)" to X and "(X == false)" to !X to
2524     // handle common cases produced by branch lowering.
2525     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2526         CB.CC == ISD::SETEQ)
2527       Cond = CondLHS;
2528     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2529              CB.CC == ISD::SETEQ) {
2530       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2531       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2532     } else {
2533       SDValue CondRHS = getValue(CB.CmpRHS);
2534 
2535       // If a pointer's DAG type is larger than its memory type then the DAG
2536       // values are zero-extended. This breaks signed comparisons so truncate
2537       // back to the underlying type before doing the compare.
2538       if (CondLHS.getValueType() != MemVT) {
2539         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2540         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2541       }
2542       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2543     }
2544   } else {
2545     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2546 
2547     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2548     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2549 
2550     SDValue CmpOp = getValue(CB.CmpMHS);
2551     EVT VT = CmpOp.getValueType();
2552 
2553     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2554       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2555                           ISD::SETLE);
2556     } else {
2557       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2558                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2559       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2560                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2561     }
2562   }
2563 
2564   // Update successor info
2565   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2566   // TrueBB and FalseBB are always different unless the incoming IR is
2567   // degenerate. This only happens when running llc on weird IR.
2568   if (CB.TrueBB != CB.FalseBB)
2569     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2570   SwitchBB->normalizeSuccProbs();
2571 
2572   // If the lhs block is the next block, invert the condition so that we can
2573   // fall through to the lhs instead of the rhs block.
2574   if (CB.TrueBB == NextBlock(SwitchBB)) {
2575     std::swap(CB.TrueBB, CB.FalseBB);
2576     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2577     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2578   }
2579 
2580   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2581                                MVT::Other, getControlRoot(), Cond,
2582                                DAG.getBasicBlock(CB.TrueBB));
2583 
2584   setValue(CurInst, BrCond);
2585 
2586   // Insert the false branch. Do this even if it's a fall through branch,
2587   // this makes it easier to do DAG optimizations which require inverting
2588   // the branch condition.
2589   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2590                        DAG.getBasicBlock(CB.FalseBB));
2591 
2592   DAG.setRoot(BrCond);
2593 }
2594 
2595 /// visitJumpTable - Emit JumpTable node in the current MBB
2596 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2597   // Emit the code for the jump table
2598   assert(JT.Reg != -1U && "Should lower JT Header first!");
2599   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2600   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2601                                      JT.Reg, PTy);
2602   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2603   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2604                                     MVT::Other, Index.getValue(1),
2605                                     Table, Index);
2606   DAG.setRoot(BrJumpTable);
2607 }
2608 
2609 /// visitJumpTableHeader - This function emits necessary code to produce index
2610 /// in the JumpTable from switch case.
2611 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2612                                                JumpTableHeader &JTH,
2613                                                MachineBasicBlock *SwitchBB) {
2614   SDLoc dl = getCurSDLoc();
2615 
2616   // Subtract the lowest switch case value from the value being switched on.
2617   SDValue SwitchOp = getValue(JTH.SValue);
2618   EVT VT = SwitchOp.getValueType();
2619   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2620                             DAG.getConstant(JTH.First, dl, VT));
2621 
2622   // The SDNode we just created, which holds the value being switched on minus
2623   // the smallest case value, needs to be copied to a virtual register so it
2624   // can be used as an index into the jump table in a subsequent basic block.
2625   // This value may be smaller or larger than the target's pointer type, and
2626   // therefore require extension or truncating.
2627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2628   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2629 
2630   unsigned JumpTableReg =
2631       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2632   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2633                                     JumpTableReg, SwitchOp);
2634   JT.Reg = JumpTableReg;
2635 
2636   if (!JTH.FallthroughUnreachable) {
2637     // Emit the range check for the jump table, and branch to the default block
2638     // for the switch statement if the value being switched on exceeds the
2639     // largest case in the switch.
2640     SDValue CMP = DAG.getSetCC(
2641         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2642                                    Sub.getValueType()),
2643         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2644 
2645     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2646                                  MVT::Other, CopyTo, CMP,
2647                                  DAG.getBasicBlock(JT.Default));
2648 
2649     // Avoid emitting unnecessary branches to the next block.
2650     if (JT.MBB != NextBlock(SwitchBB))
2651       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2652                            DAG.getBasicBlock(JT.MBB));
2653 
2654     DAG.setRoot(BrCond);
2655   } else {
2656     // Avoid emitting unnecessary branches to the next block.
2657     if (JT.MBB != NextBlock(SwitchBB))
2658       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2659                               DAG.getBasicBlock(JT.MBB)));
2660     else
2661       DAG.setRoot(CopyTo);
2662   }
2663 }
2664 
2665 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2666 /// variable if there exists one.
2667 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2668                                  SDValue &Chain) {
2669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2670   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2671   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2672   MachineFunction &MF = DAG.getMachineFunction();
2673   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2674   MachineSDNode *Node =
2675       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2676   if (Global) {
2677     MachinePointerInfo MPInfo(Global);
2678     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2679                  MachineMemOperand::MODereferenceable;
2680     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2681         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2682     DAG.setNodeMemRefs(Node, {MemRef});
2683   }
2684   if (PtrTy != PtrMemTy)
2685     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2686   return SDValue(Node, 0);
2687 }
2688 
2689 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2690 /// tail spliced into a stack protector check success bb.
2691 ///
2692 /// For a high level explanation of how this fits into the stack protector
2693 /// generation see the comment on the declaration of class
2694 /// StackProtectorDescriptor.
2695 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2696                                                   MachineBasicBlock *ParentBB) {
2697 
2698   // First create the loads to the guard/stack slot for the comparison.
2699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2700   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2701   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2702 
2703   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2704   int FI = MFI.getStackProtectorIndex();
2705 
2706   SDValue Guard;
2707   SDLoc dl = getCurSDLoc();
2708   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2709   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2710   Align Align =
2711       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2712 
2713   // Generate code to load the content of the guard slot.
2714   SDValue GuardVal = DAG.getLoad(
2715       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2716       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2717       MachineMemOperand::MOVolatile);
2718 
2719   if (TLI.useStackGuardXorFP())
2720     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2721 
2722   // Retrieve guard check function, nullptr if instrumentation is inlined.
2723   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2724     // The target provides a guard check function to validate the guard value.
2725     // Generate a call to that function with the content of the guard slot as
2726     // argument.
2727     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2728     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2729 
2730     TargetLowering::ArgListTy Args;
2731     TargetLowering::ArgListEntry Entry;
2732     Entry.Node = GuardVal;
2733     Entry.Ty = FnTy->getParamType(0);
2734     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2735       Entry.IsInReg = true;
2736     Args.push_back(Entry);
2737 
2738     TargetLowering::CallLoweringInfo CLI(DAG);
2739     CLI.setDebugLoc(getCurSDLoc())
2740         .setChain(DAG.getEntryNode())
2741         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2742                    getValue(GuardCheckFn), std::move(Args));
2743 
2744     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2745     DAG.setRoot(Result.second);
2746     return;
2747   }
2748 
2749   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2750   // Otherwise, emit a volatile load to retrieve the stack guard value.
2751   SDValue Chain = DAG.getEntryNode();
2752   if (TLI.useLoadStackGuardNode()) {
2753     Guard = getLoadStackGuard(DAG, dl, Chain);
2754   } else {
2755     const Value *IRGuard = TLI.getSDagStackGuard(M);
2756     SDValue GuardPtr = getValue(IRGuard);
2757 
2758     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2759                         MachinePointerInfo(IRGuard, 0), Align,
2760                         MachineMemOperand::MOVolatile);
2761   }
2762 
2763   // Perform the comparison via a getsetcc.
2764   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2765                                                         *DAG.getContext(),
2766                                                         Guard.getValueType()),
2767                              Guard, GuardVal, ISD::SETNE);
2768 
2769   // If the guard/stackslot do not equal, branch to failure MBB.
2770   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2771                                MVT::Other, GuardVal.getOperand(0),
2772                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2773   // Otherwise branch to success MBB.
2774   SDValue Br = DAG.getNode(ISD::BR, dl,
2775                            MVT::Other, BrCond,
2776                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2777 
2778   DAG.setRoot(Br);
2779 }
2780 
2781 /// Codegen the failure basic block for a stack protector check.
2782 ///
2783 /// A failure stack protector machine basic block consists simply of a call to
2784 /// __stack_chk_fail().
2785 ///
2786 /// For a high level explanation of how this fits into the stack protector
2787 /// generation see the comment on the declaration of class
2788 /// StackProtectorDescriptor.
2789 void
2790 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2792   TargetLowering::MakeLibCallOptions CallOptions;
2793   CallOptions.setDiscardResult(true);
2794   SDValue Chain =
2795       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2796                       None, CallOptions, getCurSDLoc()).second;
2797   // On PS4/PS5, the "return address" must still be within the calling
2798   // function, even if it's at the very end, so emit an explicit TRAP here.
2799   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2800   if (TM.getTargetTriple().isPS())
2801     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2802   // WebAssembly needs an unreachable instruction after a non-returning call,
2803   // because the function return type can be different from __stack_chk_fail's
2804   // return type (void).
2805   if (TM.getTargetTriple().isWasm())
2806     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2807 
2808   DAG.setRoot(Chain);
2809 }
2810 
2811 /// visitBitTestHeader - This function emits necessary code to produce value
2812 /// suitable for "bit tests"
2813 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2814                                              MachineBasicBlock *SwitchBB) {
2815   SDLoc dl = getCurSDLoc();
2816 
2817   // Subtract the minimum value.
2818   SDValue SwitchOp = getValue(B.SValue);
2819   EVT VT = SwitchOp.getValueType();
2820   SDValue RangeSub =
2821       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2822 
2823   // Determine the type of the test operands.
2824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2825   bool UsePtrType = false;
2826   if (!TLI.isTypeLegal(VT)) {
2827     UsePtrType = true;
2828   } else {
2829     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2830       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2831         // Switch table case range are encoded into series of masks.
2832         // Just use pointer type, it's guaranteed to fit.
2833         UsePtrType = true;
2834         break;
2835       }
2836   }
2837   SDValue Sub = RangeSub;
2838   if (UsePtrType) {
2839     VT = TLI.getPointerTy(DAG.getDataLayout());
2840     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2841   }
2842 
2843   B.RegVT = VT.getSimpleVT();
2844   B.Reg = FuncInfo.CreateReg(B.RegVT);
2845   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2846 
2847   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2848 
2849   if (!B.FallthroughUnreachable)
2850     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2851   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2852   SwitchBB->normalizeSuccProbs();
2853 
2854   SDValue Root = CopyTo;
2855   if (!B.FallthroughUnreachable) {
2856     // Conditional branch to the default block.
2857     SDValue RangeCmp = DAG.getSetCC(dl,
2858         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2859                                RangeSub.getValueType()),
2860         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2861         ISD::SETUGT);
2862 
2863     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2864                        DAG.getBasicBlock(B.Default));
2865   }
2866 
2867   // Avoid emitting unnecessary branches to the next block.
2868   if (MBB != NextBlock(SwitchBB))
2869     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2870 
2871   DAG.setRoot(Root);
2872 }
2873 
2874 /// visitBitTestCase - this function produces one "bit test"
2875 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2876                                            MachineBasicBlock* NextMBB,
2877                                            BranchProbability BranchProbToNext,
2878                                            unsigned Reg,
2879                                            BitTestCase &B,
2880                                            MachineBasicBlock *SwitchBB) {
2881   SDLoc dl = getCurSDLoc();
2882   MVT VT = BB.RegVT;
2883   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2884   SDValue Cmp;
2885   unsigned PopCount = countPopulation(B.Mask);
2886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2887   if (PopCount == 1) {
2888     // Testing for a single bit; just compare the shift count with what it
2889     // would need to be to shift a 1 bit in that position.
2890     Cmp = DAG.getSetCC(
2891         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2892         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2893         ISD::SETEQ);
2894   } else if (PopCount == BB.Range) {
2895     // There is only one zero bit in the range, test for it directly.
2896     Cmp = DAG.getSetCC(
2897         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2898         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2899         ISD::SETNE);
2900   } else {
2901     // Make desired shift
2902     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2903                                     DAG.getConstant(1, dl, VT), ShiftOp);
2904 
2905     // Emit bit tests and jumps
2906     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2907                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2908     Cmp = DAG.getSetCC(
2909         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2910         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2911   }
2912 
2913   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2914   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2915   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2916   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2917   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2918   // one as they are relative probabilities (and thus work more like weights),
2919   // and hence we need to normalize them to let the sum of them become one.
2920   SwitchBB->normalizeSuccProbs();
2921 
2922   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2923                               MVT::Other, getControlRoot(),
2924                               Cmp, DAG.getBasicBlock(B.TargetBB));
2925 
2926   // Avoid emitting unnecessary branches to the next block.
2927   if (NextMBB != NextBlock(SwitchBB))
2928     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2929                         DAG.getBasicBlock(NextMBB));
2930 
2931   DAG.setRoot(BrAnd);
2932 }
2933 
2934 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2935   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2936 
2937   // Retrieve successors. Look through artificial IR level blocks like
2938   // catchswitch for successors.
2939   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2940   const BasicBlock *EHPadBB = I.getSuccessor(1);
2941 
2942   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2943   // have to do anything here to lower funclet bundles.
2944   assert(!I.hasOperandBundlesOtherThan(
2945              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2946               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2947               LLVMContext::OB_cfguardtarget,
2948               LLVMContext::OB_clang_arc_attachedcall}) &&
2949          "Cannot lower invokes with arbitrary operand bundles yet!");
2950 
2951   const Value *Callee(I.getCalledOperand());
2952   const Function *Fn = dyn_cast<Function>(Callee);
2953   if (isa<InlineAsm>(Callee))
2954     visitInlineAsm(I, EHPadBB);
2955   else if (Fn && Fn->isIntrinsic()) {
2956     switch (Fn->getIntrinsicID()) {
2957     default:
2958       llvm_unreachable("Cannot invoke this intrinsic");
2959     case Intrinsic::donothing:
2960       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2961     case Intrinsic::seh_try_begin:
2962     case Intrinsic::seh_scope_begin:
2963     case Intrinsic::seh_try_end:
2964     case Intrinsic::seh_scope_end:
2965       break;
2966     case Intrinsic::experimental_patchpoint_void:
2967     case Intrinsic::experimental_patchpoint_i64:
2968       visitPatchpoint(I, EHPadBB);
2969       break;
2970     case Intrinsic::experimental_gc_statepoint:
2971       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2972       break;
2973     case Intrinsic::wasm_rethrow: {
2974       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2975       // special because it can be invoked, so we manually lower it to a DAG
2976       // node here.
2977       SmallVector<SDValue, 8> Ops;
2978       Ops.push_back(getRoot()); // inchain
2979       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2980       Ops.push_back(
2981           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2982                                 TLI.getPointerTy(DAG.getDataLayout())));
2983       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2984       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2985       break;
2986     }
2987     }
2988   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2989     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2990     // Eventually we will support lowering the @llvm.experimental.deoptimize
2991     // intrinsic, and right now there are no plans to support other intrinsics
2992     // with deopt state.
2993     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2994   } else {
2995     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2996   }
2997 
2998   // If the value of the invoke is used outside of its defining block, make it
2999   // available as a virtual register.
3000   // We already took care of the exported value for the statepoint instruction
3001   // during call to the LowerStatepoint.
3002   if (!isa<GCStatepointInst>(I)) {
3003     CopyToExportRegsIfNeeded(&I);
3004   }
3005 
3006   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3007   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3008   BranchProbability EHPadBBProb =
3009       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3010           : BranchProbability::getZero();
3011   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3012 
3013   // Update successor info.
3014   addSuccessorWithProb(InvokeMBB, Return);
3015   for (auto &UnwindDest : UnwindDests) {
3016     UnwindDest.first->setIsEHPad();
3017     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3018   }
3019   InvokeMBB->normalizeSuccProbs();
3020 
3021   // Drop into normal successor.
3022   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3023                           DAG.getBasicBlock(Return)));
3024 }
3025 
3026 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3027   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3028 
3029   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3030   // have to do anything here to lower funclet bundles.
3031   assert(!I.hasOperandBundlesOtherThan(
3032              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3033          "Cannot lower callbrs with arbitrary operand bundles yet!");
3034 
3035   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3036   visitInlineAsm(I);
3037   CopyToExportRegsIfNeeded(&I);
3038 
3039   // Retrieve successors.
3040   SmallPtrSet<BasicBlock *, 8> Dests;
3041   Dests.insert(I.getDefaultDest());
3042   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3043 
3044   // Update successor info.
3045   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3046   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3047     BasicBlock *Dest = I.getIndirectDest(i);
3048     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3049     Target->setIsInlineAsmBrIndirectTarget();
3050     Target->setMachineBlockAddressTaken();
3051     Target->setLabelMustBeEmitted();
3052     // Don't add duplicate machine successors.
3053     if (Dests.insert(Dest).second)
3054       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3055   }
3056   CallBrMBB->normalizeSuccProbs();
3057 
3058   // Drop into default successor.
3059   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3060                           MVT::Other, getControlRoot(),
3061                           DAG.getBasicBlock(Return)));
3062 }
3063 
3064 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3065   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3066 }
3067 
3068 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3069   assert(FuncInfo.MBB->isEHPad() &&
3070          "Call to landingpad not in landing pad!");
3071 
3072   // If there aren't registers to copy the values into (e.g., during SjLj
3073   // exceptions), then don't bother to create these DAG nodes.
3074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3075   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3076   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3077       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3078     return;
3079 
3080   // If landingpad's return type is token type, we don't create DAG nodes
3081   // for its exception pointer and selector value. The extraction of exception
3082   // pointer or selector value from token type landingpads is not currently
3083   // supported.
3084   if (LP.getType()->isTokenTy())
3085     return;
3086 
3087   SmallVector<EVT, 2> ValueVTs;
3088   SDLoc dl = getCurSDLoc();
3089   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3090   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3091 
3092   // Get the two live-in registers as SDValues. The physregs have already been
3093   // copied into virtual registers.
3094   SDValue Ops[2];
3095   if (FuncInfo.ExceptionPointerVirtReg) {
3096     Ops[0] = DAG.getZExtOrTrunc(
3097         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3098                            FuncInfo.ExceptionPointerVirtReg,
3099                            TLI.getPointerTy(DAG.getDataLayout())),
3100         dl, ValueVTs[0]);
3101   } else {
3102     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3103   }
3104   Ops[1] = DAG.getZExtOrTrunc(
3105       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3106                          FuncInfo.ExceptionSelectorVirtReg,
3107                          TLI.getPointerTy(DAG.getDataLayout())),
3108       dl, ValueVTs[1]);
3109 
3110   // Merge into one.
3111   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3112                             DAG.getVTList(ValueVTs), Ops);
3113   setValue(&LP, Res);
3114 }
3115 
3116 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3117                                            MachineBasicBlock *Last) {
3118   // Update JTCases.
3119   for (JumpTableBlock &JTB : SL->JTCases)
3120     if (JTB.first.HeaderBB == First)
3121       JTB.first.HeaderBB = Last;
3122 
3123   // Update BitTestCases.
3124   for (BitTestBlock &BTB : SL->BitTestCases)
3125     if (BTB.Parent == First)
3126       BTB.Parent = Last;
3127 }
3128 
3129 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3130   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3131 
3132   // Update machine-CFG edges with unique successors.
3133   SmallSet<BasicBlock*, 32> Done;
3134   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3135     BasicBlock *BB = I.getSuccessor(i);
3136     bool Inserted = Done.insert(BB).second;
3137     if (!Inserted)
3138         continue;
3139 
3140     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3141     addSuccessorWithProb(IndirectBrMBB, Succ);
3142   }
3143   IndirectBrMBB->normalizeSuccProbs();
3144 
3145   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3146                           MVT::Other, getControlRoot(),
3147                           getValue(I.getAddress())));
3148 }
3149 
3150 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3151   if (!DAG.getTarget().Options.TrapUnreachable)
3152     return;
3153 
3154   // We may be able to ignore unreachable behind a noreturn call.
3155   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3156     const BasicBlock &BB = *I.getParent();
3157     if (&I != &BB.front()) {
3158       BasicBlock::const_iterator PredI =
3159         std::prev(BasicBlock::const_iterator(&I));
3160       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3161         if (Call->doesNotReturn())
3162           return;
3163       }
3164     }
3165   }
3166 
3167   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3168 }
3169 
3170 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3171   SDNodeFlags Flags;
3172   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3173     Flags.copyFMF(*FPOp);
3174 
3175   SDValue Op = getValue(I.getOperand(0));
3176   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3177                                     Op, Flags);
3178   setValue(&I, UnNodeValue);
3179 }
3180 
3181 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3182   SDNodeFlags Flags;
3183   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3184     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3185     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3186   }
3187   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3188     Flags.setExact(ExactOp->isExact());
3189   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3190     Flags.copyFMF(*FPOp);
3191 
3192   SDValue Op1 = getValue(I.getOperand(0));
3193   SDValue Op2 = getValue(I.getOperand(1));
3194   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3195                                      Op1, Op2, Flags);
3196   setValue(&I, BinNodeValue);
3197 }
3198 
3199 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3200   SDValue Op1 = getValue(I.getOperand(0));
3201   SDValue Op2 = getValue(I.getOperand(1));
3202 
3203   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3204       Op1.getValueType(), DAG.getDataLayout());
3205 
3206   // Coerce the shift amount to the right type if we can. This exposes the
3207   // truncate or zext to optimization early.
3208   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3209     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3210            "Unexpected shift type");
3211     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3212   }
3213 
3214   bool nuw = false;
3215   bool nsw = false;
3216   bool exact = false;
3217 
3218   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3219 
3220     if (const OverflowingBinaryOperator *OFBinOp =
3221             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3222       nuw = OFBinOp->hasNoUnsignedWrap();
3223       nsw = OFBinOp->hasNoSignedWrap();
3224     }
3225     if (const PossiblyExactOperator *ExactOp =
3226             dyn_cast<const PossiblyExactOperator>(&I))
3227       exact = ExactOp->isExact();
3228   }
3229   SDNodeFlags Flags;
3230   Flags.setExact(exact);
3231   Flags.setNoSignedWrap(nsw);
3232   Flags.setNoUnsignedWrap(nuw);
3233   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3234                             Flags);
3235   setValue(&I, Res);
3236 }
3237 
3238 void SelectionDAGBuilder::visitSDiv(const User &I) {
3239   SDValue Op1 = getValue(I.getOperand(0));
3240   SDValue Op2 = getValue(I.getOperand(1));
3241 
3242   SDNodeFlags Flags;
3243   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3244                  cast<PossiblyExactOperator>(&I)->isExact());
3245   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3246                            Op2, Flags));
3247 }
3248 
3249 void SelectionDAGBuilder::visitICmp(const User &I) {
3250   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3251   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3252     predicate = IC->getPredicate();
3253   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3254     predicate = ICmpInst::Predicate(IC->getPredicate());
3255   SDValue Op1 = getValue(I.getOperand(0));
3256   SDValue Op2 = getValue(I.getOperand(1));
3257   ISD::CondCode Opcode = getICmpCondCode(predicate);
3258 
3259   auto &TLI = DAG.getTargetLoweringInfo();
3260   EVT MemVT =
3261       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3262 
3263   // If a pointer's DAG type is larger than its memory type then the DAG values
3264   // are zero-extended. This breaks signed comparisons so truncate back to the
3265   // underlying type before doing the compare.
3266   if (Op1.getValueType() != MemVT) {
3267     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3268     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3269   }
3270 
3271   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3272                                                         I.getType());
3273   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3274 }
3275 
3276 void SelectionDAGBuilder::visitFCmp(const User &I) {
3277   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3278   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3279     predicate = FC->getPredicate();
3280   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3281     predicate = FCmpInst::Predicate(FC->getPredicate());
3282   SDValue Op1 = getValue(I.getOperand(0));
3283   SDValue Op2 = getValue(I.getOperand(1));
3284 
3285   ISD::CondCode Condition = getFCmpCondCode(predicate);
3286   auto *FPMO = cast<FPMathOperator>(&I);
3287   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3288     Condition = getFCmpCodeWithoutNaN(Condition);
3289 
3290   SDNodeFlags Flags;
3291   Flags.copyFMF(*FPMO);
3292   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3293 
3294   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3295                                                         I.getType());
3296   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3297 }
3298 
3299 // Check if the condition of the select has one use or two users that are both
3300 // selects with the same condition.
3301 static bool hasOnlySelectUsers(const Value *Cond) {
3302   return llvm::all_of(Cond->users(), [](const Value *V) {
3303     return isa<SelectInst>(V);
3304   });
3305 }
3306 
3307 void SelectionDAGBuilder::visitSelect(const User &I) {
3308   SmallVector<EVT, 4> ValueVTs;
3309   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3310                   ValueVTs);
3311   unsigned NumValues = ValueVTs.size();
3312   if (NumValues == 0) return;
3313 
3314   SmallVector<SDValue, 4> Values(NumValues);
3315   SDValue Cond     = getValue(I.getOperand(0));
3316   SDValue LHSVal   = getValue(I.getOperand(1));
3317   SDValue RHSVal   = getValue(I.getOperand(2));
3318   SmallVector<SDValue, 1> BaseOps(1, Cond);
3319   ISD::NodeType OpCode =
3320       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3321 
3322   bool IsUnaryAbs = false;
3323   bool Negate = false;
3324 
3325   SDNodeFlags Flags;
3326   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3327     Flags.copyFMF(*FPOp);
3328 
3329   // Min/max matching is only viable if all output VTs are the same.
3330   if (all_equal(ValueVTs)) {
3331     EVT VT = ValueVTs[0];
3332     LLVMContext &Ctx = *DAG.getContext();
3333     auto &TLI = DAG.getTargetLoweringInfo();
3334 
3335     // We care about the legality of the operation after it has been type
3336     // legalized.
3337     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3338       VT = TLI.getTypeToTransformTo(Ctx, VT);
3339 
3340     // If the vselect is legal, assume we want to leave this as a vector setcc +
3341     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3342     // min/max is legal on the scalar type.
3343     bool UseScalarMinMax = VT.isVector() &&
3344       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3345 
3346     Value *LHS, *RHS;
3347     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3348     ISD::NodeType Opc = ISD::DELETED_NODE;
3349     switch (SPR.Flavor) {
3350     case SPF_UMAX:    Opc = ISD::UMAX; break;
3351     case SPF_UMIN:    Opc = ISD::UMIN; break;
3352     case SPF_SMAX:    Opc = ISD::SMAX; break;
3353     case SPF_SMIN:    Opc = ISD::SMIN; break;
3354     case SPF_FMINNUM:
3355       switch (SPR.NaNBehavior) {
3356       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3357       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3358       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3359       case SPNB_RETURNS_ANY: {
3360         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3361           Opc = ISD::FMINNUM;
3362         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3363           Opc = ISD::FMINIMUM;
3364         else if (UseScalarMinMax)
3365           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3366             ISD::FMINNUM : ISD::FMINIMUM;
3367         break;
3368       }
3369       }
3370       break;
3371     case SPF_FMAXNUM:
3372       switch (SPR.NaNBehavior) {
3373       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3374       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3375       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3376       case SPNB_RETURNS_ANY:
3377 
3378         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3379           Opc = ISD::FMAXNUM;
3380         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3381           Opc = ISD::FMAXIMUM;
3382         else if (UseScalarMinMax)
3383           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3384             ISD::FMAXNUM : ISD::FMAXIMUM;
3385         break;
3386       }
3387       break;
3388     case SPF_NABS:
3389       Negate = true;
3390       [[fallthrough]];
3391     case SPF_ABS:
3392       IsUnaryAbs = true;
3393       Opc = ISD::ABS;
3394       break;
3395     default: break;
3396     }
3397 
3398     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3399         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3400          (UseScalarMinMax &&
3401           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3402         // If the underlying comparison instruction is used by any other
3403         // instruction, the consumed instructions won't be destroyed, so it is
3404         // not profitable to convert to a min/max.
3405         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3406       OpCode = Opc;
3407       LHSVal = getValue(LHS);
3408       RHSVal = getValue(RHS);
3409       BaseOps.clear();
3410     }
3411 
3412     if (IsUnaryAbs) {
3413       OpCode = Opc;
3414       LHSVal = getValue(LHS);
3415       BaseOps.clear();
3416     }
3417   }
3418 
3419   if (IsUnaryAbs) {
3420     for (unsigned i = 0; i != NumValues; ++i) {
3421       SDLoc dl = getCurSDLoc();
3422       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3423       Values[i] =
3424           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3425       if (Negate)
3426         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3427                                 Values[i]);
3428     }
3429   } else {
3430     for (unsigned i = 0; i != NumValues; ++i) {
3431       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3432       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3433       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3434       Values[i] = DAG.getNode(
3435           OpCode, getCurSDLoc(),
3436           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3437     }
3438   }
3439 
3440   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3441                            DAG.getVTList(ValueVTs), Values));
3442 }
3443 
3444 void SelectionDAGBuilder::visitTrunc(const User &I) {
3445   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3446   SDValue N = getValue(I.getOperand(0));
3447   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3448                                                         I.getType());
3449   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3450 }
3451 
3452 void SelectionDAGBuilder::visitZExt(const User &I) {
3453   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3454   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3455   SDValue N = getValue(I.getOperand(0));
3456   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3457                                                         I.getType());
3458   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3459 }
3460 
3461 void SelectionDAGBuilder::visitSExt(const User &I) {
3462   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3463   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3464   SDValue N = getValue(I.getOperand(0));
3465   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3466                                                         I.getType());
3467   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3468 }
3469 
3470 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3471   // FPTrunc is never a no-op cast, no need to check
3472   SDValue N = getValue(I.getOperand(0));
3473   SDLoc dl = getCurSDLoc();
3474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3475   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3476   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3477                            DAG.getTargetConstant(
3478                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3479 }
3480 
3481 void SelectionDAGBuilder::visitFPExt(const User &I) {
3482   // FPExt is never a no-op cast, no need to check
3483   SDValue N = getValue(I.getOperand(0));
3484   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3485                                                         I.getType());
3486   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3487 }
3488 
3489 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3490   // FPToUI is never a no-op cast, no need to check
3491   SDValue N = getValue(I.getOperand(0));
3492   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3493                                                         I.getType());
3494   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3495 }
3496 
3497 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3498   // FPToSI is never a no-op cast, no need to check
3499   SDValue N = getValue(I.getOperand(0));
3500   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3501                                                         I.getType());
3502   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3503 }
3504 
3505 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3506   // UIToFP is never a no-op cast, no need to check
3507   SDValue N = getValue(I.getOperand(0));
3508   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3509                                                         I.getType());
3510   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3511 }
3512 
3513 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3514   // SIToFP is never a no-op cast, no need to check
3515   SDValue N = getValue(I.getOperand(0));
3516   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3517                                                         I.getType());
3518   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3519 }
3520 
3521 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3522   // What to do depends on the size of the integer and the size of the pointer.
3523   // We can either truncate, zero extend, or no-op, accordingly.
3524   SDValue N = getValue(I.getOperand(0));
3525   auto &TLI = DAG.getTargetLoweringInfo();
3526   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3527                                                         I.getType());
3528   EVT PtrMemVT =
3529       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3530   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3531   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3532   setValue(&I, N);
3533 }
3534 
3535 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3536   // What to do depends on the size of the integer and the size of the pointer.
3537   // We can either truncate, zero extend, or no-op, accordingly.
3538   SDValue N = getValue(I.getOperand(0));
3539   auto &TLI = DAG.getTargetLoweringInfo();
3540   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3541   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3542   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3543   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3544   setValue(&I, N);
3545 }
3546 
3547 void SelectionDAGBuilder::visitBitCast(const User &I) {
3548   SDValue N = getValue(I.getOperand(0));
3549   SDLoc dl = getCurSDLoc();
3550   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3551                                                         I.getType());
3552 
3553   // BitCast assures us that source and destination are the same size so this is
3554   // either a BITCAST or a no-op.
3555   if (DestVT != N.getValueType())
3556     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3557                              DestVT, N)); // convert types.
3558   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3559   // might fold any kind of constant expression to an integer constant and that
3560   // is not what we are looking for. Only recognize a bitcast of a genuine
3561   // constant integer as an opaque constant.
3562   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3563     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3564                                  /*isOpaque*/true));
3565   else
3566     setValue(&I, N);            // noop cast.
3567 }
3568 
3569 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3571   const Value *SV = I.getOperand(0);
3572   SDValue N = getValue(SV);
3573   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3574 
3575   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3576   unsigned DestAS = I.getType()->getPointerAddressSpace();
3577 
3578   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3579     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3580 
3581   setValue(&I, N);
3582 }
3583 
3584 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3586   SDValue InVec = getValue(I.getOperand(0));
3587   SDValue InVal = getValue(I.getOperand(1));
3588   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3589                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3590   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3591                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3592                            InVec, InVal, InIdx));
3593 }
3594 
3595 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3596   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3597   SDValue InVec = getValue(I.getOperand(0));
3598   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3599                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3600   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3601                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3602                            InVec, InIdx));
3603 }
3604 
3605 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3606   SDValue Src1 = getValue(I.getOperand(0));
3607   SDValue Src2 = getValue(I.getOperand(1));
3608   ArrayRef<int> Mask;
3609   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3610     Mask = SVI->getShuffleMask();
3611   else
3612     Mask = cast<ConstantExpr>(I).getShuffleMask();
3613   SDLoc DL = getCurSDLoc();
3614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3615   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3616   EVT SrcVT = Src1.getValueType();
3617 
3618   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3619       VT.isScalableVector()) {
3620     // Canonical splat form of first element of first input vector.
3621     SDValue FirstElt =
3622         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3623                     DAG.getVectorIdxConstant(0, DL));
3624     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3625     return;
3626   }
3627 
3628   // For now, we only handle splats for scalable vectors.
3629   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3630   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3631   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3632 
3633   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3634   unsigned MaskNumElts = Mask.size();
3635 
3636   if (SrcNumElts == MaskNumElts) {
3637     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3638     return;
3639   }
3640 
3641   // Normalize the shuffle vector since mask and vector length don't match.
3642   if (SrcNumElts < MaskNumElts) {
3643     // Mask is longer than the source vectors. We can use concatenate vector to
3644     // make the mask and vectors lengths match.
3645 
3646     if (MaskNumElts % SrcNumElts == 0) {
3647       // Mask length is a multiple of the source vector length.
3648       // Check if the shuffle is some kind of concatenation of the input
3649       // vectors.
3650       unsigned NumConcat = MaskNumElts / SrcNumElts;
3651       bool IsConcat = true;
3652       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3653       for (unsigned i = 0; i != MaskNumElts; ++i) {
3654         int Idx = Mask[i];
3655         if (Idx < 0)
3656           continue;
3657         // Ensure the indices in each SrcVT sized piece are sequential and that
3658         // the same source is used for the whole piece.
3659         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3660             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3661              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3662           IsConcat = false;
3663           break;
3664         }
3665         // Remember which source this index came from.
3666         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3667       }
3668 
3669       // The shuffle is concatenating multiple vectors together. Just emit
3670       // a CONCAT_VECTORS operation.
3671       if (IsConcat) {
3672         SmallVector<SDValue, 8> ConcatOps;
3673         for (auto Src : ConcatSrcs) {
3674           if (Src < 0)
3675             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3676           else if (Src == 0)
3677             ConcatOps.push_back(Src1);
3678           else
3679             ConcatOps.push_back(Src2);
3680         }
3681         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3682         return;
3683       }
3684     }
3685 
3686     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3687     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3688     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3689                                     PaddedMaskNumElts);
3690 
3691     // Pad both vectors with undefs to make them the same length as the mask.
3692     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3693 
3694     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3695     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3696     MOps1[0] = Src1;
3697     MOps2[0] = Src2;
3698 
3699     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3700     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3701 
3702     // Readjust mask for new input vector length.
3703     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3704     for (unsigned i = 0; i != MaskNumElts; ++i) {
3705       int Idx = Mask[i];
3706       if (Idx >= (int)SrcNumElts)
3707         Idx -= SrcNumElts - PaddedMaskNumElts;
3708       MappedOps[i] = Idx;
3709     }
3710 
3711     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3712 
3713     // If the concatenated vector was padded, extract a subvector with the
3714     // correct number of elements.
3715     if (MaskNumElts != PaddedMaskNumElts)
3716       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3717                            DAG.getVectorIdxConstant(0, DL));
3718 
3719     setValue(&I, Result);
3720     return;
3721   }
3722 
3723   if (SrcNumElts > MaskNumElts) {
3724     // Analyze the access pattern of the vector to see if we can extract
3725     // two subvectors and do the shuffle.
3726     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3727     bool CanExtract = true;
3728     for (int Idx : Mask) {
3729       unsigned Input = 0;
3730       if (Idx < 0)
3731         continue;
3732 
3733       if (Idx >= (int)SrcNumElts) {
3734         Input = 1;
3735         Idx -= SrcNumElts;
3736       }
3737 
3738       // If all the indices come from the same MaskNumElts sized portion of
3739       // the sources we can use extract. Also make sure the extract wouldn't
3740       // extract past the end of the source.
3741       int NewStartIdx = alignDown(Idx, MaskNumElts);
3742       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3743           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3744         CanExtract = false;
3745       // Make sure we always update StartIdx as we use it to track if all
3746       // elements are undef.
3747       StartIdx[Input] = NewStartIdx;
3748     }
3749 
3750     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3751       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3752       return;
3753     }
3754     if (CanExtract) {
3755       // Extract appropriate subvector and generate a vector shuffle
3756       for (unsigned Input = 0; Input < 2; ++Input) {
3757         SDValue &Src = Input == 0 ? Src1 : Src2;
3758         if (StartIdx[Input] < 0)
3759           Src = DAG.getUNDEF(VT);
3760         else {
3761           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3762                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3763         }
3764       }
3765 
3766       // Calculate new mask.
3767       SmallVector<int, 8> MappedOps(Mask);
3768       for (int &Idx : MappedOps) {
3769         if (Idx >= (int)SrcNumElts)
3770           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3771         else if (Idx >= 0)
3772           Idx -= StartIdx[0];
3773       }
3774 
3775       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3776       return;
3777     }
3778   }
3779 
3780   // We can't use either concat vectors or extract subvectors so fall back to
3781   // replacing the shuffle with extract and build vector.
3782   // to insert and build vector.
3783   EVT EltVT = VT.getVectorElementType();
3784   SmallVector<SDValue,8> Ops;
3785   for (int Idx : Mask) {
3786     SDValue Res;
3787 
3788     if (Idx < 0) {
3789       Res = DAG.getUNDEF(EltVT);
3790     } else {
3791       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3792       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3793 
3794       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3795                         DAG.getVectorIdxConstant(Idx, DL));
3796     }
3797 
3798     Ops.push_back(Res);
3799   }
3800 
3801   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3802 }
3803 
3804 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3805   ArrayRef<unsigned> Indices = I.getIndices();
3806   const Value *Op0 = I.getOperand(0);
3807   const Value *Op1 = I.getOperand(1);
3808   Type *AggTy = I.getType();
3809   Type *ValTy = Op1->getType();
3810   bool IntoUndef = isa<UndefValue>(Op0);
3811   bool FromUndef = isa<UndefValue>(Op1);
3812 
3813   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3814 
3815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3816   SmallVector<EVT, 4> AggValueVTs;
3817   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3818   SmallVector<EVT, 4> ValValueVTs;
3819   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3820 
3821   unsigned NumAggValues = AggValueVTs.size();
3822   unsigned NumValValues = ValValueVTs.size();
3823   SmallVector<SDValue, 4> Values(NumAggValues);
3824 
3825   // Ignore an insertvalue that produces an empty object
3826   if (!NumAggValues) {
3827     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3828     return;
3829   }
3830 
3831   SDValue Agg = getValue(Op0);
3832   unsigned i = 0;
3833   // Copy the beginning value(s) from the original aggregate.
3834   for (; i != LinearIndex; ++i)
3835     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3836                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3837   // Copy values from the inserted value(s).
3838   if (NumValValues) {
3839     SDValue Val = getValue(Op1);
3840     for (; i != LinearIndex + NumValValues; ++i)
3841       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3842                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3843   }
3844   // Copy remaining value(s) from the original aggregate.
3845   for (; i != NumAggValues; ++i)
3846     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3847                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3848 
3849   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3850                            DAG.getVTList(AggValueVTs), Values));
3851 }
3852 
3853 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3854   ArrayRef<unsigned> Indices = I.getIndices();
3855   const Value *Op0 = I.getOperand(0);
3856   Type *AggTy = Op0->getType();
3857   Type *ValTy = I.getType();
3858   bool OutOfUndef = isa<UndefValue>(Op0);
3859 
3860   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3861 
3862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3863   SmallVector<EVT, 4> ValValueVTs;
3864   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3865 
3866   unsigned NumValValues = ValValueVTs.size();
3867 
3868   // Ignore a extractvalue that produces an empty object
3869   if (!NumValValues) {
3870     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3871     return;
3872   }
3873 
3874   SmallVector<SDValue, 4> Values(NumValValues);
3875 
3876   SDValue Agg = getValue(Op0);
3877   // Copy out the selected value(s).
3878   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3879     Values[i - LinearIndex] =
3880       OutOfUndef ?
3881         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3882         SDValue(Agg.getNode(), Agg.getResNo() + i);
3883 
3884   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3885                            DAG.getVTList(ValValueVTs), Values));
3886 }
3887 
3888 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3889   Value *Op0 = I.getOperand(0);
3890   // Note that the pointer operand may be a vector of pointers. Take the scalar
3891   // element which holds a pointer.
3892   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3893   SDValue N = getValue(Op0);
3894   SDLoc dl = getCurSDLoc();
3895   auto &TLI = DAG.getTargetLoweringInfo();
3896 
3897   // Normalize Vector GEP - all scalar operands should be converted to the
3898   // splat vector.
3899   bool IsVectorGEP = I.getType()->isVectorTy();
3900   ElementCount VectorElementCount =
3901       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3902                   : ElementCount::getFixed(0);
3903 
3904   if (IsVectorGEP && !N.getValueType().isVector()) {
3905     LLVMContext &Context = *DAG.getContext();
3906     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3907     if (VectorElementCount.isScalable())
3908       N = DAG.getSplatVector(VT, dl, N);
3909     else
3910       N = DAG.getSplatBuildVector(VT, dl, N);
3911   }
3912 
3913   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3914        GTI != E; ++GTI) {
3915     const Value *Idx = GTI.getOperand();
3916     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3917       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3918       if (Field) {
3919         // N = N + Offset
3920         uint64_t Offset =
3921             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3922 
3923         // In an inbounds GEP with an offset that is nonnegative even when
3924         // interpreted as signed, assume there is no unsigned overflow.
3925         SDNodeFlags Flags;
3926         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3927           Flags.setNoUnsignedWrap(true);
3928 
3929         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3930                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3931       }
3932     } else {
3933       // IdxSize is the width of the arithmetic according to IR semantics.
3934       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3935       // (and fix up the result later).
3936       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3937       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3938       TypeSize ElementSize =
3939           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3940       // We intentionally mask away the high bits here; ElementSize may not
3941       // fit in IdxTy.
3942       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3943       bool ElementScalable = ElementSize.isScalable();
3944 
3945       // If this is a scalar constant or a splat vector of constants,
3946       // handle it quickly.
3947       const auto *C = dyn_cast<Constant>(Idx);
3948       if (C && isa<VectorType>(C->getType()))
3949         C = C->getSplatValue();
3950 
3951       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3952       if (CI && CI->isZero())
3953         continue;
3954       if (CI && !ElementScalable) {
3955         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3956         LLVMContext &Context = *DAG.getContext();
3957         SDValue OffsVal;
3958         if (IsVectorGEP)
3959           OffsVal = DAG.getConstant(
3960               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3961         else
3962           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3963 
3964         // In an inbounds GEP with an offset that is nonnegative even when
3965         // interpreted as signed, assume there is no unsigned overflow.
3966         SDNodeFlags Flags;
3967         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3968           Flags.setNoUnsignedWrap(true);
3969 
3970         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3971 
3972         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3973         continue;
3974       }
3975 
3976       // N = N + Idx * ElementMul;
3977       SDValue IdxN = getValue(Idx);
3978 
3979       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3980         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3981                                   VectorElementCount);
3982         if (VectorElementCount.isScalable())
3983           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3984         else
3985           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3986       }
3987 
3988       // If the index is smaller or larger than intptr_t, truncate or extend
3989       // it.
3990       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3991 
3992       if (ElementScalable) {
3993         EVT VScaleTy = N.getValueType().getScalarType();
3994         SDValue VScale = DAG.getNode(
3995             ISD::VSCALE, dl, VScaleTy,
3996             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3997         if (IsVectorGEP)
3998           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3999         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4000       } else {
4001         // If this is a multiply by a power of two, turn it into a shl
4002         // immediately.  This is a very common case.
4003         if (ElementMul != 1) {
4004           if (ElementMul.isPowerOf2()) {
4005             unsigned Amt = ElementMul.logBase2();
4006             IdxN = DAG.getNode(ISD::SHL, dl,
4007                                N.getValueType(), IdxN,
4008                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4009           } else {
4010             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4011                                             IdxN.getValueType());
4012             IdxN = DAG.getNode(ISD::MUL, dl,
4013                                N.getValueType(), IdxN, Scale);
4014           }
4015         }
4016       }
4017 
4018       N = DAG.getNode(ISD::ADD, dl,
4019                       N.getValueType(), N, IdxN);
4020     }
4021   }
4022 
4023   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4024   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4025   if (IsVectorGEP) {
4026     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4027     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4028   }
4029 
4030   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4031     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4032 
4033   setValue(&I, N);
4034 }
4035 
4036 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4037   // If this is a fixed sized alloca in the entry block of the function,
4038   // allocate it statically on the stack.
4039   if (FuncInfo.StaticAllocaMap.count(&I))
4040     return;   // getValue will auto-populate this.
4041 
4042   SDLoc dl = getCurSDLoc();
4043   Type *Ty = I.getAllocatedType();
4044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4045   auto &DL = DAG.getDataLayout();
4046   TypeSize TySize = DL.getTypeAllocSize(Ty);
4047   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4048 
4049   SDValue AllocSize = getValue(I.getArraySize());
4050 
4051   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4052   if (AllocSize.getValueType() != IntPtr)
4053     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4054 
4055   if (TySize.isScalable())
4056     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4057                             DAG.getVScale(dl, IntPtr,
4058                                           APInt(IntPtr.getScalarSizeInBits(),
4059                                                 TySize.getKnownMinValue())));
4060   else
4061     AllocSize =
4062         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4063                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4064 
4065   // Handle alignment.  If the requested alignment is less than or equal to
4066   // the stack alignment, ignore it.  If the size is greater than or equal to
4067   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4068   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4069   if (*Alignment <= StackAlign)
4070     Alignment = None;
4071 
4072   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4073   // Round the size of the allocation up to the stack alignment size
4074   // by add SA-1 to the size. This doesn't overflow because we're computing
4075   // an address inside an alloca.
4076   SDNodeFlags Flags;
4077   Flags.setNoUnsignedWrap(true);
4078   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4079                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4080 
4081   // Mask out the low bits for alignment purposes.
4082   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4083                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4084 
4085   SDValue Ops[] = {
4086       getRoot(), AllocSize,
4087       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4088   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4089   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4090   setValue(&I, DSA);
4091   DAG.setRoot(DSA.getValue(1));
4092 
4093   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4094 }
4095 
4096 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4097   if (I.isAtomic())
4098     return visitAtomicLoad(I);
4099 
4100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4101   const Value *SV = I.getOperand(0);
4102   if (TLI.supportSwiftError()) {
4103     // Swifterror values can come from either a function parameter with
4104     // swifterror attribute or an alloca with swifterror attribute.
4105     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4106       if (Arg->hasSwiftErrorAttr())
4107         return visitLoadFromSwiftError(I);
4108     }
4109 
4110     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4111       if (Alloca->isSwiftError())
4112         return visitLoadFromSwiftError(I);
4113     }
4114   }
4115 
4116   SDValue Ptr = getValue(SV);
4117 
4118   Type *Ty = I.getType();
4119   SmallVector<EVT, 4> ValueVTs, MemVTs;
4120   SmallVector<uint64_t, 4> Offsets;
4121   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4122   unsigned NumValues = ValueVTs.size();
4123   if (NumValues == 0)
4124     return;
4125 
4126   Align Alignment = I.getAlign();
4127   AAMDNodes AAInfo = I.getAAMetadata();
4128   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4129   bool isVolatile = I.isVolatile();
4130   MachineMemOperand::Flags MMOFlags =
4131       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4132 
4133   SDValue Root;
4134   bool ConstantMemory = false;
4135   if (isVolatile)
4136     // Serialize volatile loads with other side effects.
4137     Root = getRoot();
4138   else if (NumValues > MaxParallelChains)
4139     Root = getMemoryRoot();
4140   else if (AA &&
4141            AA->pointsToConstantMemory(MemoryLocation(
4142                SV,
4143                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4144                AAInfo))) {
4145     // Do not serialize (non-volatile) loads of constant memory with anything.
4146     Root = DAG.getEntryNode();
4147     ConstantMemory = true;
4148     MMOFlags |= MachineMemOperand::MOInvariant;
4149   } else {
4150     // Do not serialize non-volatile loads against each other.
4151     Root = DAG.getRoot();
4152   }
4153 
4154   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4155                                          &I, AC, nullptr, LibInfo))
4156     MMOFlags |= MachineMemOperand::MODereferenceable;
4157 
4158   SDLoc dl = getCurSDLoc();
4159 
4160   if (isVolatile)
4161     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4162 
4163   // An aggregate load cannot wrap around the address space, so offsets to its
4164   // parts don't wrap either.
4165   SDNodeFlags Flags;
4166   Flags.setNoUnsignedWrap(true);
4167 
4168   SmallVector<SDValue, 4> Values(NumValues);
4169   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4170   EVT PtrVT = Ptr.getValueType();
4171 
4172   unsigned ChainI = 0;
4173   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4174     // Serializing loads here may result in excessive register pressure, and
4175     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4176     // could recover a bit by hoisting nodes upward in the chain by recognizing
4177     // they are side-effect free or do not alias. The optimizer should really
4178     // avoid this case by converting large object/array copies to llvm.memcpy
4179     // (MaxParallelChains should always remain as failsafe).
4180     if (ChainI == MaxParallelChains) {
4181       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4182       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4183                                   makeArrayRef(Chains.data(), ChainI));
4184       Root = Chain;
4185       ChainI = 0;
4186     }
4187     SDValue A = DAG.getNode(ISD::ADD, dl,
4188                             PtrVT, Ptr,
4189                             DAG.getConstant(Offsets[i], dl, PtrVT),
4190                             Flags);
4191 
4192     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4193                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4194                             MMOFlags, AAInfo, Ranges);
4195     Chains[ChainI] = L.getValue(1);
4196 
4197     if (MemVTs[i] != ValueVTs[i])
4198       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4199 
4200     Values[i] = L;
4201   }
4202 
4203   if (!ConstantMemory) {
4204     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4205                                 makeArrayRef(Chains.data(), ChainI));
4206     if (isVolatile)
4207       DAG.setRoot(Chain);
4208     else
4209       PendingLoads.push_back(Chain);
4210   }
4211 
4212   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4213                            DAG.getVTList(ValueVTs), Values));
4214 }
4215 
4216 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4217   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4218          "call visitStoreToSwiftError when backend supports swifterror");
4219 
4220   SmallVector<EVT, 4> ValueVTs;
4221   SmallVector<uint64_t, 4> Offsets;
4222   const Value *SrcV = I.getOperand(0);
4223   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4224                   SrcV->getType(), ValueVTs, &Offsets);
4225   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4226          "expect a single EVT for swifterror");
4227 
4228   SDValue Src = getValue(SrcV);
4229   // Create a virtual register, then update the virtual register.
4230   Register VReg =
4231       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4232   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4233   // Chain can be getRoot or getControlRoot.
4234   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4235                                       SDValue(Src.getNode(), Src.getResNo()));
4236   DAG.setRoot(CopyNode);
4237 }
4238 
4239 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4240   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4241          "call visitLoadFromSwiftError when backend supports swifterror");
4242 
4243   assert(!I.isVolatile() &&
4244          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4245          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4246          "Support volatile, non temporal, invariant for load_from_swift_error");
4247 
4248   const Value *SV = I.getOperand(0);
4249   Type *Ty = I.getType();
4250   assert(
4251       (!AA ||
4252        !AA->pointsToConstantMemory(MemoryLocation(
4253            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4254            I.getAAMetadata()))) &&
4255       "load_from_swift_error should not be constant memory");
4256 
4257   SmallVector<EVT, 4> ValueVTs;
4258   SmallVector<uint64_t, 4> Offsets;
4259   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4260                   ValueVTs, &Offsets);
4261   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4262          "expect a single EVT for swifterror");
4263 
4264   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4265   SDValue L = DAG.getCopyFromReg(
4266       getRoot(), getCurSDLoc(),
4267       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4268 
4269   setValue(&I, L);
4270 }
4271 
4272 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4273   if (I.isAtomic())
4274     return visitAtomicStore(I);
4275 
4276   const Value *SrcV = I.getOperand(0);
4277   const Value *PtrV = I.getOperand(1);
4278 
4279   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4280   if (TLI.supportSwiftError()) {
4281     // Swifterror values can come from either a function parameter with
4282     // swifterror attribute or an alloca with swifterror attribute.
4283     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4284       if (Arg->hasSwiftErrorAttr())
4285         return visitStoreToSwiftError(I);
4286     }
4287 
4288     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4289       if (Alloca->isSwiftError())
4290         return visitStoreToSwiftError(I);
4291     }
4292   }
4293 
4294   SmallVector<EVT, 4> ValueVTs, MemVTs;
4295   SmallVector<uint64_t, 4> Offsets;
4296   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4297                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4298   unsigned NumValues = ValueVTs.size();
4299   if (NumValues == 0)
4300     return;
4301 
4302   // Get the lowered operands. Note that we do this after
4303   // checking if NumResults is zero, because with zero results
4304   // the operands won't have values in the map.
4305   SDValue Src = getValue(SrcV);
4306   SDValue Ptr = getValue(PtrV);
4307 
4308   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4309   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4310   SDLoc dl = getCurSDLoc();
4311   Align Alignment = I.getAlign();
4312   AAMDNodes AAInfo = I.getAAMetadata();
4313 
4314   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4315 
4316   // An aggregate load cannot wrap around the address space, so offsets to its
4317   // parts don't wrap either.
4318   SDNodeFlags Flags;
4319   Flags.setNoUnsignedWrap(true);
4320 
4321   unsigned ChainI = 0;
4322   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4323     // See visitLoad comments.
4324     if (ChainI == MaxParallelChains) {
4325       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4326                                   makeArrayRef(Chains.data(), ChainI));
4327       Root = Chain;
4328       ChainI = 0;
4329     }
4330     SDValue Add =
4331         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4332     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4333     if (MemVTs[i] != ValueVTs[i])
4334       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4335     SDValue St =
4336         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4337                      Alignment, MMOFlags, AAInfo);
4338     Chains[ChainI] = St;
4339   }
4340 
4341   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4342                                   makeArrayRef(Chains.data(), ChainI));
4343   setValue(&I, StoreNode);
4344   DAG.setRoot(StoreNode);
4345 }
4346 
4347 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4348                                            bool IsCompressing) {
4349   SDLoc sdl = getCurSDLoc();
4350 
4351   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4352                                MaybeAlign &Alignment) {
4353     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4354     Src0 = I.getArgOperand(0);
4355     Ptr = I.getArgOperand(1);
4356     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4357     Mask = I.getArgOperand(3);
4358   };
4359   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4360                                     MaybeAlign &Alignment) {
4361     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4362     Src0 = I.getArgOperand(0);
4363     Ptr = I.getArgOperand(1);
4364     Mask = I.getArgOperand(2);
4365     Alignment = None;
4366   };
4367 
4368   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4369   MaybeAlign Alignment;
4370   if (IsCompressing)
4371     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4372   else
4373     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4374 
4375   SDValue Ptr = getValue(PtrOperand);
4376   SDValue Src0 = getValue(Src0Operand);
4377   SDValue Mask = getValue(MaskOperand);
4378   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4379 
4380   EVT VT = Src0.getValueType();
4381   if (!Alignment)
4382     Alignment = DAG.getEVTAlign(VT);
4383 
4384   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4385       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4386       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4387   SDValue StoreNode =
4388       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4389                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4390   DAG.setRoot(StoreNode);
4391   setValue(&I, StoreNode);
4392 }
4393 
4394 // Get a uniform base for the Gather/Scatter intrinsic.
4395 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4396 // We try to represent it as a base pointer + vector of indices.
4397 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4398 // The first operand of the GEP may be a single pointer or a vector of pointers
4399 // Example:
4400 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4401 //  or
4402 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4403 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4404 //
4405 // When the first GEP operand is a single pointer - it is the uniform base we
4406 // are looking for. If first operand of the GEP is a splat vector - we
4407 // extract the splat value and use it as a uniform base.
4408 // In all other cases the function returns 'false'.
4409 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4410                            ISD::MemIndexType &IndexType, SDValue &Scale,
4411                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4412                            uint64_t ElemSize) {
4413   SelectionDAG& DAG = SDB->DAG;
4414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4415   const DataLayout &DL = DAG.getDataLayout();
4416 
4417   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4418 
4419   // Handle splat constant pointer.
4420   if (auto *C = dyn_cast<Constant>(Ptr)) {
4421     C = C->getSplatValue();
4422     if (!C)
4423       return false;
4424 
4425     Base = SDB->getValue(C);
4426 
4427     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4428     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4429     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4430     IndexType = ISD::SIGNED_SCALED;
4431     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4432     return true;
4433   }
4434 
4435   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4436   if (!GEP || GEP->getParent() != CurBB)
4437     return false;
4438 
4439   if (GEP->getNumOperands() != 2)
4440     return false;
4441 
4442   const Value *BasePtr = GEP->getPointerOperand();
4443   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4444 
4445   // Make sure the base is scalar and the index is a vector.
4446   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4447     return false;
4448 
4449   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4450 
4451   // Target may not support the required addressing mode.
4452   if (ScaleVal != 1 &&
4453       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4454     return false;
4455 
4456   Base = SDB->getValue(BasePtr);
4457   Index = SDB->getValue(IndexVal);
4458   IndexType = ISD::SIGNED_SCALED;
4459 
4460   Scale =
4461       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4462   return true;
4463 }
4464 
4465 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4466   SDLoc sdl = getCurSDLoc();
4467 
4468   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4469   const Value *Ptr = I.getArgOperand(1);
4470   SDValue Src0 = getValue(I.getArgOperand(0));
4471   SDValue Mask = getValue(I.getArgOperand(3));
4472   EVT VT = Src0.getValueType();
4473   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4474                         ->getMaybeAlignValue()
4475                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4477 
4478   SDValue Base;
4479   SDValue Index;
4480   ISD::MemIndexType IndexType;
4481   SDValue Scale;
4482   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4483                                     I.getParent(), VT.getScalarStoreSize());
4484 
4485   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4486   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4487       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4488       // TODO: Make MachineMemOperands aware of scalable
4489       // vectors.
4490       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4491   if (!UniformBase) {
4492     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4493     Index = getValue(Ptr);
4494     IndexType = ISD::SIGNED_SCALED;
4495     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4496   }
4497 
4498   EVT IdxVT = Index.getValueType();
4499   EVT EltTy = IdxVT.getVectorElementType();
4500   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4501     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4502     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4503   }
4504 
4505   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4506   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4507                                          Ops, MMO, IndexType, false);
4508   DAG.setRoot(Scatter);
4509   setValue(&I, Scatter);
4510 }
4511 
4512 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4513   SDLoc sdl = getCurSDLoc();
4514 
4515   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4516                               MaybeAlign &Alignment) {
4517     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4518     Ptr = I.getArgOperand(0);
4519     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4520     Mask = I.getArgOperand(2);
4521     Src0 = I.getArgOperand(3);
4522   };
4523   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4524                                  MaybeAlign &Alignment) {
4525     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4526     Ptr = I.getArgOperand(0);
4527     Alignment = None;
4528     Mask = I.getArgOperand(1);
4529     Src0 = I.getArgOperand(2);
4530   };
4531 
4532   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4533   MaybeAlign Alignment;
4534   if (IsExpanding)
4535     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4536   else
4537     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4538 
4539   SDValue Ptr = getValue(PtrOperand);
4540   SDValue Src0 = getValue(Src0Operand);
4541   SDValue Mask = getValue(MaskOperand);
4542   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4543 
4544   EVT VT = Src0.getValueType();
4545   if (!Alignment)
4546     Alignment = DAG.getEVTAlign(VT);
4547 
4548   AAMDNodes AAInfo = I.getAAMetadata();
4549   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4550 
4551   // Do not serialize masked loads of constant memory with anything.
4552   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4553   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4554 
4555   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4556 
4557   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4558       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4559       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4560 
4561   SDValue Load =
4562       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4563                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4564   if (AddToChain)
4565     PendingLoads.push_back(Load.getValue(1));
4566   setValue(&I, Load);
4567 }
4568 
4569 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4570   SDLoc sdl = getCurSDLoc();
4571 
4572   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4573   const Value *Ptr = I.getArgOperand(0);
4574   SDValue Src0 = getValue(I.getArgOperand(3));
4575   SDValue Mask = getValue(I.getArgOperand(2));
4576 
4577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4578   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4579   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4580                         ->getMaybeAlignValue()
4581                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4582 
4583   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4584 
4585   SDValue Root = DAG.getRoot();
4586   SDValue Base;
4587   SDValue Index;
4588   ISD::MemIndexType IndexType;
4589   SDValue Scale;
4590   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4591                                     I.getParent(), VT.getScalarStoreSize());
4592   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4593   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4594       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4595       // TODO: Make MachineMemOperands aware of scalable
4596       // vectors.
4597       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4598 
4599   if (!UniformBase) {
4600     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4601     Index = getValue(Ptr);
4602     IndexType = ISD::SIGNED_SCALED;
4603     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4604   }
4605 
4606   EVT IdxVT = Index.getValueType();
4607   EVT EltTy = IdxVT.getVectorElementType();
4608   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4609     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4610     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4611   }
4612 
4613   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4614   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4615                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4616 
4617   PendingLoads.push_back(Gather.getValue(1));
4618   setValue(&I, Gather);
4619 }
4620 
4621 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4622   SDLoc dl = getCurSDLoc();
4623   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4624   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4625   SyncScope::ID SSID = I.getSyncScopeID();
4626 
4627   SDValue InChain = getRoot();
4628 
4629   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4630   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4631 
4632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4633   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4634 
4635   MachineFunction &MF = DAG.getMachineFunction();
4636   MachineMemOperand *MMO = MF.getMachineMemOperand(
4637       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4638       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4639       FailureOrdering);
4640 
4641   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4642                                    dl, MemVT, VTs, InChain,
4643                                    getValue(I.getPointerOperand()),
4644                                    getValue(I.getCompareOperand()),
4645                                    getValue(I.getNewValOperand()), MMO);
4646 
4647   SDValue OutChain = L.getValue(2);
4648 
4649   setValue(&I, L);
4650   DAG.setRoot(OutChain);
4651 }
4652 
4653 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4654   SDLoc dl = getCurSDLoc();
4655   ISD::NodeType NT;
4656   switch (I.getOperation()) {
4657   default: llvm_unreachable("Unknown atomicrmw operation");
4658   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4659   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4660   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4661   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4662   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4663   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4664   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4665   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4666   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4667   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4668   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4669   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4670   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4671   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4672   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4673   }
4674   AtomicOrdering Ordering = I.getOrdering();
4675   SyncScope::ID SSID = I.getSyncScopeID();
4676 
4677   SDValue InChain = getRoot();
4678 
4679   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4680   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4681   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4682 
4683   MachineFunction &MF = DAG.getMachineFunction();
4684   MachineMemOperand *MMO = MF.getMachineMemOperand(
4685       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4686       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4687 
4688   SDValue L =
4689     DAG.getAtomic(NT, dl, MemVT, InChain,
4690                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4691                   MMO);
4692 
4693   SDValue OutChain = L.getValue(1);
4694 
4695   setValue(&I, L);
4696   DAG.setRoot(OutChain);
4697 }
4698 
4699 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4700   SDLoc dl = getCurSDLoc();
4701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4702   SDValue Ops[3];
4703   Ops[0] = getRoot();
4704   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4705                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4706   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4707                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4708   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4709   setValue(&I, N);
4710   DAG.setRoot(N);
4711 }
4712 
4713 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4714   SDLoc dl = getCurSDLoc();
4715   AtomicOrdering Order = I.getOrdering();
4716   SyncScope::ID SSID = I.getSyncScopeID();
4717 
4718   SDValue InChain = getRoot();
4719 
4720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4721   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4722   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4723 
4724   if (!TLI.supportsUnalignedAtomics() &&
4725       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4726     report_fatal_error("Cannot generate unaligned atomic load");
4727 
4728   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4729 
4730   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4731       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4732       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4733 
4734   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4735 
4736   SDValue Ptr = getValue(I.getPointerOperand());
4737 
4738   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4739     // TODO: Once this is better exercised by tests, it should be merged with
4740     // the normal path for loads to prevent future divergence.
4741     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4742     if (MemVT != VT)
4743       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4744 
4745     setValue(&I, L);
4746     SDValue OutChain = L.getValue(1);
4747     if (!I.isUnordered())
4748       DAG.setRoot(OutChain);
4749     else
4750       PendingLoads.push_back(OutChain);
4751     return;
4752   }
4753 
4754   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4755                             Ptr, MMO);
4756 
4757   SDValue OutChain = L.getValue(1);
4758   if (MemVT != VT)
4759     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4760 
4761   setValue(&I, L);
4762   DAG.setRoot(OutChain);
4763 }
4764 
4765 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4766   SDLoc dl = getCurSDLoc();
4767 
4768   AtomicOrdering Ordering = I.getOrdering();
4769   SyncScope::ID SSID = I.getSyncScopeID();
4770 
4771   SDValue InChain = getRoot();
4772 
4773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4774   EVT MemVT =
4775       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4776 
4777   if (!TLI.supportsUnalignedAtomics() &&
4778       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4779     report_fatal_error("Cannot generate unaligned atomic store");
4780 
4781   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4782 
4783   MachineFunction &MF = DAG.getMachineFunction();
4784   MachineMemOperand *MMO = MF.getMachineMemOperand(
4785       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4786       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4787 
4788   SDValue Val = getValue(I.getValueOperand());
4789   if (Val.getValueType() != MemVT)
4790     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4791   SDValue Ptr = getValue(I.getPointerOperand());
4792 
4793   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4794     // TODO: Once this is better exercised by tests, it should be merged with
4795     // the normal path for stores to prevent future divergence.
4796     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4797     setValue(&I, S);
4798     DAG.setRoot(S);
4799     return;
4800   }
4801   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4802                                    Ptr, Val, MMO);
4803 
4804   setValue(&I, OutChain);
4805   DAG.setRoot(OutChain);
4806 }
4807 
4808 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4809 /// node.
4810 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4811                                                unsigned Intrinsic) {
4812   // Ignore the callsite's attributes. A specific call site may be marked with
4813   // readnone, but the lowering code will expect the chain based on the
4814   // definition.
4815   const Function *F = I.getCalledFunction();
4816   bool HasChain = !F->doesNotAccessMemory();
4817   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4818 
4819   // Build the operand list.
4820   SmallVector<SDValue, 8> Ops;
4821   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4822     if (OnlyLoad) {
4823       // We don't need to serialize loads against other loads.
4824       Ops.push_back(DAG.getRoot());
4825     } else {
4826       Ops.push_back(getRoot());
4827     }
4828   }
4829 
4830   // Info is set by getTgtMemIntrinsic
4831   TargetLowering::IntrinsicInfo Info;
4832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4833   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4834                                                DAG.getMachineFunction(),
4835                                                Intrinsic);
4836 
4837   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4838   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4839       Info.opc == ISD::INTRINSIC_W_CHAIN)
4840     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4841                                         TLI.getPointerTy(DAG.getDataLayout())));
4842 
4843   // Add all operands of the call to the operand list.
4844   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4845     const Value *Arg = I.getArgOperand(i);
4846     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4847       Ops.push_back(getValue(Arg));
4848       continue;
4849     }
4850 
4851     // Use TargetConstant instead of a regular constant for immarg.
4852     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4853     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4854       assert(CI->getBitWidth() <= 64 &&
4855              "large intrinsic immediates not handled");
4856       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4857     } else {
4858       Ops.push_back(
4859           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4860     }
4861   }
4862 
4863   SmallVector<EVT, 4> ValueVTs;
4864   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4865 
4866   if (HasChain)
4867     ValueVTs.push_back(MVT::Other);
4868 
4869   SDVTList VTs = DAG.getVTList(ValueVTs);
4870 
4871   // Propagate fast-math-flags from IR to node(s).
4872   SDNodeFlags Flags;
4873   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4874     Flags.copyFMF(*FPMO);
4875   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4876 
4877   // Create the node.
4878   SDValue Result;
4879   // In some cases, custom collection of operands from CallInst I may be needed.
4880   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4881   if (IsTgtIntrinsic) {
4882     // This is target intrinsic that touches memory
4883     Result =
4884         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4885                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4886                                 Info.align, Info.flags, Info.size,
4887                                 I.getAAMetadata());
4888   } else if (!HasChain) {
4889     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4890   } else if (!I.getType()->isVoidTy()) {
4891     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4892   } else {
4893     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4894   }
4895 
4896   if (HasChain) {
4897     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4898     if (OnlyLoad)
4899       PendingLoads.push_back(Chain);
4900     else
4901       DAG.setRoot(Chain);
4902   }
4903 
4904   if (!I.getType()->isVoidTy()) {
4905     if (!isa<VectorType>(I.getType()))
4906       Result = lowerRangeToAssertZExt(DAG, I, Result);
4907 
4908     MaybeAlign Alignment = I.getRetAlign();
4909     if (!Alignment)
4910       Alignment = F->getAttributes().getRetAlignment();
4911     // Insert `assertalign` node if there's an alignment.
4912     if (InsertAssertAlign && Alignment) {
4913       Result =
4914           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4915     }
4916 
4917     setValue(&I, Result);
4918   }
4919 }
4920 
4921 /// GetSignificand - Get the significand and build it into a floating-point
4922 /// number with exponent of 1:
4923 ///
4924 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4925 ///
4926 /// where Op is the hexadecimal representation of floating point value.
4927 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4928   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4929                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4930   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4931                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4932   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4933 }
4934 
4935 /// GetExponent - Get the exponent:
4936 ///
4937 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4938 ///
4939 /// where Op is the hexadecimal representation of floating point value.
4940 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4941                            const TargetLowering &TLI, const SDLoc &dl) {
4942   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4943                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4944   SDValue t1 = DAG.getNode(
4945       ISD::SRL, dl, MVT::i32, t0,
4946       DAG.getConstant(23, dl,
4947                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4948   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4949                            DAG.getConstant(127, dl, MVT::i32));
4950   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4951 }
4952 
4953 /// getF32Constant - Get 32-bit floating point constant.
4954 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4955                               const SDLoc &dl) {
4956   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4957                            MVT::f32);
4958 }
4959 
4960 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4961                                        SelectionDAG &DAG) {
4962   // TODO: What fast-math-flags should be set on the floating-point nodes?
4963 
4964   //   IntegerPartOfX = ((int32_t)(t0);
4965   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4966 
4967   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4968   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4969   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4970 
4971   //   IntegerPartOfX <<= 23;
4972   IntegerPartOfX =
4973       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4974                   DAG.getConstant(23, dl,
4975                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4976                                       MVT::i32, DAG.getDataLayout())));
4977 
4978   SDValue TwoToFractionalPartOfX;
4979   if (LimitFloatPrecision <= 6) {
4980     // For floating-point precision of 6:
4981     //
4982     //   TwoToFractionalPartOfX =
4983     //     0.997535578f +
4984     //       (0.735607626f + 0.252464424f * x) * x;
4985     //
4986     // error 0.0144103317, which is 6 bits
4987     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4988                              getF32Constant(DAG, 0x3e814304, dl));
4989     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4990                              getF32Constant(DAG, 0x3f3c50c8, dl));
4991     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4992     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4993                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4994   } else if (LimitFloatPrecision <= 12) {
4995     // For floating-point precision of 12:
4996     //
4997     //   TwoToFractionalPartOfX =
4998     //     0.999892986f +
4999     //       (0.696457318f +
5000     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5001     //
5002     // error 0.000107046256, which is 13 to 14 bits
5003     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5004                              getF32Constant(DAG, 0x3da235e3, dl));
5005     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5006                              getF32Constant(DAG, 0x3e65b8f3, dl));
5007     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5008     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5009                              getF32Constant(DAG, 0x3f324b07, dl));
5010     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5011     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5012                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5013   } else { // LimitFloatPrecision <= 18
5014     // For floating-point precision of 18:
5015     //
5016     //   TwoToFractionalPartOfX =
5017     //     0.999999982f +
5018     //       (0.693148872f +
5019     //         (0.240227044f +
5020     //           (0.554906021e-1f +
5021     //             (0.961591928e-2f +
5022     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5023     // error 2.47208000*10^(-7), which is better than 18 bits
5024     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5025                              getF32Constant(DAG, 0x3924b03e, dl));
5026     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5027                              getF32Constant(DAG, 0x3ab24b87, dl));
5028     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5029     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5030                              getF32Constant(DAG, 0x3c1d8c17, dl));
5031     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5032     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5033                              getF32Constant(DAG, 0x3d634a1d, dl));
5034     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5035     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5036                              getF32Constant(DAG, 0x3e75fe14, dl));
5037     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5038     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5039                               getF32Constant(DAG, 0x3f317234, dl));
5040     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5041     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5042                                          getF32Constant(DAG, 0x3f800000, dl));
5043   }
5044 
5045   // Add the exponent into the result in integer domain.
5046   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5047   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5048                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5049 }
5050 
5051 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5052 /// limited-precision mode.
5053 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5054                          const TargetLowering &TLI, SDNodeFlags Flags) {
5055   if (Op.getValueType() == MVT::f32 &&
5056       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5057 
5058     // Put the exponent in the right bit position for later addition to the
5059     // final result:
5060     //
5061     // t0 = Op * log2(e)
5062 
5063     // TODO: What fast-math-flags should be set here?
5064     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5065                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5066     return getLimitedPrecisionExp2(t0, dl, DAG);
5067   }
5068 
5069   // No special expansion.
5070   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5071 }
5072 
5073 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5074 /// limited-precision mode.
5075 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5076                          const TargetLowering &TLI, SDNodeFlags Flags) {
5077   // TODO: What fast-math-flags should be set on the floating-point nodes?
5078 
5079   if (Op.getValueType() == MVT::f32 &&
5080       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5081     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5082 
5083     // Scale the exponent by log(2).
5084     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5085     SDValue LogOfExponent =
5086         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5087                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5088 
5089     // Get the significand and build it into a floating-point number with
5090     // exponent of 1.
5091     SDValue X = GetSignificand(DAG, Op1, dl);
5092 
5093     SDValue LogOfMantissa;
5094     if (LimitFloatPrecision <= 6) {
5095       // For floating-point precision of 6:
5096       //
5097       //   LogofMantissa =
5098       //     -1.1609546f +
5099       //       (1.4034025f - 0.23903021f * x) * x;
5100       //
5101       // error 0.0034276066, which is better than 8 bits
5102       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5103                                getF32Constant(DAG, 0xbe74c456, dl));
5104       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5105                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5106       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5107       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5108                                   getF32Constant(DAG, 0x3f949a29, dl));
5109     } else if (LimitFloatPrecision <= 12) {
5110       // For floating-point precision of 12:
5111       //
5112       //   LogOfMantissa =
5113       //     -1.7417939f +
5114       //       (2.8212026f +
5115       //         (-1.4699568f +
5116       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5117       //
5118       // error 0.000061011436, which is 14 bits
5119       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5120                                getF32Constant(DAG, 0xbd67b6d6, dl));
5121       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5122                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5123       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5124       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5125                                getF32Constant(DAG, 0x3fbc278b, dl));
5126       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5127       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5128                                getF32Constant(DAG, 0x40348e95, dl));
5129       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5130       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5131                                   getF32Constant(DAG, 0x3fdef31a, dl));
5132     } else { // LimitFloatPrecision <= 18
5133       // For floating-point precision of 18:
5134       //
5135       //   LogOfMantissa =
5136       //     -2.1072184f +
5137       //       (4.2372794f +
5138       //         (-3.7029485f +
5139       //           (2.2781945f +
5140       //             (-0.87823314f +
5141       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5142       //
5143       // error 0.0000023660568, which is better than 18 bits
5144       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5145                                getF32Constant(DAG, 0xbc91e5ac, dl));
5146       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5147                                getF32Constant(DAG, 0x3e4350aa, dl));
5148       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5149       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5150                                getF32Constant(DAG, 0x3f60d3e3, dl));
5151       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5152       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5153                                getF32Constant(DAG, 0x4011cdf0, dl));
5154       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5155       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5156                                getF32Constant(DAG, 0x406cfd1c, dl));
5157       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5158       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5159                                getF32Constant(DAG, 0x408797cb, dl));
5160       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5161       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5162                                   getF32Constant(DAG, 0x4006dcab, dl));
5163     }
5164 
5165     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5166   }
5167 
5168   // No special expansion.
5169   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5170 }
5171 
5172 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5173 /// limited-precision mode.
5174 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5175                           const TargetLowering &TLI, SDNodeFlags Flags) {
5176   // TODO: What fast-math-flags should be set on the floating-point nodes?
5177 
5178   if (Op.getValueType() == MVT::f32 &&
5179       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5180     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5181 
5182     // Get the exponent.
5183     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5184 
5185     // Get the significand and build it into a floating-point number with
5186     // exponent of 1.
5187     SDValue X = GetSignificand(DAG, Op1, dl);
5188 
5189     // Different possible minimax approximations of significand in
5190     // floating-point for various degrees of accuracy over [1,2].
5191     SDValue Log2ofMantissa;
5192     if (LimitFloatPrecision <= 6) {
5193       // For floating-point precision of 6:
5194       //
5195       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5196       //
5197       // error 0.0049451742, which is more than 7 bits
5198       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5199                                getF32Constant(DAG, 0xbeb08fe0, dl));
5200       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5201                                getF32Constant(DAG, 0x40019463, dl));
5202       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5203       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5204                                    getF32Constant(DAG, 0x3fd6633d, dl));
5205     } else if (LimitFloatPrecision <= 12) {
5206       // For floating-point precision of 12:
5207       //
5208       //   Log2ofMantissa =
5209       //     -2.51285454f +
5210       //       (4.07009056f +
5211       //         (-2.12067489f +
5212       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5213       //
5214       // error 0.0000876136000, which is better than 13 bits
5215       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5216                                getF32Constant(DAG, 0xbda7262e, dl));
5217       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5218                                getF32Constant(DAG, 0x3f25280b, dl));
5219       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5220       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5221                                getF32Constant(DAG, 0x4007b923, dl));
5222       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5223       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5224                                getF32Constant(DAG, 0x40823e2f, dl));
5225       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5226       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5227                                    getF32Constant(DAG, 0x4020d29c, dl));
5228     } else { // LimitFloatPrecision <= 18
5229       // For floating-point precision of 18:
5230       //
5231       //   Log2ofMantissa =
5232       //     -3.0400495f +
5233       //       (6.1129976f +
5234       //         (-5.3420409f +
5235       //           (3.2865683f +
5236       //             (-1.2669343f +
5237       //               (0.27515199f -
5238       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5239       //
5240       // error 0.0000018516, which is better than 18 bits
5241       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5242                                getF32Constant(DAG, 0xbcd2769e, dl));
5243       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5244                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5245       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5246       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5247                                getF32Constant(DAG, 0x3fa22ae7, dl));
5248       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5249       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5250                                getF32Constant(DAG, 0x40525723, dl));
5251       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5252       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5253                                getF32Constant(DAG, 0x40aaf200, dl));
5254       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5255       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5256                                getF32Constant(DAG, 0x40c39dad, dl));
5257       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5258       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5259                                    getF32Constant(DAG, 0x4042902c, dl));
5260     }
5261 
5262     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5263   }
5264 
5265   // No special expansion.
5266   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5267 }
5268 
5269 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5270 /// limited-precision mode.
5271 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5272                            const TargetLowering &TLI, SDNodeFlags Flags) {
5273   // TODO: What fast-math-flags should be set on the floating-point nodes?
5274 
5275   if (Op.getValueType() == MVT::f32 &&
5276       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5277     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5278 
5279     // Scale the exponent by log10(2) [0.30102999f].
5280     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5281     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5282                                         getF32Constant(DAG, 0x3e9a209a, dl));
5283 
5284     // Get the significand and build it into a floating-point number with
5285     // exponent of 1.
5286     SDValue X = GetSignificand(DAG, Op1, dl);
5287 
5288     SDValue Log10ofMantissa;
5289     if (LimitFloatPrecision <= 6) {
5290       // For floating-point precision of 6:
5291       //
5292       //   Log10ofMantissa =
5293       //     -0.50419619f +
5294       //       (0.60948995f - 0.10380950f * x) * x;
5295       //
5296       // error 0.0014886165, which is 6 bits
5297       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5298                                getF32Constant(DAG, 0xbdd49a13, dl));
5299       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5300                                getF32Constant(DAG, 0x3f1c0789, dl));
5301       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5302       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5303                                     getF32Constant(DAG, 0x3f011300, dl));
5304     } else if (LimitFloatPrecision <= 12) {
5305       // For floating-point precision of 12:
5306       //
5307       //   Log10ofMantissa =
5308       //     -0.64831180f +
5309       //       (0.91751397f +
5310       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5311       //
5312       // error 0.00019228036, which is better than 12 bits
5313       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5314                                getF32Constant(DAG, 0x3d431f31, dl));
5315       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5316                                getF32Constant(DAG, 0x3ea21fb2, dl));
5317       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5318       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5319                                getF32Constant(DAG, 0x3f6ae232, dl));
5320       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5321       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5322                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5323     } else { // LimitFloatPrecision <= 18
5324       // For floating-point precision of 18:
5325       //
5326       //   Log10ofMantissa =
5327       //     -0.84299375f +
5328       //       (1.5327582f +
5329       //         (-1.0688956f +
5330       //           (0.49102474f +
5331       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5332       //
5333       // error 0.0000037995730, which is better than 18 bits
5334       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5335                                getF32Constant(DAG, 0x3c5d51ce, dl));
5336       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5337                                getF32Constant(DAG, 0x3e00685a, dl));
5338       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5339       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5340                                getF32Constant(DAG, 0x3efb6798, dl));
5341       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5342       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5343                                getF32Constant(DAG, 0x3f88d192, dl));
5344       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5345       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5346                                getF32Constant(DAG, 0x3fc4316c, dl));
5347       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5348       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5349                                     getF32Constant(DAG, 0x3f57ce70, dl));
5350     }
5351 
5352     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5353   }
5354 
5355   // No special expansion.
5356   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5357 }
5358 
5359 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5360 /// limited-precision mode.
5361 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5362                           const TargetLowering &TLI, SDNodeFlags Flags) {
5363   if (Op.getValueType() == MVT::f32 &&
5364       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5365     return getLimitedPrecisionExp2(Op, dl, DAG);
5366 
5367   // No special expansion.
5368   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5369 }
5370 
5371 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5372 /// limited-precision mode with x == 10.0f.
5373 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5374                          SelectionDAG &DAG, const TargetLowering &TLI,
5375                          SDNodeFlags Flags) {
5376   bool IsExp10 = false;
5377   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5378       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5379     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5380       APFloat Ten(10.0f);
5381       IsExp10 = LHSC->isExactlyValue(Ten);
5382     }
5383   }
5384 
5385   // TODO: What fast-math-flags should be set on the FMUL node?
5386   if (IsExp10) {
5387     // Put the exponent in the right bit position for later addition to the
5388     // final result:
5389     //
5390     //   #define LOG2OF10 3.3219281f
5391     //   t0 = Op * LOG2OF10;
5392     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5393                              getF32Constant(DAG, 0x40549a78, dl));
5394     return getLimitedPrecisionExp2(t0, dl, DAG);
5395   }
5396 
5397   // No special expansion.
5398   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5399 }
5400 
5401 /// ExpandPowI - Expand a llvm.powi intrinsic.
5402 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5403                           SelectionDAG &DAG) {
5404   // If RHS is a constant, we can expand this out to a multiplication tree if
5405   // it's beneficial on the target, otherwise we end up lowering to a call to
5406   // __powidf2 (for example).
5407   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5408     unsigned Val = RHSC->getSExtValue();
5409 
5410     // powi(x, 0) -> 1.0
5411     if (Val == 0)
5412       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5413 
5414     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5415             Val, DAG.shouldOptForSize())) {
5416       // Get the exponent as a positive value.
5417       if ((int)Val < 0)
5418         Val = -Val;
5419       // We use the simple binary decomposition method to generate the multiply
5420       // sequence.  There are more optimal ways to do this (for example,
5421       // powi(x,15) generates one more multiply than it should), but this has
5422       // the benefit of being both really simple and much better than a libcall.
5423       SDValue Res; // Logically starts equal to 1.0
5424       SDValue CurSquare = LHS;
5425       // TODO: Intrinsics should have fast-math-flags that propagate to these
5426       // nodes.
5427       while (Val) {
5428         if (Val & 1) {
5429           if (Res.getNode())
5430             Res =
5431                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5432           else
5433             Res = CurSquare; // 1.0*CurSquare.
5434         }
5435 
5436         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5437                                 CurSquare, CurSquare);
5438         Val >>= 1;
5439       }
5440 
5441       // If the original was negative, invert the result, producing 1/(x*x*x).
5442       if (RHSC->getSExtValue() < 0)
5443         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5444                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5445       return Res;
5446     }
5447   }
5448 
5449   // Otherwise, expand to a libcall.
5450   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5451 }
5452 
5453 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5454                             SDValue LHS, SDValue RHS, SDValue Scale,
5455                             SelectionDAG &DAG, const TargetLowering &TLI) {
5456   EVT VT = LHS.getValueType();
5457   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5458   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5459   LLVMContext &Ctx = *DAG.getContext();
5460 
5461   // If the type is legal but the operation isn't, this node might survive all
5462   // the way to operation legalization. If we end up there and we do not have
5463   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5464   // node.
5465 
5466   // Coax the legalizer into expanding the node during type legalization instead
5467   // by bumping the size by one bit. This will force it to Promote, enabling the
5468   // early expansion and avoiding the need to expand later.
5469 
5470   // We don't have to do this if Scale is 0; that can always be expanded, unless
5471   // it's a saturating signed operation. Those can experience true integer
5472   // division overflow, a case which we must avoid.
5473 
5474   // FIXME: We wouldn't have to do this (or any of the early
5475   // expansion/promotion) if it was possible to expand a libcall of an
5476   // illegal type during operation legalization. But it's not, so things
5477   // get a bit hacky.
5478   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5479   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5480       (TLI.isTypeLegal(VT) ||
5481        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5482     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5483         Opcode, VT, ScaleInt);
5484     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5485       EVT PromVT;
5486       if (VT.isScalarInteger())
5487         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5488       else if (VT.isVector()) {
5489         PromVT = VT.getVectorElementType();
5490         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5491         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5492       } else
5493         llvm_unreachable("Wrong VT for DIVFIX?");
5494       if (Signed) {
5495         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5496         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5497       } else {
5498         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5499         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5500       }
5501       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5502       // For saturating operations, we need to shift up the LHS to get the
5503       // proper saturation width, and then shift down again afterwards.
5504       if (Saturating)
5505         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5506                           DAG.getConstant(1, DL, ShiftTy));
5507       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5508       if (Saturating)
5509         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5510                           DAG.getConstant(1, DL, ShiftTy));
5511       return DAG.getZExtOrTrunc(Res, DL, VT);
5512     }
5513   }
5514 
5515   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5516 }
5517 
5518 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5519 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5520 static void
5521 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5522                      const SDValue &N) {
5523   switch (N.getOpcode()) {
5524   case ISD::CopyFromReg: {
5525     SDValue Op = N.getOperand(1);
5526     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5527                       Op.getValueType().getSizeInBits());
5528     return;
5529   }
5530   case ISD::BITCAST:
5531   case ISD::AssertZext:
5532   case ISD::AssertSext:
5533   case ISD::TRUNCATE:
5534     getUnderlyingArgRegs(Regs, N.getOperand(0));
5535     return;
5536   case ISD::BUILD_PAIR:
5537   case ISD::BUILD_VECTOR:
5538   case ISD::CONCAT_VECTORS:
5539     for (SDValue Op : N->op_values())
5540       getUnderlyingArgRegs(Regs, Op);
5541     return;
5542   default:
5543     return;
5544   }
5545 }
5546 
5547 /// If the DbgValueInst is a dbg_value of a function argument, create the
5548 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5549 /// instruction selection, they will be inserted to the entry BB.
5550 /// We don't currently support this for variadic dbg_values, as they shouldn't
5551 /// appear for function arguments or in the prologue.
5552 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5553     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5554     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5555   const Argument *Arg = dyn_cast<Argument>(V);
5556   if (!Arg)
5557     return false;
5558 
5559   MachineFunction &MF = DAG.getMachineFunction();
5560   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5561 
5562   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5563   // we've been asked to pursue.
5564   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5565                               bool Indirect) {
5566     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5567       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5568       // pointing at the VReg, which will be patched up later.
5569       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5570       auto MIB = BuildMI(MF, DL, Inst);
5571       MIB.addReg(Reg);
5572       MIB.addImm(0);
5573       MIB.addMetadata(Variable);
5574       auto *NewDIExpr = FragExpr;
5575       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5576       // the DIExpression.
5577       if (Indirect)
5578         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5579       MIB.addMetadata(NewDIExpr);
5580       return MIB;
5581     } else {
5582       // Create a completely standard DBG_VALUE.
5583       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5584       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5585     }
5586   };
5587 
5588   if (Kind == FuncArgumentDbgValueKind::Value) {
5589     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5590     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5591     // the entry block.
5592     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5593     if (!IsInEntryBlock)
5594       return false;
5595 
5596     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5597     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5598     // variable that also is a param.
5599     //
5600     // Although, if we are at the top of the entry block already, we can still
5601     // emit using ArgDbgValue. This might catch some situations when the
5602     // dbg.value refers to an argument that isn't used in the entry block, so
5603     // any CopyToReg node would be optimized out and the only way to express
5604     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5605     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5606     // we should only emit as ArgDbgValue if the Variable is an argument to the
5607     // current function, and the dbg.value intrinsic is found in the entry
5608     // block.
5609     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5610         !DL->getInlinedAt();
5611     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5612     if (!IsInPrologue && !VariableIsFunctionInputArg)
5613       return false;
5614 
5615     // Here we assume that a function argument on IR level only can be used to
5616     // describe one input parameter on source level. If we for example have
5617     // source code like this
5618     //
5619     //    struct A { long x, y; };
5620     //    void foo(struct A a, long b) {
5621     //      ...
5622     //      b = a.x;
5623     //      ...
5624     //    }
5625     //
5626     // and IR like this
5627     //
5628     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5629     //  entry:
5630     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5631     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5632     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5633     //    ...
5634     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5635     //    ...
5636     //
5637     // then the last dbg.value is describing a parameter "b" using a value that
5638     // is an argument. But since we already has used %a1 to describe a parameter
5639     // we should not handle that last dbg.value here (that would result in an
5640     // incorrect hoisting of the DBG_VALUE to the function entry).
5641     // Notice that we allow one dbg.value per IR level argument, to accommodate
5642     // for the situation with fragments above.
5643     if (VariableIsFunctionInputArg) {
5644       unsigned ArgNo = Arg->getArgNo();
5645       if (ArgNo >= FuncInfo.DescribedArgs.size())
5646         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5647       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5648         return false;
5649       FuncInfo.DescribedArgs.set(ArgNo);
5650     }
5651   }
5652 
5653   bool IsIndirect = false;
5654   Optional<MachineOperand> Op;
5655   // Some arguments' frame index is recorded during argument lowering.
5656   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5657   if (FI != std::numeric_limits<int>::max())
5658     Op = MachineOperand::CreateFI(FI);
5659 
5660   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5661   if (!Op && N.getNode()) {
5662     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5663     Register Reg;
5664     if (ArgRegsAndSizes.size() == 1)
5665       Reg = ArgRegsAndSizes.front().first;
5666 
5667     if (Reg && Reg.isVirtual()) {
5668       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5669       Register PR = RegInfo.getLiveInPhysReg(Reg);
5670       if (PR)
5671         Reg = PR;
5672     }
5673     if (Reg) {
5674       Op = MachineOperand::CreateReg(Reg, false);
5675       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5676     }
5677   }
5678 
5679   if (!Op && N.getNode()) {
5680     // Check if frame index is available.
5681     SDValue LCandidate = peekThroughBitcasts(N);
5682     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5683       if (FrameIndexSDNode *FINode =
5684           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5685         Op = MachineOperand::CreateFI(FINode->getIndex());
5686   }
5687 
5688   if (!Op) {
5689     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5690     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5691                                          SplitRegs) {
5692       unsigned Offset = 0;
5693       for (const auto &RegAndSize : SplitRegs) {
5694         // If the expression is already a fragment, the current register
5695         // offset+size might extend beyond the fragment. In this case, only
5696         // the register bits that are inside the fragment are relevant.
5697         int RegFragmentSizeInBits = RegAndSize.second;
5698         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5699           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5700           // The register is entirely outside the expression fragment,
5701           // so is irrelevant for debug info.
5702           if (Offset >= ExprFragmentSizeInBits)
5703             break;
5704           // The register is partially outside the expression fragment, only
5705           // the low bits within the fragment are relevant for debug info.
5706           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5707             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5708           }
5709         }
5710 
5711         auto FragmentExpr = DIExpression::createFragmentExpression(
5712             Expr, Offset, RegFragmentSizeInBits);
5713         Offset += RegAndSize.second;
5714         // If a valid fragment expression cannot be created, the variable's
5715         // correct value cannot be determined and so it is set as Undef.
5716         if (!FragmentExpr) {
5717           SDDbgValue *SDV = DAG.getConstantDbgValue(
5718               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5719           DAG.AddDbgValue(SDV, false);
5720           continue;
5721         }
5722         MachineInstr *NewMI =
5723             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5724                              Kind != FuncArgumentDbgValueKind::Value);
5725         FuncInfo.ArgDbgValues.push_back(NewMI);
5726       }
5727     };
5728 
5729     // Check if ValueMap has reg number.
5730     DenseMap<const Value *, Register>::const_iterator
5731       VMI = FuncInfo.ValueMap.find(V);
5732     if (VMI != FuncInfo.ValueMap.end()) {
5733       const auto &TLI = DAG.getTargetLoweringInfo();
5734       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5735                        V->getType(), None);
5736       if (RFV.occupiesMultipleRegs()) {
5737         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5738         return true;
5739       }
5740 
5741       Op = MachineOperand::CreateReg(VMI->second, false);
5742       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5743     } else if (ArgRegsAndSizes.size() > 1) {
5744       // This was split due to the calling convention, and no virtual register
5745       // mapping exists for the value.
5746       splitMultiRegDbgValue(ArgRegsAndSizes);
5747       return true;
5748     }
5749   }
5750 
5751   if (!Op)
5752     return false;
5753 
5754   assert(Variable->isValidLocationForIntrinsic(DL) &&
5755          "Expected inlined-at fields to agree");
5756   MachineInstr *NewMI = nullptr;
5757 
5758   if (Op->isReg())
5759     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5760   else
5761     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5762                     Variable, Expr);
5763 
5764   // Otherwise, use ArgDbgValues.
5765   FuncInfo.ArgDbgValues.push_back(NewMI);
5766   return true;
5767 }
5768 
5769 /// Return the appropriate SDDbgValue based on N.
5770 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5771                                              DILocalVariable *Variable,
5772                                              DIExpression *Expr,
5773                                              const DebugLoc &dl,
5774                                              unsigned DbgSDNodeOrder) {
5775   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5776     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5777     // stack slot locations.
5778     //
5779     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5780     // debug values here after optimization:
5781     //
5782     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5783     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5784     //
5785     // Both describe the direct values of their associated variables.
5786     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5787                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5788   }
5789   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5790                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5791 }
5792 
5793 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5794   switch (Intrinsic) {
5795   case Intrinsic::smul_fix:
5796     return ISD::SMULFIX;
5797   case Intrinsic::umul_fix:
5798     return ISD::UMULFIX;
5799   case Intrinsic::smul_fix_sat:
5800     return ISD::SMULFIXSAT;
5801   case Intrinsic::umul_fix_sat:
5802     return ISD::UMULFIXSAT;
5803   case Intrinsic::sdiv_fix:
5804     return ISD::SDIVFIX;
5805   case Intrinsic::udiv_fix:
5806     return ISD::UDIVFIX;
5807   case Intrinsic::sdiv_fix_sat:
5808     return ISD::SDIVFIXSAT;
5809   case Intrinsic::udiv_fix_sat:
5810     return ISD::UDIVFIXSAT;
5811   default:
5812     llvm_unreachable("Unhandled fixed point intrinsic");
5813   }
5814 }
5815 
5816 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5817                                            const char *FunctionName) {
5818   assert(FunctionName && "FunctionName must not be nullptr");
5819   SDValue Callee = DAG.getExternalSymbol(
5820       FunctionName,
5821       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5822   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5823 }
5824 
5825 /// Given a @llvm.call.preallocated.setup, return the corresponding
5826 /// preallocated call.
5827 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5828   assert(cast<CallBase>(PreallocatedSetup)
5829                  ->getCalledFunction()
5830                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5831          "expected call_preallocated_setup Value");
5832   for (const auto *U : PreallocatedSetup->users()) {
5833     auto *UseCall = cast<CallBase>(U);
5834     const Function *Fn = UseCall->getCalledFunction();
5835     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5836       return UseCall;
5837     }
5838   }
5839   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5840 }
5841 
5842 /// Lower the call to the specified intrinsic function.
5843 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5844                                              unsigned Intrinsic) {
5845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5846   SDLoc sdl = getCurSDLoc();
5847   DebugLoc dl = getCurDebugLoc();
5848   SDValue Res;
5849 
5850   SDNodeFlags Flags;
5851   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5852     Flags.copyFMF(*FPOp);
5853 
5854   switch (Intrinsic) {
5855   default:
5856     // By default, turn this into a target intrinsic node.
5857     visitTargetIntrinsic(I, Intrinsic);
5858     return;
5859   case Intrinsic::vscale: {
5860     match(&I, m_VScale(DAG.getDataLayout()));
5861     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5862     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5863     return;
5864   }
5865   case Intrinsic::vastart:  visitVAStart(I); return;
5866   case Intrinsic::vaend:    visitVAEnd(I); return;
5867   case Intrinsic::vacopy:   visitVACopy(I); return;
5868   case Intrinsic::returnaddress:
5869     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5870                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5871                              getValue(I.getArgOperand(0))));
5872     return;
5873   case Intrinsic::addressofreturnaddress:
5874     setValue(&I,
5875              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5876                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5877     return;
5878   case Intrinsic::sponentry:
5879     setValue(&I,
5880              DAG.getNode(ISD::SPONENTRY, sdl,
5881                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5882     return;
5883   case Intrinsic::frameaddress:
5884     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5885                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5886                              getValue(I.getArgOperand(0))));
5887     return;
5888   case Intrinsic::read_volatile_register:
5889   case Intrinsic::read_register: {
5890     Value *Reg = I.getArgOperand(0);
5891     SDValue Chain = getRoot();
5892     SDValue RegName =
5893         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5894     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5895     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5896       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5897     setValue(&I, Res);
5898     DAG.setRoot(Res.getValue(1));
5899     return;
5900   }
5901   case Intrinsic::write_register: {
5902     Value *Reg = I.getArgOperand(0);
5903     Value *RegValue = I.getArgOperand(1);
5904     SDValue Chain = getRoot();
5905     SDValue RegName =
5906         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5907     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5908                             RegName, getValue(RegValue)));
5909     return;
5910   }
5911   case Intrinsic::memcpy: {
5912     const auto &MCI = cast<MemCpyInst>(I);
5913     SDValue Op1 = getValue(I.getArgOperand(0));
5914     SDValue Op2 = getValue(I.getArgOperand(1));
5915     SDValue Op3 = getValue(I.getArgOperand(2));
5916     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5917     Align DstAlign = MCI.getDestAlign().valueOrOne();
5918     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5919     Align Alignment = std::min(DstAlign, SrcAlign);
5920     bool isVol = MCI.isVolatile();
5921     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5922     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5923     // node.
5924     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5925     SDValue MC = DAG.getMemcpy(
5926         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5927         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5928         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5929     updateDAGForMaybeTailCall(MC);
5930     return;
5931   }
5932   case Intrinsic::memcpy_inline: {
5933     const auto &MCI = cast<MemCpyInlineInst>(I);
5934     SDValue Dst = getValue(I.getArgOperand(0));
5935     SDValue Src = getValue(I.getArgOperand(1));
5936     SDValue Size = getValue(I.getArgOperand(2));
5937     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5938     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5939     Align DstAlign = MCI.getDestAlign().valueOrOne();
5940     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5941     Align Alignment = std::min(DstAlign, SrcAlign);
5942     bool isVol = MCI.isVolatile();
5943     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5944     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5945     // node.
5946     SDValue MC = DAG.getMemcpy(
5947         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5948         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5949         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5950     updateDAGForMaybeTailCall(MC);
5951     return;
5952   }
5953   case Intrinsic::memset: {
5954     const auto &MSI = cast<MemSetInst>(I);
5955     SDValue Op1 = getValue(I.getArgOperand(0));
5956     SDValue Op2 = getValue(I.getArgOperand(1));
5957     SDValue Op3 = getValue(I.getArgOperand(2));
5958     // @llvm.memset defines 0 and 1 to both mean no alignment.
5959     Align Alignment = MSI.getDestAlign().valueOrOne();
5960     bool isVol = MSI.isVolatile();
5961     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5962     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5963     SDValue MS = DAG.getMemset(
5964         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5965         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5966     updateDAGForMaybeTailCall(MS);
5967     return;
5968   }
5969   case Intrinsic::memset_inline: {
5970     const auto &MSII = cast<MemSetInlineInst>(I);
5971     SDValue Dst = getValue(I.getArgOperand(0));
5972     SDValue Value = getValue(I.getArgOperand(1));
5973     SDValue Size = getValue(I.getArgOperand(2));
5974     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5975     // @llvm.memset defines 0 and 1 to both mean no alignment.
5976     Align DstAlign = MSII.getDestAlign().valueOrOne();
5977     bool isVol = MSII.isVolatile();
5978     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5979     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5980     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5981                                /* AlwaysInline */ true, isTC,
5982                                MachinePointerInfo(I.getArgOperand(0)),
5983                                I.getAAMetadata());
5984     updateDAGForMaybeTailCall(MC);
5985     return;
5986   }
5987   case Intrinsic::memmove: {
5988     const auto &MMI = cast<MemMoveInst>(I);
5989     SDValue Op1 = getValue(I.getArgOperand(0));
5990     SDValue Op2 = getValue(I.getArgOperand(1));
5991     SDValue Op3 = getValue(I.getArgOperand(2));
5992     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5993     Align DstAlign = MMI.getDestAlign().valueOrOne();
5994     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5995     Align Alignment = std::min(DstAlign, SrcAlign);
5996     bool isVol = MMI.isVolatile();
5997     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5998     // FIXME: Support passing different dest/src alignments to the memmove DAG
5999     // node.
6000     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6001     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6002                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6003                                 MachinePointerInfo(I.getArgOperand(1)),
6004                                 I.getAAMetadata(), AA);
6005     updateDAGForMaybeTailCall(MM);
6006     return;
6007   }
6008   case Intrinsic::memcpy_element_unordered_atomic: {
6009     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6010     SDValue Dst = getValue(MI.getRawDest());
6011     SDValue Src = getValue(MI.getRawSource());
6012     SDValue Length = getValue(MI.getLength());
6013 
6014     Type *LengthTy = MI.getLength()->getType();
6015     unsigned ElemSz = MI.getElementSizeInBytes();
6016     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6017     SDValue MC =
6018         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6019                             isTC, MachinePointerInfo(MI.getRawDest()),
6020                             MachinePointerInfo(MI.getRawSource()));
6021     updateDAGForMaybeTailCall(MC);
6022     return;
6023   }
6024   case Intrinsic::memmove_element_unordered_atomic: {
6025     auto &MI = cast<AtomicMemMoveInst>(I);
6026     SDValue Dst = getValue(MI.getRawDest());
6027     SDValue Src = getValue(MI.getRawSource());
6028     SDValue Length = getValue(MI.getLength());
6029 
6030     Type *LengthTy = MI.getLength()->getType();
6031     unsigned ElemSz = MI.getElementSizeInBytes();
6032     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6033     SDValue MC =
6034         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6035                              isTC, MachinePointerInfo(MI.getRawDest()),
6036                              MachinePointerInfo(MI.getRawSource()));
6037     updateDAGForMaybeTailCall(MC);
6038     return;
6039   }
6040   case Intrinsic::memset_element_unordered_atomic: {
6041     auto &MI = cast<AtomicMemSetInst>(I);
6042     SDValue Dst = getValue(MI.getRawDest());
6043     SDValue Val = getValue(MI.getValue());
6044     SDValue Length = getValue(MI.getLength());
6045 
6046     Type *LengthTy = MI.getLength()->getType();
6047     unsigned ElemSz = MI.getElementSizeInBytes();
6048     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6049     SDValue MC =
6050         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6051                             isTC, MachinePointerInfo(MI.getRawDest()));
6052     updateDAGForMaybeTailCall(MC);
6053     return;
6054   }
6055   case Intrinsic::call_preallocated_setup: {
6056     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6057     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6058     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6059                               getRoot(), SrcValue);
6060     setValue(&I, Res);
6061     DAG.setRoot(Res);
6062     return;
6063   }
6064   case Intrinsic::call_preallocated_arg: {
6065     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6066     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6067     SDValue Ops[3];
6068     Ops[0] = getRoot();
6069     Ops[1] = SrcValue;
6070     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6071                                    MVT::i32); // arg index
6072     SDValue Res = DAG.getNode(
6073         ISD::PREALLOCATED_ARG, sdl,
6074         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6075     setValue(&I, Res);
6076     DAG.setRoot(Res.getValue(1));
6077     return;
6078   }
6079   case Intrinsic::dbg_addr:
6080   case Intrinsic::dbg_declare: {
6081     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6082     // they are non-variadic.
6083     const auto &DI = cast<DbgVariableIntrinsic>(I);
6084     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6085     DILocalVariable *Variable = DI.getVariable();
6086     DIExpression *Expression = DI.getExpression();
6087     dropDanglingDebugInfo(Variable, Expression);
6088     assert(Variable && "Missing variable");
6089     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6090                       << "\n");
6091     // Check if address has undef value.
6092     const Value *Address = DI.getVariableLocationOp(0);
6093     if (!Address || isa<UndefValue>(Address) ||
6094         (Address->use_empty() && !isa<Argument>(Address))) {
6095       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6096                         << " (bad/undef/unused-arg address)\n");
6097       return;
6098     }
6099 
6100     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6101 
6102     // Check if this variable can be described by a frame index, typically
6103     // either as a static alloca or a byval parameter.
6104     int FI = std::numeric_limits<int>::max();
6105     if (const auto *AI =
6106             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6107       if (AI->isStaticAlloca()) {
6108         auto I = FuncInfo.StaticAllocaMap.find(AI);
6109         if (I != FuncInfo.StaticAllocaMap.end())
6110           FI = I->second;
6111       }
6112     } else if (const auto *Arg = dyn_cast<Argument>(
6113                    Address->stripInBoundsConstantOffsets())) {
6114       FI = FuncInfo.getArgumentFrameIndex(Arg);
6115     }
6116 
6117     // llvm.dbg.addr is control dependent and always generates indirect
6118     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6119     // the MachineFunction variable table.
6120     if (FI != std::numeric_limits<int>::max()) {
6121       if (Intrinsic == Intrinsic::dbg_addr) {
6122         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6123             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6124             dl, SDNodeOrder);
6125         DAG.AddDbgValue(SDV, isParameter);
6126       } else {
6127         LLVM_DEBUG(dbgs() << "Skipping " << DI
6128                           << " (variable info stashed in MF side table)\n");
6129       }
6130       return;
6131     }
6132 
6133     SDValue &N = NodeMap[Address];
6134     if (!N.getNode() && isa<Argument>(Address))
6135       // Check unused arguments map.
6136       N = UnusedArgNodeMap[Address];
6137     SDDbgValue *SDV;
6138     if (N.getNode()) {
6139       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6140         Address = BCI->getOperand(0);
6141       // Parameters are handled specially.
6142       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6143       if (isParameter && FINode) {
6144         // Byval parameter. We have a frame index at this point.
6145         SDV =
6146             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6147                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6148       } else if (isa<Argument>(Address)) {
6149         // Address is an argument, so try to emit its dbg value using
6150         // virtual register info from the FuncInfo.ValueMap.
6151         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6152                                  FuncArgumentDbgValueKind::Declare, N);
6153         return;
6154       } else {
6155         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6156                               true, dl, SDNodeOrder);
6157       }
6158       DAG.AddDbgValue(SDV, isParameter);
6159     } else {
6160       // If Address is an argument then try to emit its dbg value using
6161       // virtual register info from the FuncInfo.ValueMap.
6162       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6163                                     FuncArgumentDbgValueKind::Declare, N)) {
6164         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6165                           << " (could not emit func-arg dbg_value)\n");
6166       }
6167     }
6168     return;
6169   }
6170   case Intrinsic::dbg_label: {
6171     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6172     DILabel *Label = DI.getLabel();
6173     assert(Label && "Missing label");
6174 
6175     SDDbgLabel *SDV;
6176     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6177     DAG.AddDbgLabel(SDV);
6178     return;
6179   }
6180   case Intrinsic::dbg_value: {
6181     const DbgValueInst &DI = cast<DbgValueInst>(I);
6182     assert(DI.getVariable() && "Missing variable");
6183 
6184     DILocalVariable *Variable = DI.getVariable();
6185     DIExpression *Expression = DI.getExpression();
6186     dropDanglingDebugInfo(Variable, Expression);
6187     SmallVector<Value *, 4> Values(DI.getValues());
6188     if (Values.empty())
6189       return;
6190 
6191     if (llvm::is_contained(Values, nullptr))
6192       return;
6193 
6194     bool IsVariadic = DI.hasArgList();
6195     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6196                           SDNodeOrder, IsVariadic))
6197       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6198     return;
6199   }
6200 
6201   case Intrinsic::eh_typeid_for: {
6202     // Find the type id for the given typeinfo.
6203     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6204     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6205     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6206     setValue(&I, Res);
6207     return;
6208   }
6209 
6210   case Intrinsic::eh_return_i32:
6211   case Intrinsic::eh_return_i64:
6212     DAG.getMachineFunction().setCallsEHReturn(true);
6213     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6214                             MVT::Other,
6215                             getControlRoot(),
6216                             getValue(I.getArgOperand(0)),
6217                             getValue(I.getArgOperand(1))));
6218     return;
6219   case Intrinsic::eh_unwind_init:
6220     DAG.getMachineFunction().setCallsUnwindInit(true);
6221     return;
6222   case Intrinsic::eh_dwarf_cfa:
6223     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6224                              TLI.getPointerTy(DAG.getDataLayout()),
6225                              getValue(I.getArgOperand(0))));
6226     return;
6227   case Intrinsic::eh_sjlj_callsite: {
6228     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6229     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6230     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6231 
6232     MMI.setCurrentCallSite(CI->getZExtValue());
6233     return;
6234   }
6235   case Intrinsic::eh_sjlj_functioncontext: {
6236     // Get and store the index of the function context.
6237     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6238     AllocaInst *FnCtx =
6239       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6240     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6241     MFI.setFunctionContextIndex(FI);
6242     return;
6243   }
6244   case Intrinsic::eh_sjlj_setjmp: {
6245     SDValue Ops[2];
6246     Ops[0] = getRoot();
6247     Ops[1] = getValue(I.getArgOperand(0));
6248     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6249                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6250     setValue(&I, Op.getValue(0));
6251     DAG.setRoot(Op.getValue(1));
6252     return;
6253   }
6254   case Intrinsic::eh_sjlj_longjmp:
6255     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6256                             getRoot(), getValue(I.getArgOperand(0))));
6257     return;
6258   case Intrinsic::eh_sjlj_setup_dispatch:
6259     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6260                             getRoot()));
6261     return;
6262   case Intrinsic::masked_gather:
6263     visitMaskedGather(I);
6264     return;
6265   case Intrinsic::masked_load:
6266     visitMaskedLoad(I);
6267     return;
6268   case Intrinsic::masked_scatter:
6269     visitMaskedScatter(I);
6270     return;
6271   case Intrinsic::masked_store:
6272     visitMaskedStore(I);
6273     return;
6274   case Intrinsic::masked_expandload:
6275     visitMaskedLoad(I, true /* IsExpanding */);
6276     return;
6277   case Intrinsic::masked_compressstore:
6278     visitMaskedStore(I, true /* IsCompressing */);
6279     return;
6280   case Intrinsic::powi:
6281     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6282                             getValue(I.getArgOperand(1)), DAG));
6283     return;
6284   case Intrinsic::log:
6285     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6286     return;
6287   case Intrinsic::log2:
6288     setValue(&I,
6289              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6290     return;
6291   case Intrinsic::log10:
6292     setValue(&I,
6293              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6294     return;
6295   case Intrinsic::exp:
6296     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6297     return;
6298   case Intrinsic::exp2:
6299     setValue(&I,
6300              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6301     return;
6302   case Intrinsic::pow:
6303     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6304                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6305     return;
6306   case Intrinsic::sqrt:
6307   case Intrinsic::fabs:
6308   case Intrinsic::sin:
6309   case Intrinsic::cos:
6310   case Intrinsic::floor:
6311   case Intrinsic::ceil:
6312   case Intrinsic::trunc:
6313   case Intrinsic::rint:
6314   case Intrinsic::nearbyint:
6315   case Intrinsic::round:
6316   case Intrinsic::roundeven:
6317   case Intrinsic::canonicalize: {
6318     unsigned Opcode;
6319     switch (Intrinsic) {
6320     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6321     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6322     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6323     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6324     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6325     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6326     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6327     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6328     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6329     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6330     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6331     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6332     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6333     }
6334 
6335     setValue(&I, DAG.getNode(Opcode, sdl,
6336                              getValue(I.getArgOperand(0)).getValueType(),
6337                              getValue(I.getArgOperand(0)), Flags));
6338     return;
6339   }
6340   case Intrinsic::lround:
6341   case Intrinsic::llround:
6342   case Intrinsic::lrint:
6343   case Intrinsic::llrint: {
6344     unsigned Opcode;
6345     switch (Intrinsic) {
6346     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6347     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6348     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6349     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6350     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6351     }
6352 
6353     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6354     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6355                              getValue(I.getArgOperand(0))));
6356     return;
6357   }
6358   case Intrinsic::minnum:
6359     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6360                              getValue(I.getArgOperand(0)).getValueType(),
6361                              getValue(I.getArgOperand(0)),
6362                              getValue(I.getArgOperand(1)), Flags));
6363     return;
6364   case Intrinsic::maxnum:
6365     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6366                              getValue(I.getArgOperand(0)).getValueType(),
6367                              getValue(I.getArgOperand(0)),
6368                              getValue(I.getArgOperand(1)), Flags));
6369     return;
6370   case Intrinsic::minimum:
6371     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6372                              getValue(I.getArgOperand(0)).getValueType(),
6373                              getValue(I.getArgOperand(0)),
6374                              getValue(I.getArgOperand(1)), Flags));
6375     return;
6376   case Intrinsic::maximum:
6377     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6378                              getValue(I.getArgOperand(0)).getValueType(),
6379                              getValue(I.getArgOperand(0)),
6380                              getValue(I.getArgOperand(1)), Flags));
6381     return;
6382   case Intrinsic::copysign:
6383     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6384                              getValue(I.getArgOperand(0)).getValueType(),
6385                              getValue(I.getArgOperand(0)),
6386                              getValue(I.getArgOperand(1)), Flags));
6387     return;
6388   case Intrinsic::arithmetic_fence: {
6389     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6390                              getValue(I.getArgOperand(0)).getValueType(),
6391                              getValue(I.getArgOperand(0)), Flags));
6392     return;
6393   }
6394   case Intrinsic::fma:
6395     setValue(&I, DAG.getNode(
6396                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6397                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6398                      getValue(I.getArgOperand(2)), Flags));
6399     return;
6400 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6401   case Intrinsic::INTRINSIC:
6402 #include "llvm/IR/ConstrainedOps.def"
6403     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6404     return;
6405 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6406 #include "llvm/IR/VPIntrinsics.def"
6407     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6408     return;
6409   case Intrinsic::fptrunc_round: {
6410     // Get the last argument, the metadata and convert it to an integer in the
6411     // call
6412     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6413     Optional<RoundingMode> RoundMode =
6414         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6415 
6416     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6417 
6418     // Propagate fast-math-flags from IR to node(s).
6419     SDNodeFlags Flags;
6420     Flags.copyFMF(*cast<FPMathOperator>(&I));
6421     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6422 
6423     SDValue Result;
6424     Result = DAG.getNode(
6425         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6426         DAG.getTargetConstant((int)*RoundMode, sdl,
6427                               TLI.getPointerTy(DAG.getDataLayout())));
6428     setValue(&I, Result);
6429 
6430     return;
6431   }
6432   case Intrinsic::fmuladd: {
6433     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6434     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6435         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6436       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6437                                getValue(I.getArgOperand(0)).getValueType(),
6438                                getValue(I.getArgOperand(0)),
6439                                getValue(I.getArgOperand(1)),
6440                                getValue(I.getArgOperand(2)), Flags));
6441     } else {
6442       // TODO: Intrinsic calls should have fast-math-flags.
6443       SDValue Mul = DAG.getNode(
6444           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6445           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6446       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6447                                 getValue(I.getArgOperand(0)).getValueType(),
6448                                 Mul, getValue(I.getArgOperand(2)), Flags);
6449       setValue(&I, Add);
6450     }
6451     return;
6452   }
6453   case Intrinsic::convert_to_fp16:
6454     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6455                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6456                                          getValue(I.getArgOperand(0)),
6457                                          DAG.getTargetConstant(0, sdl,
6458                                                                MVT::i32))));
6459     return;
6460   case Intrinsic::convert_from_fp16:
6461     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6462                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6463                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6464                                          getValue(I.getArgOperand(0)))));
6465     return;
6466   case Intrinsic::fptosi_sat: {
6467     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6468     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6469                              getValue(I.getArgOperand(0)),
6470                              DAG.getValueType(VT.getScalarType())));
6471     return;
6472   }
6473   case Intrinsic::fptoui_sat: {
6474     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6475     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6476                              getValue(I.getArgOperand(0)),
6477                              DAG.getValueType(VT.getScalarType())));
6478     return;
6479   }
6480   case Intrinsic::set_rounding:
6481     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6482                       {getRoot(), getValue(I.getArgOperand(0))});
6483     setValue(&I, Res);
6484     DAG.setRoot(Res.getValue(0));
6485     return;
6486   case Intrinsic::is_fpclass: {
6487     const DataLayout DLayout = DAG.getDataLayout();
6488     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6489     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6490     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6491     MachineFunction &MF = DAG.getMachineFunction();
6492     const Function &F = MF.getFunction();
6493     SDValue Op = getValue(I.getArgOperand(0));
6494     SDNodeFlags Flags;
6495     Flags.setNoFPExcept(
6496         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6497     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6498     // expansion can use illegal types. Making expansion early allows
6499     // legalizing these types prior to selection.
6500     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6501       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6502       setValue(&I, Result);
6503       return;
6504     }
6505 
6506     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6507     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6508     setValue(&I, V);
6509     return;
6510   }
6511   case Intrinsic::pcmarker: {
6512     SDValue Tmp = getValue(I.getArgOperand(0));
6513     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6514     return;
6515   }
6516   case Intrinsic::readcyclecounter: {
6517     SDValue Op = getRoot();
6518     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6519                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6520     setValue(&I, Res);
6521     DAG.setRoot(Res.getValue(1));
6522     return;
6523   }
6524   case Intrinsic::bitreverse:
6525     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6526                              getValue(I.getArgOperand(0)).getValueType(),
6527                              getValue(I.getArgOperand(0))));
6528     return;
6529   case Intrinsic::bswap:
6530     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6531                              getValue(I.getArgOperand(0)).getValueType(),
6532                              getValue(I.getArgOperand(0))));
6533     return;
6534   case Intrinsic::cttz: {
6535     SDValue Arg = getValue(I.getArgOperand(0));
6536     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6537     EVT Ty = Arg.getValueType();
6538     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6539                              sdl, Ty, Arg));
6540     return;
6541   }
6542   case Intrinsic::ctlz: {
6543     SDValue Arg = getValue(I.getArgOperand(0));
6544     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6545     EVT Ty = Arg.getValueType();
6546     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6547                              sdl, Ty, Arg));
6548     return;
6549   }
6550   case Intrinsic::ctpop: {
6551     SDValue Arg = getValue(I.getArgOperand(0));
6552     EVT Ty = Arg.getValueType();
6553     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6554     return;
6555   }
6556   case Intrinsic::fshl:
6557   case Intrinsic::fshr: {
6558     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6559     SDValue X = getValue(I.getArgOperand(0));
6560     SDValue Y = getValue(I.getArgOperand(1));
6561     SDValue Z = getValue(I.getArgOperand(2));
6562     EVT VT = X.getValueType();
6563 
6564     if (X == Y) {
6565       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6566       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6567     } else {
6568       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6569       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6570     }
6571     return;
6572   }
6573   case Intrinsic::sadd_sat: {
6574     SDValue Op1 = getValue(I.getArgOperand(0));
6575     SDValue Op2 = getValue(I.getArgOperand(1));
6576     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6577     return;
6578   }
6579   case Intrinsic::uadd_sat: {
6580     SDValue Op1 = getValue(I.getArgOperand(0));
6581     SDValue Op2 = getValue(I.getArgOperand(1));
6582     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6583     return;
6584   }
6585   case Intrinsic::ssub_sat: {
6586     SDValue Op1 = getValue(I.getArgOperand(0));
6587     SDValue Op2 = getValue(I.getArgOperand(1));
6588     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6589     return;
6590   }
6591   case Intrinsic::usub_sat: {
6592     SDValue Op1 = getValue(I.getArgOperand(0));
6593     SDValue Op2 = getValue(I.getArgOperand(1));
6594     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6595     return;
6596   }
6597   case Intrinsic::sshl_sat: {
6598     SDValue Op1 = getValue(I.getArgOperand(0));
6599     SDValue Op2 = getValue(I.getArgOperand(1));
6600     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6601     return;
6602   }
6603   case Intrinsic::ushl_sat: {
6604     SDValue Op1 = getValue(I.getArgOperand(0));
6605     SDValue Op2 = getValue(I.getArgOperand(1));
6606     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6607     return;
6608   }
6609   case Intrinsic::smul_fix:
6610   case Intrinsic::umul_fix:
6611   case Intrinsic::smul_fix_sat:
6612   case Intrinsic::umul_fix_sat: {
6613     SDValue Op1 = getValue(I.getArgOperand(0));
6614     SDValue Op2 = getValue(I.getArgOperand(1));
6615     SDValue Op3 = getValue(I.getArgOperand(2));
6616     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6617                              Op1.getValueType(), Op1, Op2, Op3));
6618     return;
6619   }
6620   case Intrinsic::sdiv_fix:
6621   case Intrinsic::udiv_fix:
6622   case Intrinsic::sdiv_fix_sat:
6623   case Intrinsic::udiv_fix_sat: {
6624     SDValue Op1 = getValue(I.getArgOperand(0));
6625     SDValue Op2 = getValue(I.getArgOperand(1));
6626     SDValue Op3 = getValue(I.getArgOperand(2));
6627     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6628                               Op1, Op2, Op3, DAG, TLI));
6629     return;
6630   }
6631   case Intrinsic::smax: {
6632     SDValue Op1 = getValue(I.getArgOperand(0));
6633     SDValue Op2 = getValue(I.getArgOperand(1));
6634     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6635     return;
6636   }
6637   case Intrinsic::smin: {
6638     SDValue Op1 = getValue(I.getArgOperand(0));
6639     SDValue Op2 = getValue(I.getArgOperand(1));
6640     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6641     return;
6642   }
6643   case Intrinsic::umax: {
6644     SDValue Op1 = getValue(I.getArgOperand(0));
6645     SDValue Op2 = getValue(I.getArgOperand(1));
6646     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6647     return;
6648   }
6649   case Intrinsic::umin: {
6650     SDValue Op1 = getValue(I.getArgOperand(0));
6651     SDValue Op2 = getValue(I.getArgOperand(1));
6652     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6653     return;
6654   }
6655   case Intrinsic::abs: {
6656     // TODO: Preserve "int min is poison" arg in SDAG?
6657     SDValue Op1 = getValue(I.getArgOperand(0));
6658     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6659     return;
6660   }
6661   case Intrinsic::stacksave: {
6662     SDValue Op = getRoot();
6663     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6664     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6665     setValue(&I, Res);
6666     DAG.setRoot(Res.getValue(1));
6667     return;
6668   }
6669   case Intrinsic::stackrestore:
6670     Res = getValue(I.getArgOperand(0));
6671     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6672     return;
6673   case Intrinsic::get_dynamic_area_offset: {
6674     SDValue Op = getRoot();
6675     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6676     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6677     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6678     // target.
6679     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6680       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6681                          " intrinsic!");
6682     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6683                       Op);
6684     DAG.setRoot(Op);
6685     setValue(&I, Res);
6686     return;
6687   }
6688   case Intrinsic::stackguard: {
6689     MachineFunction &MF = DAG.getMachineFunction();
6690     const Module &M = *MF.getFunction().getParent();
6691     SDValue Chain = getRoot();
6692     if (TLI.useLoadStackGuardNode()) {
6693       Res = getLoadStackGuard(DAG, sdl, Chain);
6694     } else {
6695       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6696       const Value *Global = TLI.getSDagStackGuard(M);
6697       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6698       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6699                         MachinePointerInfo(Global, 0), Align,
6700                         MachineMemOperand::MOVolatile);
6701     }
6702     if (TLI.useStackGuardXorFP())
6703       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6704     DAG.setRoot(Chain);
6705     setValue(&I, Res);
6706     return;
6707   }
6708   case Intrinsic::stackprotector: {
6709     // Emit code into the DAG to store the stack guard onto the stack.
6710     MachineFunction &MF = DAG.getMachineFunction();
6711     MachineFrameInfo &MFI = MF.getFrameInfo();
6712     SDValue Src, Chain = getRoot();
6713 
6714     if (TLI.useLoadStackGuardNode())
6715       Src = getLoadStackGuard(DAG, sdl, Chain);
6716     else
6717       Src = getValue(I.getArgOperand(0));   // The guard's value.
6718 
6719     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6720 
6721     int FI = FuncInfo.StaticAllocaMap[Slot];
6722     MFI.setStackProtectorIndex(FI);
6723     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6724 
6725     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6726 
6727     // Store the stack protector onto the stack.
6728     Res = DAG.getStore(
6729         Chain, sdl, Src, FIN,
6730         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6731         MaybeAlign(), MachineMemOperand::MOVolatile);
6732     setValue(&I, Res);
6733     DAG.setRoot(Res);
6734     return;
6735   }
6736   case Intrinsic::objectsize:
6737     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6738 
6739   case Intrinsic::is_constant:
6740     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6741 
6742   case Intrinsic::annotation:
6743   case Intrinsic::ptr_annotation:
6744   case Intrinsic::launder_invariant_group:
6745   case Intrinsic::strip_invariant_group:
6746     // Drop the intrinsic, but forward the value
6747     setValue(&I, getValue(I.getOperand(0)));
6748     return;
6749 
6750   case Intrinsic::assume:
6751   case Intrinsic::experimental_noalias_scope_decl:
6752   case Intrinsic::var_annotation:
6753   case Intrinsic::sideeffect:
6754     // Discard annotate attributes, noalias scope declarations, assumptions, and
6755     // artificial side-effects.
6756     return;
6757 
6758   case Intrinsic::codeview_annotation: {
6759     // Emit a label associated with this metadata.
6760     MachineFunction &MF = DAG.getMachineFunction();
6761     MCSymbol *Label =
6762         MF.getMMI().getContext().createTempSymbol("annotation", true);
6763     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6764     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6765     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6766     DAG.setRoot(Res);
6767     return;
6768   }
6769 
6770   case Intrinsic::init_trampoline: {
6771     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6772 
6773     SDValue Ops[6];
6774     Ops[0] = getRoot();
6775     Ops[1] = getValue(I.getArgOperand(0));
6776     Ops[2] = getValue(I.getArgOperand(1));
6777     Ops[3] = getValue(I.getArgOperand(2));
6778     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6779     Ops[5] = DAG.getSrcValue(F);
6780 
6781     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6782 
6783     DAG.setRoot(Res);
6784     return;
6785   }
6786   case Intrinsic::adjust_trampoline:
6787     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6788                              TLI.getPointerTy(DAG.getDataLayout()),
6789                              getValue(I.getArgOperand(0))));
6790     return;
6791   case Intrinsic::gcroot: {
6792     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6793            "only valid in functions with gc specified, enforced by Verifier");
6794     assert(GFI && "implied by previous");
6795     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6796     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6797 
6798     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6799     GFI->addStackRoot(FI->getIndex(), TypeMap);
6800     return;
6801   }
6802   case Intrinsic::gcread:
6803   case Intrinsic::gcwrite:
6804     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6805   case Intrinsic::flt_rounds:
6806     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6807     setValue(&I, Res);
6808     DAG.setRoot(Res.getValue(1));
6809     return;
6810 
6811   case Intrinsic::expect:
6812     // Just replace __builtin_expect(exp, c) with EXP.
6813     setValue(&I, getValue(I.getArgOperand(0)));
6814     return;
6815 
6816   case Intrinsic::ubsantrap:
6817   case Intrinsic::debugtrap:
6818   case Intrinsic::trap: {
6819     StringRef TrapFuncName =
6820         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6821     if (TrapFuncName.empty()) {
6822       switch (Intrinsic) {
6823       case Intrinsic::trap:
6824         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6825         break;
6826       case Intrinsic::debugtrap:
6827         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6828         break;
6829       case Intrinsic::ubsantrap:
6830         DAG.setRoot(DAG.getNode(
6831             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6832             DAG.getTargetConstant(
6833                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6834                 MVT::i32)));
6835         break;
6836       default: llvm_unreachable("unknown trap intrinsic");
6837       }
6838       return;
6839     }
6840     TargetLowering::ArgListTy Args;
6841     if (Intrinsic == Intrinsic::ubsantrap) {
6842       Args.push_back(TargetLoweringBase::ArgListEntry());
6843       Args[0].Val = I.getArgOperand(0);
6844       Args[0].Node = getValue(Args[0].Val);
6845       Args[0].Ty = Args[0].Val->getType();
6846     }
6847 
6848     TargetLowering::CallLoweringInfo CLI(DAG);
6849     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6850         CallingConv::C, I.getType(),
6851         DAG.getExternalSymbol(TrapFuncName.data(),
6852                               TLI.getPointerTy(DAG.getDataLayout())),
6853         std::move(Args));
6854 
6855     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6856     DAG.setRoot(Result.second);
6857     return;
6858   }
6859 
6860   case Intrinsic::uadd_with_overflow:
6861   case Intrinsic::sadd_with_overflow:
6862   case Intrinsic::usub_with_overflow:
6863   case Intrinsic::ssub_with_overflow:
6864   case Intrinsic::umul_with_overflow:
6865   case Intrinsic::smul_with_overflow: {
6866     ISD::NodeType Op;
6867     switch (Intrinsic) {
6868     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6869     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6870     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6871     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6872     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6873     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6874     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6875     }
6876     SDValue Op1 = getValue(I.getArgOperand(0));
6877     SDValue Op2 = getValue(I.getArgOperand(1));
6878 
6879     EVT ResultVT = Op1.getValueType();
6880     EVT OverflowVT = MVT::i1;
6881     if (ResultVT.isVector())
6882       OverflowVT = EVT::getVectorVT(
6883           *Context, OverflowVT, ResultVT.getVectorElementCount());
6884 
6885     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6886     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6887     return;
6888   }
6889   case Intrinsic::prefetch: {
6890     SDValue Ops[5];
6891     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6892     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6893     Ops[0] = DAG.getRoot();
6894     Ops[1] = getValue(I.getArgOperand(0));
6895     Ops[2] = getValue(I.getArgOperand(1));
6896     Ops[3] = getValue(I.getArgOperand(2));
6897     Ops[4] = getValue(I.getArgOperand(3));
6898     SDValue Result = DAG.getMemIntrinsicNode(
6899         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6900         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6901         /* align */ None, Flags);
6902 
6903     // Chain the prefetch in parallell with any pending loads, to stay out of
6904     // the way of later optimizations.
6905     PendingLoads.push_back(Result);
6906     Result = getRoot();
6907     DAG.setRoot(Result);
6908     return;
6909   }
6910   case Intrinsic::lifetime_start:
6911   case Intrinsic::lifetime_end: {
6912     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6913     // Stack coloring is not enabled in O0, discard region information.
6914     if (TM.getOptLevel() == CodeGenOpt::None)
6915       return;
6916 
6917     const int64_t ObjectSize =
6918         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6919     Value *const ObjectPtr = I.getArgOperand(1);
6920     SmallVector<const Value *, 4> Allocas;
6921     getUnderlyingObjects(ObjectPtr, Allocas);
6922 
6923     for (const Value *Alloca : Allocas) {
6924       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6925 
6926       // Could not find an Alloca.
6927       if (!LifetimeObject)
6928         continue;
6929 
6930       // First check that the Alloca is static, otherwise it won't have a
6931       // valid frame index.
6932       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6933       if (SI == FuncInfo.StaticAllocaMap.end())
6934         return;
6935 
6936       const int FrameIndex = SI->second;
6937       int64_t Offset;
6938       if (GetPointerBaseWithConstantOffset(
6939               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6940         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6941       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6942                                 Offset);
6943       DAG.setRoot(Res);
6944     }
6945     return;
6946   }
6947   case Intrinsic::pseudoprobe: {
6948     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6949     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6950     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6951     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6952     DAG.setRoot(Res);
6953     return;
6954   }
6955   case Intrinsic::invariant_start:
6956     // Discard region information.
6957     setValue(&I,
6958              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6959     return;
6960   case Intrinsic::invariant_end:
6961     // Discard region information.
6962     return;
6963   case Intrinsic::clear_cache:
6964     /// FunctionName may be null.
6965     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6966       lowerCallToExternalSymbol(I, FunctionName);
6967     return;
6968   case Intrinsic::donothing:
6969   case Intrinsic::seh_try_begin:
6970   case Intrinsic::seh_scope_begin:
6971   case Intrinsic::seh_try_end:
6972   case Intrinsic::seh_scope_end:
6973     // ignore
6974     return;
6975   case Intrinsic::experimental_stackmap:
6976     visitStackmap(I);
6977     return;
6978   case Intrinsic::experimental_patchpoint_void:
6979   case Intrinsic::experimental_patchpoint_i64:
6980     visitPatchpoint(I);
6981     return;
6982   case Intrinsic::experimental_gc_statepoint:
6983     LowerStatepoint(cast<GCStatepointInst>(I));
6984     return;
6985   case Intrinsic::experimental_gc_result:
6986     visitGCResult(cast<GCResultInst>(I));
6987     return;
6988   case Intrinsic::experimental_gc_relocate:
6989     visitGCRelocate(cast<GCRelocateInst>(I));
6990     return;
6991   case Intrinsic::instrprof_cover:
6992     llvm_unreachable("instrprof failed to lower a cover");
6993   case Intrinsic::instrprof_increment:
6994     llvm_unreachable("instrprof failed to lower an increment");
6995   case Intrinsic::instrprof_value_profile:
6996     llvm_unreachable("instrprof failed to lower a value profiling call");
6997   case Intrinsic::localescape: {
6998     MachineFunction &MF = DAG.getMachineFunction();
6999     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7000 
7001     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7002     // is the same on all targets.
7003     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7004       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7005       if (isa<ConstantPointerNull>(Arg))
7006         continue; // Skip null pointers. They represent a hole in index space.
7007       AllocaInst *Slot = cast<AllocaInst>(Arg);
7008       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7009              "can only escape static allocas");
7010       int FI = FuncInfo.StaticAllocaMap[Slot];
7011       MCSymbol *FrameAllocSym =
7012           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7013               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7014       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7015               TII->get(TargetOpcode::LOCAL_ESCAPE))
7016           .addSym(FrameAllocSym)
7017           .addFrameIndex(FI);
7018     }
7019 
7020     return;
7021   }
7022 
7023   case Intrinsic::localrecover: {
7024     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7025     MachineFunction &MF = DAG.getMachineFunction();
7026 
7027     // Get the symbol that defines the frame offset.
7028     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7029     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7030     unsigned IdxVal =
7031         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7032     MCSymbol *FrameAllocSym =
7033         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7034             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7035 
7036     Value *FP = I.getArgOperand(1);
7037     SDValue FPVal = getValue(FP);
7038     EVT PtrVT = FPVal.getValueType();
7039 
7040     // Create a MCSymbol for the label to avoid any target lowering
7041     // that would make this PC relative.
7042     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7043     SDValue OffsetVal =
7044         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7045 
7046     // Add the offset to the FP.
7047     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7048     setValue(&I, Add);
7049 
7050     return;
7051   }
7052 
7053   case Intrinsic::eh_exceptionpointer:
7054   case Intrinsic::eh_exceptioncode: {
7055     // Get the exception pointer vreg, copy from it, and resize it to fit.
7056     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7057     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7058     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7059     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7060     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7061     if (Intrinsic == Intrinsic::eh_exceptioncode)
7062       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7063     setValue(&I, N);
7064     return;
7065   }
7066   case Intrinsic::xray_customevent: {
7067     // Here we want to make sure that the intrinsic behaves as if it has a
7068     // specific calling convention, and only for x86_64.
7069     // FIXME: Support other platforms later.
7070     const auto &Triple = DAG.getTarget().getTargetTriple();
7071     if (Triple.getArch() != Triple::x86_64)
7072       return;
7073 
7074     SmallVector<SDValue, 8> Ops;
7075 
7076     // We want to say that we always want the arguments in registers.
7077     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7078     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7079     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7080     SDValue Chain = getRoot();
7081     Ops.push_back(LogEntryVal);
7082     Ops.push_back(StrSizeVal);
7083     Ops.push_back(Chain);
7084 
7085     // We need to enforce the calling convention for the callsite, so that
7086     // argument ordering is enforced correctly, and that register allocation can
7087     // see that some registers may be assumed clobbered and have to preserve
7088     // them across calls to the intrinsic.
7089     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7090                                            sdl, NodeTys, Ops);
7091     SDValue patchableNode = SDValue(MN, 0);
7092     DAG.setRoot(patchableNode);
7093     setValue(&I, patchableNode);
7094     return;
7095   }
7096   case Intrinsic::xray_typedevent: {
7097     // Here we want to make sure that the intrinsic behaves as if it has a
7098     // specific calling convention, and only for x86_64.
7099     // FIXME: Support other platforms later.
7100     const auto &Triple = DAG.getTarget().getTargetTriple();
7101     if (Triple.getArch() != Triple::x86_64)
7102       return;
7103 
7104     SmallVector<SDValue, 8> Ops;
7105 
7106     // We want to say that we always want the arguments in registers.
7107     // It's unclear to me how manipulating the selection DAG here forces callers
7108     // to provide arguments in registers instead of on the stack.
7109     SDValue LogTypeId = getValue(I.getArgOperand(0));
7110     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7111     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7112     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7113     SDValue Chain = getRoot();
7114     Ops.push_back(LogTypeId);
7115     Ops.push_back(LogEntryVal);
7116     Ops.push_back(StrSizeVal);
7117     Ops.push_back(Chain);
7118 
7119     // We need to enforce the calling convention for the callsite, so that
7120     // argument ordering is enforced correctly, and that register allocation can
7121     // see that some registers may be assumed clobbered and have to preserve
7122     // them across calls to the intrinsic.
7123     MachineSDNode *MN = DAG.getMachineNode(
7124         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7125     SDValue patchableNode = SDValue(MN, 0);
7126     DAG.setRoot(patchableNode);
7127     setValue(&I, patchableNode);
7128     return;
7129   }
7130   case Intrinsic::experimental_deoptimize:
7131     LowerDeoptimizeCall(&I);
7132     return;
7133   case Intrinsic::experimental_stepvector:
7134     visitStepVector(I);
7135     return;
7136   case Intrinsic::vector_reduce_fadd:
7137   case Intrinsic::vector_reduce_fmul:
7138   case Intrinsic::vector_reduce_add:
7139   case Intrinsic::vector_reduce_mul:
7140   case Intrinsic::vector_reduce_and:
7141   case Intrinsic::vector_reduce_or:
7142   case Intrinsic::vector_reduce_xor:
7143   case Intrinsic::vector_reduce_smax:
7144   case Intrinsic::vector_reduce_smin:
7145   case Intrinsic::vector_reduce_umax:
7146   case Intrinsic::vector_reduce_umin:
7147   case Intrinsic::vector_reduce_fmax:
7148   case Intrinsic::vector_reduce_fmin:
7149     visitVectorReduce(I, Intrinsic);
7150     return;
7151 
7152   case Intrinsic::icall_branch_funnel: {
7153     SmallVector<SDValue, 16> Ops;
7154     Ops.push_back(getValue(I.getArgOperand(0)));
7155 
7156     int64_t Offset;
7157     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7158         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7159     if (!Base)
7160       report_fatal_error(
7161           "llvm.icall.branch.funnel operand must be a GlobalValue");
7162     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7163 
7164     struct BranchFunnelTarget {
7165       int64_t Offset;
7166       SDValue Target;
7167     };
7168     SmallVector<BranchFunnelTarget, 8> Targets;
7169 
7170     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7171       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7172           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7173       if (ElemBase != Base)
7174         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7175                            "to the same GlobalValue");
7176 
7177       SDValue Val = getValue(I.getArgOperand(Op + 1));
7178       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7179       if (!GA)
7180         report_fatal_error(
7181             "llvm.icall.branch.funnel operand must be a GlobalValue");
7182       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7183                                      GA->getGlobal(), sdl, Val.getValueType(),
7184                                      GA->getOffset())});
7185     }
7186     llvm::sort(Targets,
7187                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7188                  return T1.Offset < T2.Offset;
7189                });
7190 
7191     for (auto &T : Targets) {
7192       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7193       Ops.push_back(T.Target);
7194     }
7195 
7196     Ops.push_back(DAG.getRoot()); // Chain
7197     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7198                                  MVT::Other, Ops),
7199               0);
7200     DAG.setRoot(N);
7201     setValue(&I, N);
7202     HasTailCall = true;
7203     return;
7204   }
7205 
7206   case Intrinsic::wasm_landingpad_index:
7207     // Information this intrinsic contained has been transferred to
7208     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7209     // delete it now.
7210     return;
7211 
7212   case Intrinsic::aarch64_settag:
7213   case Intrinsic::aarch64_settag_zero: {
7214     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7215     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7216     SDValue Val = TSI.EmitTargetCodeForSetTag(
7217         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7218         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7219         ZeroMemory);
7220     DAG.setRoot(Val);
7221     setValue(&I, Val);
7222     return;
7223   }
7224   case Intrinsic::ptrmask: {
7225     SDValue Ptr = getValue(I.getOperand(0));
7226     SDValue Const = getValue(I.getOperand(1));
7227 
7228     EVT PtrVT = Ptr.getValueType();
7229     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7230                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7231     return;
7232   }
7233   case Intrinsic::threadlocal_address: {
7234     setValue(&I, getValue(I.getOperand(0)));
7235     return;
7236   }
7237   case Intrinsic::get_active_lane_mask: {
7238     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7239     SDValue Index = getValue(I.getOperand(0));
7240     EVT ElementVT = Index.getValueType();
7241 
7242     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7243       visitTargetIntrinsic(I, Intrinsic);
7244       return;
7245     }
7246 
7247     SDValue TripCount = getValue(I.getOperand(1));
7248     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7249 
7250     SDValue VectorIndex, VectorTripCount;
7251     if (VecTy.isScalableVector()) {
7252       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7253       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7254     } else {
7255       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7256       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7257     }
7258     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7259     SDValue VectorInduction = DAG.getNode(
7260         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7261     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7262                                  VectorTripCount, ISD::CondCode::SETULT);
7263     setValue(&I, SetCC);
7264     return;
7265   }
7266   case Intrinsic::vector_insert: {
7267     SDValue Vec = getValue(I.getOperand(0));
7268     SDValue SubVec = getValue(I.getOperand(1));
7269     SDValue Index = getValue(I.getOperand(2));
7270 
7271     // The intrinsic's index type is i64, but the SDNode requires an index type
7272     // suitable for the target. Convert the index as required.
7273     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7274     if (Index.getValueType() != VectorIdxTy)
7275       Index = DAG.getVectorIdxConstant(
7276           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7277 
7278     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7279     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7280                              Index));
7281     return;
7282   }
7283   case Intrinsic::vector_extract: {
7284     SDValue Vec = getValue(I.getOperand(0));
7285     SDValue Index = getValue(I.getOperand(1));
7286     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7287 
7288     // The intrinsic's index type is i64, but the SDNode requires an index type
7289     // suitable for the target. Convert the index as required.
7290     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7291     if (Index.getValueType() != VectorIdxTy)
7292       Index = DAG.getVectorIdxConstant(
7293           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7294 
7295     setValue(&I,
7296              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7297     return;
7298   }
7299   case Intrinsic::experimental_vector_reverse:
7300     visitVectorReverse(I);
7301     return;
7302   case Intrinsic::experimental_vector_splice:
7303     visitVectorSplice(I);
7304     return;
7305   }
7306 }
7307 
7308 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7309     const ConstrainedFPIntrinsic &FPI) {
7310   SDLoc sdl = getCurSDLoc();
7311 
7312   // We do not need to serialize constrained FP intrinsics against
7313   // each other or against (nonvolatile) loads, so they can be
7314   // chained like loads.
7315   SDValue Chain = DAG.getRoot();
7316   SmallVector<SDValue, 4> Opers;
7317   Opers.push_back(Chain);
7318   if (FPI.isUnaryOp()) {
7319     Opers.push_back(getValue(FPI.getArgOperand(0)));
7320   } else if (FPI.isTernaryOp()) {
7321     Opers.push_back(getValue(FPI.getArgOperand(0)));
7322     Opers.push_back(getValue(FPI.getArgOperand(1)));
7323     Opers.push_back(getValue(FPI.getArgOperand(2)));
7324   } else {
7325     Opers.push_back(getValue(FPI.getArgOperand(0)));
7326     Opers.push_back(getValue(FPI.getArgOperand(1)));
7327   }
7328 
7329   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7330     assert(Result.getNode()->getNumValues() == 2);
7331 
7332     // Push node to the appropriate list so that future instructions can be
7333     // chained up correctly.
7334     SDValue OutChain = Result.getValue(1);
7335     switch (EB) {
7336     case fp::ExceptionBehavior::ebIgnore:
7337       // The only reason why ebIgnore nodes still need to be chained is that
7338       // they might depend on the current rounding mode, and therefore must
7339       // not be moved across instruction that may change that mode.
7340       [[fallthrough]];
7341     case fp::ExceptionBehavior::ebMayTrap:
7342       // These must not be moved across calls or instructions that may change
7343       // floating-point exception masks.
7344       PendingConstrainedFP.push_back(OutChain);
7345       break;
7346     case fp::ExceptionBehavior::ebStrict:
7347       // These must not be moved across calls or instructions that may change
7348       // floating-point exception masks or read floating-point exception flags.
7349       // In addition, they cannot be optimized out even if unused.
7350       PendingConstrainedFPStrict.push_back(OutChain);
7351       break;
7352     }
7353   };
7354 
7355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7356   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7357   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7358   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7359 
7360   SDNodeFlags Flags;
7361   if (EB == fp::ExceptionBehavior::ebIgnore)
7362     Flags.setNoFPExcept(true);
7363 
7364   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7365     Flags.copyFMF(*FPOp);
7366 
7367   unsigned Opcode;
7368   switch (FPI.getIntrinsicID()) {
7369   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7370 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7371   case Intrinsic::INTRINSIC:                                                   \
7372     Opcode = ISD::STRICT_##DAGN;                                               \
7373     break;
7374 #include "llvm/IR/ConstrainedOps.def"
7375   case Intrinsic::experimental_constrained_fmuladd: {
7376     Opcode = ISD::STRICT_FMA;
7377     // Break fmuladd into fmul and fadd.
7378     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7379         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7380       Opers.pop_back();
7381       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7382       pushOutChain(Mul, EB);
7383       Opcode = ISD::STRICT_FADD;
7384       Opers.clear();
7385       Opers.push_back(Mul.getValue(1));
7386       Opers.push_back(Mul.getValue(0));
7387       Opers.push_back(getValue(FPI.getArgOperand(2)));
7388     }
7389     break;
7390   }
7391   }
7392 
7393   // A few strict DAG nodes carry additional operands that are not
7394   // set up by the default code above.
7395   switch (Opcode) {
7396   default: break;
7397   case ISD::STRICT_FP_ROUND:
7398     Opers.push_back(
7399         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7400     break;
7401   case ISD::STRICT_FSETCC:
7402   case ISD::STRICT_FSETCCS: {
7403     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7404     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7405     if (TM.Options.NoNaNsFPMath)
7406       Condition = getFCmpCodeWithoutNaN(Condition);
7407     Opers.push_back(DAG.getCondCode(Condition));
7408     break;
7409   }
7410   }
7411 
7412   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7413   pushOutChain(Result, EB);
7414 
7415   SDValue FPResult = Result.getValue(0);
7416   setValue(&FPI, FPResult);
7417 }
7418 
7419 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7420   Optional<unsigned> ResOPC;
7421   switch (VPIntrin.getIntrinsicID()) {
7422 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7423   case Intrinsic::VPID:                                                        \
7424     ResOPC = ISD::VPSD;                                                        \
7425     break;
7426 #include "llvm/IR/VPIntrinsics.def"
7427   }
7428 
7429   if (!ResOPC)
7430     llvm_unreachable(
7431         "Inconsistency: no SDNode available for this VPIntrinsic!");
7432 
7433   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7434       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7435     if (VPIntrin.getFastMathFlags().allowReassoc())
7436       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7437                                                 : ISD::VP_REDUCE_FMUL;
7438   }
7439 
7440   return *ResOPC;
7441 }
7442 
7443 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7444                                       SmallVector<SDValue, 7> &OpValues) {
7445   SDLoc DL = getCurSDLoc();
7446   Value *PtrOperand = VPIntrin.getArgOperand(0);
7447   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7448   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7449   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7450   SDValue LD;
7451   bool AddToChain = true;
7452   // Do not serialize variable-length loads of constant memory with
7453   // anything.
7454   if (!Alignment)
7455     Alignment = DAG.getEVTAlign(VT);
7456   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7457   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7458   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7459   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7460       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7461       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7462   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7463                      MMO, false /*IsExpanding */);
7464   if (AddToChain)
7465     PendingLoads.push_back(LD.getValue(1));
7466   setValue(&VPIntrin, LD);
7467 }
7468 
7469 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7470                                         SmallVector<SDValue, 7> &OpValues) {
7471   SDLoc DL = getCurSDLoc();
7472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7473   Value *PtrOperand = VPIntrin.getArgOperand(0);
7474   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7475   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7476   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7477   SDValue LD;
7478   if (!Alignment)
7479     Alignment = DAG.getEVTAlign(VT.getScalarType());
7480   unsigned AS =
7481     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7482   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7483      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7484      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7485   SDValue Base, Index, Scale;
7486   ISD::MemIndexType IndexType;
7487   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7488                                     this, VPIntrin.getParent(),
7489                                     VT.getScalarStoreSize());
7490   if (!UniformBase) {
7491     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7492     Index = getValue(PtrOperand);
7493     IndexType = ISD::SIGNED_SCALED;
7494     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7495   }
7496   EVT IdxVT = Index.getValueType();
7497   EVT EltTy = IdxVT.getVectorElementType();
7498   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7499     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7500     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7501   }
7502   LD = DAG.getGatherVP(
7503       DAG.getVTList(VT, MVT::Other), VT, DL,
7504       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7505       IndexType);
7506   PendingLoads.push_back(LD.getValue(1));
7507   setValue(&VPIntrin, LD);
7508 }
7509 
7510 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7511                                        SmallVector<SDValue, 7> &OpValues) {
7512   SDLoc DL = getCurSDLoc();
7513   Value *PtrOperand = VPIntrin.getArgOperand(1);
7514   EVT VT = OpValues[0].getValueType();
7515   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7516   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7517   SDValue ST;
7518   if (!Alignment)
7519     Alignment = DAG.getEVTAlign(VT);
7520   SDValue Ptr = OpValues[1];
7521   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7522   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7523       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7524       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7525   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7526                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7527                       /* IsTruncating */ false, /*IsCompressing*/ false);
7528   DAG.setRoot(ST);
7529   setValue(&VPIntrin, ST);
7530 }
7531 
7532 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7533                                               SmallVector<SDValue, 7> &OpValues) {
7534   SDLoc DL = getCurSDLoc();
7535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7536   Value *PtrOperand = VPIntrin.getArgOperand(1);
7537   EVT VT = OpValues[0].getValueType();
7538   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7539   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7540   SDValue ST;
7541   if (!Alignment)
7542     Alignment = DAG.getEVTAlign(VT.getScalarType());
7543   unsigned AS =
7544       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7545   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7546       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7547       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7548   SDValue Base, Index, Scale;
7549   ISD::MemIndexType IndexType;
7550   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7551                                     this, VPIntrin.getParent(),
7552                                     VT.getScalarStoreSize());
7553   if (!UniformBase) {
7554     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7555     Index = getValue(PtrOperand);
7556     IndexType = ISD::SIGNED_SCALED;
7557     Scale =
7558       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7559   }
7560   EVT IdxVT = Index.getValueType();
7561   EVT EltTy = IdxVT.getVectorElementType();
7562   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7563     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7564     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7565   }
7566   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7567                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7568                          OpValues[2], OpValues[3]},
7569                         MMO, IndexType);
7570   DAG.setRoot(ST);
7571   setValue(&VPIntrin, ST);
7572 }
7573 
7574 void SelectionDAGBuilder::visitVPStridedLoad(
7575     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7576   SDLoc DL = getCurSDLoc();
7577   Value *PtrOperand = VPIntrin.getArgOperand(0);
7578   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7579   if (!Alignment)
7580     Alignment = DAG.getEVTAlign(VT.getScalarType());
7581   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7582   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7583   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7584   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7585   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7586   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7587       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7588       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7589 
7590   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7591                                     OpValues[2], OpValues[3], MMO,
7592                                     false /*IsExpanding*/);
7593 
7594   if (AddToChain)
7595     PendingLoads.push_back(LD.getValue(1));
7596   setValue(&VPIntrin, LD);
7597 }
7598 
7599 void SelectionDAGBuilder::visitVPStridedStore(
7600     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7601   SDLoc DL = getCurSDLoc();
7602   Value *PtrOperand = VPIntrin.getArgOperand(1);
7603   EVT VT = OpValues[0].getValueType();
7604   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7605   if (!Alignment)
7606     Alignment = DAG.getEVTAlign(VT.getScalarType());
7607   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7608   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7609       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7610       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7611 
7612   SDValue ST = DAG.getStridedStoreVP(
7613       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7614       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7615       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7616       /*IsCompressing*/ false);
7617 
7618   DAG.setRoot(ST);
7619   setValue(&VPIntrin, ST);
7620 }
7621 
7622 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7624   SDLoc DL = getCurSDLoc();
7625 
7626   ISD::CondCode Condition;
7627   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7628   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7629   if (IsFP) {
7630     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7631     // flags, but calls that don't return floating-point types can't be
7632     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7633     Condition = getFCmpCondCode(CondCode);
7634     if (TM.Options.NoNaNsFPMath)
7635       Condition = getFCmpCodeWithoutNaN(Condition);
7636   } else {
7637     Condition = getICmpCondCode(CondCode);
7638   }
7639 
7640   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7641   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7642   // #2 is the condition code
7643   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7644   SDValue EVL = getValue(VPIntrin.getOperand(4));
7645   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7646   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7647          "Unexpected target EVL type");
7648   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7649 
7650   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7651                                                         VPIntrin.getType());
7652   setValue(&VPIntrin,
7653            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7654 }
7655 
7656 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7657     const VPIntrinsic &VPIntrin) {
7658   SDLoc DL = getCurSDLoc();
7659   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7660 
7661   auto IID = VPIntrin.getIntrinsicID();
7662 
7663   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7664     return visitVPCmp(*CmpI);
7665 
7666   SmallVector<EVT, 4> ValueVTs;
7667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7668   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7669   SDVTList VTs = DAG.getVTList(ValueVTs);
7670 
7671   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7672 
7673   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7674   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7675          "Unexpected target EVL type");
7676 
7677   // Request operands.
7678   SmallVector<SDValue, 7> OpValues;
7679   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7680     auto Op = getValue(VPIntrin.getArgOperand(I));
7681     if (I == EVLParamPos)
7682       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7683     OpValues.push_back(Op);
7684   }
7685 
7686   switch (Opcode) {
7687   default: {
7688     SDNodeFlags SDFlags;
7689     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7690       SDFlags.copyFMF(*FPMO);
7691     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7692     setValue(&VPIntrin, Result);
7693     break;
7694   }
7695   case ISD::VP_LOAD:
7696     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7697     break;
7698   case ISD::VP_GATHER:
7699     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7700     break;
7701   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7702     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7703     break;
7704   case ISD::VP_STORE:
7705     visitVPStore(VPIntrin, OpValues);
7706     break;
7707   case ISD::VP_SCATTER:
7708     visitVPScatter(VPIntrin, OpValues);
7709     break;
7710   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7711     visitVPStridedStore(VPIntrin, OpValues);
7712     break;
7713   case ISD::VP_FMULADD: {
7714     assert(OpValues.size() == 5 && "Unexpected number of operands");
7715     SDNodeFlags SDFlags;
7716     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7717       SDFlags.copyFMF(*FPMO);
7718     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7719         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7720       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7721     } else {
7722       SDValue Mul = DAG.getNode(
7723           ISD::VP_FMUL, DL, VTs,
7724           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7725       SDValue Add =
7726           DAG.getNode(ISD::VP_FADD, DL, VTs,
7727                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7728       setValue(&VPIntrin, Add);
7729     }
7730     break;
7731   }
7732   }
7733 }
7734 
7735 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7736                                           const BasicBlock *EHPadBB,
7737                                           MCSymbol *&BeginLabel) {
7738   MachineFunction &MF = DAG.getMachineFunction();
7739   MachineModuleInfo &MMI = MF.getMMI();
7740 
7741   // Insert a label before the invoke call to mark the try range.  This can be
7742   // used to detect deletion of the invoke via the MachineModuleInfo.
7743   BeginLabel = MMI.getContext().createTempSymbol();
7744 
7745   // For SjLj, keep track of which landing pads go with which invokes
7746   // so as to maintain the ordering of pads in the LSDA.
7747   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7748   if (CallSiteIndex) {
7749     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7750     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7751 
7752     // Now that the call site is handled, stop tracking it.
7753     MMI.setCurrentCallSite(0);
7754   }
7755 
7756   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7757 }
7758 
7759 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7760                                         const BasicBlock *EHPadBB,
7761                                         MCSymbol *BeginLabel) {
7762   assert(BeginLabel && "BeginLabel should've been set");
7763 
7764   MachineFunction &MF = DAG.getMachineFunction();
7765   MachineModuleInfo &MMI = MF.getMMI();
7766 
7767   // Insert a label at the end of the invoke call to mark the try range.  This
7768   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7769   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7770   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7771 
7772   // Inform MachineModuleInfo of range.
7773   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7774   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7775   // actually use outlined funclets and their LSDA info style.
7776   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7777     assert(II && "II should've been set");
7778     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7779     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7780   } else if (!isScopedEHPersonality(Pers)) {
7781     assert(EHPadBB);
7782     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7783   }
7784 
7785   return Chain;
7786 }
7787 
7788 std::pair<SDValue, SDValue>
7789 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7790                                     const BasicBlock *EHPadBB) {
7791   MCSymbol *BeginLabel = nullptr;
7792 
7793   if (EHPadBB) {
7794     // Both PendingLoads and PendingExports must be flushed here;
7795     // this call might not return.
7796     (void)getRoot();
7797     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7798     CLI.setChain(getRoot());
7799   }
7800 
7801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7802   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7803 
7804   assert((CLI.IsTailCall || Result.second.getNode()) &&
7805          "Non-null chain expected with non-tail call!");
7806   assert((Result.second.getNode() || !Result.first.getNode()) &&
7807          "Null value expected with tail call!");
7808 
7809   if (!Result.second.getNode()) {
7810     // As a special case, a null chain means that a tail call has been emitted
7811     // and the DAG root is already updated.
7812     HasTailCall = true;
7813 
7814     // Since there's no actual continuation from this block, nothing can be
7815     // relying on us setting vregs for them.
7816     PendingExports.clear();
7817   } else {
7818     DAG.setRoot(Result.second);
7819   }
7820 
7821   if (EHPadBB) {
7822     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7823                            BeginLabel));
7824   }
7825 
7826   return Result;
7827 }
7828 
7829 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7830                                       bool isTailCall,
7831                                       bool isMustTailCall,
7832                                       const BasicBlock *EHPadBB) {
7833   auto &DL = DAG.getDataLayout();
7834   FunctionType *FTy = CB.getFunctionType();
7835   Type *RetTy = CB.getType();
7836 
7837   TargetLowering::ArgListTy Args;
7838   Args.reserve(CB.arg_size());
7839 
7840   const Value *SwiftErrorVal = nullptr;
7841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7842 
7843   if (isTailCall) {
7844     // Avoid emitting tail calls in functions with the disable-tail-calls
7845     // attribute.
7846     auto *Caller = CB.getParent()->getParent();
7847     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7848         "true" && !isMustTailCall)
7849       isTailCall = false;
7850 
7851     // We can't tail call inside a function with a swifterror argument. Lowering
7852     // does not support this yet. It would have to move into the swifterror
7853     // register before the call.
7854     if (TLI.supportSwiftError() &&
7855         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7856       isTailCall = false;
7857   }
7858 
7859   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7860     TargetLowering::ArgListEntry Entry;
7861     const Value *V = *I;
7862 
7863     // Skip empty types
7864     if (V->getType()->isEmptyTy())
7865       continue;
7866 
7867     SDValue ArgNode = getValue(V);
7868     Entry.Node = ArgNode; Entry.Ty = V->getType();
7869 
7870     Entry.setAttributes(&CB, I - CB.arg_begin());
7871 
7872     // Use swifterror virtual register as input to the call.
7873     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7874       SwiftErrorVal = V;
7875       // We find the virtual register for the actual swifterror argument.
7876       // Instead of using the Value, we use the virtual register instead.
7877       Entry.Node =
7878           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7879                           EVT(TLI.getPointerTy(DL)));
7880     }
7881 
7882     Args.push_back(Entry);
7883 
7884     // If we have an explicit sret argument that is an Instruction, (i.e., it
7885     // might point to function-local memory), we can't meaningfully tail-call.
7886     if (Entry.IsSRet && isa<Instruction>(V))
7887       isTailCall = false;
7888   }
7889 
7890   // If call site has a cfguardtarget operand bundle, create and add an
7891   // additional ArgListEntry.
7892   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7893     TargetLowering::ArgListEntry Entry;
7894     Value *V = Bundle->Inputs[0];
7895     SDValue ArgNode = getValue(V);
7896     Entry.Node = ArgNode;
7897     Entry.Ty = V->getType();
7898     Entry.IsCFGuardTarget = true;
7899     Args.push_back(Entry);
7900   }
7901 
7902   // Check if target-independent constraints permit a tail call here.
7903   // Target-dependent constraints are checked within TLI->LowerCallTo.
7904   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7905     isTailCall = false;
7906 
7907   // Disable tail calls if there is an swifterror argument. Targets have not
7908   // been updated to support tail calls.
7909   if (TLI.supportSwiftError() && SwiftErrorVal)
7910     isTailCall = false;
7911 
7912   ConstantInt *CFIType = nullptr;
7913   if (CB.isIndirectCall()) {
7914     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7915       if (!TLI.supportKCFIBundles())
7916         report_fatal_error(
7917             "Target doesn't support calls with kcfi operand bundles.");
7918       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7919       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7920     }
7921   }
7922 
7923   TargetLowering::CallLoweringInfo CLI(DAG);
7924   CLI.setDebugLoc(getCurSDLoc())
7925       .setChain(getRoot())
7926       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7927       .setTailCall(isTailCall)
7928       .setConvergent(CB.isConvergent())
7929       .setIsPreallocated(
7930           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7931       .setCFIType(CFIType);
7932   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7933 
7934   if (Result.first.getNode()) {
7935     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7936     setValue(&CB, Result.first);
7937   }
7938 
7939   // The last element of CLI.InVals has the SDValue for swifterror return.
7940   // Here we copy it to a virtual register and update SwiftErrorMap for
7941   // book-keeping.
7942   if (SwiftErrorVal && TLI.supportSwiftError()) {
7943     // Get the last element of InVals.
7944     SDValue Src = CLI.InVals.back();
7945     Register VReg =
7946         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7947     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7948     DAG.setRoot(CopyNode);
7949   }
7950 }
7951 
7952 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7953                              SelectionDAGBuilder &Builder) {
7954   // Check to see if this load can be trivially constant folded, e.g. if the
7955   // input is from a string literal.
7956   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7957     // Cast pointer to the type we really want to load.
7958     Type *LoadTy =
7959         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7960     if (LoadVT.isVector())
7961       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7962 
7963     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7964                                          PointerType::getUnqual(LoadTy));
7965 
7966     if (const Constant *LoadCst =
7967             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7968                                          LoadTy, Builder.DAG.getDataLayout()))
7969       return Builder.getValue(LoadCst);
7970   }
7971 
7972   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7973   // still constant memory, the input chain can be the entry node.
7974   SDValue Root;
7975   bool ConstantMemory = false;
7976 
7977   // Do not serialize (non-volatile) loads of constant memory with anything.
7978   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7979     Root = Builder.DAG.getEntryNode();
7980     ConstantMemory = true;
7981   } else {
7982     // Do not serialize non-volatile loads against each other.
7983     Root = Builder.DAG.getRoot();
7984   }
7985 
7986   SDValue Ptr = Builder.getValue(PtrVal);
7987   SDValue LoadVal =
7988       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7989                           MachinePointerInfo(PtrVal), Align(1));
7990 
7991   if (!ConstantMemory)
7992     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7993   return LoadVal;
7994 }
7995 
7996 /// Record the value for an instruction that produces an integer result,
7997 /// converting the type where necessary.
7998 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7999                                                   SDValue Value,
8000                                                   bool IsSigned) {
8001   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8002                                                     I.getType(), true);
8003   if (IsSigned)
8004     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8005   else
8006     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8007   setValue(&I, Value);
8008 }
8009 
8010 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8011 /// true and lower it. Otherwise return false, and it will be lowered like a
8012 /// normal call.
8013 /// The caller already checked that \p I calls the appropriate LibFunc with a
8014 /// correct prototype.
8015 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8016   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8017   const Value *Size = I.getArgOperand(2);
8018   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8019   if (CSize && CSize->getZExtValue() == 0) {
8020     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8021                                                           I.getType(), true);
8022     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8023     return true;
8024   }
8025 
8026   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8027   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8028       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8029       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8030   if (Res.first.getNode()) {
8031     processIntegerCallValue(I, Res.first, true);
8032     PendingLoads.push_back(Res.second);
8033     return true;
8034   }
8035 
8036   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8037   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8038   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8039     return false;
8040 
8041   // If the target has a fast compare for the given size, it will return a
8042   // preferred load type for that size. Require that the load VT is legal and
8043   // that the target supports unaligned loads of that type. Otherwise, return
8044   // INVALID.
8045   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8046     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8047     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8048     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8049       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8050       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8051       // TODO: Check alignment of src and dest ptrs.
8052       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8053       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8054       if (!TLI.isTypeLegal(LVT) ||
8055           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8056           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8057         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8058     }
8059 
8060     return LVT;
8061   };
8062 
8063   // This turns into unaligned loads. We only do this if the target natively
8064   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8065   // we'll only produce a small number of byte loads.
8066   MVT LoadVT;
8067   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8068   switch (NumBitsToCompare) {
8069   default:
8070     return false;
8071   case 16:
8072     LoadVT = MVT::i16;
8073     break;
8074   case 32:
8075     LoadVT = MVT::i32;
8076     break;
8077   case 64:
8078   case 128:
8079   case 256:
8080     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8081     break;
8082   }
8083 
8084   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8085     return false;
8086 
8087   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8088   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8089 
8090   // Bitcast to a wide integer type if the loads are vectors.
8091   if (LoadVT.isVector()) {
8092     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8093     LoadL = DAG.getBitcast(CmpVT, LoadL);
8094     LoadR = DAG.getBitcast(CmpVT, LoadR);
8095   }
8096 
8097   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8098   processIntegerCallValue(I, Cmp, false);
8099   return true;
8100 }
8101 
8102 /// See if we can lower a memchr call into an optimized form. If so, return
8103 /// true and lower it. Otherwise return false, and it will be lowered like a
8104 /// normal call.
8105 /// The caller already checked that \p I calls the appropriate LibFunc with a
8106 /// correct prototype.
8107 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8108   const Value *Src = I.getArgOperand(0);
8109   const Value *Char = I.getArgOperand(1);
8110   const Value *Length = I.getArgOperand(2);
8111 
8112   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8113   std::pair<SDValue, SDValue> Res =
8114     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8115                                 getValue(Src), getValue(Char), getValue(Length),
8116                                 MachinePointerInfo(Src));
8117   if (Res.first.getNode()) {
8118     setValue(&I, Res.first);
8119     PendingLoads.push_back(Res.second);
8120     return true;
8121   }
8122 
8123   return false;
8124 }
8125 
8126 /// See if we can lower a mempcpy call into an optimized form. If so, return
8127 /// true and lower it. Otherwise return false, and it will be lowered like a
8128 /// normal call.
8129 /// The caller already checked that \p I calls the appropriate LibFunc with a
8130 /// correct prototype.
8131 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8132   SDValue Dst = getValue(I.getArgOperand(0));
8133   SDValue Src = getValue(I.getArgOperand(1));
8134   SDValue Size = getValue(I.getArgOperand(2));
8135 
8136   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8137   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8138   // DAG::getMemcpy needs Alignment to be defined.
8139   Align Alignment = std::min(DstAlign, SrcAlign);
8140 
8141   bool isVol = false;
8142   SDLoc sdl = getCurSDLoc();
8143 
8144   // In the mempcpy context we need to pass in a false value for isTailCall
8145   // because the return pointer needs to be adjusted by the size of
8146   // the copied memory.
8147   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8148   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8149                              /*isTailCall=*/false,
8150                              MachinePointerInfo(I.getArgOperand(0)),
8151                              MachinePointerInfo(I.getArgOperand(1)),
8152                              I.getAAMetadata());
8153   assert(MC.getNode() != nullptr &&
8154          "** memcpy should not be lowered as TailCall in mempcpy context **");
8155   DAG.setRoot(MC);
8156 
8157   // Check if Size needs to be truncated or extended.
8158   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8159 
8160   // Adjust return pointer to point just past the last dst byte.
8161   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8162                                     Dst, Size);
8163   setValue(&I, DstPlusSize);
8164   return true;
8165 }
8166 
8167 /// See if we can lower a strcpy call into an optimized form.  If so, return
8168 /// true and lower it, otherwise return false and it will be lowered like a
8169 /// normal call.
8170 /// The caller already checked that \p I calls the appropriate LibFunc with a
8171 /// correct prototype.
8172 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8173   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8174 
8175   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8176   std::pair<SDValue, SDValue> Res =
8177     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8178                                 getValue(Arg0), getValue(Arg1),
8179                                 MachinePointerInfo(Arg0),
8180                                 MachinePointerInfo(Arg1), isStpcpy);
8181   if (Res.first.getNode()) {
8182     setValue(&I, Res.first);
8183     DAG.setRoot(Res.second);
8184     return true;
8185   }
8186 
8187   return false;
8188 }
8189 
8190 /// See if we can lower a strcmp call into an optimized form.  If so, return
8191 /// true and lower it, otherwise return false and it will be lowered like a
8192 /// normal call.
8193 /// The caller already checked that \p I calls the appropriate LibFunc with a
8194 /// correct prototype.
8195 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8196   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8197 
8198   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8199   std::pair<SDValue, SDValue> Res =
8200     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8201                                 getValue(Arg0), getValue(Arg1),
8202                                 MachinePointerInfo(Arg0),
8203                                 MachinePointerInfo(Arg1));
8204   if (Res.first.getNode()) {
8205     processIntegerCallValue(I, Res.first, true);
8206     PendingLoads.push_back(Res.second);
8207     return true;
8208   }
8209 
8210   return false;
8211 }
8212 
8213 /// See if we can lower a strlen call into an optimized form.  If so, return
8214 /// true and lower it, otherwise return false and it will be lowered like a
8215 /// normal call.
8216 /// The caller already checked that \p I calls the appropriate LibFunc with a
8217 /// correct prototype.
8218 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8219   const Value *Arg0 = I.getArgOperand(0);
8220 
8221   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8222   std::pair<SDValue, SDValue> Res =
8223     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8224                                 getValue(Arg0), MachinePointerInfo(Arg0));
8225   if (Res.first.getNode()) {
8226     processIntegerCallValue(I, Res.first, false);
8227     PendingLoads.push_back(Res.second);
8228     return true;
8229   }
8230 
8231   return false;
8232 }
8233 
8234 /// See if we can lower a strnlen call into an optimized form.  If so, return
8235 /// true and lower it, otherwise return false and it will be lowered like a
8236 /// normal call.
8237 /// The caller already checked that \p I calls the appropriate LibFunc with a
8238 /// correct prototype.
8239 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8240   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8241 
8242   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8243   std::pair<SDValue, SDValue> Res =
8244     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8245                                  getValue(Arg0), getValue(Arg1),
8246                                  MachinePointerInfo(Arg0));
8247   if (Res.first.getNode()) {
8248     processIntegerCallValue(I, Res.first, false);
8249     PendingLoads.push_back(Res.second);
8250     return true;
8251   }
8252 
8253   return false;
8254 }
8255 
8256 /// See if we can lower a unary floating-point operation into an SDNode with
8257 /// the specified Opcode.  If so, return true and lower it, otherwise return
8258 /// false and it will be lowered like a normal call.
8259 /// The caller already checked that \p I calls the appropriate LibFunc with a
8260 /// correct prototype.
8261 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8262                                               unsigned Opcode) {
8263   // We already checked this call's prototype; verify it doesn't modify errno.
8264   if (!I.onlyReadsMemory())
8265     return false;
8266 
8267   SDNodeFlags Flags;
8268   Flags.copyFMF(cast<FPMathOperator>(I));
8269 
8270   SDValue Tmp = getValue(I.getArgOperand(0));
8271   setValue(&I,
8272            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8273   return true;
8274 }
8275 
8276 /// See if we can lower a binary floating-point operation into an SDNode with
8277 /// the specified Opcode. If so, return true and lower it. Otherwise return
8278 /// false, and it will be lowered like a normal call.
8279 /// The caller already checked that \p I calls the appropriate LibFunc with a
8280 /// correct prototype.
8281 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8282                                                unsigned Opcode) {
8283   // We already checked this call's prototype; verify it doesn't modify errno.
8284   if (!I.onlyReadsMemory())
8285     return false;
8286 
8287   SDNodeFlags Flags;
8288   Flags.copyFMF(cast<FPMathOperator>(I));
8289 
8290   SDValue Tmp0 = getValue(I.getArgOperand(0));
8291   SDValue Tmp1 = getValue(I.getArgOperand(1));
8292   EVT VT = Tmp0.getValueType();
8293   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8294   return true;
8295 }
8296 
8297 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8298   // Handle inline assembly differently.
8299   if (I.isInlineAsm()) {
8300     visitInlineAsm(I);
8301     return;
8302   }
8303 
8304   if (Function *F = I.getCalledFunction()) {
8305     diagnoseDontCall(I);
8306 
8307     if (F->isDeclaration()) {
8308       // Is this an LLVM intrinsic or a target-specific intrinsic?
8309       unsigned IID = F->getIntrinsicID();
8310       if (!IID)
8311         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8312           IID = II->getIntrinsicID(F);
8313 
8314       if (IID) {
8315         visitIntrinsicCall(I, IID);
8316         return;
8317       }
8318     }
8319 
8320     // Check for well-known libc/libm calls.  If the function is internal, it
8321     // can't be a library call.  Don't do the check if marked as nobuiltin for
8322     // some reason or the call site requires strict floating point semantics.
8323     LibFunc Func;
8324     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8325         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8326         LibInfo->hasOptimizedCodeGen(Func)) {
8327       switch (Func) {
8328       default: break;
8329       case LibFunc_bcmp:
8330         if (visitMemCmpBCmpCall(I))
8331           return;
8332         break;
8333       case LibFunc_copysign:
8334       case LibFunc_copysignf:
8335       case LibFunc_copysignl:
8336         // We already checked this call's prototype; verify it doesn't modify
8337         // errno.
8338         if (I.onlyReadsMemory()) {
8339           SDValue LHS = getValue(I.getArgOperand(0));
8340           SDValue RHS = getValue(I.getArgOperand(1));
8341           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8342                                    LHS.getValueType(), LHS, RHS));
8343           return;
8344         }
8345         break;
8346       case LibFunc_fabs:
8347       case LibFunc_fabsf:
8348       case LibFunc_fabsl:
8349         if (visitUnaryFloatCall(I, ISD::FABS))
8350           return;
8351         break;
8352       case LibFunc_fmin:
8353       case LibFunc_fminf:
8354       case LibFunc_fminl:
8355         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8356           return;
8357         break;
8358       case LibFunc_fmax:
8359       case LibFunc_fmaxf:
8360       case LibFunc_fmaxl:
8361         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8362           return;
8363         break;
8364       case LibFunc_sin:
8365       case LibFunc_sinf:
8366       case LibFunc_sinl:
8367         if (visitUnaryFloatCall(I, ISD::FSIN))
8368           return;
8369         break;
8370       case LibFunc_cos:
8371       case LibFunc_cosf:
8372       case LibFunc_cosl:
8373         if (visitUnaryFloatCall(I, ISD::FCOS))
8374           return;
8375         break;
8376       case LibFunc_sqrt:
8377       case LibFunc_sqrtf:
8378       case LibFunc_sqrtl:
8379       case LibFunc_sqrt_finite:
8380       case LibFunc_sqrtf_finite:
8381       case LibFunc_sqrtl_finite:
8382         if (visitUnaryFloatCall(I, ISD::FSQRT))
8383           return;
8384         break;
8385       case LibFunc_floor:
8386       case LibFunc_floorf:
8387       case LibFunc_floorl:
8388         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8389           return;
8390         break;
8391       case LibFunc_nearbyint:
8392       case LibFunc_nearbyintf:
8393       case LibFunc_nearbyintl:
8394         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8395           return;
8396         break;
8397       case LibFunc_ceil:
8398       case LibFunc_ceilf:
8399       case LibFunc_ceill:
8400         if (visitUnaryFloatCall(I, ISD::FCEIL))
8401           return;
8402         break;
8403       case LibFunc_rint:
8404       case LibFunc_rintf:
8405       case LibFunc_rintl:
8406         if (visitUnaryFloatCall(I, ISD::FRINT))
8407           return;
8408         break;
8409       case LibFunc_round:
8410       case LibFunc_roundf:
8411       case LibFunc_roundl:
8412         if (visitUnaryFloatCall(I, ISD::FROUND))
8413           return;
8414         break;
8415       case LibFunc_trunc:
8416       case LibFunc_truncf:
8417       case LibFunc_truncl:
8418         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8419           return;
8420         break;
8421       case LibFunc_log2:
8422       case LibFunc_log2f:
8423       case LibFunc_log2l:
8424         if (visitUnaryFloatCall(I, ISD::FLOG2))
8425           return;
8426         break;
8427       case LibFunc_exp2:
8428       case LibFunc_exp2f:
8429       case LibFunc_exp2l:
8430         if (visitUnaryFloatCall(I, ISD::FEXP2))
8431           return;
8432         break;
8433       case LibFunc_memcmp:
8434         if (visitMemCmpBCmpCall(I))
8435           return;
8436         break;
8437       case LibFunc_mempcpy:
8438         if (visitMemPCpyCall(I))
8439           return;
8440         break;
8441       case LibFunc_memchr:
8442         if (visitMemChrCall(I))
8443           return;
8444         break;
8445       case LibFunc_strcpy:
8446         if (visitStrCpyCall(I, false))
8447           return;
8448         break;
8449       case LibFunc_stpcpy:
8450         if (visitStrCpyCall(I, true))
8451           return;
8452         break;
8453       case LibFunc_strcmp:
8454         if (visitStrCmpCall(I))
8455           return;
8456         break;
8457       case LibFunc_strlen:
8458         if (visitStrLenCall(I))
8459           return;
8460         break;
8461       case LibFunc_strnlen:
8462         if (visitStrNLenCall(I))
8463           return;
8464         break;
8465       }
8466     }
8467   }
8468 
8469   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8470   // have to do anything here to lower funclet bundles.
8471   // CFGuardTarget bundles are lowered in LowerCallTo.
8472   assert(!I.hasOperandBundlesOtherThan(
8473              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8474               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8475               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8476          "Cannot lower calls with arbitrary operand bundles!");
8477 
8478   SDValue Callee = getValue(I.getCalledOperand());
8479 
8480   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8481     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8482   else
8483     // Check if we can potentially perform a tail call. More detailed checking
8484     // is be done within LowerCallTo, after more information about the call is
8485     // known.
8486     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8487 }
8488 
8489 namespace {
8490 
8491 /// AsmOperandInfo - This contains information for each constraint that we are
8492 /// lowering.
8493 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8494 public:
8495   /// CallOperand - If this is the result output operand or a clobber
8496   /// this is null, otherwise it is the incoming operand to the CallInst.
8497   /// This gets modified as the asm is processed.
8498   SDValue CallOperand;
8499 
8500   /// AssignedRegs - If this is a register or register class operand, this
8501   /// contains the set of register corresponding to the operand.
8502   RegsForValue AssignedRegs;
8503 
8504   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8505     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8506   }
8507 
8508   /// Whether or not this operand accesses memory
8509   bool hasMemory(const TargetLowering &TLI) const {
8510     // Indirect operand accesses access memory.
8511     if (isIndirect)
8512       return true;
8513 
8514     for (const auto &Code : Codes)
8515       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8516         return true;
8517 
8518     return false;
8519   }
8520 };
8521 
8522 
8523 } // end anonymous namespace
8524 
8525 /// Make sure that the output operand \p OpInfo and its corresponding input
8526 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8527 /// out).
8528 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8529                                SDISelAsmOperandInfo &MatchingOpInfo,
8530                                SelectionDAG &DAG) {
8531   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8532     return;
8533 
8534   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8535   const auto &TLI = DAG.getTargetLoweringInfo();
8536 
8537   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8538       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8539                                        OpInfo.ConstraintVT);
8540   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8541       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8542                                        MatchingOpInfo.ConstraintVT);
8543   if ((OpInfo.ConstraintVT.isInteger() !=
8544        MatchingOpInfo.ConstraintVT.isInteger()) ||
8545       (MatchRC.second != InputRC.second)) {
8546     // FIXME: error out in a more elegant fashion
8547     report_fatal_error("Unsupported asm: input constraint"
8548                        " with a matching output constraint of"
8549                        " incompatible type!");
8550   }
8551   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8552 }
8553 
8554 /// Get a direct memory input to behave well as an indirect operand.
8555 /// This may introduce stores, hence the need for a \p Chain.
8556 /// \return The (possibly updated) chain.
8557 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8558                                         SDISelAsmOperandInfo &OpInfo,
8559                                         SelectionDAG &DAG) {
8560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8561 
8562   // If we don't have an indirect input, put it in the constpool if we can,
8563   // otherwise spill it to a stack slot.
8564   // TODO: This isn't quite right. We need to handle these according to
8565   // the addressing mode that the constraint wants. Also, this may take
8566   // an additional register for the computation and we don't want that
8567   // either.
8568 
8569   // If the operand is a float, integer, or vector constant, spill to a
8570   // constant pool entry to get its address.
8571   const Value *OpVal = OpInfo.CallOperandVal;
8572   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8573       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8574     OpInfo.CallOperand = DAG.getConstantPool(
8575         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8576     return Chain;
8577   }
8578 
8579   // Otherwise, create a stack slot and emit a store to it before the asm.
8580   Type *Ty = OpVal->getType();
8581   auto &DL = DAG.getDataLayout();
8582   uint64_t TySize = DL.getTypeAllocSize(Ty);
8583   MachineFunction &MF = DAG.getMachineFunction();
8584   int SSFI = MF.getFrameInfo().CreateStackObject(
8585       TySize, DL.getPrefTypeAlign(Ty), false);
8586   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8587   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8588                             MachinePointerInfo::getFixedStack(MF, SSFI),
8589                             TLI.getMemValueType(DL, Ty));
8590   OpInfo.CallOperand = StackSlot;
8591 
8592   return Chain;
8593 }
8594 
8595 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8596 /// specified operand.  We prefer to assign virtual registers, to allow the
8597 /// register allocator to handle the assignment process.  However, if the asm
8598 /// uses features that we can't model on machineinstrs, we have SDISel do the
8599 /// allocation.  This produces generally horrible, but correct, code.
8600 ///
8601 ///   OpInfo describes the operand
8602 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8603 static llvm::Optional<unsigned>
8604 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8605                      SDISelAsmOperandInfo &OpInfo,
8606                      SDISelAsmOperandInfo &RefOpInfo) {
8607   LLVMContext &Context = *DAG.getContext();
8608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8609 
8610   MachineFunction &MF = DAG.getMachineFunction();
8611   SmallVector<unsigned, 4> Regs;
8612   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8613 
8614   // No work to do for memory/address operands.
8615   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8616       OpInfo.ConstraintType == TargetLowering::C_Address)
8617     return None;
8618 
8619   // If this is a constraint for a single physreg, or a constraint for a
8620   // register class, find it.
8621   unsigned AssignedReg;
8622   const TargetRegisterClass *RC;
8623   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8624       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8625   // RC is unset only on failure. Return immediately.
8626   if (!RC)
8627     return None;
8628 
8629   // Get the actual register value type.  This is important, because the user
8630   // may have asked for (e.g.) the AX register in i32 type.  We need to
8631   // remember that AX is actually i16 to get the right extension.
8632   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8633 
8634   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8635     // If this is an FP operand in an integer register (or visa versa), or more
8636     // generally if the operand value disagrees with the register class we plan
8637     // to stick it in, fix the operand type.
8638     //
8639     // If this is an input value, the bitcast to the new type is done now.
8640     // Bitcast for output value is done at the end of visitInlineAsm().
8641     if ((OpInfo.Type == InlineAsm::isOutput ||
8642          OpInfo.Type == InlineAsm::isInput) &&
8643         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8644       // Try to convert to the first EVT that the reg class contains.  If the
8645       // types are identical size, use a bitcast to convert (e.g. two differing
8646       // vector types).  Note: output bitcast is done at the end of
8647       // visitInlineAsm().
8648       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8649         // Exclude indirect inputs while they are unsupported because the code
8650         // to perform the load is missing and thus OpInfo.CallOperand still
8651         // refers to the input address rather than the pointed-to value.
8652         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8653           OpInfo.CallOperand =
8654               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8655         OpInfo.ConstraintVT = RegVT;
8656         // If the operand is an FP value and we want it in integer registers,
8657         // use the corresponding integer type. This turns an f64 value into
8658         // i64, which can be passed with two i32 values on a 32-bit machine.
8659       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8660         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8661         if (OpInfo.Type == InlineAsm::isInput)
8662           OpInfo.CallOperand =
8663               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8664         OpInfo.ConstraintVT = VT;
8665       }
8666     }
8667   }
8668 
8669   // No need to allocate a matching input constraint since the constraint it's
8670   // matching to has already been allocated.
8671   if (OpInfo.isMatchingInputConstraint())
8672     return None;
8673 
8674   EVT ValueVT = OpInfo.ConstraintVT;
8675   if (OpInfo.ConstraintVT == MVT::Other)
8676     ValueVT = RegVT;
8677 
8678   // Initialize NumRegs.
8679   unsigned NumRegs = 1;
8680   if (OpInfo.ConstraintVT != MVT::Other)
8681     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8682 
8683   // If this is a constraint for a specific physical register, like {r17},
8684   // assign it now.
8685 
8686   // If this associated to a specific register, initialize iterator to correct
8687   // place. If virtual, make sure we have enough registers
8688 
8689   // Initialize iterator if necessary
8690   TargetRegisterClass::iterator I = RC->begin();
8691   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8692 
8693   // Do not check for single registers.
8694   if (AssignedReg) {
8695     I = std::find(I, RC->end(), AssignedReg);
8696     if (I == RC->end()) {
8697       // RC does not contain the selected register, which indicates a
8698       // mismatch between the register and the required type/bitwidth.
8699       return {AssignedReg};
8700     }
8701   }
8702 
8703   for (; NumRegs; --NumRegs, ++I) {
8704     assert(I != RC->end() && "Ran out of registers to allocate!");
8705     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8706     Regs.push_back(R);
8707   }
8708 
8709   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8710   return None;
8711 }
8712 
8713 static unsigned
8714 findMatchingInlineAsmOperand(unsigned OperandNo,
8715                              const std::vector<SDValue> &AsmNodeOperands) {
8716   // Scan until we find the definition we already emitted of this operand.
8717   unsigned CurOp = InlineAsm::Op_FirstOperand;
8718   for (; OperandNo; --OperandNo) {
8719     // Advance to the next operand.
8720     unsigned OpFlag =
8721         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8722     assert((InlineAsm::isRegDefKind(OpFlag) ||
8723             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8724             InlineAsm::isMemKind(OpFlag)) &&
8725            "Skipped past definitions?");
8726     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8727   }
8728   return CurOp;
8729 }
8730 
8731 namespace {
8732 
8733 class ExtraFlags {
8734   unsigned Flags = 0;
8735 
8736 public:
8737   explicit ExtraFlags(const CallBase &Call) {
8738     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8739     if (IA->hasSideEffects())
8740       Flags |= InlineAsm::Extra_HasSideEffects;
8741     if (IA->isAlignStack())
8742       Flags |= InlineAsm::Extra_IsAlignStack;
8743     if (Call.isConvergent())
8744       Flags |= InlineAsm::Extra_IsConvergent;
8745     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8746   }
8747 
8748   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8749     // Ideally, we would only check against memory constraints.  However, the
8750     // meaning of an Other constraint can be target-specific and we can't easily
8751     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8752     // for Other constraints as well.
8753     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8754         OpInfo.ConstraintType == TargetLowering::C_Other) {
8755       if (OpInfo.Type == InlineAsm::isInput)
8756         Flags |= InlineAsm::Extra_MayLoad;
8757       else if (OpInfo.Type == InlineAsm::isOutput)
8758         Flags |= InlineAsm::Extra_MayStore;
8759       else if (OpInfo.Type == InlineAsm::isClobber)
8760         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8761     }
8762   }
8763 
8764   unsigned get() const { return Flags; }
8765 };
8766 
8767 } // end anonymous namespace
8768 
8769 /// visitInlineAsm - Handle a call to an InlineAsm object.
8770 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8771                                          const BasicBlock *EHPadBB) {
8772   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8773 
8774   /// ConstraintOperands - Information about all of the constraints.
8775   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8776 
8777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8778   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8779       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8780 
8781   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8782   // AsmDialect, MayLoad, MayStore).
8783   bool HasSideEffect = IA->hasSideEffects();
8784   ExtraFlags ExtraInfo(Call);
8785 
8786   for (auto &T : TargetConstraints) {
8787     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8788     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8789 
8790     if (OpInfo.CallOperandVal)
8791       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8792 
8793     if (!HasSideEffect)
8794       HasSideEffect = OpInfo.hasMemory(TLI);
8795 
8796     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8797     // FIXME: Could we compute this on OpInfo rather than T?
8798 
8799     // Compute the constraint code and ConstraintType to use.
8800     TLI.ComputeConstraintToUse(T, SDValue());
8801 
8802     if (T.ConstraintType == TargetLowering::C_Immediate &&
8803         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8804       // We've delayed emitting a diagnostic like the "n" constraint because
8805       // inlining could cause an integer showing up.
8806       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8807                                           "' expects an integer constant "
8808                                           "expression");
8809 
8810     ExtraInfo.update(T);
8811   }
8812 
8813   // We won't need to flush pending loads if this asm doesn't touch
8814   // memory and is nonvolatile.
8815   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8816 
8817   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8818   if (EmitEHLabels) {
8819     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8820   }
8821   bool IsCallBr = isa<CallBrInst>(Call);
8822 
8823   if (IsCallBr || EmitEHLabels) {
8824     // If this is a callbr or invoke we need to flush pending exports since
8825     // inlineasm_br and invoke are terminators.
8826     // We need to do this before nodes are glued to the inlineasm_br node.
8827     Chain = getControlRoot();
8828   }
8829 
8830   MCSymbol *BeginLabel = nullptr;
8831   if (EmitEHLabels) {
8832     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8833   }
8834 
8835   // Second pass over the constraints: compute which constraint option to use.
8836   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8837     // If this is an output operand with a matching input operand, look up the
8838     // matching input. If their types mismatch, e.g. one is an integer, the
8839     // other is floating point, or their sizes are different, flag it as an
8840     // error.
8841     if (OpInfo.hasMatchingInput()) {
8842       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8843       patchMatchingInput(OpInfo, Input, DAG);
8844     }
8845 
8846     // Compute the constraint code and ConstraintType to use.
8847     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8848 
8849     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8850          OpInfo.Type == InlineAsm::isClobber) ||
8851         OpInfo.ConstraintType == TargetLowering::C_Address)
8852       continue;
8853 
8854     // If this is a memory input, and if the operand is not indirect, do what we
8855     // need to provide an address for the memory input.
8856     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8857         !OpInfo.isIndirect) {
8858       assert((OpInfo.isMultipleAlternative ||
8859               (OpInfo.Type == InlineAsm::isInput)) &&
8860              "Can only indirectify direct input operands!");
8861 
8862       // Memory operands really want the address of the value.
8863       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8864 
8865       // There is no longer a Value* corresponding to this operand.
8866       OpInfo.CallOperandVal = nullptr;
8867 
8868       // It is now an indirect operand.
8869       OpInfo.isIndirect = true;
8870     }
8871 
8872   }
8873 
8874   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8875   std::vector<SDValue> AsmNodeOperands;
8876   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8877   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8878       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8879 
8880   // If we have a !srcloc metadata node associated with it, we want to attach
8881   // this to the ultimately generated inline asm machineinstr.  To do this, we
8882   // pass in the third operand as this (potentially null) inline asm MDNode.
8883   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8884   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8885 
8886   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8887   // bits as operand 3.
8888   AsmNodeOperands.push_back(DAG.getTargetConstant(
8889       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8890 
8891   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8892   // this, assign virtual and physical registers for inputs and otput.
8893   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8894     // Assign Registers.
8895     SDISelAsmOperandInfo &RefOpInfo =
8896         OpInfo.isMatchingInputConstraint()
8897             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8898             : OpInfo;
8899     const auto RegError =
8900         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8901     if (RegError) {
8902       const MachineFunction &MF = DAG.getMachineFunction();
8903       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8904       const char *RegName = TRI.getName(RegError.value());
8905       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8906                                    "' allocated for constraint '" +
8907                                    Twine(OpInfo.ConstraintCode) +
8908                                    "' does not match required type");
8909       return;
8910     }
8911 
8912     auto DetectWriteToReservedRegister = [&]() {
8913       const MachineFunction &MF = DAG.getMachineFunction();
8914       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8915       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8916         if (Register::isPhysicalRegister(Reg) &&
8917             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8918           const char *RegName = TRI.getName(Reg);
8919           emitInlineAsmError(Call, "write to reserved register '" +
8920                                        Twine(RegName) + "'");
8921           return true;
8922         }
8923       }
8924       return false;
8925     };
8926     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8927             (OpInfo.Type == InlineAsm::isInput &&
8928              !OpInfo.isMatchingInputConstraint())) &&
8929            "Only address as input operand is allowed.");
8930 
8931     switch (OpInfo.Type) {
8932     case InlineAsm::isOutput:
8933       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8934         unsigned ConstraintID =
8935             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8936         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8937                "Failed to convert memory constraint code to constraint id.");
8938 
8939         // Add information to the INLINEASM node to know about this output.
8940         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8941         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8942         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8943                                                         MVT::i32));
8944         AsmNodeOperands.push_back(OpInfo.CallOperand);
8945       } else {
8946         // Otherwise, this outputs to a register (directly for C_Register /
8947         // C_RegisterClass, and a target-defined fashion for
8948         // C_Immediate/C_Other). Find a register that we can use.
8949         if (OpInfo.AssignedRegs.Regs.empty()) {
8950           emitInlineAsmError(
8951               Call, "couldn't allocate output register for constraint '" +
8952                         Twine(OpInfo.ConstraintCode) + "'");
8953           return;
8954         }
8955 
8956         if (DetectWriteToReservedRegister())
8957           return;
8958 
8959         // Add information to the INLINEASM node to know that this register is
8960         // set.
8961         OpInfo.AssignedRegs.AddInlineAsmOperands(
8962             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8963                                   : InlineAsm::Kind_RegDef,
8964             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8965       }
8966       break;
8967 
8968     case InlineAsm::isInput:
8969     case InlineAsm::isLabel: {
8970       SDValue InOperandVal = OpInfo.CallOperand;
8971 
8972       if (OpInfo.isMatchingInputConstraint()) {
8973         // If this is required to match an output register we have already set,
8974         // just use its register.
8975         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8976                                                   AsmNodeOperands);
8977         unsigned OpFlag =
8978           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8979         if (InlineAsm::isRegDefKind(OpFlag) ||
8980             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8981           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8982           if (OpInfo.isIndirect) {
8983             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8984             emitInlineAsmError(Call, "inline asm not supported yet: "
8985                                      "don't know how to handle tied "
8986                                      "indirect register inputs");
8987             return;
8988           }
8989 
8990           SmallVector<unsigned, 4> Regs;
8991           MachineFunction &MF = DAG.getMachineFunction();
8992           MachineRegisterInfo &MRI = MF.getRegInfo();
8993           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8994           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8995           Register TiedReg = R->getReg();
8996           MVT RegVT = R->getSimpleValueType(0);
8997           const TargetRegisterClass *RC =
8998               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8999               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9000                                       : TRI.getMinimalPhysRegClass(TiedReg);
9001           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9002           for (unsigned i = 0; i != NumRegs; ++i)
9003             Regs.push_back(MRI.createVirtualRegister(RC));
9004 
9005           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9006 
9007           SDLoc dl = getCurSDLoc();
9008           // Use the produced MatchedRegs object to
9009           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9010           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9011                                            true, OpInfo.getMatchedOperand(), dl,
9012                                            DAG, AsmNodeOperands);
9013           break;
9014         }
9015 
9016         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9017         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9018                "Unexpected number of operands");
9019         // Add information to the INLINEASM node to know about this input.
9020         // See InlineAsm.h isUseOperandTiedToDef.
9021         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9022         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9023                                                     OpInfo.getMatchedOperand());
9024         AsmNodeOperands.push_back(DAG.getTargetConstant(
9025             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9026         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9027         break;
9028       }
9029 
9030       // Treat indirect 'X' constraint as memory.
9031       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9032           OpInfo.isIndirect)
9033         OpInfo.ConstraintType = TargetLowering::C_Memory;
9034 
9035       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9036           OpInfo.ConstraintType == TargetLowering::C_Other) {
9037         std::vector<SDValue> Ops;
9038         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9039                                           Ops, DAG);
9040         if (Ops.empty()) {
9041           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9042             if (isa<ConstantSDNode>(InOperandVal)) {
9043               emitInlineAsmError(Call, "value out of range for constraint '" +
9044                                            Twine(OpInfo.ConstraintCode) + "'");
9045               return;
9046             }
9047 
9048           emitInlineAsmError(Call,
9049                              "invalid operand for inline asm constraint '" +
9050                                  Twine(OpInfo.ConstraintCode) + "'");
9051           return;
9052         }
9053 
9054         // Add information to the INLINEASM node to know about this input.
9055         unsigned ResOpType =
9056           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9057         AsmNodeOperands.push_back(DAG.getTargetConstant(
9058             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9059         llvm::append_range(AsmNodeOperands, Ops);
9060         break;
9061       }
9062 
9063       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9064           OpInfo.ConstraintType == TargetLowering::C_Address) {
9065         assert((OpInfo.isIndirect ||
9066                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9067                "Operand must be indirect to be a mem!");
9068         assert(InOperandVal.getValueType() ==
9069                    TLI.getPointerTy(DAG.getDataLayout()) &&
9070                "Memory operands expect pointer values");
9071 
9072         unsigned ConstraintID =
9073             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9074         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9075                "Failed to convert memory constraint code to constraint id.");
9076 
9077         // Add information to the INLINEASM node to know about this input.
9078         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9079         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9080         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9081                                                         getCurSDLoc(),
9082                                                         MVT::i32));
9083         AsmNodeOperands.push_back(InOperandVal);
9084         break;
9085       }
9086 
9087       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9088               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9089              "Unknown constraint type!");
9090 
9091       // TODO: Support this.
9092       if (OpInfo.isIndirect) {
9093         emitInlineAsmError(
9094             Call, "Don't know how to handle indirect register inputs yet "
9095                   "for constraint '" +
9096                       Twine(OpInfo.ConstraintCode) + "'");
9097         return;
9098       }
9099 
9100       // Copy the input into the appropriate registers.
9101       if (OpInfo.AssignedRegs.Regs.empty()) {
9102         emitInlineAsmError(Call,
9103                            "couldn't allocate input reg for constraint '" +
9104                                Twine(OpInfo.ConstraintCode) + "'");
9105         return;
9106       }
9107 
9108       if (DetectWriteToReservedRegister())
9109         return;
9110 
9111       SDLoc dl = getCurSDLoc();
9112 
9113       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9114                                         &Call);
9115 
9116       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9117                                                dl, DAG, AsmNodeOperands);
9118       break;
9119     }
9120     case InlineAsm::isClobber:
9121       // Add the clobbered value to the operand list, so that the register
9122       // allocator is aware that the physreg got clobbered.
9123       if (!OpInfo.AssignedRegs.Regs.empty())
9124         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9125                                                  false, 0, getCurSDLoc(), DAG,
9126                                                  AsmNodeOperands);
9127       break;
9128     }
9129   }
9130 
9131   // Finish up input operands.  Set the input chain and add the flag last.
9132   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9133   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9134 
9135   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9136   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9137                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9138   Flag = Chain.getValue(1);
9139 
9140   // Do additional work to generate outputs.
9141 
9142   SmallVector<EVT, 1> ResultVTs;
9143   SmallVector<SDValue, 1> ResultValues;
9144   SmallVector<SDValue, 8> OutChains;
9145 
9146   llvm::Type *CallResultType = Call.getType();
9147   ArrayRef<Type *> ResultTypes;
9148   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9149     ResultTypes = StructResult->elements();
9150   else if (!CallResultType->isVoidTy())
9151     ResultTypes = makeArrayRef(CallResultType);
9152 
9153   auto CurResultType = ResultTypes.begin();
9154   auto handleRegAssign = [&](SDValue V) {
9155     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9156     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9157     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9158     ++CurResultType;
9159     // If the type of the inline asm call site return value is different but has
9160     // same size as the type of the asm output bitcast it.  One example of this
9161     // is for vectors with different width / number of elements.  This can
9162     // happen for register classes that can contain multiple different value
9163     // types.  The preg or vreg allocated may not have the same VT as was
9164     // expected.
9165     //
9166     // This can also happen for a return value that disagrees with the register
9167     // class it is put in, eg. a double in a general-purpose register on a
9168     // 32-bit machine.
9169     if (ResultVT != V.getValueType() &&
9170         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9171       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9172     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9173              V.getValueType().isInteger()) {
9174       // If a result value was tied to an input value, the computed result
9175       // may have a wider width than the expected result.  Extract the
9176       // relevant portion.
9177       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9178     }
9179     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9180     ResultVTs.push_back(ResultVT);
9181     ResultValues.push_back(V);
9182   };
9183 
9184   // Deal with output operands.
9185   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9186     if (OpInfo.Type == InlineAsm::isOutput) {
9187       SDValue Val;
9188       // Skip trivial output operands.
9189       if (OpInfo.AssignedRegs.Regs.empty())
9190         continue;
9191 
9192       switch (OpInfo.ConstraintType) {
9193       case TargetLowering::C_Register:
9194       case TargetLowering::C_RegisterClass:
9195         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9196                                                   Chain, &Flag, &Call);
9197         break;
9198       case TargetLowering::C_Immediate:
9199       case TargetLowering::C_Other:
9200         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9201                                               OpInfo, DAG);
9202         break;
9203       case TargetLowering::C_Memory:
9204         break; // Already handled.
9205       case TargetLowering::C_Address:
9206         break; // Silence warning.
9207       case TargetLowering::C_Unknown:
9208         assert(false && "Unexpected unknown constraint");
9209       }
9210 
9211       // Indirect output manifest as stores. Record output chains.
9212       if (OpInfo.isIndirect) {
9213         const Value *Ptr = OpInfo.CallOperandVal;
9214         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9215         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9216                                      MachinePointerInfo(Ptr));
9217         OutChains.push_back(Store);
9218       } else {
9219         // generate CopyFromRegs to associated registers.
9220         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9221         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9222           for (const SDValue &V : Val->op_values())
9223             handleRegAssign(V);
9224         } else
9225           handleRegAssign(Val);
9226       }
9227     }
9228   }
9229 
9230   // Set results.
9231   if (!ResultValues.empty()) {
9232     assert(CurResultType == ResultTypes.end() &&
9233            "Mismatch in number of ResultTypes");
9234     assert(ResultValues.size() == ResultTypes.size() &&
9235            "Mismatch in number of output operands in asm result");
9236 
9237     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9238                             DAG.getVTList(ResultVTs), ResultValues);
9239     setValue(&Call, V);
9240   }
9241 
9242   // Collect store chains.
9243   if (!OutChains.empty())
9244     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9245 
9246   if (EmitEHLabels) {
9247     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9248   }
9249 
9250   // Only Update Root if inline assembly has a memory effect.
9251   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9252       EmitEHLabels)
9253     DAG.setRoot(Chain);
9254 }
9255 
9256 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9257                                              const Twine &Message) {
9258   LLVMContext &Ctx = *DAG.getContext();
9259   Ctx.emitError(&Call, Message);
9260 
9261   // Make sure we leave the DAG in a valid state
9262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9263   SmallVector<EVT, 1> ValueVTs;
9264   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9265 
9266   if (ValueVTs.empty())
9267     return;
9268 
9269   SmallVector<SDValue, 1> Ops;
9270   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9271     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9272 
9273   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9274 }
9275 
9276 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9277   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9278                           MVT::Other, getRoot(),
9279                           getValue(I.getArgOperand(0)),
9280                           DAG.getSrcValue(I.getArgOperand(0))));
9281 }
9282 
9283 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9284   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9285   const DataLayout &DL = DAG.getDataLayout();
9286   SDValue V = DAG.getVAArg(
9287       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9288       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9289       DL.getABITypeAlign(I.getType()).value());
9290   DAG.setRoot(V.getValue(1));
9291 
9292   if (I.getType()->isPointerTy())
9293     V = DAG.getPtrExtOrTrunc(
9294         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9295   setValue(&I, V);
9296 }
9297 
9298 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9299   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9300                           MVT::Other, getRoot(),
9301                           getValue(I.getArgOperand(0)),
9302                           DAG.getSrcValue(I.getArgOperand(0))));
9303 }
9304 
9305 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9306   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9307                           MVT::Other, getRoot(),
9308                           getValue(I.getArgOperand(0)),
9309                           getValue(I.getArgOperand(1)),
9310                           DAG.getSrcValue(I.getArgOperand(0)),
9311                           DAG.getSrcValue(I.getArgOperand(1))));
9312 }
9313 
9314 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9315                                                     const Instruction &I,
9316                                                     SDValue Op) {
9317   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9318   if (!Range)
9319     return Op;
9320 
9321   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9322   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9323     return Op;
9324 
9325   APInt Lo = CR.getUnsignedMin();
9326   if (!Lo.isMinValue())
9327     return Op;
9328 
9329   APInt Hi = CR.getUnsignedMax();
9330   unsigned Bits = std::max(Hi.getActiveBits(),
9331                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9332 
9333   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9334 
9335   SDLoc SL = getCurSDLoc();
9336 
9337   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9338                              DAG.getValueType(SmallVT));
9339   unsigned NumVals = Op.getNode()->getNumValues();
9340   if (NumVals == 1)
9341     return ZExt;
9342 
9343   SmallVector<SDValue, 4> Ops;
9344 
9345   Ops.push_back(ZExt);
9346   for (unsigned I = 1; I != NumVals; ++I)
9347     Ops.push_back(Op.getValue(I));
9348 
9349   return DAG.getMergeValues(Ops, SL);
9350 }
9351 
9352 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9353 /// the call being lowered.
9354 ///
9355 /// This is a helper for lowering intrinsics that follow a target calling
9356 /// convention or require stack pointer adjustment. Only a subset of the
9357 /// intrinsic's operands need to participate in the calling convention.
9358 void SelectionDAGBuilder::populateCallLoweringInfo(
9359     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9360     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9361     bool IsPatchPoint) {
9362   TargetLowering::ArgListTy Args;
9363   Args.reserve(NumArgs);
9364 
9365   // Populate the argument list.
9366   // Attributes for args start at offset 1, after the return attribute.
9367   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9368        ArgI != ArgE; ++ArgI) {
9369     const Value *V = Call->getOperand(ArgI);
9370 
9371     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9372 
9373     TargetLowering::ArgListEntry Entry;
9374     Entry.Node = getValue(V);
9375     Entry.Ty = V->getType();
9376     Entry.setAttributes(Call, ArgI);
9377     Args.push_back(Entry);
9378   }
9379 
9380   CLI.setDebugLoc(getCurSDLoc())
9381       .setChain(getRoot())
9382       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9383       .setDiscardResult(Call->use_empty())
9384       .setIsPatchPoint(IsPatchPoint)
9385       .setIsPreallocated(
9386           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9387 }
9388 
9389 /// Add a stack map intrinsic call's live variable operands to a stackmap
9390 /// or patchpoint target node's operand list.
9391 ///
9392 /// Constants are converted to TargetConstants purely as an optimization to
9393 /// avoid constant materialization and register allocation.
9394 ///
9395 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9396 /// generate addess computation nodes, and so FinalizeISel can convert the
9397 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9398 /// address materialization and register allocation, but may also be required
9399 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9400 /// alloca in the entry block, then the runtime may assume that the alloca's
9401 /// StackMap location can be read immediately after compilation and that the
9402 /// location is valid at any point during execution (this is similar to the
9403 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9404 /// only available in a register, then the runtime would need to trap when
9405 /// execution reaches the StackMap in order to read the alloca's location.
9406 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9407                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9408                                 SelectionDAGBuilder &Builder) {
9409   SelectionDAG &DAG = Builder.DAG;
9410   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9411     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9412 
9413     // Things on the stack are pointer-typed, meaning that they are already
9414     // legal and can be emitted directly to target nodes.
9415     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9416       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9417     } else {
9418       // Otherwise emit a target independent node to be legalised.
9419       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9420     }
9421   }
9422 }
9423 
9424 /// Lower llvm.experimental.stackmap.
9425 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9426   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9427   //                                  [live variables...])
9428 
9429   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9430 
9431   SDValue Chain, InFlag, Callee;
9432   SmallVector<SDValue, 32> Ops;
9433 
9434   SDLoc DL = getCurSDLoc();
9435   Callee = getValue(CI.getCalledOperand());
9436 
9437   // The stackmap intrinsic only records the live variables (the arguments
9438   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9439   // intrinsic, this won't be lowered to a function call. This means we don't
9440   // have to worry about calling conventions and target specific lowering code.
9441   // Instead we perform the call lowering right here.
9442   //
9443   // chain, flag = CALLSEQ_START(chain, 0, 0)
9444   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9445   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9446   //
9447   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9448   InFlag = Chain.getValue(1);
9449 
9450   // Add the STACKMAP operands, starting with DAG house-keeping.
9451   Ops.push_back(Chain);
9452   Ops.push_back(InFlag);
9453 
9454   // Add the <id>, <numShadowBytes> operands.
9455   //
9456   // These do not require legalisation, and can be emitted directly to target
9457   // constant nodes.
9458   SDValue ID = getValue(CI.getArgOperand(0));
9459   assert(ID.getValueType() == MVT::i64);
9460   SDValue IDConst = DAG.getTargetConstant(
9461       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9462   Ops.push_back(IDConst);
9463 
9464   SDValue Shad = getValue(CI.getArgOperand(1));
9465   assert(Shad.getValueType() == MVT::i32);
9466   SDValue ShadConst = DAG.getTargetConstant(
9467       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9468   Ops.push_back(ShadConst);
9469 
9470   // Add the live variables.
9471   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9472 
9473   // Create the STACKMAP node.
9474   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9475   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9476   InFlag = Chain.getValue(1);
9477 
9478   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9479 
9480   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9481 
9482   // Set the root to the target-lowered call chain.
9483   DAG.setRoot(Chain);
9484 
9485   // Inform the Frame Information that we have a stackmap in this function.
9486   FuncInfo.MF->getFrameInfo().setHasStackMap();
9487 }
9488 
9489 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9490 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9491                                           const BasicBlock *EHPadBB) {
9492   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9493   //                                                 i32 <numBytes>,
9494   //                                                 i8* <target>,
9495   //                                                 i32 <numArgs>,
9496   //                                                 [Args...],
9497   //                                                 [live variables...])
9498 
9499   CallingConv::ID CC = CB.getCallingConv();
9500   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9501   bool HasDef = !CB.getType()->isVoidTy();
9502   SDLoc dl = getCurSDLoc();
9503   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9504 
9505   // Handle immediate and symbolic callees.
9506   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9507     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9508                                    /*isTarget=*/true);
9509   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9510     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9511                                          SDLoc(SymbolicCallee),
9512                                          SymbolicCallee->getValueType(0));
9513 
9514   // Get the real number of arguments participating in the call <numArgs>
9515   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9516   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9517 
9518   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9519   // Intrinsics include all meta-operands up to but not including CC.
9520   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9521   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9522          "Not enough arguments provided to the patchpoint intrinsic");
9523 
9524   // For AnyRegCC the arguments are lowered later on manually.
9525   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9526   Type *ReturnTy =
9527       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9528 
9529   TargetLowering::CallLoweringInfo CLI(DAG);
9530   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9531                            ReturnTy, true);
9532   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9533 
9534   SDNode *CallEnd = Result.second.getNode();
9535   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9536     CallEnd = CallEnd->getOperand(0).getNode();
9537 
9538   /// Get a call instruction from the call sequence chain.
9539   /// Tail calls are not allowed.
9540   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9541          "Expected a callseq node.");
9542   SDNode *Call = CallEnd->getOperand(0).getNode();
9543   bool HasGlue = Call->getGluedNode();
9544 
9545   // Replace the target specific call node with the patchable intrinsic.
9546   SmallVector<SDValue, 8> Ops;
9547 
9548   // Push the chain.
9549   Ops.push_back(*(Call->op_begin()));
9550 
9551   // Optionally, push the glue (if any).
9552   if (HasGlue)
9553     Ops.push_back(*(Call->op_end() - 1));
9554 
9555   // Push the register mask info.
9556   if (HasGlue)
9557     Ops.push_back(*(Call->op_end() - 2));
9558   else
9559     Ops.push_back(*(Call->op_end() - 1));
9560 
9561   // Add the <id> and <numBytes> constants.
9562   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9563   Ops.push_back(DAG.getTargetConstant(
9564                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9565   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9566   Ops.push_back(DAG.getTargetConstant(
9567                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9568                   MVT::i32));
9569 
9570   // Add the callee.
9571   Ops.push_back(Callee);
9572 
9573   // Adjust <numArgs> to account for any arguments that have been passed on the
9574   // stack instead.
9575   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9576   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9577   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9578   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9579 
9580   // Add the calling convention
9581   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9582 
9583   // Add the arguments we omitted previously. The register allocator should
9584   // place these in any free register.
9585   if (IsAnyRegCC)
9586     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9587       Ops.push_back(getValue(CB.getArgOperand(i)));
9588 
9589   // Push the arguments from the call instruction.
9590   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9591   Ops.append(Call->op_begin() + 2, e);
9592 
9593   // Push live variables for the stack map.
9594   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9595 
9596   SDVTList NodeTys;
9597   if (IsAnyRegCC && HasDef) {
9598     // Create the return types based on the intrinsic definition
9599     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9600     SmallVector<EVT, 3> ValueVTs;
9601     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9602     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9603 
9604     // There is always a chain and a glue type at the end
9605     ValueVTs.push_back(MVT::Other);
9606     ValueVTs.push_back(MVT::Glue);
9607     NodeTys = DAG.getVTList(ValueVTs);
9608   } else
9609     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9610 
9611   // Replace the target specific call node with a PATCHPOINT node.
9612   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9613 
9614   // Update the NodeMap.
9615   if (HasDef) {
9616     if (IsAnyRegCC)
9617       setValue(&CB, SDValue(PPV.getNode(), 0));
9618     else
9619       setValue(&CB, Result.first);
9620   }
9621 
9622   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9623   // call sequence. Furthermore the location of the chain and glue can change
9624   // when the AnyReg calling convention is used and the intrinsic returns a
9625   // value.
9626   if (IsAnyRegCC && HasDef) {
9627     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9628     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9629     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9630   } else
9631     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9632   DAG.DeleteNode(Call);
9633 
9634   // Inform the Frame Information that we have a patchpoint in this function.
9635   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9636 }
9637 
9638 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9639                                             unsigned Intrinsic) {
9640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9641   SDValue Op1 = getValue(I.getArgOperand(0));
9642   SDValue Op2;
9643   if (I.arg_size() > 1)
9644     Op2 = getValue(I.getArgOperand(1));
9645   SDLoc dl = getCurSDLoc();
9646   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9647   SDValue Res;
9648   SDNodeFlags SDFlags;
9649   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9650     SDFlags.copyFMF(*FPMO);
9651 
9652   switch (Intrinsic) {
9653   case Intrinsic::vector_reduce_fadd:
9654     if (SDFlags.hasAllowReassociation())
9655       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9656                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9657                         SDFlags);
9658     else
9659       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9660     break;
9661   case Intrinsic::vector_reduce_fmul:
9662     if (SDFlags.hasAllowReassociation())
9663       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9664                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9665                         SDFlags);
9666     else
9667       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9668     break;
9669   case Intrinsic::vector_reduce_add:
9670     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9671     break;
9672   case Intrinsic::vector_reduce_mul:
9673     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9674     break;
9675   case Intrinsic::vector_reduce_and:
9676     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9677     break;
9678   case Intrinsic::vector_reduce_or:
9679     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9680     break;
9681   case Intrinsic::vector_reduce_xor:
9682     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9683     break;
9684   case Intrinsic::vector_reduce_smax:
9685     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9686     break;
9687   case Intrinsic::vector_reduce_smin:
9688     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9689     break;
9690   case Intrinsic::vector_reduce_umax:
9691     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9692     break;
9693   case Intrinsic::vector_reduce_umin:
9694     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9695     break;
9696   case Intrinsic::vector_reduce_fmax:
9697     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9698     break;
9699   case Intrinsic::vector_reduce_fmin:
9700     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9701     break;
9702   default:
9703     llvm_unreachable("Unhandled vector reduce intrinsic");
9704   }
9705   setValue(&I, Res);
9706 }
9707 
9708 /// Returns an AttributeList representing the attributes applied to the return
9709 /// value of the given call.
9710 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9711   SmallVector<Attribute::AttrKind, 2> Attrs;
9712   if (CLI.RetSExt)
9713     Attrs.push_back(Attribute::SExt);
9714   if (CLI.RetZExt)
9715     Attrs.push_back(Attribute::ZExt);
9716   if (CLI.IsInReg)
9717     Attrs.push_back(Attribute::InReg);
9718 
9719   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9720                             Attrs);
9721 }
9722 
9723 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9724 /// implementation, which just calls LowerCall.
9725 /// FIXME: When all targets are
9726 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9727 std::pair<SDValue, SDValue>
9728 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9729   // Handle the incoming return values from the call.
9730   CLI.Ins.clear();
9731   Type *OrigRetTy = CLI.RetTy;
9732   SmallVector<EVT, 4> RetTys;
9733   SmallVector<uint64_t, 4> Offsets;
9734   auto &DL = CLI.DAG.getDataLayout();
9735   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9736 
9737   if (CLI.IsPostTypeLegalization) {
9738     // If we are lowering a libcall after legalization, split the return type.
9739     SmallVector<EVT, 4> OldRetTys;
9740     SmallVector<uint64_t, 4> OldOffsets;
9741     RetTys.swap(OldRetTys);
9742     Offsets.swap(OldOffsets);
9743 
9744     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9745       EVT RetVT = OldRetTys[i];
9746       uint64_t Offset = OldOffsets[i];
9747       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9748       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9749       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9750       RetTys.append(NumRegs, RegisterVT);
9751       for (unsigned j = 0; j != NumRegs; ++j)
9752         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9753     }
9754   }
9755 
9756   SmallVector<ISD::OutputArg, 4> Outs;
9757   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9758 
9759   bool CanLowerReturn =
9760       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9761                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9762 
9763   SDValue DemoteStackSlot;
9764   int DemoteStackIdx = -100;
9765   if (!CanLowerReturn) {
9766     // FIXME: equivalent assert?
9767     // assert(!CS.hasInAllocaArgument() &&
9768     //        "sret demotion is incompatible with inalloca");
9769     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9770     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9771     MachineFunction &MF = CLI.DAG.getMachineFunction();
9772     DemoteStackIdx =
9773         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9774     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9775                                               DL.getAllocaAddrSpace());
9776 
9777     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9778     ArgListEntry Entry;
9779     Entry.Node = DemoteStackSlot;
9780     Entry.Ty = StackSlotPtrType;
9781     Entry.IsSExt = false;
9782     Entry.IsZExt = false;
9783     Entry.IsInReg = false;
9784     Entry.IsSRet = true;
9785     Entry.IsNest = false;
9786     Entry.IsByVal = false;
9787     Entry.IsByRef = false;
9788     Entry.IsReturned = false;
9789     Entry.IsSwiftSelf = false;
9790     Entry.IsSwiftAsync = false;
9791     Entry.IsSwiftError = false;
9792     Entry.IsCFGuardTarget = false;
9793     Entry.Alignment = Alignment;
9794     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9795     CLI.NumFixedArgs += 1;
9796     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9797 
9798     // sret demotion isn't compatible with tail-calls, since the sret argument
9799     // points into the callers stack frame.
9800     CLI.IsTailCall = false;
9801   } else {
9802     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9803         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9804     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9805       ISD::ArgFlagsTy Flags;
9806       if (NeedsRegBlock) {
9807         Flags.setInConsecutiveRegs();
9808         if (I == RetTys.size() - 1)
9809           Flags.setInConsecutiveRegsLast();
9810       }
9811       EVT VT = RetTys[I];
9812       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9813                                                      CLI.CallConv, VT);
9814       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9815                                                        CLI.CallConv, VT);
9816       for (unsigned i = 0; i != NumRegs; ++i) {
9817         ISD::InputArg MyFlags;
9818         MyFlags.Flags = Flags;
9819         MyFlags.VT = RegisterVT;
9820         MyFlags.ArgVT = VT;
9821         MyFlags.Used = CLI.IsReturnValueUsed;
9822         if (CLI.RetTy->isPointerTy()) {
9823           MyFlags.Flags.setPointer();
9824           MyFlags.Flags.setPointerAddrSpace(
9825               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9826         }
9827         if (CLI.RetSExt)
9828           MyFlags.Flags.setSExt();
9829         if (CLI.RetZExt)
9830           MyFlags.Flags.setZExt();
9831         if (CLI.IsInReg)
9832           MyFlags.Flags.setInReg();
9833         CLI.Ins.push_back(MyFlags);
9834       }
9835     }
9836   }
9837 
9838   // We push in swifterror return as the last element of CLI.Ins.
9839   ArgListTy &Args = CLI.getArgs();
9840   if (supportSwiftError()) {
9841     for (const ArgListEntry &Arg : Args) {
9842       if (Arg.IsSwiftError) {
9843         ISD::InputArg MyFlags;
9844         MyFlags.VT = getPointerTy(DL);
9845         MyFlags.ArgVT = EVT(getPointerTy(DL));
9846         MyFlags.Flags.setSwiftError();
9847         CLI.Ins.push_back(MyFlags);
9848       }
9849     }
9850   }
9851 
9852   // Handle all of the outgoing arguments.
9853   CLI.Outs.clear();
9854   CLI.OutVals.clear();
9855   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9856     SmallVector<EVT, 4> ValueVTs;
9857     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9858     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9859     Type *FinalType = Args[i].Ty;
9860     if (Args[i].IsByVal)
9861       FinalType = Args[i].IndirectType;
9862     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9863         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9864     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9865          ++Value) {
9866       EVT VT = ValueVTs[Value];
9867       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9868       SDValue Op = SDValue(Args[i].Node.getNode(),
9869                            Args[i].Node.getResNo() + Value);
9870       ISD::ArgFlagsTy Flags;
9871 
9872       // Certain targets (such as MIPS), may have a different ABI alignment
9873       // for a type depending on the context. Give the target a chance to
9874       // specify the alignment it wants.
9875       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9876       Flags.setOrigAlign(OriginalAlignment);
9877 
9878       if (Args[i].Ty->isPointerTy()) {
9879         Flags.setPointer();
9880         Flags.setPointerAddrSpace(
9881             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9882       }
9883       if (Args[i].IsZExt)
9884         Flags.setZExt();
9885       if (Args[i].IsSExt)
9886         Flags.setSExt();
9887       if (Args[i].IsInReg) {
9888         // If we are using vectorcall calling convention, a structure that is
9889         // passed InReg - is surely an HVA
9890         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9891             isa<StructType>(FinalType)) {
9892           // The first value of a structure is marked
9893           if (0 == Value)
9894             Flags.setHvaStart();
9895           Flags.setHva();
9896         }
9897         // Set InReg Flag
9898         Flags.setInReg();
9899       }
9900       if (Args[i].IsSRet)
9901         Flags.setSRet();
9902       if (Args[i].IsSwiftSelf)
9903         Flags.setSwiftSelf();
9904       if (Args[i].IsSwiftAsync)
9905         Flags.setSwiftAsync();
9906       if (Args[i].IsSwiftError)
9907         Flags.setSwiftError();
9908       if (Args[i].IsCFGuardTarget)
9909         Flags.setCFGuardTarget();
9910       if (Args[i].IsByVal)
9911         Flags.setByVal();
9912       if (Args[i].IsByRef)
9913         Flags.setByRef();
9914       if (Args[i].IsPreallocated) {
9915         Flags.setPreallocated();
9916         // Set the byval flag for CCAssignFn callbacks that don't know about
9917         // preallocated.  This way we can know how many bytes we should've
9918         // allocated and how many bytes a callee cleanup function will pop.  If
9919         // we port preallocated to more targets, we'll have to add custom
9920         // preallocated handling in the various CC lowering callbacks.
9921         Flags.setByVal();
9922       }
9923       if (Args[i].IsInAlloca) {
9924         Flags.setInAlloca();
9925         // Set the byval flag for CCAssignFn callbacks that don't know about
9926         // inalloca.  This way we can know how many bytes we should've allocated
9927         // and how many bytes a callee cleanup function will pop.  If we port
9928         // inalloca to more targets, we'll have to add custom inalloca handling
9929         // in the various CC lowering callbacks.
9930         Flags.setByVal();
9931       }
9932       Align MemAlign;
9933       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9934         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9935         Flags.setByValSize(FrameSize);
9936 
9937         // info is not there but there are cases it cannot get right.
9938         if (auto MA = Args[i].Alignment)
9939           MemAlign = *MA;
9940         else
9941           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9942       } else if (auto MA = Args[i].Alignment) {
9943         MemAlign = *MA;
9944       } else {
9945         MemAlign = OriginalAlignment;
9946       }
9947       Flags.setMemAlign(MemAlign);
9948       if (Args[i].IsNest)
9949         Flags.setNest();
9950       if (NeedsRegBlock)
9951         Flags.setInConsecutiveRegs();
9952 
9953       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9954                                                  CLI.CallConv, VT);
9955       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9956                                                         CLI.CallConv, VT);
9957       SmallVector<SDValue, 4> Parts(NumParts);
9958       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9959 
9960       if (Args[i].IsSExt)
9961         ExtendKind = ISD::SIGN_EXTEND;
9962       else if (Args[i].IsZExt)
9963         ExtendKind = ISD::ZERO_EXTEND;
9964 
9965       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9966       // for now.
9967       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9968           CanLowerReturn) {
9969         assert((CLI.RetTy == Args[i].Ty ||
9970                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9971                  CLI.RetTy->getPointerAddressSpace() ==
9972                      Args[i].Ty->getPointerAddressSpace())) &&
9973                RetTys.size() == NumValues && "unexpected use of 'returned'");
9974         // Before passing 'returned' to the target lowering code, ensure that
9975         // either the register MVT and the actual EVT are the same size or that
9976         // the return value and argument are extended in the same way; in these
9977         // cases it's safe to pass the argument register value unchanged as the
9978         // return register value (although it's at the target's option whether
9979         // to do so)
9980         // TODO: allow code generation to take advantage of partially preserved
9981         // registers rather than clobbering the entire register when the
9982         // parameter extension method is not compatible with the return
9983         // extension method
9984         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9985             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9986              CLI.RetZExt == Args[i].IsZExt))
9987           Flags.setReturned();
9988       }
9989 
9990       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9991                      CLI.CallConv, ExtendKind);
9992 
9993       for (unsigned j = 0; j != NumParts; ++j) {
9994         // if it isn't first piece, alignment must be 1
9995         // For scalable vectors the scalable part is currently handled
9996         // by individual targets, so we just use the known minimum size here.
9997         ISD::OutputArg MyFlags(
9998             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9999             i < CLI.NumFixedArgs, i,
10000             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
10001         if (NumParts > 1 && j == 0)
10002           MyFlags.Flags.setSplit();
10003         else if (j != 0) {
10004           MyFlags.Flags.setOrigAlign(Align(1));
10005           if (j == NumParts - 1)
10006             MyFlags.Flags.setSplitEnd();
10007         }
10008 
10009         CLI.Outs.push_back(MyFlags);
10010         CLI.OutVals.push_back(Parts[j]);
10011       }
10012 
10013       if (NeedsRegBlock && Value == NumValues - 1)
10014         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10015     }
10016   }
10017 
10018   SmallVector<SDValue, 4> InVals;
10019   CLI.Chain = LowerCall(CLI, InVals);
10020 
10021   // Update CLI.InVals to use outside of this function.
10022   CLI.InVals = InVals;
10023 
10024   // Verify that the target's LowerCall behaved as expected.
10025   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10026          "LowerCall didn't return a valid chain!");
10027   assert((!CLI.IsTailCall || InVals.empty()) &&
10028          "LowerCall emitted a return value for a tail call!");
10029   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10030          "LowerCall didn't emit the correct number of values!");
10031 
10032   // For a tail call, the return value is merely live-out and there aren't
10033   // any nodes in the DAG representing it. Return a special value to
10034   // indicate that a tail call has been emitted and no more Instructions
10035   // should be processed in the current block.
10036   if (CLI.IsTailCall) {
10037     CLI.DAG.setRoot(CLI.Chain);
10038     return std::make_pair(SDValue(), SDValue());
10039   }
10040 
10041 #ifndef NDEBUG
10042   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10043     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10044     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10045            "LowerCall emitted a value with the wrong type!");
10046   }
10047 #endif
10048 
10049   SmallVector<SDValue, 4> ReturnValues;
10050   if (!CanLowerReturn) {
10051     // The instruction result is the result of loading from the
10052     // hidden sret parameter.
10053     SmallVector<EVT, 1> PVTs;
10054     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10055 
10056     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10057     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10058     EVT PtrVT = PVTs[0];
10059 
10060     unsigned NumValues = RetTys.size();
10061     ReturnValues.resize(NumValues);
10062     SmallVector<SDValue, 4> Chains(NumValues);
10063 
10064     // An aggregate return value cannot wrap around the address space, so
10065     // offsets to its parts don't wrap either.
10066     SDNodeFlags Flags;
10067     Flags.setNoUnsignedWrap(true);
10068 
10069     MachineFunction &MF = CLI.DAG.getMachineFunction();
10070     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10071     for (unsigned i = 0; i < NumValues; ++i) {
10072       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10073                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10074                                                         PtrVT), Flags);
10075       SDValue L = CLI.DAG.getLoad(
10076           RetTys[i], CLI.DL, CLI.Chain, Add,
10077           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10078                                             DemoteStackIdx, Offsets[i]),
10079           HiddenSRetAlign);
10080       ReturnValues[i] = L;
10081       Chains[i] = L.getValue(1);
10082     }
10083 
10084     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10085   } else {
10086     // Collect the legal value parts into potentially illegal values
10087     // that correspond to the original function's return values.
10088     Optional<ISD::NodeType> AssertOp;
10089     if (CLI.RetSExt)
10090       AssertOp = ISD::AssertSext;
10091     else if (CLI.RetZExt)
10092       AssertOp = ISD::AssertZext;
10093     unsigned CurReg = 0;
10094     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10095       EVT VT = RetTys[I];
10096       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10097                                                      CLI.CallConv, VT);
10098       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10099                                                        CLI.CallConv, VT);
10100 
10101       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10102                                               NumRegs, RegisterVT, VT, nullptr,
10103                                               CLI.CallConv, AssertOp));
10104       CurReg += NumRegs;
10105     }
10106 
10107     // For a function returning void, there is no return value. We can't create
10108     // such a node, so we just return a null return value in that case. In
10109     // that case, nothing will actually look at the value.
10110     if (ReturnValues.empty())
10111       return std::make_pair(SDValue(), CLI.Chain);
10112   }
10113 
10114   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10115                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10116   return std::make_pair(Res, CLI.Chain);
10117 }
10118 
10119 /// Places new result values for the node in Results (their number
10120 /// and types must exactly match those of the original return values of
10121 /// the node), or leaves Results empty, which indicates that the node is not
10122 /// to be custom lowered after all.
10123 void TargetLowering::LowerOperationWrapper(SDNode *N,
10124                                            SmallVectorImpl<SDValue> &Results,
10125                                            SelectionDAG &DAG) const {
10126   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10127 
10128   if (!Res.getNode())
10129     return;
10130 
10131   // If the original node has one result, take the return value from
10132   // LowerOperation as is. It might not be result number 0.
10133   if (N->getNumValues() == 1) {
10134     Results.push_back(Res);
10135     return;
10136   }
10137 
10138   // If the original node has multiple results, then the return node should
10139   // have the same number of results.
10140   assert((N->getNumValues() == Res->getNumValues()) &&
10141       "Lowering returned the wrong number of results!");
10142 
10143   // Places new result values base on N result number.
10144   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10145     Results.push_back(Res.getValue(I));
10146 }
10147 
10148 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10149   llvm_unreachable("LowerOperation not implemented for this target!");
10150 }
10151 
10152 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10153                                                      unsigned Reg,
10154                                                      ISD::NodeType ExtendType) {
10155   SDValue Op = getNonRegisterValue(V);
10156   assert((Op.getOpcode() != ISD::CopyFromReg ||
10157           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10158          "Copy from a reg to the same reg!");
10159   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10160 
10161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10162   // If this is an InlineAsm we have to match the registers required, not the
10163   // notional registers required by the type.
10164 
10165   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10166                    None); // This is not an ABI copy.
10167   SDValue Chain = DAG.getEntryNode();
10168 
10169   if (ExtendType == ISD::ANY_EXTEND) {
10170     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10171     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10172       ExtendType = PreferredExtendIt->second;
10173   }
10174   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10175   PendingExports.push_back(Chain);
10176 }
10177 
10178 #include "llvm/CodeGen/SelectionDAGISel.h"
10179 
10180 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10181 /// entry block, return true.  This includes arguments used by switches, since
10182 /// the switch may expand into multiple basic blocks.
10183 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10184   // With FastISel active, we may be splitting blocks, so force creation
10185   // of virtual registers for all non-dead arguments.
10186   if (FastISel)
10187     return A->use_empty();
10188 
10189   const BasicBlock &Entry = A->getParent()->front();
10190   for (const User *U : A->users())
10191     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10192       return false;  // Use not in entry block.
10193 
10194   return true;
10195 }
10196 
10197 using ArgCopyElisionMapTy =
10198     DenseMap<const Argument *,
10199              std::pair<const AllocaInst *, const StoreInst *>>;
10200 
10201 /// Scan the entry block of the function in FuncInfo for arguments that look
10202 /// like copies into a local alloca. Record any copied arguments in
10203 /// ArgCopyElisionCandidates.
10204 static void
10205 findArgumentCopyElisionCandidates(const DataLayout &DL,
10206                                   FunctionLoweringInfo *FuncInfo,
10207                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10208   // Record the state of every static alloca used in the entry block. Argument
10209   // allocas are all used in the entry block, so we need approximately as many
10210   // entries as we have arguments.
10211   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10212   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10213   unsigned NumArgs = FuncInfo->Fn->arg_size();
10214   StaticAllocas.reserve(NumArgs * 2);
10215 
10216   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10217     if (!V)
10218       return nullptr;
10219     V = V->stripPointerCasts();
10220     const auto *AI = dyn_cast<AllocaInst>(V);
10221     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10222       return nullptr;
10223     auto Iter = StaticAllocas.insert({AI, Unknown});
10224     return &Iter.first->second;
10225   };
10226 
10227   // Look for stores of arguments to static allocas. Look through bitcasts and
10228   // GEPs to handle type coercions, as long as the alloca is fully initialized
10229   // by the store. Any non-store use of an alloca escapes it and any subsequent
10230   // unanalyzed store might write it.
10231   // FIXME: Handle structs initialized with multiple stores.
10232   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10233     // Look for stores, and handle non-store uses conservatively.
10234     const auto *SI = dyn_cast<StoreInst>(&I);
10235     if (!SI) {
10236       // We will look through cast uses, so ignore them completely.
10237       if (I.isCast())
10238         continue;
10239       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10240       // to allocas.
10241       if (I.isDebugOrPseudoInst())
10242         continue;
10243       // This is an unknown instruction. Assume it escapes or writes to all
10244       // static alloca operands.
10245       for (const Use &U : I.operands()) {
10246         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10247           *Info = StaticAllocaInfo::Clobbered;
10248       }
10249       continue;
10250     }
10251 
10252     // If the stored value is a static alloca, mark it as escaped.
10253     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10254       *Info = StaticAllocaInfo::Clobbered;
10255 
10256     // Check if the destination is a static alloca.
10257     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10258     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10259     if (!Info)
10260       continue;
10261     const AllocaInst *AI = cast<AllocaInst>(Dst);
10262 
10263     // Skip allocas that have been initialized or clobbered.
10264     if (*Info != StaticAllocaInfo::Unknown)
10265       continue;
10266 
10267     // Check if the stored value is an argument, and that this store fully
10268     // initializes the alloca.
10269     // If the argument type has padding bits we can't directly forward a pointer
10270     // as the upper bits may contain garbage.
10271     // Don't elide copies from the same argument twice.
10272     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10273     const auto *Arg = dyn_cast<Argument>(Val);
10274     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10275         Arg->getType()->isEmptyTy() ||
10276         DL.getTypeStoreSize(Arg->getType()) !=
10277             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10278         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10279         ArgCopyElisionCandidates.count(Arg)) {
10280       *Info = StaticAllocaInfo::Clobbered;
10281       continue;
10282     }
10283 
10284     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10285                       << '\n');
10286 
10287     // Mark this alloca and store for argument copy elision.
10288     *Info = StaticAllocaInfo::Elidable;
10289     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10290 
10291     // Stop scanning if we've seen all arguments. This will happen early in -O0
10292     // builds, which is useful, because -O0 builds have large entry blocks and
10293     // many allocas.
10294     if (ArgCopyElisionCandidates.size() == NumArgs)
10295       break;
10296   }
10297 }
10298 
10299 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10300 /// ArgVal is a load from a suitable fixed stack object.
10301 static void tryToElideArgumentCopy(
10302     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10303     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10304     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10305     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10306     SDValue ArgVal, bool &ArgHasUses) {
10307   // Check if this is a load from a fixed stack object.
10308   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10309   if (!LNode)
10310     return;
10311   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10312   if (!FINode)
10313     return;
10314 
10315   // Check that the fixed stack object is the right size and alignment.
10316   // Look at the alignment that the user wrote on the alloca instead of looking
10317   // at the stack object.
10318   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10319   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10320   const AllocaInst *AI = ArgCopyIter->second.first;
10321   int FixedIndex = FINode->getIndex();
10322   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10323   int OldIndex = AllocaIndex;
10324   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10325   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10326     LLVM_DEBUG(
10327         dbgs() << "  argument copy elision failed due to bad fixed stack "
10328                   "object size\n");
10329     return;
10330   }
10331   Align RequiredAlignment = AI->getAlign();
10332   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10333     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10334                          "greater than stack argument alignment ("
10335                       << DebugStr(RequiredAlignment) << " vs "
10336                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10337     return;
10338   }
10339 
10340   // Perform the elision. Delete the old stack object and replace its only use
10341   // in the variable info map. Mark the stack object as mutable.
10342   LLVM_DEBUG({
10343     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10344            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10345            << '\n';
10346   });
10347   MFI.RemoveStackObject(OldIndex);
10348   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10349   AllocaIndex = FixedIndex;
10350   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10351   Chains.push_back(ArgVal.getValue(1));
10352 
10353   // Avoid emitting code for the store implementing the copy.
10354   const StoreInst *SI = ArgCopyIter->second.second;
10355   ElidedArgCopyInstrs.insert(SI);
10356 
10357   // Check for uses of the argument again so that we can avoid exporting ArgVal
10358   // if it is't used by anything other than the store.
10359   for (const Value *U : Arg.users()) {
10360     if (U != SI) {
10361       ArgHasUses = true;
10362       break;
10363     }
10364   }
10365 }
10366 
10367 void SelectionDAGISel::LowerArguments(const Function &F) {
10368   SelectionDAG &DAG = SDB->DAG;
10369   SDLoc dl = SDB->getCurSDLoc();
10370   const DataLayout &DL = DAG.getDataLayout();
10371   SmallVector<ISD::InputArg, 16> Ins;
10372 
10373   // In Naked functions we aren't going to save any registers.
10374   if (F.hasFnAttribute(Attribute::Naked))
10375     return;
10376 
10377   if (!FuncInfo->CanLowerReturn) {
10378     // Put in an sret pointer parameter before all the other parameters.
10379     SmallVector<EVT, 1> ValueVTs;
10380     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10381                     F.getReturnType()->getPointerTo(
10382                         DAG.getDataLayout().getAllocaAddrSpace()),
10383                     ValueVTs);
10384 
10385     // NOTE: Assuming that a pointer will never break down to more than one VT
10386     // or one register.
10387     ISD::ArgFlagsTy Flags;
10388     Flags.setSRet();
10389     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10390     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10391                          ISD::InputArg::NoArgIndex, 0);
10392     Ins.push_back(RetArg);
10393   }
10394 
10395   // Look for stores of arguments to static allocas. Mark such arguments with a
10396   // flag to ask the target to give us the memory location of that argument if
10397   // available.
10398   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10399   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10400                                     ArgCopyElisionCandidates);
10401 
10402   // Set up the incoming argument description vector.
10403   for (const Argument &Arg : F.args()) {
10404     unsigned ArgNo = Arg.getArgNo();
10405     SmallVector<EVT, 4> ValueVTs;
10406     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10407     bool isArgValueUsed = !Arg.use_empty();
10408     unsigned PartBase = 0;
10409     Type *FinalType = Arg.getType();
10410     if (Arg.hasAttribute(Attribute::ByVal))
10411       FinalType = Arg.getParamByValType();
10412     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10413         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10414     for (unsigned Value = 0, NumValues = ValueVTs.size();
10415          Value != NumValues; ++Value) {
10416       EVT VT = ValueVTs[Value];
10417       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10418       ISD::ArgFlagsTy Flags;
10419 
10420 
10421       if (Arg.getType()->isPointerTy()) {
10422         Flags.setPointer();
10423         Flags.setPointerAddrSpace(
10424             cast<PointerType>(Arg.getType())->getAddressSpace());
10425       }
10426       if (Arg.hasAttribute(Attribute::ZExt))
10427         Flags.setZExt();
10428       if (Arg.hasAttribute(Attribute::SExt))
10429         Flags.setSExt();
10430       if (Arg.hasAttribute(Attribute::InReg)) {
10431         // If we are using vectorcall calling convention, a structure that is
10432         // passed InReg - is surely an HVA
10433         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10434             isa<StructType>(Arg.getType())) {
10435           // The first value of a structure is marked
10436           if (0 == Value)
10437             Flags.setHvaStart();
10438           Flags.setHva();
10439         }
10440         // Set InReg Flag
10441         Flags.setInReg();
10442       }
10443       if (Arg.hasAttribute(Attribute::StructRet))
10444         Flags.setSRet();
10445       if (Arg.hasAttribute(Attribute::SwiftSelf))
10446         Flags.setSwiftSelf();
10447       if (Arg.hasAttribute(Attribute::SwiftAsync))
10448         Flags.setSwiftAsync();
10449       if (Arg.hasAttribute(Attribute::SwiftError))
10450         Flags.setSwiftError();
10451       if (Arg.hasAttribute(Attribute::ByVal))
10452         Flags.setByVal();
10453       if (Arg.hasAttribute(Attribute::ByRef))
10454         Flags.setByRef();
10455       if (Arg.hasAttribute(Attribute::InAlloca)) {
10456         Flags.setInAlloca();
10457         // Set the byval flag for CCAssignFn callbacks that don't know about
10458         // inalloca.  This way we can know how many bytes we should've allocated
10459         // and how many bytes a callee cleanup function will pop.  If we port
10460         // inalloca to more targets, we'll have to add custom inalloca handling
10461         // in the various CC lowering callbacks.
10462         Flags.setByVal();
10463       }
10464       if (Arg.hasAttribute(Attribute::Preallocated)) {
10465         Flags.setPreallocated();
10466         // Set the byval flag for CCAssignFn callbacks that don't know about
10467         // preallocated.  This way we can know how many bytes we should've
10468         // allocated and how many bytes a callee cleanup function will pop.  If
10469         // we port preallocated to more targets, we'll have to add custom
10470         // preallocated handling in the various CC lowering callbacks.
10471         Flags.setByVal();
10472       }
10473 
10474       // Certain targets (such as MIPS), may have a different ABI alignment
10475       // for a type depending on the context. Give the target a chance to
10476       // specify the alignment it wants.
10477       const Align OriginalAlignment(
10478           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10479       Flags.setOrigAlign(OriginalAlignment);
10480 
10481       Align MemAlign;
10482       Type *ArgMemTy = nullptr;
10483       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10484           Flags.isByRef()) {
10485         if (!ArgMemTy)
10486           ArgMemTy = Arg.getPointeeInMemoryValueType();
10487 
10488         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10489 
10490         // For in-memory arguments, size and alignment should be passed from FE.
10491         // BE will guess if this info is not there but there are cases it cannot
10492         // get right.
10493         if (auto ParamAlign = Arg.getParamStackAlign())
10494           MemAlign = *ParamAlign;
10495         else if ((ParamAlign = Arg.getParamAlign()))
10496           MemAlign = *ParamAlign;
10497         else
10498           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10499         if (Flags.isByRef())
10500           Flags.setByRefSize(MemSize);
10501         else
10502           Flags.setByValSize(MemSize);
10503       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10504         MemAlign = *ParamAlign;
10505       } else {
10506         MemAlign = OriginalAlignment;
10507       }
10508       Flags.setMemAlign(MemAlign);
10509 
10510       if (Arg.hasAttribute(Attribute::Nest))
10511         Flags.setNest();
10512       if (NeedsRegBlock)
10513         Flags.setInConsecutiveRegs();
10514       if (ArgCopyElisionCandidates.count(&Arg))
10515         Flags.setCopyElisionCandidate();
10516       if (Arg.hasAttribute(Attribute::Returned))
10517         Flags.setReturned();
10518 
10519       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10520           *CurDAG->getContext(), F.getCallingConv(), VT);
10521       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10522           *CurDAG->getContext(), F.getCallingConv(), VT);
10523       for (unsigned i = 0; i != NumRegs; ++i) {
10524         // For scalable vectors, use the minimum size; individual targets
10525         // are responsible for handling scalable vector arguments and
10526         // return values.
10527         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10528                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10529         if (NumRegs > 1 && i == 0)
10530           MyFlags.Flags.setSplit();
10531         // if it isn't first piece, alignment must be 1
10532         else if (i > 0) {
10533           MyFlags.Flags.setOrigAlign(Align(1));
10534           if (i == NumRegs - 1)
10535             MyFlags.Flags.setSplitEnd();
10536         }
10537         Ins.push_back(MyFlags);
10538       }
10539       if (NeedsRegBlock && Value == NumValues - 1)
10540         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10541       PartBase += VT.getStoreSize().getKnownMinSize();
10542     }
10543   }
10544 
10545   // Call the target to set up the argument values.
10546   SmallVector<SDValue, 8> InVals;
10547   SDValue NewRoot = TLI->LowerFormalArguments(
10548       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10549 
10550   // Verify that the target's LowerFormalArguments behaved as expected.
10551   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10552          "LowerFormalArguments didn't return a valid chain!");
10553   assert(InVals.size() == Ins.size() &&
10554          "LowerFormalArguments didn't emit the correct number of values!");
10555   LLVM_DEBUG({
10556     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10557       assert(InVals[i].getNode() &&
10558              "LowerFormalArguments emitted a null value!");
10559       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10560              "LowerFormalArguments emitted a value with the wrong type!");
10561     }
10562   });
10563 
10564   // Update the DAG with the new chain value resulting from argument lowering.
10565   DAG.setRoot(NewRoot);
10566 
10567   // Set up the argument values.
10568   unsigned i = 0;
10569   if (!FuncInfo->CanLowerReturn) {
10570     // Create a virtual register for the sret pointer, and put in a copy
10571     // from the sret argument into it.
10572     SmallVector<EVT, 1> ValueVTs;
10573     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10574                     F.getReturnType()->getPointerTo(
10575                         DAG.getDataLayout().getAllocaAddrSpace()),
10576                     ValueVTs);
10577     MVT VT = ValueVTs[0].getSimpleVT();
10578     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10579     Optional<ISD::NodeType> AssertOp;
10580     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10581                                         nullptr, F.getCallingConv(), AssertOp);
10582 
10583     MachineFunction& MF = SDB->DAG.getMachineFunction();
10584     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10585     Register SRetReg =
10586         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10587     FuncInfo->DemoteRegister = SRetReg;
10588     NewRoot =
10589         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10590     DAG.setRoot(NewRoot);
10591 
10592     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10593     ++i;
10594   }
10595 
10596   SmallVector<SDValue, 4> Chains;
10597   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10598   for (const Argument &Arg : F.args()) {
10599     SmallVector<SDValue, 4> ArgValues;
10600     SmallVector<EVT, 4> ValueVTs;
10601     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10602     unsigned NumValues = ValueVTs.size();
10603     if (NumValues == 0)
10604       continue;
10605 
10606     bool ArgHasUses = !Arg.use_empty();
10607 
10608     // Elide the copying store if the target loaded this argument from a
10609     // suitable fixed stack object.
10610     if (Ins[i].Flags.isCopyElisionCandidate()) {
10611       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10612                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10613                              InVals[i], ArgHasUses);
10614     }
10615 
10616     // If this argument is unused then remember its value. It is used to generate
10617     // debugging information.
10618     bool isSwiftErrorArg =
10619         TLI->supportSwiftError() &&
10620         Arg.hasAttribute(Attribute::SwiftError);
10621     if (!ArgHasUses && !isSwiftErrorArg) {
10622       SDB->setUnusedArgValue(&Arg, InVals[i]);
10623 
10624       // Also remember any frame index for use in FastISel.
10625       if (FrameIndexSDNode *FI =
10626           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10627         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10628     }
10629 
10630     for (unsigned Val = 0; Val != NumValues; ++Val) {
10631       EVT VT = ValueVTs[Val];
10632       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10633                                                       F.getCallingConv(), VT);
10634       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10635           *CurDAG->getContext(), F.getCallingConv(), VT);
10636 
10637       // Even an apparent 'unused' swifterror argument needs to be returned. So
10638       // we do generate a copy for it that can be used on return from the
10639       // function.
10640       if (ArgHasUses || isSwiftErrorArg) {
10641         Optional<ISD::NodeType> AssertOp;
10642         if (Arg.hasAttribute(Attribute::SExt))
10643           AssertOp = ISD::AssertSext;
10644         else if (Arg.hasAttribute(Attribute::ZExt))
10645           AssertOp = ISD::AssertZext;
10646 
10647         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10648                                              PartVT, VT, nullptr,
10649                                              F.getCallingConv(), AssertOp));
10650       }
10651 
10652       i += NumParts;
10653     }
10654 
10655     // We don't need to do anything else for unused arguments.
10656     if (ArgValues.empty())
10657       continue;
10658 
10659     // Note down frame index.
10660     if (FrameIndexSDNode *FI =
10661         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10662       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10663 
10664     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10665                                      SDB->getCurSDLoc());
10666 
10667     SDB->setValue(&Arg, Res);
10668     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10669       // We want to associate the argument with the frame index, among
10670       // involved operands, that correspond to the lowest address. The
10671       // getCopyFromParts function, called earlier, is swapping the order of
10672       // the operands to BUILD_PAIR depending on endianness. The result of
10673       // that swapping is that the least significant bits of the argument will
10674       // be in the first operand of the BUILD_PAIR node, and the most
10675       // significant bits will be in the second operand.
10676       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10677       if (LoadSDNode *LNode =
10678           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10679         if (FrameIndexSDNode *FI =
10680             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10681           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10682     }
10683 
10684     // Analyses past this point are naive and don't expect an assertion.
10685     if (Res.getOpcode() == ISD::AssertZext)
10686       Res = Res.getOperand(0);
10687 
10688     // Update the SwiftErrorVRegDefMap.
10689     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10690       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10691       if (Register::isVirtualRegister(Reg))
10692         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10693                                    Reg);
10694     }
10695 
10696     // If this argument is live outside of the entry block, insert a copy from
10697     // wherever we got it to the vreg that other BB's will reference it as.
10698     if (Res.getOpcode() == ISD::CopyFromReg) {
10699       // If we can, though, try to skip creating an unnecessary vreg.
10700       // FIXME: This isn't very clean... it would be nice to make this more
10701       // general.
10702       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10703       if (Register::isVirtualRegister(Reg)) {
10704         FuncInfo->ValueMap[&Arg] = Reg;
10705         continue;
10706       }
10707     }
10708     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10709       FuncInfo->InitializeRegForValue(&Arg);
10710       SDB->CopyToExportRegsIfNeeded(&Arg);
10711     }
10712   }
10713 
10714   if (!Chains.empty()) {
10715     Chains.push_back(NewRoot);
10716     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10717   }
10718 
10719   DAG.setRoot(NewRoot);
10720 
10721   assert(i == InVals.size() && "Argument register count mismatch!");
10722 
10723   // If any argument copy elisions occurred and we have debug info, update the
10724   // stale frame indices used in the dbg.declare variable info table.
10725   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10726   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10727     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10728       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10729       if (I != ArgCopyElisionFrameIndexMap.end())
10730         VI.Slot = I->second;
10731     }
10732   }
10733 
10734   // Finally, if the target has anything special to do, allow it to do so.
10735   emitFunctionEntryCode();
10736 }
10737 
10738 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10739 /// ensure constants are generated when needed.  Remember the virtual registers
10740 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10741 /// directly add them, because expansion might result in multiple MBB's for one
10742 /// BB.  As such, the start of the BB might correspond to a different MBB than
10743 /// the end.
10744 void
10745 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10747   const Instruction *TI = LLVMBB->getTerminator();
10748 
10749   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10750 
10751   // Check PHI nodes in successors that expect a value to be available from this
10752   // block.
10753   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10754     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10755     if (!isa<PHINode>(SuccBB->begin())) continue;
10756     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10757 
10758     // If this terminator has multiple identical successors (common for
10759     // switches), only handle each succ once.
10760     if (!SuccsHandled.insert(SuccMBB).second)
10761       continue;
10762 
10763     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10764 
10765     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10766     // nodes and Machine PHI nodes, but the incoming operands have not been
10767     // emitted yet.
10768     for (const PHINode &PN : SuccBB->phis()) {
10769       // Ignore dead phi's.
10770       if (PN.use_empty())
10771         continue;
10772 
10773       // Skip empty types
10774       if (PN.getType()->isEmptyTy())
10775         continue;
10776 
10777       unsigned Reg;
10778       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10779 
10780       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10781         unsigned &RegOut = ConstantsOut[C];
10782         if (RegOut == 0) {
10783           RegOut = FuncInfo.CreateRegs(C);
10784           // We need to zero/sign extend ConstantInt phi operands to match
10785           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10786           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10787           if (auto *CI = dyn_cast<ConstantInt>(C))
10788             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10789                                                     : ISD::ZERO_EXTEND;
10790           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10791         }
10792         Reg = RegOut;
10793       } else {
10794         DenseMap<const Value *, Register>::iterator I =
10795           FuncInfo.ValueMap.find(PHIOp);
10796         if (I != FuncInfo.ValueMap.end())
10797           Reg = I->second;
10798         else {
10799           assert(isa<AllocaInst>(PHIOp) &&
10800                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10801                  "Didn't codegen value into a register!??");
10802           Reg = FuncInfo.CreateRegs(PHIOp);
10803           CopyValueToVirtualRegister(PHIOp, Reg);
10804         }
10805       }
10806 
10807       // Remember that this register needs to added to the machine PHI node as
10808       // the input for this MBB.
10809       SmallVector<EVT, 4> ValueVTs;
10810       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10811       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10812         EVT VT = ValueVTs[vti];
10813         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10814         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10815           FuncInfo.PHINodesToUpdate.push_back(
10816               std::make_pair(&*MBBI++, Reg + i));
10817         Reg += NumRegisters;
10818       }
10819     }
10820   }
10821 
10822   ConstantsOut.clear();
10823 }
10824 
10825 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10826   MachineFunction::iterator I(MBB);
10827   if (++I == FuncInfo.MF->end())
10828     return nullptr;
10829   return &*I;
10830 }
10831 
10832 /// During lowering new call nodes can be created (such as memset, etc.).
10833 /// Those will become new roots of the current DAG, but complications arise
10834 /// when they are tail calls. In such cases, the call lowering will update
10835 /// the root, but the builder still needs to know that a tail call has been
10836 /// lowered in order to avoid generating an additional return.
10837 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10838   // If the node is null, we do have a tail call.
10839   if (MaybeTC.getNode() != nullptr)
10840     DAG.setRoot(MaybeTC);
10841   else
10842     HasTailCall = true;
10843 }
10844 
10845 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10846                                         MachineBasicBlock *SwitchMBB,
10847                                         MachineBasicBlock *DefaultMBB) {
10848   MachineFunction *CurMF = FuncInfo.MF;
10849   MachineBasicBlock *NextMBB = nullptr;
10850   MachineFunction::iterator BBI(W.MBB);
10851   if (++BBI != FuncInfo.MF->end())
10852     NextMBB = &*BBI;
10853 
10854   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10855 
10856   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10857 
10858   if (Size == 2 && W.MBB == SwitchMBB) {
10859     // If any two of the cases has the same destination, and if one value
10860     // is the same as the other, but has one bit unset that the other has set,
10861     // use bit manipulation to do two compares at once.  For example:
10862     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10863     // TODO: This could be extended to merge any 2 cases in switches with 3
10864     // cases.
10865     // TODO: Handle cases where W.CaseBB != SwitchBB.
10866     CaseCluster &Small = *W.FirstCluster;
10867     CaseCluster &Big = *W.LastCluster;
10868 
10869     if (Small.Low == Small.High && Big.Low == Big.High &&
10870         Small.MBB == Big.MBB) {
10871       const APInt &SmallValue = Small.Low->getValue();
10872       const APInt &BigValue = Big.Low->getValue();
10873 
10874       // Check that there is only one bit different.
10875       APInt CommonBit = BigValue ^ SmallValue;
10876       if (CommonBit.isPowerOf2()) {
10877         SDValue CondLHS = getValue(Cond);
10878         EVT VT = CondLHS.getValueType();
10879         SDLoc DL = getCurSDLoc();
10880 
10881         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10882                                  DAG.getConstant(CommonBit, DL, VT));
10883         SDValue Cond = DAG.getSetCC(
10884             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10885             ISD::SETEQ);
10886 
10887         // Update successor info.
10888         // Both Small and Big will jump to Small.BB, so we sum up the
10889         // probabilities.
10890         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10891         if (BPI)
10892           addSuccessorWithProb(
10893               SwitchMBB, DefaultMBB,
10894               // The default destination is the first successor in IR.
10895               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10896         else
10897           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10898 
10899         // Insert the true branch.
10900         SDValue BrCond =
10901             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10902                         DAG.getBasicBlock(Small.MBB));
10903         // Insert the false branch.
10904         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10905                              DAG.getBasicBlock(DefaultMBB));
10906 
10907         DAG.setRoot(BrCond);
10908         return;
10909       }
10910     }
10911   }
10912 
10913   if (TM.getOptLevel() != CodeGenOpt::None) {
10914     // Here, we order cases by probability so the most likely case will be
10915     // checked first. However, two clusters can have the same probability in
10916     // which case their relative ordering is non-deterministic. So we use Low
10917     // as a tie-breaker as clusters are guaranteed to never overlap.
10918     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10919                [](const CaseCluster &a, const CaseCluster &b) {
10920       return a.Prob != b.Prob ?
10921              a.Prob > b.Prob :
10922              a.Low->getValue().slt(b.Low->getValue());
10923     });
10924 
10925     // Rearrange the case blocks so that the last one falls through if possible
10926     // without changing the order of probabilities.
10927     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10928       --I;
10929       if (I->Prob > W.LastCluster->Prob)
10930         break;
10931       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10932         std::swap(*I, *W.LastCluster);
10933         break;
10934       }
10935     }
10936   }
10937 
10938   // Compute total probability.
10939   BranchProbability DefaultProb = W.DefaultProb;
10940   BranchProbability UnhandledProbs = DefaultProb;
10941   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10942     UnhandledProbs += I->Prob;
10943 
10944   MachineBasicBlock *CurMBB = W.MBB;
10945   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10946     bool FallthroughUnreachable = false;
10947     MachineBasicBlock *Fallthrough;
10948     if (I == W.LastCluster) {
10949       // For the last cluster, fall through to the default destination.
10950       Fallthrough = DefaultMBB;
10951       FallthroughUnreachable = isa<UnreachableInst>(
10952           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10953     } else {
10954       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10955       CurMF->insert(BBI, Fallthrough);
10956       // Put Cond in a virtual register to make it available from the new blocks.
10957       ExportFromCurrentBlock(Cond);
10958     }
10959     UnhandledProbs -= I->Prob;
10960 
10961     switch (I->Kind) {
10962       case CC_JumpTable: {
10963         // FIXME: Optimize away range check based on pivot comparisons.
10964         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10965         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10966 
10967         // The jump block hasn't been inserted yet; insert it here.
10968         MachineBasicBlock *JumpMBB = JT->MBB;
10969         CurMF->insert(BBI, JumpMBB);
10970 
10971         auto JumpProb = I->Prob;
10972         auto FallthroughProb = UnhandledProbs;
10973 
10974         // If the default statement is a target of the jump table, we evenly
10975         // distribute the default probability to successors of CurMBB. Also
10976         // update the probability on the edge from JumpMBB to Fallthrough.
10977         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10978                                               SE = JumpMBB->succ_end();
10979              SI != SE; ++SI) {
10980           if (*SI == DefaultMBB) {
10981             JumpProb += DefaultProb / 2;
10982             FallthroughProb -= DefaultProb / 2;
10983             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10984             JumpMBB->normalizeSuccProbs();
10985             break;
10986           }
10987         }
10988 
10989         if (FallthroughUnreachable)
10990           JTH->FallthroughUnreachable = true;
10991 
10992         if (!JTH->FallthroughUnreachable)
10993           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10994         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10995         CurMBB->normalizeSuccProbs();
10996 
10997         // The jump table header will be inserted in our current block, do the
10998         // range check, and fall through to our fallthrough block.
10999         JTH->HeaderBB = CurMBB;
11000         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11001 
11002         // If we're in the right place, emit the jump table header right now.
11003         if (CurMBB == SwitchMBB) {
11004           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11005           JTH->Emitted = true;
11006         }
11007         break;
11008       }
11009       case CC_BitTests: {
11010         // FIXME: Optimize away range check based on pivot comparisons.
11011         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11012 
11013         // The bit test blocks haven't been inserted yet; insert them here.
11014         for (BitTestCase &BTC : BTB->Cases)
11015           CurMF->insert(BBI, BTC.ThisBB);
11016 
11017         // Fill in fields of the BitTestBlock.
11018         BTB->Parent = CurMBB;
11019         BTB->Default = Fallthrough;
11020 
11021         BTB->DefaultProb = UnhandledProbs;
11022         // If the cases in bit test don't form a contiguous range, we evenly
11023         // distribute the probability on the edge to Fallthrough to two
11024         // successors of CurMBB.
11025         if (!BTB->ContiguousRange) {
11026           BTB->Prob += DefaultProb / 2;
11027           BTB->DefaultProb -= DefaultProb / 2;
11028         }
11029 
11030         if (FallthroughUnreachable)
11031           BTB->FallthroughUnreachable = true;
11032 
11033         // If we're in the right place, emit the bit test header right now.
11034         if (CurMBB == SwitchMBB) {
11035           visitBitTestHeader(*BTB, SwitchMBB);
11036           BTB->Emitted = true;
11037         }
11038         break;
11039       }
11040       case CC_Range: {
11041         const Value *RHS, *LHS, *MHS;
11042         ISD::CondCode CC;
11043         if (I->Low == I->High) {
11044           // Check Cond == I->Low.
11045           CC = ISD::SETEQ;
11046           LHS = Cond;
11047           RHS=I->Low;
11048           MHS = nullptr;
11049         } else {
11050           // Check I->Low <= Cond <= I->High.
11051           CC = ISD::SETLE;
11052           LHS = I->Low;
11053           MHS = Cond;
11054           RHS = I->High;
11055         }
11056 
11057         // If Fallthrough is unreachable, fold away the comparison.
11058         if (FallthroughUnreachable)
11059           CC = ISD::SETTRUE;
11060 
11061         // The false probability is the sum of all unhandled cases.
11062         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11063                      getCurSDLoc(), I->Prob, UnhandledProbs);
11064 
11065         if (CurMBB == SwitchMBB)
11066           visitSwitchCase(CB, SwitchMBB);
11067         else
11068           SL->SwitchCases.push_back(CB);
11069 
11070         break;
11071       }
11072     }
11073     CurMBB = Fallthrough;
11074   }
11075 }
11076 
11077 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11078                                               CaseClusterIt First,
11079                                               CaseClusterIt Last) {
11080   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11081     if (X.Prob != CC.Prob)
11082       return X.Prob > CC.Prob;
11083 
11084     // Ties are broken by comparing the case value.
11085     return X.Low->getValue().slt(CC.Low->getValue());
11086   });
11087 }
11088 
11089 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11090                                         const SwitchWorkListItem &W,
11091                                         Value *Cond,
11092                                         MachineBasicBlock *SwitchMBB) {
11093   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11094          "Clusters not sorted?");
11095 
11096   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11097 
11098   // Balance the tree based on branch probabilities to create a near-optimal (in
11099   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11100   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11101   CaseClusterIt LastLeft = W.FirstCluster;
11102   CaseClusterIt FirstRight = W.LastCluster;
11103   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11104   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11105 
11106   // Move LastLeft and FirstRight towards each other from opposite directions to
11107   // find a partitioning of the clusters which balances the probability on both
11108   // sides. If LeftProb and RightProb are equal, alternate which side is
11109   // taken to ensure 0-probability nodes are distributed evenly.
11110   unsigned I = 0;
11111   while (LastLeft + 1 < FirstRight) {
11112     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11113       LeftProb += (++LastLeft)->Prob;
11114     else
11115       RightProb += (--FirstRight)->Prob;
11116     I++;
11117   }
11118 
11119   while (true) {
11120     // Our binary search tree differs from a typical BST in that ours can have up
11121     // to three values in each leaf. The pivot selection above doesn't take that
11122     // into account, which means the tree might require more nodes and be less
11123     // efficient. We compensate for this here.
11124 
11125     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11126     unsigned NumRight = W.LastCluster - FirstRight + 1;
11127 
11128     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11129       // If one side has less than 3 clusters, and the other has more than 3,
11130       // consider taking a cluster from the other side.
11131 
11132       if (NumLeft < NumRight) {
11133         // Consider moving the first cluster on the right to the left side.
11134         CaseCluster &CC = *FirstRight;
11135         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11136         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11137         if (LeftSideRank <= RightSideRank) {
11138           // Moving the cluster to the left does not demote it.
11139           ++LastLeft;
11140           ++FirstRight;
11141           continue;
11142         }
11143       } else {
11144         assert(NumRight < NumLeft);
11145         // Consider moving the last element on the left to the right side.
11146         CaseCluster &CC = *LastLeft;
11147         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11148         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11149         if (RightSideRank <= LeftSideRank) {
11150           // Moving the cluster to the right does not demot it.
11151           --LastLeft;
11152           --FirstRight;
11153           continue;
11154         }
11155       }
11156     }
11157     break;
11158   }
11159 
11160   assert(LastLeft + 1 == FirstRight);
11161   assert(LastLeft >= W.FirstCluster);
11162   assert(FirstRight <= W.LastCluster);
11163 
11164   // Use the first element on the right as pivot since we will make less-than
11165   // comparisons against it.
11166   CaseClusterIt PivotCluster = FirstRight;
11167   assert(PivotCluster > W.FirstCluster);
11168   assert(PivotCluster <= W.LastCluster);
11169 
11170   CaseClusterIt FirstLeft = W.FirstCluster;
11171   CaseClusterIt LastRight = W.LastCluster;
11172 
11173   const ConstantInt *Pivot = PivotCluster->Low;
11174 
11175   // New blocks will be inserted immediately after the current one.
11176   MachineFunction::iterator BBI(W.MBB);
11177   ++BBI;
11178 
11179   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11180   // we can branch to its destination directly if it's squeezed exactly in
11181   // between the known lower bound and Pivot - 1.
11182   MachineBasicBlock *LeftMBB;
11183   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11184       FirstLeft->Low == W.GE &&
11185       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11186     LeftMBB = FirstLeft->MBB;
11187   } else {
11188     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11189     FuncInfo.MF->insert(BBI, LeftMBB);
11190     WorkList.push_back(
11191         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11192     // Put Cond in a virtual register to make it available from the new blocks.
11193     ExportFromCurrentBlock(Cond);
11194   }
11195 
11196   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11197   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11198   // directly if RHS.High equals the current upper bound.
11199   MachineBasicBlock *RightMBB;
11200   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11201       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11202     RightMBB = FirstRight->MBB;
11203   } else {
11204     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11205     FuncInfo.MF->insert(BBI, RightMBB);
11206     WorkList.push_back(
11207         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11208     // Put Cond in a virtual register to make it available from the new blocks.
11209     ExportFromCurrentBlock(Cond);
11210   }
11211 
11212   // Create the CaseBlock record that will be used to lower the branch.
11213   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11214                getCurSDLoc(), LeftProb, RightProb);
11215 
11216   if (W.MBB == SwitchMBB)
11217     visitSwitchCase(CB, SwitchMBB);
11218   else
11219     SL->SwitchCases.push_back(CB);
11220 }
11221 
11222 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11223 // from the swith statement.
11224 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11225                                             BranchProbability PeeledCaseProb) {
11226   if (PeeledCaseProb == BranchProbability::getOne())
11227     return BranchProbability::getZero();
11228   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11229 
11230   uint32_t Numerator = CaseProb.getNumerator();
11231   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11232   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11233 }
11234 
11235 // Try to peel the top probability case if it exceeds the threshold.
11236 // Return current MachineBasicBlock for the switch statement if the peeling
11237 // does not occur.
11238 // If the peeling is performed, return the newly created MachineBasicBlock
11239 // for the peeled switch statement. Also update Clusters to remove the peeled
11240 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11241 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11242     const SwitchInst &SI, CaseClusterVector &Clusters,
11243     BranchProbability &PeeledCaseProb) {
11244   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11245   // Don't perform if there is only one cluster or optimizing for size.
11246   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11247       TM.getOptLevel() == CodeGenOpt::None ||
11248       SwitchMBB->getParent()->getFunction().hasMinSize())
11249     return SwitchMBB;
11250 
11251   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11252   unsigned PeeledCaseIndex = 0;
11253   bool SwitchPeeled = false;
11254   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11255     CaseCluster &CC = Clusters[Index];
11256     if (CC.Prob < TopCaseProb)
11257       continue;
11258     TopCaseProb = CC.Prob;
11259     PeeledCaseIndex = Index;
11260     SwitchPeeled = true;
11261   }
11262   if (!SwitchPeeled)
11263     return SwitchMBB;
11264 
11265   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11266                     << TopCaseProb << "\n");
11267 
11268   // Record the MBB for the peeled switch statement.
11269   MachineFunction::iterator BBI(SwitchMBB);
11270   ++BBI;
11271   MachineBasicBlock *PeeledSwitchMBB =
11272       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11273   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11274 
11275   ExportFromCurrentBlock(SI.getCondition());
11276   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11277   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11278                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11279   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11280 
11281   Clusters.erase(PeeledCaseIt);
11282   for (CaseCluster &CC : Clusters) {
11283     LLVM_DEBUG(
11284         dbgs() << "Scale the probablity for one cluster, before scaling: "
11285                << CC.Prob << "\n");
11286     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11287     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11288   }
11289   PeeledCaseProb = TopCaseProb;
11290   return PeeledSwitchMBB;
11291 }
11292 
11293 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11294   // Extract cases from the switch.
11295   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11296   CaseClusterVector Clusters;
11297   Clusters.reserve(SI.getNumCases());
11298   for (auto I : SI.cases()) {
11299     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11300     const ConstantInt *CaseVal = I.getCaseValue();
11301     BranchProbability Prob =
11302         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11303             : BranchProbability(1, SI.getNumCases() + 1);
11304     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11305   }
11306 
11307   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11308 
11309   // Cluster adjacent cases with the same destination. We do this at all
11310   // optimization levels because it's cheap to do and will make codegen faster
11311   // if there are many clusters.
11312   sortAndRangeify(Clusters);
11313 
11314   // The branch probablity of the peeled case.
11315   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11316   MachineBasicBlock *PeeledSwitchMBB =
11317       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11318 
11319   // If there is only the default destination, jump there directly.
11320   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11321   if (Clusters.empty()) {
11322     assert(PeeledSwitchMBB == SwitchMBB);
11323     SwitchMBB->addSuccessor(DefaultMBB);
11324     if (DefaultMBB != NextBlock(SwitchMBB)) {
11325       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11326                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11327     }
11328     return;
11329   }
11330 
11331   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11332   SL->findBitTestClusters(Clusters, &SI);
11333 
11334   LLVM_DEBUG({
11335     dbgs() << "Case clusters: ";
11336     for (const CaseCluster &C : Clusters) {
11337       if (C.Kind == CC_JumpTable)
11338         dbgs() << "JT:";
11339       if (C.Kind == CC_BitTests)
11340         dbgs() << "BT:";
11341 
11342       C.Low->getValue().print(dbgs(), true);
11343       if (C.Low != C.High) {
11344         dbgs() << '-';
11345         C.High->getValue().print(dbgs(), true);
11346       }
11347       dbgs() << ' ';
11348     }
11349     dbgs() << '\n';
11350   });
11351 
11352   assert(!Clusters.empty());
11353   SwitchWorkList WorkList;
11354   CaseClusterIt First = Clusters.begin();
11355   CaseClusterIt Last = Clusters.end() - 1;
11356   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11357   // Scale the branchprobability for DefaultMBB if the peel occurs and
11358   // DefaultMBB is not replaced.
11359   if (PeeledCaseProb != BranchProbability::getZero() &&
11360       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11361     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11362   WorkList.push_back(
11363       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11364 
11365   while (!WorkList.empty()) {
11366     SwitchWorkListItem W = WorkList.pop_back_val();
11367     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11368 
11369     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11370         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11371       // For optimized builds, lower large range as a balanced binary tree.
11372       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11373       continue;
11374     }
11375 
11376     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11377   }
11378 }
11379 
11380 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11382   auto DL = getCurSDLoc();
11383   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11384   setValue(&I, DAG.getStepVector(DL, ResultVT));
11385 }
11386 
11387 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11389   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11390 
11391   SDLoc DL = getCurSDLoc();
11392   SDValue V = getValue(I.getOperand(0));
11393   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11394 
11395   if (VT.isScalableVector()) {
11396     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11397     return;
11398   }
11399 
11400   // Use VECTOR_SHUFFLE for the fixed-length vector
11401   // to maintain existing behavior.
11402   SmallVector<int, 8> Mask;
11403   unsigned NumElts = VT.getVectorMinNumElements();
11404   for (unsigned i = 0; i != NumElts; ++i)
11405     Mask.push_back(NumElts - 1 - i);
11406 
11407   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11408 }
11409 
11410 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11411   SmallVector<EVT, 4> ValueVTs;
11412   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11413                   ValueVTs);
11414   unsigned NumValues = ValueVTs.size();
11415   if (NumValues == 0) return;
11416 
11417   SmallVector<SDValue, 4> Values(NumValues);
11418   SDValue Op = getValue(I.getOperand(0));
11419 
11420   for (unsigned i = 0; i != NumValues; ++i)
11421     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11422                             SDValue(Op.getNode(), Op.getResNo() + i));
11423 
11424   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11425                            DAG.getVTList(ValueVTs), Values));
11426 }
11427 
11428 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11430   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11431 
11432   SDLoc DL = getCurSDLoc();
11433   SDValue V1 = getValue(I.getOperand(0));
11434   SDValue V2 = getValue(I.getOperand(1));
11435   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11436 
11437   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11438   if (VT.isScalableVector()) {
11439     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11440     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11441                              DAG.getConstant(Imm, DL, IdxVT)));
11442     return;
11443   }
11444 
11445   unsigned NumElts = VT.getVectorNumElements();
11446 
11447   uint64_t Idx = (NumElts + Imm) % NumElts;
11448 
11449   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11450   SmallVector<int, 8> Mask;
11451   for (unsigned i = 0; i < NumElts; ++i)
11452     Mask.push_back(Idx + i);
11453   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11454 }
11455