xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 04bb32e58a6592e70148d41c999eb3949268328c)
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       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1699     }
1700 
1701     llvm_unreachable("Unknown vector constant");
1702   }
1703 
1704   // If this is a static alloca, generate it as the frameindex instead of
1705   // computation.
1706   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1707     DenseMap<const AllocaInst*, int>::iterator SI =
1708       FuncInfo.StaticAllocaMap.find(AI);
1709     if (SI != FuncInfo.StaticAllocaMap.end())
1710       return DAG.getFrameIndex(SI->second,
1711                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1712   }
1713 
1714   // If this is an instruction which fast-isel has deferred, select it now.
1715   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1716     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1717 
1718     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1719                      Inst->getType(), None);
1720     SDValue Chain = DAG.getEntryNode();
1721     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1722   }
1723 
1724   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1725     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1726 
1727   if (const auto *BB = dyn_cast<BasicBlock>(V))
1728     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1729 
1730   llvm_unreachable("Can't get register for value!");
1731 }
1732 
1733 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1734   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1735   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1736   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1737   bool IsSEH = isAsynchronousEHPersonality(Pers);
1738   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1739   if (!IsSEH)
1740     CatchPadMBB->setIsEHScopeEntry();
1741   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1742   if (IsMSVCCXX || IsCoreCLR)
1743     CatchPadMBB->setIsEHFuncletEntry();
1744 }
1745 
1746 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1747   // Update machine-CFG edge.
1748   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1749   FuncInfo.MBB->addSuccessor(TargetMBB);
1750   TargetMBB->setIsEHCatchretTarget(true);
1751   DAG.getMachineFunction().setHasEHCatchret(true);
1752 
1753   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1754   bool IsSEH = isAsynchronousEHPersonality(Pers);
1755   if (IsSEH) {
1756     // If this is not a fall-through branch or optimizations are switched off,
1757     // emit the branch.
1758     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1759         TM.getOptLevel() == CodeGenOpt::None)
1760       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1761                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1762     return;
1763   }
1764 
1765   // Figure out the funclet membership for the catchret's successor.
1766   // This will be used by the FuncletLayout pass to determine how to order the
1767   // BB's.
1768   // A 'catchret' returns to the outer scope's color.
1769   Value *ParentPad = I.getCatchSwitchParentPad();
1770   const BasicBlock *SuccessorColor;
1771   if (isa<ConstantTokenNone>(ParentPad))
1772     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1773   else
1774     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1775   assert(SuccessorColor && "No parent funclet for catchret!");
1776   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1777   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1778 
1779   // Create the terminator node.
1780   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1781                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1782                             DAG.getBasicBlock(SuccessorColorMBB));
1783   DAG.setRoot(Ret);
1784 }
1785 
1786 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1787   // Don't emit any special code for the cleanuppad instruction. It just marks
1788   // the start of an EH scope/funclet.
1789   FuncInfo.MBB->setIsEHScopeEntry();
1790   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1791   if (Pers != EHPersonality::Wasm_CXX) {
1792     FuncInfo.MBB->setIsEHFuncletEntry();
1793     FuncInfo.MBB->setIsCleanupFuncletEntry();
1794   }
1795 }
1796 
1797 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1798 // not match, it is OK to add only the first unwind destination catchpad to the
1799 // successors, because there will be at least one invoke instruction within the
1800 // catch scope that points to the next unwind destination, if one exists, so
1801 // CFGSort cannot mess up with BB sorting order.
1802 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1803 // call within them, and catchpads only consisting of 'catch (...)' have a
1804 // '__cxa_end_catch' call within them, both of which generate invokes in case
1805 // the next unwind destination exists, i.e., the next unwind destination is not
1806 // the caller.)
1807 //
1808 // Having at most one EH pad successor is also simpler and helps later
1809 // transformations.
1810 //
1811 // For example,
1812 // current:
1813 //   invoke void @foo to ... unwind label %catch.dispatch
1814 // catch.dispatch:
1815 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1816 // catch.start:
1817 //   ...
1818 //   ... in this BB or some other child BB dominated by this BB there will be an
1819 //   invoke that points to 'next' BB as an unwind destination
1820 //
1821 // next: ; We don't need to add this to 'current' BB's successor
1822 //   ...
1823 static void findWasmUnwindDestinations(
1824     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1825     BranchProbability Prob,
1826     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1827         &UnwindDests) {
1828   while (EHPadBB) {
1829     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1830     if (isa<CleanupPadInst>(Pad)) {
1831       // Stop on cleanup pads.
1832       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1833       UnwindDests.back().first->setIsEHScopeEntry();
1834       break;
1835     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1836       // Add the catchpad handlers to the possible destinations. We don't
1837       // continue to the unwind destination of the catchswitch for wasm.
1838       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1839         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1840         UnwindDests.back().first->setIsEHScopeEntry();
1841       }
1842       break;
1843     } else {
1844       continue;
1845     }
1846   }
1847 }
1848 
1849 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1850 /// many places it could ultimately go. In the IR, we have a single unwind
1851 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1852 /// This function skips over imaginary basic blocks that hold catchswitch
1853 /// instructions, and finds all the "real" machine
1854 /// basic block destinations. As those destinations may not be successors of
1855 /// EHPadBB, here we also calculate the edge probability to those destinations.
1856 /// The passed-in Prob is the edge probability to EHPadBB.
1857 static void findUnwindDestinations(
1858     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1859     BranchProbability Prob,
1860     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1861         &UnwindDests) {
1862   EHPersonality Personality =
1863     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1864   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1865   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1866   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1867   bool IsSEH = isAsynchronousEHPersonality(Personality);
1868 
1869   if (IsWasmCXX) {
1870     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1871     assert(UnwindDests.size() <= 1 &&
1872            "There should be at most one unwind destination for wasm");
1873     return;
1874   }
1875 
1876   while (EHPadBB) {
1877     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1878     BasicBlock *NewEHPadBB = nullptr;
1879     if (isa<LandingPadInst>(Pad)) {
1880       // Stop on landingpads. They are not funclets.
1881       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1882       break;
1883     } else if (isa<CleanupPadInst>(Pad)) {
1884       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1885       // personalities.
1886       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1887       UnwindDests.back().first->setIsEHScopeEntry();
1888       UnwindDests.back().first->setIsEHFuncletEntry();
1889       break;
1890     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1891       // Add the catchpad handlers to the possible destinations.
1892       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1893         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1894         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1895         if (IsMSVCCXX || IsCoreCLR)
1896           UnwindDests.back().first->setIsEHFuncletEntry();
1897         if (!IsSEH)
1898           UnwindDests.back().first->setIsEHScopeEntry();
1899       }
1900       NewEHPadBB = CatchSwitch->getUnwindDest();
1901     } else {
1902       continue;
1903     }
1904 
1905     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1906     if (BPI && NewEHPadBB)
1907       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1908     EHPadBB = NewEHPadBB;
1909   }
1910 }
1911 
1912 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1913   // Update successor info.
1914   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1915   auto UnwindDest = I.getUnwindDest();
1916   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1917   BranchProbability UnwindDestProb =
1918       (BPI && UnwindDest)
1919           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1920           : BranchProbability::getZero();
1921   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1922   for (auto &UnwindDest : UnwindDests) {
1923     UnwindDest.first->setIsEHPad();
1924     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1925   }
1926   FuncInfo.MBB->normalizeSuccProbs();
1927 
1928   // Create the terminator node.
1929   SDValue Ret =
1930       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1931   DAG.setRoot(Ret);
1932 }
1933 
1934 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1935   report_fatal_error("visitCatchSwitch not yet implemented!");
1936 }
1937 
1938 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1940   auto &DL = DAG.getDataLayout();
1941   SDValue Chain = getControlRoot();
1942   SmallVector<ISD::OutputArg, 8> Outs;
1943   SmallVector<SDValue, 8> OutVals;
1944 
1945   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1946   // lower
1947   //
1948   //   %val = call <ty> @llvm.experimental.deoptimize()
1949   //   ret <ty> %val
1950   //
1951   // differently.
1952   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1953     LowerDeoptimizingReturn();
1954     return;
1955   }
1956 
1957   if (!FuncInfo.CanLowerReturn) {
1958     unsigned DemoteReg = FuncInfo.DemoteRegister;
1959     const Function *F = I.getParent()->getParent();
1960 
1961     // Emit a store of the return value through the virtual register.
1962     // Leave Outs empty so that LowerReturn won't try to load return
1963     // registers the usual way.
1964     SmallVector<EVT, 1> PtrValueVTs;
1965     ComputeValueVTs(TLI, DL,
1966                     F->getReturnType()->getPointerTo(
1967                         DAG.getDataLayout().getAllocaAddrSpace()),
1968                     PtrValueVTs);
1969 
1970     SDValue RetPtr =
1971         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1972     SDValue RetOp = getValue(I.getOperand(0));
1973 
1974     SmallVector<EVT, 4> ValueVTs, MemVTs;
1975     SmallVector<uint64_t, 4> Offsets;
1976     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1977                     &Offsets);
1978     unsigned NumValues = ValueVTs.size();
1979 
1980     SmallVector<SDValue, 4> Chains(NumValues);
1981     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1982     for (unsigned i = 0; i != NumValues; ++i) {
1983       // An aggregate return value cannot wrap around the address space, so
1984       // offsets to its parts don't wrap either.
1985       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1986                                            TypeSize::Fixed(Offsets[i]));
1987 
1988       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1989       if (MemVTs[i] != ValueVTs[i])
1990         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1991       Chains[i] = DAG.getStore(
1992           Chain, getCurSDLoc(), Val,
1993           // FIXME: better loc info would be nice.
1994           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1995           commonAlignment(BaseAlign, Offsets[i]));
1996     }
1997 
1998     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1999                         MVT::Other, Chains);
2000   } else if (I.getNumOperands() != 0) {
2001     SmallVector<EVT, 4> ValueVTs;
2002     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2003     unsigned NumValues = ValueVTs.size();
2004     if (NumValues) {
2005       SDValue RetOp = getValue(I.getOperand(0));
2006 
2007       const Function *F = I.getParent()->getParent();
2008 
2009       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2010           I.getOperand(0)->getType(), F->getCallingConv(),
2011           /*IsVarArg*/ false, DL);
2012 
2013       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2014       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2015         ExtendKind = ISD::SIGN_EXTEND;
2016       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2017         ExtendKind = ISD::ZERO_EXTEND;
2018 
2019       LLVMContext &Context = F->getContext();
2020       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2021 
2022       for (unsigned j = 0; j != NumValues; ++j) {
2023         EVT VT = ValueVTs[j];
2024 
2025         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2026           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2027 
2028         CallingConv::ID CC = F->getCallingConv();
2029 
2030         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2031         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2032         SmallVector<SDValue, 4> Parts(NumParts);
2033         getCopyToParts(DAG, getCurSDLoc(),
2034                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2035                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2036 
2037         // 'inreg' on function refers to return value
2038         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2039         if (RetInReg)
2040           Flags.setInReg();
2041 
2042         if (I.getOperand(0)->getType()->isPointerTy()) {
2043           Flags.setPointer();
2044           Flags.setPointerAddrSpace(
2045               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2046         }
2047 
2048         if (NeedsRegBlock) {
2049           Flags.setInConsecutiveRegs();
2050           if (j == NumValues - 1)
2051             Flags.setInConsecutiveRegsLast();
2052         }
2053 
2054         // Propagate extension type if any
2055         if (ExtendKind == ISD::SIGN_EXTEND)
2056           Flags.setSExt();
2057         else if (ExtendKind == ISD::ZERO_EXTEND)
2058           Flags.setZExt();
2059 
2060         for (unsigned i = 0; i < NumParts; ++i) {
2061           Outs.push_back(ISD::OutputArg(Flags,
2062                                         Parts[i].getValueType().getSimpleVT(),
2063                                         VT, /*isfixed=*/true, 0, 0));
2064           OutVals.push_back(Parts[i]);
2065         }
2066       }
2067     }
2068   }
2069 
2070   // Push in swifterror virtual register as the last element of Outs. This makes
2071   // sure swifterror virtual register will be returned in the swifterror
2072   // physical register.
2073   const Function *F = I.getParent()->getParent();
2074   if (TLI.supportSwiftError() &&
2075       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2076     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2077     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2078     Flags.setSwiftError();
2079     Outs.push_back(ISD::OutputArg(
2080         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2081         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2082     // Create SDNode for the swifterror virtual register.
2083     OutVals.push_back(
2084         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2085                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2086                         EVT(TLI.getPointerTy(DL))));
2087   }
2088 
2089   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2090   CallingConv::ID CallConv =
2091     DAG.getMachineFunction().getFunction().getCallingConv();
2092   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2093       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2094 
2095   // Verify that the target's LowerReturn behaved as expected.
2096   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2097          "LowerReturn didn't return a valid chain!");
2098 
2099   // Update the DAG with the new chain value resulting from return lowering.
2100   DAG.setRoot(Chain);
2101 }
2102 
2103 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2104 /// created for it, emit nodes to copy the value into the virtual
2105 /// registers.
2106 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2107   // Skip empty types
2108   if (V->getType()->isEmptyTy())
2109     return;
2110 
2111   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2112   if (VMI != FuncInfo.ValueMap.end()) {
2113     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2114     CopyValueToVirtualRegister(V, VMI->second);
2115   }
2116 }
2117 
2118 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2119 /// the current basic block, add it to ValueMap now so that we'll get a
2120 /// CopyTo/FromReg.
2121 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2122   // No need to export constants.
2123   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2124 
2125   // Already exported?
2126   if (FuncInfo.isExportedInst(V)) return;
2127 
2128   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2129   CopyValueToVirtualRegister(V, Reg);
2130 }
2131 
2132 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2133                                                      const BasicBlock *FromBB) {
2134   // The operands of the setcc have to be in this block.  We don't know
2135   // how to export them from some other block.
2136   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2137     // Can export from current BB.
2138     if (VI->getParent() == FromBB)
2139       return true;
2140 
2141     // Is already exported, noop.
2142     return FuncInfo.isExportedInst(V);
2143   }
2144 
2145   // If this is an argument, we can export it if the BB is the entry block or
2146   // if it is already exported.
2147   if (isa<Argument>(V)) {
2148     if (FromBB->isEntryBlock())
2149       return true;
2150 
2151     // Otherwise, can only export this if it is already exported.
2152     return FuncInfo.isExportedInst(V);
2153   }
2154 
2155   // Otherwise, constants can always be exported.
2156   return true;
2157 }
2158 
2159 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2160 BranchProbability
2161 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2162                                         const MachineBasicBlock *Dst) const {
2163   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2164   const BasicBlock *SrcBB = Src->getBasicBlock();
2165   const BasicBlock *DstBB = Dst->getBasicBlock();
2166   if (!BPI) {
2167     // If BPI is not available, set the default probability as 1 / N, where N is
2168     // the number of successors.
2169     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2170     return BranchProbability(1, SuccSize);
2171   }
2172   return BPI->getEdgeProbability(SrcBB, DstBB);
2173 }
2174 
2175 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2176                                                MachineBasicBlock *Dst,
2177                                                BranchProbability Prob) {
2178   if (!FuncInfo.BPI)
2179     Src->addSuccessorWithoutProb(Dst);
2180   else {
2181     if (Prob.isUnknown())
2182       Prob = getEdgeProbability(Src, Dst);
2183     Src->addSuccessor(Dst, Prob);
2184   }
2185 }
2186 
2187 static bool InBlock(const Value *V, const BasicBlock *BB) {
2188   if (const Instruction *I = dyn_cast<Instruction>(V))
2189     return I->getParent() == BB;
2190   return true;
2191 }
2192 
2193 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2194 /// This function emits a branch and is used at the leaves of an OR or an
2195 /// AND operator tree.
2196 void
2197 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2198                                                   MachineBasicBlock *TBB,
2199                                                   MachineBasicBlock *FBB,
2200                                                   MachineBasicBlock *CurBB,
2201                                                   MachineBasicBlock *SwitchBB,
2202                                                   BranchProbability TProb,
2203                                                   BranchProbability FProb,
2204                                                   bool InvertCond) {
2205   const BasicBlock *BB = CurBB->getBasicBlock();
2206 
2207   // If the leaf of the tree is a comparison, merge the condition into
2208   // the caseblock.
2209   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2210     // The operands of the cmp have to be in this block.  We don't know
2211     // how to export them from some other block.  If this is the first block
2212     // of the sequence, no exporting is needed.
2213     if (CurBB == SwitchBB ||
2214         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2215          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2216       ISD::CondCode Condition;
2217       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2218         ICmpInst::Predicate Pred =
2219             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2220         Condition = getICmpCondCode(Pred);
2221       } else {
2222         const FCmpInst *FC = cast<FCmpInst>(Cond);
2223         FCmpInst::Predicate Pred =
2224             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2225         Condition = getFCmpCondCode(Pred);
2226         if (TM.Options.NoNaNsFPMath)
2227           Condition = getFCmpCodeWithoutNaN(Condition);
2228       }
2229 
2230       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2231                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2232       SL->SwitchCases.push_back(CB);
2233       return;
2234     }
2235   }
2236 
2237   // Create a CaseBlock record representing this branch.
2238   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2239   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2240                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2241   SL->SwitchCases.push_back(CB);
2242 }
2243 
2244 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2245                                                MachineBasicBlock *TBB,
2246                                                MachineBasicBlock *FBB,
2247                                                MachineBasicBlock *CurBB,
2248                                                MachineBasicBlock *SwitchBB,
2249                                                Instruction::BinaryOps Opc,
2250                                                BranchProbability TProb,
2251                                                BranchProbability FProb,
2252                                                bool InvertCond) {
2253   // Skip over not part of the tree and remember to invert op and operands at
2254   // next level.
2255   Value *NotCond;
2256   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2257       InBlock(NotCond, CurBB->getBasicBlock())) {
2258     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2259                          !InvertCond);
2260     return;
2261   }
2262 
2263   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2264   const Value *BOpOp0, *BOpOp1;
2265   // Compute the effective opcode for Cond, taking into account whether it needs
2266   // to be inverted, e.g.
2267   //   and (not (or A, B)), C
2268   // gets lowered as
2269   //   and (and (not A, not B), C)
2270   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2271   if (BOp) {
2272     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2273                ? Instruction::And
2274                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2275                       ? Instruction::Or
2276                       : (Instruction::BinaryOps)0);
2277     if (InvertCond) {
2278       if (BOpc == Instruction::And)
2279         BOpc = Instruction::Or;
2280       else if (BOpc == Instruction::Or)
2281         BOpc = Instruction::And;
2282     }
2283   }
2284 
2285   // If this node is not part of the or/and tree, emit it as a branch.
2286   // Note that all nodes in the tree should have same opcode.
2287   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2288   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2289       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2290       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2291     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2292                                  TProb, FProb, InvertCond);
2293     return;
2294   }
2295 
2296   //  Create TmpBB after CurBB.
2297   MachineFunction::iterator BBI(CurBB);
2298   MachineFunction &MF = DAG.getMachineFunction();
2299   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2300   CurBB->getParent()->insert(++BBI, TmpBB);
2301 
2302   if (Opc == Instruction::Or) {
2303     // Codegen X | Y as:
2304     // BB1:
2305     //   jmp_if_X TBB
2306     //   jmp TmpBB
2307     // TmpBB:
2308     //   jmp_if_Y TBB
2309     //   jmp FBB
2310     //
2311 
2312     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2313     // The requirement is that
2314     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2315     //     = TrueProb for original BB.
2316     // Assuming the original probabilities are A and B, one choice is to set
2317     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2318     // A/(1+B) and 2B/(1+B). This choice assumes that
2319     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2320     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2321     // TmpBB, but the math is more complicated.
2322 
2323     auto NewTrueProb = TProb / 2;
2324     auto NewFalseProb = TProb / 2 + FProb;
2325     // Emit the LHS condition.
2326     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2327                          NewFalseProb, InvertCond);
2328 
2329     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2330     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2331     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2332     // Emit the RHS condition into TmpBB.
2333     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2334                          Probs[1], InvertCond);
2335   } else {
2336     assert(Opc == Instruction::And && "Unknown merge op!");
2337     // Codegen X & Y as:
2338     // BB1:
2339     //   jmp_if_X TmpBB
2340     //   jmp FBB
2341     // TmpBB:
2342     //   jmp_if_Y TBB
2343     //   jmp FBB
2344     //
2345     //  This requires creation of TmpBB after CurBB.
2346 
2347     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2348     // The requirement is that
2349     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2350     //     = FalseProb for original BB.
2351     // Assuming the original probabilities are A and B, one choice is to set
2352     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2353     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2354     // TrueProb for BB1 * FalseProb for TmpBB.
2355 
2356     auto NewTrueProb = TProb + FProb / 2;
2357     auto NewFalseProb = FProb / 2;
2358     // Emit the LHS condition.
2359     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2360                          NewFalseProb, InvertCond);
2361 
2362     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2363     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2364     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2365     // Emit the RHS condition into TmpBB.
2366     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2367                          Probs[1], InvertCond);
2368   }
2369 }
2370 
2371 /// If the set of cases should be emitted as a series of branches, return true.
2372 /// If we should emit this as a bunch of and/or'd together conditions, return
2373 /// false.
2374 bool
2375 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2376   if (Cases.size() != 2) return true;
2377 
2378   // If this is two comparisons of the same values or'd or and'd together, they
2379   // will get folded into a single comparison, so don't emit two blocks.
2380   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2381        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2382       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2383        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2384     return false;
2385   }
2386 
2387   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2388   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2389   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2390       Cases[0].CC == Cases[1].CC &&
2391       isa<Constant>(Cases[0].CmpRHS) &&
2392       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2393     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2394       return false;
2395     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2396       return false;
2397   }
2398 
2399   return true;
2400 }
2401 
2402 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2403   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2404 
2405   // Update machine-CFG edges.
2406   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2407 
2408   if (I.isUnconditional()) {
2409     // Update machine-CFG edges.
2410     BrMBB->addSuccessor(Succ0MBB);
2411 
2412     // If this is not a fall-through branch or optimizations are switched off,
2413     // emit the branch.
2414     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2415       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2416                               MVT::Other, getControlRoot(),
2417                               DAG.getBasicBlock(Succ0MBB)));
2418 
2419     return;
2420   }
2421 
2422   // If this condition is one of the special cases we handle, do special stuff
2423   // now.
2424   const Value *CondVal = I.getCondition();
2425   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2426 
2427   // If this is a series of conditions that are or'd or and'd together, emit
2428   // this as a sequence of branches instead of setcc's with and/or operations.
2429   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2430   // unpredictable branches, and vector extracts because those jumps are likely
2431   // expensive for any target), this should improve performance.
2432   // For example, instead of something like:
2433   //     cmp A, B
2434   //     C = seteq
2435   //     cmp D, E
2436   //     F = setle
2437   //     or C, F
2438   //     jnz foo
2439   // Emit:
2440   //     cmp A, B
2441   //     je foo
2442   //     cmp D, E
2443   //     jle foo
2444   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2445   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2446       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2447     Value *Vec;
2448     const Value *BOp0, *BOp1;
2449     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2450     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2451       Opcode = Instruction::And;
2452     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2453       Opcode = Instruction::Or;
2454 
2455     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2456                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2457       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2458                            getEdgeProbability(BrMBB, Succ0MBB),
2459                            getEdgeProbability(BrMBB, Succ1MBB),
2460                            /*InvertCond=*/false);
2461       // If the compares in later blocks need to use values not currently
2462       // exported from this block, export them now.  This block should always
2463       // be the first entry.
2464       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2465 
2466       // Allow some cases to be rejected.
2467       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2468         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2469           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2470           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2471         }
2472 
2473         // Emit the branch for this block.
2474         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2475         SL->SwitchCases.erase(SL->SwitchCases.begin());
2476         return;
2477       }
2478 
2479       // Okay, we decided not to do this, remove any inserted MBB's and clear
2480       // SwitchCases.
2481       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2482         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2483 
2484       SL->SwitchCases.clear();
2485     }
2486   }
2487 
2488   // Create a CaseBlock record representing this branch.
2489   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2490                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2491 
2492   // Use visitSwitchCase to actually insert the fast branch sequence for this
2493   // cond branch.
2494   visitSwitchCase(CB, BrMBB);
2495 }
2496 
2497 /// visitSwitchCase - Emits the necessary code to represent a single node in
2498 /// the binary search tree resulting from lowering a switch instruction.
2499 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2500                                           MachineBasicBlock *SwitchBB) {
2501   SDValue Cond;
2502   SDValue CondLHS = getValue(CB.CmpLHS);
2503   SDLoc dl = CB.DL;
2504 
2505   if (CB.CC == ISD::SETTRUE) {
2506     // Branch or fall through to TrueBB.
2507     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2508     SwitchBB->normalizeSuccProbs();
2509     if (CB.TrueBB != NextBlock(SwitchBB)) {
2510       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2511                               DAG.getBasicBlock(CB.TrueBB)));
2512     }
2513     return;
2514   }
2515 
2516   auto &TLI = DAG.getTargetLoweringInfo();
2517   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2518 
2519   // Build the setcc now.
2520   if (!CB.CmpMHS) {
2521     // Fold "(X == true)" to X and "(X == false)" to !X to
2522     // handle common cases produced by branch lowering.
2523     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2524         CB.CC == ISD::SETEQ)
2525       Cond = CondLHS;
2526     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2527              CB.CC == ISD::SETEQ) {
2528       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2529       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2530     } else {
2531       SDValue CondRHS = getValue(CB.CmpRHS);
2532 
2533       // If a pointer's DAG type is larger than its memory type then the DAG
2534       // values are zero-extended. This breaks signed comparisons so truncate
2535       // back to the underlying type before doing the compare.
2536       if (CondLHS.getValueType() != MemVT) {
2537         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2538         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2539       }
2540       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2541     }
2542   } else {
2543     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2544 
2545     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2546     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2547 
2548     SDValue CmpOp = getValue(CB.CmpMHS);
2549     EVT VT = CmpOp.getValueType();
2550 
2551     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2552       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2553                           ISD::SETLE);
2554     } else {
2555       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2556                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2557       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2558                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2559     }
2560   }
2561 
2562   // Update successor info
2563   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2564   // TrueBB and FalseBB are always different unless the incoming IR is
2565   // degenerate. This only happens when running llc on weird IR.
2566   if (CB.TrueBB != CB.FalseBB)
2567     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2568   SwitchBB->normalizeSuccProbs();
2569 
2570   // If the lhs block is the next block, invert the condition so that we can
2571   // fall through to the lhs instead of the rhs block.
2572   if (CB.TrueBB == NextBlock(SwitchBB)) {
2573     std::swap(CB.TrueBB, CB.FalseBB);
2574     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2575     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2576   }
2577 
2578   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2579                                MVT::Other, getControlRoot(), Cond,
2580                                DAG.getBasicBlock(CB.TrueBB));
2581 
2582   setValue(CurInst, BrCond);
2583 
2584   // Insert the false branch. Do this even if it's a fall through branch,
2585   // this makes it easier to do DAG optimizations which require inverting
2586   // the branch condition.
2587   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2588                        DAG.getBasicBlock(CB.FalseBB));
2589 
2590   DAG.setRoot(BrCond);
2591 }
2592 
2593 /// visitJumpTable - Emit JumpTable node in the current MBB
2594 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2595   // Emit the code for the jump table
2596   assert(JT.Reg != -1U && "Should lower JT Header first!");
2597   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2598   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2599                                      JT.Reg, PTy);
2600   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2601   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2602                                     MVT::Other, Index.getValue(1),
2603                                     Table, Index);
2604   DAG.setRoot(BrJumpTable);
2605 }
2606 
2607 /// visitJumpTableHeader - This function emits necessary code to produce index
2608 /// in the JumpTable from switch case.
2609 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2610                                                JumpTableHeader &JTH,
2611                                                MachineBasicBlock *SwitchBB) {
2612   SDLoc dl = getCurSDLoc();
2613 
2614   // Subtract the lowest switch case value from the value being switched on.
2615   SDValue SwitchOp = getValue(JTH.SValue);
2616   EVT VT = SwitchOp.getValueType();
2617   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2618                             DAG.getConstant(JTH.First, dl, VT));
2619 
2620   // The SDNode we just created, which holds the value being switched on minus
2621   // the smallest case value, needs to be copied to a virtual register so it
2622   // can be used as an index into the jump table in a subsequent basic block.
2623   // This value may be smaller or larger than the target's pointer type, and
2624   // therefore require extension or truncating.
2625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2626   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2627 
2628   unsigned JumpTableReg =
2629       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2630   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2631                                     JumpTableReg, SwitchOp);
2632   JT.Reg = JumpTableReg;
2633 
2634   if (!JTH.FallthroughUnreachable) {
2635     // Emit the range check for the jump table, and branch to the default block
2636     // for the switch statement if the value being switched on exceeds the
2637     // largest case in the switch.
2638     SDValue CMP = DAG.getSetCC(
2639         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2640                                    Sub.getValueType()),
2641         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2642 
2643     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2644                                  MVT::Other, CopyTo, CMP,
2645                                  DAG.getBasicBlock(JT.Default));
2646 
2647     // Avoid emitting unnecessary branches to the next block.
2648     if (JT.MBB != NextBlock(SwitchBB))
2649       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2650                            DAG.getBasicBlock(JT.MBB));
2651 
2652     DAG.setRoot(BrCond);
2653   } else {
2654     // Avoid emitting unnecessary branches to the next block.
2655     if (JT.MBB != NextBlock(SwitchBB))
2656       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2657                               DAG.getBasicBlock(JT.MBB)));
2658     else
2659       DAG.setRoot(CopyTo);
2660   }
2661 }
2662 
2663 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2664 /// variable if there exists one.
2665 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2666                                  SDValue &Chain) {
2667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2668   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2669   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2670   MachineFunction &MF = DAG.getMachineFunction();
2671   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2672   MachineSDNode *Node =
2673       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2674   if (Global) {
2675     MachinePointerInfo MPInfo(Global);
2676     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2677                  MachineMemOperand::MODereferenceable;
2678     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2679         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2680     DAG.setNodeMemRefs(Node, {MemRef});
2681   }
2682   if (PtrTy != PtrMemTy)
2683     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2684   return SDValue(Node, 0);
2685 }
2686 
2687 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2688 /// tail spliced into a stack protector check success bb.
2689 ///
2690 /// For a high level explanation of how this fits into the stack protector
2691 /// generation see the comment on the declaration of class
2692 /// StackProtectorDescriptor.
2693 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2694                                                   MachineBasicBlock *ParentBB) {
2695 
2696   // First create the loads to the guard/stack slot for the comparison.
2697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2698   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2699   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2700 
2701   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2702   int FI = MFI.getStackProtectorIndex();
2703 
2704   SDValue Guard;
2705   SDLoc dl = getCurSDLoc();
2706   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2707   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2708   Align Align =
2709       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2710 
2711   // Generate code to load the content of the guard slot.
2712   SDValue GuardVal = DAG.getLoad(
2713       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2714       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2715       MachineMemOperand::MOVolatile);
2716 
2717   if (TLI.useStackGuardXorFP())
2718     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2719 
2720   // Retrieve guard check function, nullptr if instrumentation is inlined.
2721   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2722     // The target provides a guard check function to validate the guard value.
2723     // Generate a call to that function with the content of the guard slot as
2724     // argument.
2725     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2726     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2727 
2728     TargetLowering::ArgListTy Args;
2729     TargetLowering::ArgListEntry Entry;
2730     Entry.Node = GuardVal;
2731     Entry.Ty = FnTy->getParamType(0);
2732     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2733       Entry.IsInReg = true;
2734     Args.push_back(Entry);
2735 
2736     TargetLowering::CallLoweringInfo CLI(DAG);
2737     CLI.setDebugLoc(getCurSDLoc())
2738         .setChain(DAG.getEntryNode())
2739         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2740                    getValue(GuardCheckFn), std::move(Args));
2741 
2742     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2743     DAG.setRoot(Result.second);
2744     return;
2745   }
2746 
2747   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2748   // Otherwise, emit a volatile load to retrieve the stack guard value.
2749   SDValue Chain = DAG.getEntryNode();
2750   if (TLI.useLoadStackGuardNode()) {
2751     Guard = getLoadStackGuard(DAG, dl, Chain);
2752   } else {
2753     const Value *IRGuard = TLI.getSDagStackGuard(M);
2754     SDValue GuardPtr = getValue(IRGuard);
2755 
2756     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2757                         MachinePointerInfo(IRGuard, 0), Align,
2758                         MachineMemOperand::MOVolatile);
2759   }
2760 
2761   // Perform the comparison via a getsetcc.
2762   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2763                                                         *DAG.getContext(),
2764                                                         Guard.getValueType()),
2765                              Guard, GuardVal, ISD::SETNE);
2766 
2767   // If the guard/stackslot do not equal, branch to failure MBB.
2768   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2769                                MVT::Other, GuardVal.getOperand(0),
2770                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2771   // Otherwise branch to success MBB.
2772   SDValue Br = DAG.getNode(ISD::BR, dl,
2773                            MVT::Other, BrCond,
2774                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2775 
2776   DAG.setRoot(Br);
2777 }
2778 
2779 /// Codegen the failure basic block for a stack protector check.
2780 ///
2781 /// A failure stack protector machine basic block consists simply of a call to
2782 /// __stack_chk_fail().
2783 ///
2784 /// For a high level explanation of how this fits into the stack protector
2785 /// generation see the comment on the declaration of class
2786 /// StackProtectorDescriptor.
2787 void
2788 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2790   TargetLowering::MakeLibCallOptions CallOptions;
2791   CallOptions.setDiscardResult(true);
2792   SDValue Chain =
2793       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2794                       None, CallOptions, getCurSDLoc()).second;
2795   // On PS4/PS5, the "return address" must still be within the calling
2796   // function, even if it's at the very end, so emit an explicit TRAP here.
2797   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2798   if (TM.getTargetTriple().isPS())
2799     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2800   // WebAssembly needs an unreachable instruction after a non-returning call,
2801   // because the function return type can be different from __stack_chk_fail's
2802   // return type (void).
2803   if (TM.getTargetTriple().isWasm())
2804     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2805 
2806   DAG.setRoot(Chain);
2807 }
2808 
2809 /// visitBitTestHeader - This function emits necessary code to produce value
2810 /// suitable for "bit tests"
2811 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2812                                              MachineBasicBlock *SwitchBB) {
2813   SDLoc dl = getCurSDLoc();
2814 
2815   // Subtract the minimum value.
2816   SDValue SwitchOp = getValue(B.SValue);
2817   EVT VT = SwitchOp.getValueType();
2818   SDValue RangeSub =
2819       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2820 
2821   // Determine the type of the test operands.
2822   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2823   bool UsePtrType = false;
2824   if (!TLI.isTypeLegal(VT)) {
2825     UsePtrType = true;
2826   } else {
2827     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2828       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2829         // Switch table case range are encoded into series of masks.
2830         // Just use pointer type, it's guaranteed to fit.
2831         UsePtrType = true;
2832         break;
2833       }
2834   }
2835   SDValue Sub = RangeSub;
2836   if (UsePtrType) {
2837     VT = TLI.getPointerTy(DAG.getDataLayout());
2838     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2839   }
2840 
2841   B.RegVT = VT.getSimpleVT();
2842   B.Reg = FuncInfo.CreateReg(B.RegVT);
2843   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2844 
2845   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2846 
2847   if (!B.FallthroughUnreachable)
2848     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2849   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2850   SwitchBB->normalizeSuccProbs();
2851 
2852   SDValue Root = CopyTo;
2853   if (!B.FallthroughUnreachable) {
2854     // Conditional branch to the default block.
2855     SDValue RangeCmp = DAG.getSetCC(dl,
2856         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2857                                RangeSub.getValueType()),
2858         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2859         ISD::SETUGT);
2860 
2861     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2862                        DAG.getBasicBlock(B.Default));
2863   }
2864 
2865   // Avoid emitting unnecessary branches to the next block.
2866   if (MBB != NextBlock(SwitchBB))
2867     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2868 
2869   DAG.setRoot(Root);
2870 }
2871 
2872 /// visitBitTestCase - this function produces one "bit test"
2873 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2874                                            MachineBasicBlock* NextMBB,
2875                                            BranchProbability BranchProbToNext,
2876                                            unsigned Reg,
2877                                            BitTestCase &B,
2878                                            MachineBasicBlock *SwitchBB) {
2879   SDLoc dl = getCurSDLoc();
2880   MVT VT = BB.RegVT;
2881   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2882   SDValue Cmp;
2883   unsigned PopCount = countPopulation(B.Mask);
2884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2885   if (PopCount == 1) {
2886     // Testing for a single bit; just compare the shift count with what it
2887     // would need to be to shift a 1 bit in that position.
2888     Cmp = DAG.getSetCC(
2889         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2890         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2891         ISD::SETEQ);
2892   } else if (PopCount == BB.Range) {
2893     // There is only one zero bit in the range, test for it directly.
2894     Cmp = DAG.getSetCC(
2895         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2896         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2897         ISD::SETNE);
2898   } else {
2899     // Make desired shift
2900     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2901                                     DAG.getConstant(1, dl, VT), ShiftOp);
2902 
2903     // Emit bit tests and jumps
2904     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2905                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2906     Cmp = DAG.getSetCC(
2907         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2908         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2909   }
2910 
2911   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2912   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2913   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2914   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2915   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2916   // one as they are relative probabilities (and thus work more like weights),
2917   // and hence we need to normalize them to let the sum of them become one.
2918   SwitchBB->normalizeSuccProbs();
2919 
2920   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2921                               MVT::Other, getControlRoot(),
2922                               Cmp, DAG.getBasicBlock(B.TargetBB));
2923 
2924   // Avoid emitting unnecessary branches to the next block.
2925   if (NextMBB != NextBlock(SwitchBB))
2926     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2927                         DAG.getBasicBlock(NextMBB));
2928 
2929   DAG.setRoot(BrAnd);
2930 }
2931 
2932 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2933   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2934 
2935   // Retrieve successors. Look through artificial IR level blocks like
2936   // catchswitch for successors.
2937   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2938   const BasicBlock *EHPadBB = I.getSuccessor(1);
2939 
2940   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2941   // have to do anything here to lower funclet bundles.
2942   assert(!I.hasOperandBundlesOtherThan(
2943              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2944               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2945               LLVMContext::OB_cfguardtarget,
2946               LLVMContext::OB_clang_arc_attachedcall}) &&
2947          "Cannot lower invokes with arbitrary operand bundles yet!");
2948 
2949   const Value *Callee(I.getCalledOperand());
2950   const Function *Fn = dyn_cast<Function>(Callee);
2951   if (isa<InlineAsm>(Callee))
2952     visitInlineAsm(I, EHPadBB);
2953   else if (Fn && Fn->isIntrinsic()) {
2954     switch (Fn->getIntrinsicID()) {
2955     default:
2956       llvm_unreachable("Cannot invoke this intrinsic");
2957     case Intrinsic::donothing:
2958       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2959     case Intrinsic::seh_try_begin:
2960     case Intrinsic::seh_scope_begin:
2961     case Intrinsic::seh_try_end:
2962     case Intrinsic::seh_scope_end:
2963       break;
2964     case Intrinsic::experimental_patchpoint_void:
2965     case Intrinsic::experimental_patchpoint_i64:
2966       visitPatchpoint(I, EHPadBB);
2967       break;
2968     case Intrinsic::experimental_gc_statepoint:
2969       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2970       break;
2971     case Intrinsic::wasm_rethrow: {
2972       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2973       // special because it can be invoked, so we manually lower it to a DAG
2974       // node here.
2975       SmallVector<SDValue, 8> Ops;
2976       Ops.push_back(getRoot()); // inchain
2977       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2978       Ops.push_back(
2979           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2980                                 TLI.getPointerTy(DAG.getDataLayout())));
2981       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2982       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2983       break;
2984     }
2985     }
2986   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2987     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2988     // Eventually we will support lowering the @llvm.experimental.deoptimize
2989     // intrinsic, and right now there are no plans to support other intrinsics
2990     // with deopt state.
2991     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2992   } else {
2993     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2994   }
2995 
2996   // If the value of the invoke is used outside of its defining block, make it
2997   // available as a virtual register.
2998   // We already took care of the exported value for the statepoint instruction
2999   // during call to the LowerStatepoint.
3000   if (!isa<GCStatepointInst>(I)) {
3001     CopyToExportRegsIfNeeded(&I);
3002   }
3003 
3004   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3005   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3006   BranchProbability EHPadBBProb =
3007       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3008           : BranchProbability::getZero();
3009   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3010 
3011   // Update successor info.
3012   addSuccessorWithProb(InvokeMBB, Return);
3013   for (auto &UnwindDest : UnwindDests) {
3014     UnwindDest.first->setIsEHPad();
3015     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3016   }
3017   InvokeMBB->normalizeSuccProbs();
3018 
3019   // Drop into normal successor.
3020   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3021                           DAG.getBasicBlock(Return)));
3022 }
3023 
3024 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3025   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3026 
3027   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3028   // have to do anything here to lower funclet bundles.
3029   assert(!I.hasOperandBundlesOtherThan(
3030              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3031          "Cannot lower callbrs with arbitrary operand bundles yet!");
3032 
3033   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3034   visitInlineAsm(I);
3035   CopyToExportRegsIfNeeded(&I);
3036 
3037   // Retrieve successors.
3038   SmallPtrSet<BasicBlock *, 8> Dests;
3039   Dests.insert(I.getDefaultDest());
3040   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3041 
3042   // Update successor info.
3043   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3044   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3045     BasicBlock *Dest = I.getIndirectDest(i);
3046     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3047     Target->setIsInlineAsmBrIndirectTarget();
3048     Target->setMachineBlockAddressTaken();
3049     Target->setLabelMustBeEmitted();
3050     // Don't add duplicate machine successors.
3051     if (Dests.insert(Dest).second)
3052       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3053   }
3054   CallBrMBB->normalizeSuccProbs();
3055 
3056   // Drop into default successor.
3057   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3058                           MVT::Other, getControlRoot(),
3059                           DAG.getBasicBlock(Return)));
3060 }
3061 
3062 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3063   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3064 }
3065 
3066 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3067   assert(FuncInfo.MBB->isEHPad() &&
3068          "Call to landingpad not in landing pad!");
3069 
3070   // If there aren't registers to copy the values into (e.g., during SjLj
3071   // exceptions), then don't bother to create these DAG nodes.
3072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3073   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3074   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3075       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3076     return;
3077 
3078   // If landingpad's return type is token type, we don't create DAG nodes
3079   // for its exception pointer and selector value. The extraction of exception
3080   // pointer or selector value from token type landingpads is not currently
3081   // supported.
3082   if (LP.getType()->isTokenTy())
3083     return;
3084 
3085   SmallVector<EVT, 2> ValueVTs;
3086   SDLoc dl = getCurSDLoc();
3087   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3088   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3089 
3090   // Get the two live-in registers as SDValues. The physregs have already been
3091   // copied into virtual registers.
3092   SDValue Ops[2];
3093   if (FuncInfo.ExceptionPointerVirtReg) {
3094     Ops[0] = DAG.getZExtOrTrunc(
3095         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3096                            FuncInfo.ExceptionPointerVirtReg,
3097                            TLI.getPointerTy(DAG.getDataLayout())),
3098         dl, ValueVTs[0]);
3099   } else {
3100     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3101   }
3102   Ops[1] = DAG.getZExtOrTrunc(
3103       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3104                          FuncInfo.ExceptionSelectorVirtReg,
3105                          TLI.getPointerTy(DAG.getDataLayout())),
3106       dl, ValueVTs[1]);
3107 
3108   // Merge into one.
3109   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3110                             DAG.getVTList(ValueVTs), Ops);
3111   setValue(&LP, Res);
3112 }
3113 
3114 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3115                                            MachineBasicBlock *Last) {
3116   // Update JTCases.
3117   for (JumpTableBlock &JTB : SL->JTCases)
3118     if (JTB.first.HeaderBB == First)
3119       JTB.first.HeaderBB = Last;
3120 
3121   // Update BitTestCases.
3122   for (BitTestBlock &BTB : SL->BitTestCases)
3123     if (BTB.Parent == First)
3124       BTB.Parent = Last;
3125 }
3126 
3127 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3128   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3129 
3130   // Update machine-CFG edges with unique successors.
3131   SmallSet<BasicBlock*, 32> Done;
3132   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3133     BasicBlock *BB = I.getSuccessor(i);
3134     bool Inserted = Done.insert(BB).second;
3135     if (!Inserted)
3136         continue;
3137 
3138     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3139     addSuccessorWithProb(IndirectBrMBB, Succ);
3140   }
3141   IndirectBrMBB->normalizeSuccProbs();
3142 
3143   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3144                           MVT::Other, getControlRoot(),
3145                           getValue(I.getAddress())));
3146 }
3147 
3148 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3149   if (!DAG.getTarget().Options.TrapUnreachable)
3150     return;
3151 
3152   // We may be able to ignore unreachable behind a noreturn call.
3153   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3154     const BasicBlock &BB = *I.getParent();
3155     if (&I != &BB.front()) {
3156       BasicBlock::const_iterator PredI =
3157         std::prev(BasicBlock::const_iterator(&I));
3158       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3159         if (Call->doesNotReturn())
3160           return;
3161       }
3162     }
3163   }
3164 
3165   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3166 }
3167 
3168 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3169   SDNodeFlags Flags;
3170   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3171     Flags.copyFMF(*FPOp);
3172 
3173   SDValue Op = getValue(I.getOperand(0));
3174   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3175                                     Op, Flags);
3176   setValue(&I, UnNodeValue);
3177 }
3178 
3179 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3180   SDNodeFlags Flags;
3181   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3182     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3183     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3184   }
3185   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3186     Flags.setExact(ExactOp->isExact());
3187   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3188     Flags.copyFMF(*FPOp);
3189 
3190   SDValue Op1 = getValue(I.getOperand(0));
3191   SDValue Op2 = getValue(I.getOperand(1));
3192   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3193                                      Op1, Op2, Flags);
3194   setValue(&I, BinNodeValue);
3195 }
3196 
3197 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3198   SDValue Op1 = getValue(I.getOperand(0));
3199   SDValue Op2 = getValue(I.getOperand(1));
3200 
3201   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3202       Op1.getValueType(), DAG.getDataLayout());
3203 
3204   // Coerce the shift amount to the right type if we can. This exposes the
3205   // truncate or zext to optimization early.
3206   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3207     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3208            "Unexpected shift type");
3209     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3210   }
3211 
3212   bool nuw = false;
3213   bool nsw = false;
3214   bool exact = false;
3215 
3216   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3217 
3218     if (const OverflowingBinaryOperator *OFBinOp =
3219             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3220       nuw = OFBinOp->hasNoUnsignedWrap();
3221       nsw = OFBinOp->hasNoSignedWrap();
3222     }
3223     if (const PossiblyExactOperator *ExactOp =
3224             dyn_cast<const PossiblyExactOperator>(&I))
3225       exact = ExactOp->isExact();
3226   }
3227   SDNodeFlags Flags;
3228   Flags.setExact(exact);
3229   Flags.setNoSignedWrap(nsw);
3230   Flags.setNoUnsignedWrap(nuw);
3231   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3232                             Flags);
3233   setValue(&I, Res);
3234 }
3235 
3236 void SelectionDAGBuilder::visitSDiv(const User &I) {
3237   SDValue Op1 = getValue(I.getOperand(0));
3238   SDValue Op2 = getValue(I.getOperand(1));
3239 
3240   SDNodeFlags Flags;
3241   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3242                  cast<PossiblyExactOperator>(&I)->isExact());
3243   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3244                            Op2, Flags));
3245 }
3246 
3247 void SelectionDAGBuilder::visitICmp(const User &I) {
3248   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3249   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3250     predicate = IC->getPredicate();
3251   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3252     predicate = ICmpInst::Predicate(IC->getPredicate());
3253   SDValue Op1 = getValue(I.getOperand(0));
3254   SDValue Op2 = getValue(I.getOperand(1));
3255   ISD::CondCode Opcode = getICmpCondCode(predicate);
3256 
3257   auto &TLI = DAG.getTargetLoweringInfo();
3258   EVT MemVT =
3259       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3260 
3261   // If a pointer's DAG type is larger than its memory type then the DAG values
3262   // are zero-extended. This breaks signed comparisons so truncate back to the
3263   // underlying type before doing the compare.
3264   if (Op1.getValueType() != MemVT) {
3265     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3266     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3267   }
3268 
3269   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3270                                                         I.getType());
3271   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3272 }
3273 
3274 void SelectionDAGBuilder::visitFCmp(const User &I) {
3275   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3276   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3277     predicate = FC->getPredicate();
3278   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3279     predicate = FCmpInst::Predicate(FC->getPredicate());
3280   SDValue Op1 = getValue(I.getOperand(0));
3281   SDValue Op2 = getValue(I.getOperand(1));
3282 
3283   ISD::CondCode Condition = getFCmpCondCode(predicate);
3284   auto *FPMO = cast<FPMathOperator>(&I);
3285   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3286     Condition = getFCmpCodeWithoutNaN(Condition);
3287 
3288   SDNodeFlags Flags;
3289   Flags.copyFMF(*FPMO);
3290   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3291 
3292   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3293                                                         I.getType());
3294   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3295 }
3296 
3297 // Check if the condition of the select has one use or two users that are both
3298 // selects with the same condition.
3299 static bool hasOnlySelectUsers(const Value *Cond) {
3300   return llvm::all_of(Cond->users(), [](const Value *V) {
3301     return isa<SelectInst>(V);
3302   });
3303 }
3304 
3305 void SelectionDAGBuilder::visitSelect(const User &I) {
3306   SmallVector<EVT, 4> ValueVTs;
3307   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3308                   ValueVTs);
3309   unsigned NumValues = ValueVTs.size();
3310   if (NumValues == 0) return;
3311 
3312   SmallVector<SDValue, 4> Values(NumValues);
3313   SDValue Cond     = getValue(I.getOperand(0));
3314   SDValue LHSVal   = getValue(I.getOperand(1));
3315   SDValue RHSVal   = getValue(I.getOperand(2));
3316   SmallVector<SDValue, 1> BaseOps(1, Cond);
3317   ISD::NodeType OpCode =
3318       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3319 
3320   bool IsUnaryAbs = false;
3321   bool Negate = false;
3322 
3323   SDNodeFlags Flags;
3324   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3325     Flags.copyFMF(*FPOp);
3326 
3327   // Min/max matching is only viable if all output VTs are the same.
3328   if (all_equal(ValueVTs)) {
3329     EVT VT = ValueVTs[0];
3330     LLVMContext &Ctx = *DAG.getContext();
3331     auto &TLI = DAG.getTargetLoweringInfo();
3332 
3333     // We care about the legality of the operation after it has been type
3334     // legalized.
3335     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3336       VT = TLI.getTypeToTransformTo(Ctx, VT);
3337 
3338     // If the vselect is legal, assume we want to leave this as a vector setcc +
3339     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3340     // min/max is legal on the scalar type.
3341     bool UseScalarMinMax = VT.isVector() &&
3342       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3343 
3344     Value *LHS, *RHS;
3345     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3346     ISD::NodeType Opc = ISD::DELETED_NODE;
3347     switch (SPR.Flavor) {
3348     case SPF_UMAX:    Opc = ISD::UMAX; break;
3349     case SPF_UMIN:    Opc = ISD::UMIN; break;
3350     case SPF_SMAX:    Opc = ISD::SMAX; break;
3351     case SPF_SMIN:    Opc = ISD::SMIN; break;
3352     case SPF_FMINNUM:
3353       switch (SPR.NaNBehavior) {
3354       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3355       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3356       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3357       case SPNB_RETURNS_ANY: {
3358         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3359           Opc = ISD::FMINNUM;
3360         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3361           Opc = ISD::FMINIMUM;
3362         else if (UseScalarMinMax)
3363           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3364             ISD::FMINNUM : ISD::FMINIMUM;
3365         break;
3366       }
3367       }
3368       break;
3369     case SPF_FMAXNUM:
3370       switch (SPR.NaNBehavior) {
3371       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3372       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3373       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3374       case SPNB_RETURNS_ANY:
3375 
3376         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3377           Opc = ISD::FMAXNUM;
3378         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3379           Opc = ISD::FMAXIMUM;
3380         else if (UseScalarMinMax)
3381           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3382             ISD::FMAXNUM : ISD::FMAXIMUM;
3383         break;
3384       }
3385       break;
3386     case SPF_NABS:
3387       Negate = true;
3388       [[fallthrough]];
3389     case SPF_ABS:
3390       IsUnaryAbs = true;
3391       Opc = ISD::ABS;
3392       break;
3393     default: break;
3394     }
3395 
3396     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3397         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3398          (UseScalarMinMax &&
3399           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3400         // If the underlying comparison instruction is used by any other
3401         // instruction, the consumed instructions won't be destroyed, so it is
3402         // not profitable to convert to a min/max.
3403         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3404       OpCode = Opc;
3405       LHSVal = getValue(LHS);
3406       RHSVal = getValue(RHS);
3407       BaseOps.clear();
3408     }
3409 
3410     if (IsUnaryAbs) {
3411       OpCode = Opc;
3412       LHSVal = getValue(LHS);
3413       BaseOps.clear();
3414     }
3415   }
3416 
3417   if (IsUnaryAbs) {
3418     for (unsigned i = 0; i != NumValues; ++i) {
3419       SDLoc dl = getCurSDLoc();
3420       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3421       Values[i] =
3422           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3423       if (Negate)
3424         Values[i] = DAG.getNegative(Values[i], dl, VT);
3425     }
3426   } else {
3427     for (unsigned i = 0; i != NumValues; ++i) {
3428       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3429       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3430       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3431       Values[i] = DAG.getNode(
3432           OpCode, getCurSDLoc(),
3433           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3434     }
3435   }
3436 
3437   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3438                            DAG.getVTList(ValueVTs), Values));
3439 }
3440 
3441 void SelectionDAGBuilder::visitTrunc(const User &I) {
3442   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3443   SDValue N = getValue(I.getOperand(0));
3444   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3445                                                         I.getType());
3446   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3447 }
3448 
3449 void SelectionDAGBuilder::visitZExt(const User &I) {
3450   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3451   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3452   SDValue N = getValue(I.getOperand(0));
3453   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3454                                                         I.getType());
3455   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitSExt(const User &I) {
3459   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3460   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3461   SDValue N = getValue(I.getOperand(0));
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3465 }
3466 
3467 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3468   // FPTrunc is never a no-op cast, no need to check
3469   SDValue N = getValue(I.getOperand(0));
3470   SDLoc dl = getCurSDLoc();
3471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3472   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3473   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3474                            DAG.getTargetConstant(
3475                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3476 }
3477 
3478 void SelectionDAGBuilder::visitFPExt(const User &I) {
3479   // FPExt is never a no-op cast, no need to check
3480   SDValue N = getValue(I.getOperand(0));
3481   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3482                                                         I.getType());
3483   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3484 }
3485 
3486 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3487   // FPToUI is never a no-op cast, no need to check
3488   SDValue N = getValue(I.getOperand(0));
3489   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3490                                                         I.getType());
3491   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3492 }
3493 
3494 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3495   // FPToSI is never a no-op cast, no need to check
3496   SDValue N = getValue(I.getOperand(0));
3497   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3498                                                         I.getType());
3499   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3500 }
3501 
3502 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3503   // UIToFP is never a no-op cast, no need to check
3504   SDValue N = getValue(I.getOperand(0));
3505   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3506                                                         I.getType());
3507   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3508 }
3509 
3510 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3511   // SIToFP is never a no-op cast, no need to check
3512   SDValue N = getValue(I.getOperand(0));
3513   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3514                                                         I.getType());
3515   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3516 }
3517 
3518 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3519   // What to do depends on the size of the integer and the size of the pointer.
3520   // We can either truncate, zero extend, or no-op, accordingly.
3521   SDValue N = getValue(I.getOperand(0));
3522   auto &TLI = DAG.getTargetLoweringInfo();
3523   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3524                                                         I.getType());
3525   EVT PtrMemVT =
3526       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3527   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3528   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3529   setValue(&I, N);
3530 }
3531 
3532 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3533   // What to do depends on the size of the integer and the size of the pointer.
3534   // We can either truncate, zero extend, or no-op, accordingly.
3535   SDValue N = getValue(I.getOperand(0));
3536   auto &TLI = DAG.getTargetLoweringInfo();
3537   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3538   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3539   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3540   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3541   setValue(&I, N);
3542 }
3543 
3544 void SelectionDAGBuilder::visitBitCast(const User &I) {
3545   SDValue N = getValue(I.getOperand(0));
3546   SDLoc dl = getCurSDLoc();
3547   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3548                                                         I.getType());
3549 
3550   // BitCast assures us that source and destination are the same size so this is
3551   // either a BITCAST or a no-op.
3552   if (DestVT != N.getValueType())
3553     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3554                              DestVT, N)); // convert types.
3555   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3556   // might fold any kind of constant expression to an integer constant and that
3557   // is not what we are looking for. Only recognize a bitcast of a genuine
3558   // constant integer as an opaque constant.
3559   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3560     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3561                                  /*isOpaque*/true));
3562   else
3563     setValue(&I, N);            // noop cast.
3564 }
3565 
3566 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3567   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3568   const Value *SV = I.getOperand(0);
3569   SDValue N = getValue(SV);
3570   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3571 
3572   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3573   unsigned DestAS = I.getType()->getPointerAddressSpace();
3574 
3575   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3576     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3577 
3578   setValue(&I, N);
3579 }
3580 
3581 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3583   SDValue InVec = getValue(I.getOperand(0));
3584   SDValue InVal = getValue(I.getOperand(1));
3585   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3586                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3587   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3588                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3589                            InVec, InVal, InIdx));
3590 }
3591 
3592 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3594   SDValue InVec = getValue(I.getOperand(0));
3595   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3596                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3597   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3598                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3599                            InVec, InIdx));
3600 }
3601 
3602 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3603   SDValue Src1 = getValue(I.getOperand(0));
3604   SDValue Src2 = getValue(I.getOperand(1));
3605   ArrayRef<int> Mask;
3606   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3607     Mask = SVI->getShuffleMask();
3608   else
3609     Mask = cast<ConstantExpr>(I).getShuffleMask();
3610   SDLoc DL = getCurSDLoc();
3611   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3612   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3613   EVT SrcVT = Src1.getValueType();
3614 
3615   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3616       VT.isScalableVector()) {
3617     // Canonical splat form of first element of first input vector.
3618     SDValue FirstElt =
3619         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3620                     DAG.getVectorIdxConstant(0, DL));
3621     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3622     return;
3623   }
3624 
3625   // For now, we only handle splats for scalable vectors.
3626   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3627   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3628   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3629 
3630   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3631   unsigned MaskNumElts = Mask.size();
3632 
3633   if (SrcNumElts == MaskNumElts) {
3634     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3635     return;
3636   }
3637 
3638   // Normalize the shuffle vector since mask and vector length don't match.
3639   if (SrcNumElts < MaskNumElts) {
3640     // Mask is longer than the source vectors. We can use concatenate vector to
3641     // make the mask and vectors lengths match.
3642 
3643     if (MaskNumElts % SrcNumElts == 0) {
3644       // Mask length is a multiple of the source vector length.
3645       // Check if the shuffle is some kind of concatenation of the input
3646       // vectors.
3647       unsigned NumConcat = MaskNumElts / SrcNumElts;
3648       bool IsConcat = true;
3649       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3650       for (unsigned i = 0; i != MaskNumElts; ++i) {
3651         int Idx = Mask[i];
3652         if (Idx < 0)
3653           continue;
3654         // Ensure the indices in each SrcVT sized piece are sequential and that
3655         // the same source is used for the whole piece.
3656         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3657             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3658              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3659           IsConcat = false;
3660           break;
3661         }
3662         // Remember which source this index came from.
3663         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3664       }
3665 
3666       // The shuffle is concatenating multiple vectors together. Just emit
3667       // a CONCAT_VECTORS operation.
3668       if (IsConcat) {
3669         SmallVector<SDValue, 8> ConcatOps;
3670         for (auto Src : ConcatSrcs) {
3671           if (Src < 0)
3672             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3673           else if (Src == 0)
3674             ConcatOps.push_back(Src1);
3675           else
3676             ConcatOps.push_back(Src2);
3677         }
3678         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3679         return;
3680       }
3681     }
3682 
3683     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3684     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3685     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3686                                     PaddedMaskNumElts);
3687 
3688     // Pad both vectors with undefs to make them the same length as the mask.
3689     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3690 
3691     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3692     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3693     MOps1[0] = Src1;
3694     MOps2[0] = Src2;
3695 
3696     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3697     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3698 
3699     // Readjust mask for new input vector length.
3700     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3701     for (unsigned i = 0; i != MaskNumElts; ++i) {
3702       int Idx = Mask[i];
3703       if (Idx >= (int)SrcNumElts)
3704         Idx -= SrcNumElts - PaddedMaskNumElts;
3705       MappedOps[i] = Idx;
3706     }
3707 
3708     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3709 
3710     // If the concatenated vector was padded, extract a subvector with the
3711     // correct number of elements.
3712     if (MaskNumElts != PaddedMaskNumElts)
3713       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3714                            DAG.getVectorIdxConstant(0, DL));
3715 
3716     setValue(&I, Result);
3717     return;
3718   }
3719 
3720   if (SrcNumElts > MaskNumElts) {
3721     // Analyze the access pattern of the vector to see if we can extract
3722     // two subvectors and do the shuffle.
3723     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3724     bool CanExtract = true;
3725     for (int Idx : Mask) {
3726       unsigned Input = 0;
3727       if (Idx < 0)
3728         continue;
3729 
3730       if (Idx >= (int)SrcNumElts) {
3731         Input = 1;
3732         Idx -= SrcNumElts;
3733       }
3734 
3735       // If all the indices come from the same MaskNumElts sized portion of
3736       // the sources we can use extract. Also make sure the extract wouldn't
3737       // extract past the end of the source.
3738       int NewStartIdx = alignDown(Idx, MaskNumElts);
3739       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3740           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3741         CanExtract = false;
3742       // Make sure we always update StartIdx as we use it to track if all
3743       // elements are undef.
3744       StartIdx[Input] = NewStartIdx;
3745     }
3746 
3747     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3748       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3749       return;
3750     }
3751     if (CanExtract) {
3752       // Extract appropriate subvector and generate a vector shuffle
3753       for (unsigned Input = 0; Input < 2; ++Input) {
3754         SDValue &Src = Input == 0 ? Src1 : Src2;
3755         if (StartIdx[Input] < 0)
3756           Src = DAG.getUNDEF(VT);
3757         else {
3758           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3759                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3760         }
3761       }
3762 
3763       // Calculate new mask.
3764       SmallVector<int, 8> MappedOps(Mask);
3765       for (int &Idx : MappedOps) {
3766         if (Idx >= (int)SrcNumElts)
3767           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3768         else if (Idx >= 0)
3769           Idx -= StartIdx[0];
3770       }
3771 
3772       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3773       return;
3774     }
3775   }
3776 
3777   // We can't use either concat vectors or extract subvectors so fall back to
3778   // replacing the shuffle with extract and build vector.
3779   // to insert and build vector.
3780   EVT EltVT = VT.getVectorElementType();
3781   SmallVector<SDValue,8> Ops;
3782   for (int Idx : Mask) {
3783     SDValue Res;
3784 
3785     if (Idx < 0) {
3786       Res = DAG.getUNDEF(EltVT);
3787     } else {
3788       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3789       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3790 
3791       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3792                         DAG.getVectorIdxConstant(Idx, DL));
3793     }
3794 
3795     Ops.push_back(Res);
3796   }
3797 
3798   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3799 }
3800 
3801 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3802   ArrayRef<unsigned> Indices = I.getIndices();
3803   const Value *Op0 = I.getOperand(0);
3804   const Value *Op1 = I.getOperand(1);
3805   Type *AggTy = I.getType();
3806   Type *ValTy = Op1->getType();
3807   bool IntoUndef = isa<UndefValue>(Op0);
3808   bool FromUndef = isa<UndefValue>(Op1);
3809 
3810   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3811 
3812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3813   SmallVector<EVT, 4> AggValueVTs;
3814   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3815   SmallVector<EVT, 4> ValValueVTs;
3816   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3817 
3818   unsigned NumAggValues = AggValueVTs.size();
3819   unsigned NumValValues = ValValueVTs.size();
3820   SmallVector<SDValue, 4> Values(NumAggValues);
3821 
3822   // Ignore an insertvalue that produces an empty object
3823   if (!NumAggValues) {
3824     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3825     return;
3826   }
3827 
3828   SDValue Agg = getValue(Op0);
3829   unsigned i = 0;
3830   // Copy the beginning value(s) from the original aggregate.
3831   for (; i != LinearIndex; ++i)
3832     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3833                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3834   // Copy values from the inserted value(s).
3835   if (NumValValues) {
3836     SDValue Val = getValue(Op1);
3837     for (; i != LinearIndex + NumValValues; ++i)
3838       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3839                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3840   }
3841   // Copy remaining value(s) from the original aggregate.
3842   for (; i != NumAggValues; ++i)
3843     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3844                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3845 
3846   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3847                            DAG.getVTList(AggValueVTs), Values));
3848 }
3849 
3850 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3851   ArrayRef<unsigned> Indices = I.getIndices();
3852   const Value *Op0 = I.getOperand(0);
3853   Type *AggTy = Op0->getType();
3854   Type *ValTy = I.getType();
3855   bool OutOfUndef = isa<UndefValue>(Op0);
3856 
3857   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3858 
3859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3860   SmallVector<EVT, 4> ValValueVTs;
3861   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3862 
3863   unsigned NumValValues = ValValueVTs.size();
3864 
3865   // Ignore a extractvalue that produces an empty object
3866   if (!NumValValues) {
3867     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3868     return;
3869   }
3870 
3871   SmallVector<SDValue, 4> Values(NumValValues);
3872 
3873   SDValue Agg = getValue(Op0);
3874   // Copy out the selected value(s).
3875   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3876     Values[i - LinearIndex] =
3877       OutOfUndef ?
3878         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3879         SDValue(Agg.getNode(), Agg.getResNo() + i);
3880 
3881   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3882                            DAG.getVTList(ValValueVTs), Values));
3883 }
3884 
3885 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3886   Value *Op0 = I.getOperand(0);
3887   // Note that the pointer operand may be a vector of pointers. Take the scalar
3888   // element which holds a pointer.
3889   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3890   SDValue N = getValue(Op0);
3891   SDLoc dl = getCurSDLoc();
3892   auto &TLI = DAG.getTargetLoweringInfo();
3893 
3894   // Normalize Vector GEP - all scalar operands should be converted to the
3895   // splat vector.
3896   bool IsVectorGEP = I.getType()->isVectorTy();
3897   ElementCount VectorElementCount =
3898       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3899                   : ElementCount::getFixed(0);
3900 
3901   if (IsVectorGEP && !N.getValueType().isVector()) {
3902     LLVMContext &Context = *DAG.getContext();
3903     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3904     N = DAG.getSplat(VT, dl, N);
3905   }
3906 
3907   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3908        GTI != E; ++GTI) {
3909     const Value *Idx = GTI.getOperand();
3910     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3911       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3912       if (Field) {
3913         // N = N + Offset
3914         uint64_t Offset =
3915             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3916 
3917         // In an inbounds GEP with an offset that is nonnegative even when
3918         // interpreted as signed, assume there is no unsigned overflow.
3919         SDNodeFlags Flags;
3920         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3921           Flags.setNoUnsignedWrap(true);
3922 
3923         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3924                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3925       }
3926     } else {
3927       // IdxSize is the width of the arithmetic according to IR semantics.
3928       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3929       // (and fix up the result later).
3930       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3931       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3932       TypeSize ElementSize =
3933           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3934       // We intentionally mask away the high bits here; ElementSize may not
3935       // fit in IdxTy.
3936       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3937       bool ElementScalable = ElementSize.isScalable();
3938 
3939       // If this is a scalar constant or a splat vector of constants,
3940       // handle it quickly.
3941       const auto *C = dyn_cast<Constant>(Idx);
3942       if (C && isa<VectorType>(C->getType()))
3943         C = C->getSplatValue();
3944 
3945       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3946       if (CI && CI->isZero())
3947         continue;
3948       if (CI && !ElementScalable) {
3949         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3950         LLVMContext &Context = *DAG.getContext();
3951         SDValue OffsVal;
3952         if (IsVectorGEP)
3953           OffsVal = DAG.getConstant(
3954               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3955         else
3956           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3957 
3958         // In an inbounds GEP with an offset that is nonnegative even when
3959         // interpreted as signed, assume there is no unsigned overflow.
3960         SDNodeFlags Flags;
3961         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3962           Flags.setNoUnsignedWrap(true);
3963 
3964         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3965 
3966         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3967         continue;
3968       }
3969 
3970       // N = N + Idx * ElementMul;
3971       SDValue IdxN = getValue(Idx);
3972 
3973       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3974         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3975                                   VectorElementCount);
3976         IdxN = DAG.getSplat(VT, dl, IdxN);
3977       }
3978 
3979       // If the index is smaller or larger than intptr_t, truncate or extend
3980       // it.
3981       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3982 
3983       if (ElementScalable) {
3984         EVT VScaleTy = N.getValueType().getScalarType();
3985         SDValue VScale = DAG.getNode(
3986             ISD::VSCALE, dl, VScaleTy,
3987             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3988         if (IsVectorGEP)
3989           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3990         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3991       } else {
3992         // If this is a multiply by a power of two, turn it into a shl
3993         // immediately.  This is a very common case.
3994         if (ElementMul != 1) {
3995           if (ElementMul.isPowerOf2()) {
3996             unsigned Amt = ElementMul.logBase2();
3997             IdxN = DAG.getNode(ISD::SHL, dl,
3998                                N.getValueType(), IdxN,
3999                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4000           } else {
4001             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4002                                             IdxN.getValueType());
4003             IdxN = DAG.getNode(ISD::MUL, dl,
4004                                N.getValueType(), IdxN, Scale);
4005           }
4006         }
4007       }
4008 
4009       N = DAG.getNode(ISD::ADD, dl,
4010                       N.getValueType(), N, IdxN);
4011     }
4012   }
4013 
4014   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4015   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4016   if (IsVectorGEP) {
4017     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4018     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4019   }
4020 
4021   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4022     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4023 
4024   setValue(&I, N);
4025 }
4026 
4027 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4028   // If this is a fixed sized alloca in the entry block of the function,
4029   // allocate it statically on the stack.
4030   if (FuncInfo.StaticAllocaMap.count(&I))
4031     return;   // getValue will auto-populate this.
4032 
4033   SDLoc dl = getCurSDLoc();
4034   Type *Ty = I.getAllocatedType();
4035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4036   auto &DL = DAG.getDataLayout();
4037   TypeSize TySize = DL.getTypeAllocSize(Ty);
4038   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4039 
4040   SDValue AllocSize = getValue(I.getArraySize());
4041 
4042   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4043   if (AllocSize.getValueType() != IntPtr)
4044     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4045 
4046   if (TySize.isScalable())
4047     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4048                             DAG.getVScale(dl, IntPtr,
4049                                           APInt(IntPtr.getScalarSizeInBits(),
4050                                                 TySize.getKnownMinValue())));
4051   else
4052     AllocSize =
4053         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4054                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4055 
4056   // Handle alignment.  If the requested alignment is less than or equal to
4057   // the stack alignment, ignore it.  If the size is greater than or equal to
4058   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4059   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4060   if (*Alignment <= StackAlign)
4061     Alignment = None;
4062 
4063   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4064   // Round the size of the allocation up to the stack alignment size
4065   // by add SA-1 to the size. This doesn't overflow because we're computing
4066   // an address inside an alloca.
4067   SDNodeFlags Flags;
4068   Flags.setNoUnsignedWrap(true);
4069   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4070                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4071 
4072   // Mask out the low bits for alignment purposes.
4073   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4074                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4075 
4076   SDValue Ops[] = {
4077       getRoot(), AllocSize,
4078       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4079   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4080   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4081   setValue(&I, DSA);
4082   DAG.setRoot(DSA.getValue(1));
4083 
4084   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4085 }
4086 
4087 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4088   if (I.isAtomic())
4089     return visitAtomicLoad(I);
4090 
4091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4092   const Value *SV = I.getOperand(0);
4093   if (TLI.supportSwiftError()) {
4094     // Swifterror values can come from either a function parameter with
4095     // swifterror attribute or an alloca with swifterror attribute.
4096     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4097       if (Arg->hasSwiftErrorAttr())
4098         return visitLoadFromSwiftError(I);
4099     }
4100 
4101     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4102       if (Alloca->isSwiftError())
4103         return visitLoadFromSwiftError(I);
4104     }
4105   }
4106 
4107   SDValue Ptr = getValue(SV);
4108 
4109   Type *Ty = I.getType();
4110   SmallVector<EVT, 4> ValueVTs, MemVTs;
4111   SmallVector<uint64_t, 4> Offsets;
4112   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4113   unsigned NumValues = ValueVTs.size();
4114   if (NumValues == 0)
4115     return;
4116 
4117   Align Alignment = I.getAlign();
4118   AAMDNodes AAInfo = I.getAAMetadata();
4119   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4120   bool isVolatile = I.isVolatile();
4121   MachineMemOperand::Flags MMOFlags =
4122       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4123 
4124   SDValue Root;
4125   bool ConstantMemory = false;
4126   if (isVolatile)
4127     // Serialize volatile loads with other side effects.
4128     Root = getRoot();
4129   else if (NumValues > MaxParallelChains)
4130     Root = getMemoryRoot();
4131   else if (AA &&
4132            AA->pointsToConstantMemory(MemoryLocation(
4133                SV,
4134                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4135                AAInfo))) {
4136     // Do not serialize (non-volatile) loads of constant memory with anything.
4137     Root = DAG.getEntryNode();
4138     ConstantMemory = true;
4139     MMOFlags |= MachineMemOperand::MOInvariant;
4140   } else {
4141     // Do not serialize non-volatile loads against each other.
4142     Root = DAG.getRoot();
4143   }
4144 
4145   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4146                                          &I, AC, nullptr, LibInfo))
4147     MMOFlags |= MachineMemOperand::MODereferenceable;
4148 
4149   SDLoc dl = getCurSDLoc();
4150 
4151   if (isVolatile)
4152     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4153 
4154   // An aggregate load cannot wrap around the address space, so offsets to its
4155   // parts don't wrap either.
4156   SDNodeFlags Flags;
4157   Flags.setNoUnsignedWrap(true);
4158 
4159   SmallVector<SDValue, 4> Values(NumValues);
4160   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4161   EVT PtrVT = Ptr.getValueType();
4162 
4163   unsigned ChainI = 0;
4164   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4165     // Serializing loads here may result in excessive register pressure, and
4166     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4167     // could recover a bit by hoisting nodes upward in the chain by recognizing
4168     // they are side-effect free or do not alias. The optimizer should really
4169     // avoid this case by converting large object/array copies to llvm.memcpy
4170     // (MaxParallelChains should always remain as failsafe).
4171     if (ChainI == MaxParallelChains) {
4172       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4173       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4174                                   makeArrayRef(Chains.data(), ChainI));
4175       Root = Chain;
4176       ChainI = 0;
4177     }
4178     SDValue A = DAG.getNode(ISD::ADD, dl,
4179                             PtrVT, Ptr,
4180                             DAG.getConstant(Offsets[i], dl, PtrVT),
4181                             Flags);
4182 
4183     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4184                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4185                             MMOFlags, AAInfo, Ranges);
4186     Chains[ChainI] = L.getValue(1);
4187 
4188     if (MemVTs[i] != ValueVTs[i])
4189       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4190 
4191     Values[i] = L;
4192   }
4193 
4194   if (!ConstantMemory) {
4195     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4196                                 makeArrayRef(Chains.data(), ChainI));
4197     if (isVolatile)
4198       DAG.setRoot(Chain);
4199     else
4200       PendingLoads.push_back(Chain);
4201   }
4202 
4203   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4204                            DAG.getVTList(ValueVTs), Values));
4205 }
4206 
4207 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4208   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4209          "call visitStoreToSwiftError when backend supports swifterror");
4210 
4211   SmallVector<EVT, 4> ValueVTs;
4212   SmallVector<uint64_t, 4> Offsets;
4213   const Value *SrcV = I.getOperand(0);
4214   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4215                   SrcV->getType(), ValueVTs, &Offsets);
4216   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4217          "expect a single EVT for swifterror");
4218 
4219   SDValue Src = getValue(SrcV);
4220   // Create a virtual register, then update the virtual register.
4221   Register VReg =
4222       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4223   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4224   // Chain can be getRoot or getControlRoot.
4225   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4226                                       SDValue(Src.getNode(), Src.getResNo()));
4227   DAG.setRoot(CopyNode);
4228 }
4229 
4230 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4231   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4232          "call visitLoadFromSwiftError when backend supports swifterror");
4233 
4234   assert(!I.isVolatile() &&
4235          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4236          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4237          "Support volatile, non temporal, invariant for load_from_swift_error");
4238 
4239   const Value *SV = I.getOperand(0);
4240   Type *Ty = I.getType();
4241   assert(
4242       (!AA ||
4243        !AA->pointsToConstantMemory(MemoryLocation(
4244            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4245            I.getAAMetadata()))) &&
4246       "load_from_swift_error should not be constant memory");
4247 
4248   SmallVector<EVT, 4> ValueVTs;
4249   SmallVector<uint64_t, 4> Offsets;
4250   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4251                   ValueVTs, &Offsets);
4252   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4253          "expect a single EVT for swifterror");
4254 
4255   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4256   SDValue L = DAG.getCopyFromReg(
4257       getRoot(), getCurSDLoc(),
4258       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4259 
4260   setValue(&I, L);
4261 }
4262 
4263 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4264   if (I.isAtomic())
4265     return visitAtomicStore(I);
4266 
4267   const Value *SrcV = I.getOperand(0);
4268   const Value *PtrV = I.getOperand(1);
4269 
4270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4271   if (TLI.supportSwiftError()) {
4272     // Swifterror values can come from either a function parameter with
4273     // swifterror attribute or an alloca with swifterror attribute.
4274     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4275       if (Arg->hasSwiftErrorAttr())
4276         return visitStoreToSwiftError(I);
4277     }
4278 
4279     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4280       if (Alloca->isSwiftError())
4281         return visitStoreToSwiftError(I);
4282     }
4283   }
4284 
4285   SmallVector<EVT, 4> ValueVTs, MemVTs;
4286   SmallVector<uint64_t, 4> Offsets;
4287   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4288                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4289   unsigned NumValues = ValueVTs.size();
4290   if (NumValues == 0)
4291     return;
4292 
4293   // Get the lowered operands. Note that we do this after
4294   // checking if NumResults is zero, because with zero results
4295   // the operands won't have values in the map.
4296   SDValue Src = getValue(SrcV);
4297   SDValue Ptr = getValue(PtrV);
4298 
4299   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4300   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4301   SDLoc dl = getCurSDLoc();
4302   Align Alignment = I.getAlign();
4303   AAMDNodes AAInfo = I.getAAMetadata();
4304 
4305   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4306 
4307   // An aggregate load cannot wrap around the address space, so offsets to its
4308   // parts don't wrap either.
4309   SDNodeFlags Flags;
4310   Flags.setNoUnsignedWrap(true);
4311 
4312   unsigned ChainI = 0;
4313   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4314     // See visitLoad comments.
4315     if (ChainI == MaxParallelChains) {
4316       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4317                                   makeArrayRef(Chains.data(), ChainI));
4318       Root = Chain;
4319       ChainI = 0;
4320     }
4321     SDValue Add =
4322         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4323     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4324     if (MemVTs[i] != ValueVTs[i])
4325       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4326     SDValue St =
4327         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4328                      Alignment, MMOFlags, AAInfo);
4329     Chains[ChainI] = St;
4330   }
4331 
4332   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4333                                   makeArrayRef(Chains.data(), ChainI));
4334   setValue(&I, StoreNode);
4335   DAG.setRoot(StoreNode);
4336 }
4337 
4338 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4339                                            bool IsCompressing) {
4340   SDLoc sdl = getCurSDLoc();
4341 
4342   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4343                                MaybeAlign &Alignment) {
4344     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4345     Src0 = I.getArgOperand(0);
4346     Ptr = I.getArgOperand(1);
4347     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4348     Mask = I.getArgOperand(3);
4349   };
4350   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4351                                     MaybeAlign &Alignment) {
4352     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4353     Src0 = I.getArgOperand(0);
4354     Ptr = I.getArgOperand(1);
4355     Mask = I.getArgOperand(2);
4356     Alignment = None;
4357   };
4358 
4359   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4360   MaybeAlign Alignment;
4361   if (IsCompressing)
4362     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4363   else
4364     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4365 
4366   SDValue Ptr = getValue(PtrOperand);
4367   SDValue Src0 = getValue(Src0Operand);
4368   SDValue Mask = getValue(MaskOperand);
4369   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4370 
4371   EVT VT = Src0.getValueType();
4372   if (!Alignment)
4373     Alignment = DAG.getEVTAlign(VT);
4374 
4375   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4376       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4377       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4378   SDValue StoreNode =
4379       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4380                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4381   DAG.setRoot(StoreNode);
4382   setValue(&I, StoreNode);
4383 }
4384 
4385 // Get a uniform base for the Gather/Scatter intrinsic.
4386 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4387 // We try to represent it as a base pointer + vector of indices.
4388 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4389 // The first operand of the GEP may be a single pointer or a vector of pointers
4390 // Example:
4391 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4392 //  or
4393 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4394 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4395 //
4396 // When the first GEP operand is a single pointer - it is the uniform base we
4397 // are looking for. If first operand of the GEP is a splat vector - we
4398 // extract the splat value and use it as a uniform base.
4399 // In all other cases the function returns 'false'.
4400 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4401                            ISD::MemIndexType &IndexType, SDValue &Scale,
4402                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4403                            uint64_t ElemSize) {
4404   SelectionDAG& DAG = SDB->DAG;
4405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4406   const DataLayout &DL = DAG.getDataLayout();
4407 
4408   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4409 
4410   // Handle splat constant pointer.
4411   if (auto *C = dyn_cast<Constant>(Ptr)) {
4412     C = C->getSplatValue();
4413     if (!C)
4414       return false;
4415 
4416     Base = SDB->getValue(C);
4417 
4418     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4419     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4420     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4421     IndexType = ISD::SIGNED_SCALED;
4422     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4423     return true;
4424   }
4425 
4426   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4427   if (!GEP || GEP->getParent() != CurBB)
4428     return false;
4429 
4430   if (GEP->getNumOperands() != 2)
4431     return false;
4432 
4433   const Value *BasePtr = GEP->getPointerOperand();
4434   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4435 
4436   // Make sure the base is scalar and the index is a vector.
4437   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4438     return false;
4439 
4440   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4441 
4442   // Target may not support the required addressing mode.
4443   if (ScaleVal != 1 &&
4444       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4445     return false;
4446 
4447   Base = SDB->getValue(BasePtr);
4448   Index = SDB->getValue(IndexVal);
4449   IndexType = ISD::SIGNED_SCALED;
4450 
4451   Scale =
4452       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4453   return true;
4454 }
4455 
4456 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4457   SDLoc sdl = getCurSDLoc();
4458 
4459   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4460   const Value *Ptr = I.getArgOperand(1);
4461   SDValue Src0 = getValue(I.getArgOperand(0));
4462   SDValue Mask = getValue(I.getArgOperand(3));
4463   EVT VT = Src0.getValueType();
4464   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4465                         ->getMaybeAlignValue()
4466                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4468 
4469   SDValue Base;
4470   SDValue Index;
4471   ISD::MemIndexType IndexType;
4472   SDValue Scale;
4473   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4474                                     I.getParent(), VT.getScalarStoreSize());
4475 
4476   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4477   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4478       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4479       // TODO: Make MachineMemOperands aware of scalable
4480       // vectors.
4481       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4482   if (!UniformBase) {
4483     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4484     Index = getValue(Ptr);
4485     IndexType = ISD::SIGNED_SCALED;
4486     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4487   }
4488 
4489   EVT IdxVT = Index.getValueType();
4490   EVT EltTy = IdxVT.getVectorElementType();
4491   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4492     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4493     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4494   }
4495 
4496   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4497   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4498                                          Ops, MMO, IndexType, false);
4499   DAG.setRoot(Scatter);
4500   setValue(&I, Scatter);
4501 }
4502 
4503 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4504   SDLoc sdl = getCurSDLoc();
4505 
4506   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4507                               MaybeAlign &Alignment) {
4508     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4509     Ptr = I.getArgOperand(0);
4510     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4511     Mask = I.getArgOperand(2);
4512     Src0 = I.getArgOperand(3);
4513   };
4514   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4515                                  MaybeAlign &Alignment) {
4516     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4517     Ptr = I.getArgOperand(0);
4518     Alignment = None;
4519     Mask = I.getArgOperand(1);
4520     Src0 = I.getArgOperand(2);
4521   };
4522 
4523   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4524   MaybeAlign Alignment;
4525   if (IsExpanding)
4526     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4527   else
4528     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4529 
4530   SDValue Ptr = getValue(PtrOperand);
4531   SDValue Src0 = getValue(Src0Operand);
4532   SDValue Mask = getValue(MaskOperand);
4533   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4534 
4535   EVT VT = Src0.getValueType();
4536   if (!Alignment)
4537     Alignment = DAG.getEVTAlign(VT);
4538 
4539   AAMDNodes AAInfo = I.getAAMetadata();
4540   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4541 
4542   // Do not serialize masked loads of constant memory with anything.
4543   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4544   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4545 
4546   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4547 
4548   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4549       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4550       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4551 
4552   SDValue Load =
4553       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4554                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4555   if (AddToChain)
4556     PendingLoads.push_back(Load.getValue(1));
4557   setValue(&I, Load);
4558 }
4559 
4560 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4561   SDLoc sdl = getCurSDLoc();
4562 
4563   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4564   const Value *Ptr = I.getArgOperand(0);
4565   SDValue Src0 = getValue(I.getArgOperand(3));
4566   SDValue Mask = getValue(I.getArgOperand(2));
4567 
4568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4569   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4570   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4571                         ->getMaybeAlignValue()
4572                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4573 
4574   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4575 
4576   SDValue Root = DAG.getRoot();
4577   SDValue Base;
4578   SDValue Index;
4579   ISD::MemIndexType IndexType;
4580   SDValue Scale;
4581   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4582                                     I.getParent(), VT.getScalarStoreSize());
4583   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4584   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4585       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4586       // TODO: Make MachineMemOperands aware of scalable
4587       // vectors.
4588       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4589 
4590   if (!UniformBase) {
4591     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4592     Index = getValue(Ptr);
4593     IndexType = ISD::SIGNED_SCALED;
4594     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4595   }
4596 
4597   EVT IdxVT = Index.getValueType();
4598   EVT EltTy = IdxVT.getVectorElementType();
4599   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4600     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4601     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4602   }
4603 
4604   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4605   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4606                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4607 
4608   PendingLoads.push_back(Gather.getValue(1));
4609   setValue(&I, Gather);
4610 }
4611 
4612 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4613   SDLoc dl = getCurSDLoc();
4614   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4615   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4616   SyncScope::ID SSID = I.getSyncScopeID();
4617 
4618   SDValue InChain = getRoot();
4619 
4620   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4621   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4622 
4623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4624   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4625 
4626   MachineFunction &MF = DAG.getMachineFunction();
4627   MachineMemOperand *MMO = MF.getMachineMemOperand(
4628       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4629       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4630       FailureOrdering);
4631 
4632   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4633                                    dl, MemVT, VTs, InChain,
4634                                    getValue(I.getPointerOperand()),
4635                                    getValue(I.getCompareOperand()),
4636                                    getValue(I.getNewValOperand()), MMO);
4637 
4638   SDValue OutChain = L.getValue(2);
4639 
4640   setValue(&I, L);
4641   DAG.setRoot(OutChain);
4642 }
4643 
4644 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4645   SDLoc dl = getCurSDLoc();
4646   ISD::NodeType NT;
4647   switch (I.getOperation()) {
4648   default: llvm_unreachable("Unknown atomicrmw operation");
4649   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4650   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4651   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4652   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4653   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4654   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4655   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4656   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4657   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4658   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4659   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4660   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4661   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4662   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4663   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4664   }
4665   AtomicOrdering Ordering = I.getOrdering();
4666   SyncScope::ID SSID = I.getSyncScopeID();
4667 
4668   SDValue InChain = getRoot();
4669 
4670   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4672   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4673 
4674   MachineFunction &MF = DAG.getMachineFunction();
4675   MachineMemOperand *MMO = MF.getMachineMemOperand(
4676       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4677       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4678 
4679   SDValue L =
4680     DAG.getAtomic(NT, dl, MemVT, InChain,
4681                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4682                   MMO);
4683 
4684   SDValue OutChain = L.getValue(1);
4685 
4686   setValue(&I, L);
4687   DAG.setRoot(OutChain);
4688 }
4689 
4690 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4691   SDLoc dl = getCurSDLoc();
4692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4693   SDValue Ops[3];
4694   Ops[0] = getRoot();
4695   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4696                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4697   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4698                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4699   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4700   setValue(&I, N);
4701   DAG.setRoot(N);
4702 }
4703 
4704 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4705   SDLoc dl = getCurSDLoc();
4706   AtomicOrdering Order = I.getOrdering();
4707   SyncScope::ID SSID = I.getSyncScopeID();
4708 
4709   SDValue InChain = getRoot();
4710 
4711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4712   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4713   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4714 
4715   if (!TLI.supportsUnalignedAtomics() &&
4716       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4717     report_fatal_error("Cannot generate unaligned atomic load");
4718 
4719   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4720 
4721   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4722       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4723       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4724 
4725   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4726 
4727   SDValue Ptr = getValue(I.getPointerOperand());
4728 
4729   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4730     // TODO: Once this is better exercised by tests, it should be merged with
4731     // the normal path for loads to prevent future divergence.
4732     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4733     if (MemVT != VT)
4734       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4735 
4736     setValue(&I, L);
4737     SDValue OutChain = L.getValue(1);
4738     if (!I.isUnordered())
4739       DAG.setRoot(OutChain);
4740     else
4741       PendingLoads.push_back(OutChain);
4742     return;
4743   }
4744 
4745   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4746                             Ptr, MMO);
4747 
4748   SDValue OutChain = L.getValue(1);
4749   if (MemVT != VT)
4750     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4751 
4752   setValue(&I, L);
4753   DAG.setRoot(OutChain);
4754 }
4755 
4756 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4757   SDLoc dl = getCurSDLoc();
4758 
4759   AtomicOrdering Ordering = I.getOrdering();
4760   SyncScope::ID SSID = I.getSyncScopeID();
4761 
4762   SDValue InChain = getRoot();
4763 
4764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4765   EVT MemVT =
4766       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4767 
4768   if (!TLI.supportsUnalignedAtomics() &&
4769       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4770     report_fatal_error("Cannot generate unaligned atomic store");
4771 
4772   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4773 
4774   MachineFunction &MF = DAG.getMachineFunction();
4775   MachineMemOperand *MMO = MF.getMachineMemOperand(
4776       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4777       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4778 
4779   SDValue Val = getValue(I.getValueOperand());
4780   if (Val.getValueType() != MemVT)
4781     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4782   SDValue Ptr = getValue(I.getPointerOperand());
4783 
4784   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4785     // TODO: Once this is better exercised by tests, it should be merged with
4786     // the normal path for stores to prevent future divergence.
4787     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4788     setValue(&I, S);
4789     DAG.setRoot(S);
4790     return;
4791   }
4792   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4793                                    Ptr, Val, MMO);
4794 
4795   setValue(&I, OutChain);
4796   DAG.setRoot(OutChain);
4797 }
4798 
4799 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4800 /// node.
4801 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4802                                                unsigned Intrinsic) {
4803   // Ignore the callsite's attributes. A specific call site may be marked with
4804   // readnone, but the lowering code will expect the chain based on the
4805   // definition.
4806   const Function *F = I.getCalledFunction();
4807   bool HasChain = !F->doesNotAccessMemory();
4808   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4809 
4810   // Build the operand list.
4811   SmallVector<SDValue, 8> Ops;
4812   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4813     if (OnlyLoad) {
4814       // We don't need to serialize loads against other loads.
4815       Ops.push_back(DAG.getRoot());
4816     } else {
4817       Ops.push_back(getRoot());
4818     }
4819   }
4820 
4821   // Info is set by getTgtMemIntrinsic
4822   TargetLowering::IntrinsicInfo Info;
4823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4824   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4825                                                DAG.getMachineFunction(),
4826                                                Intrinsic);
4827 
4828   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4829   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4830       Info.opc == ISD::INTRINSIC_W_CHAIN)
4831     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4832                                         TLI.getPointerTy(DAG.getDataLayout())));
4833 
4834   // Add all operands of the call to the operand list.
4835   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4836     const Value *Arg = I.getArgOperand(i);
4837     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4838       Ops.push_back(getValue(Arg));
4839       continue;
4840     }
4841 
4842     // Use TargetConstant instead of a regular constant for immarg.
4843     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4844     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4845       assert(CI->getBitWidth() <= 64 &&
4846              "large intrinsic immediates not handled");
4847       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4848     } else {
4849       Ops.push_back(
4850           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4851     }
4852   }
4853 
4854   SmallVector<EVT, 4> ValueVTs;
4855   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4856 
4857   if (HasChain)
4858     ValueVTs.push_back(MVT::Other);
4859 
4860   SDVTList VTs = DAG.getVTList(ValueVTs);
4861 
4862   // Propagate fast-math-flags from IR to node(s).
4863   SDNodeFlags Flags;
4864   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4865     Flags.copyFMF(*FPMO);
4866   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4867 
4868   // Create the node.
4869   SDValue Result;
4870   // In some cases, custom collection of operands from CallInst I may be needed.
4871   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4872   if (IsTgtIntrinsic) {
4873     // This is target intrinsic that touches memory
4874     Result =
4875         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4876                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4877                                 Info.align, Info.flags, Info.size,
4878                                 I.getAAMetadata());
4879   } else if (!HasChain) {
4880     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4881   } else if (!I.getType()->isVoidTy()) {
4882     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4883   } else {
4884     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4885   }
4886 
4887   if (HasChain) {
4888     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4889     if (OnlyLoad)
4890       PendingLoads.push_back(Chain);
4891     else
4892       DAG.setRoot(Chain);
4893   }
4894 
4895   if (!I.getType()->isVoidTy()) {
4896     if (!isa<VectorType>(I.getType()))
4897       Result = lowerRangeToAssertZExt(DAG, I, Result);
4898 
4899     MaybeAlign Alignment = I.getRetAlign();
4900     if (!Alignment)
4901       Alignment = F->getAttributes().getRetAlignment();
4902     // Insert `assertalign` node if there's an alignment.
4903     if (InsertAssertAlign && Alignment) {
4904       Result =
4905           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4906     }
4907 
4908     setValue(&I, Result);
4909   }
4910 }
4911 
4912 /// GetSignificand - Get the significand and build it into a floating-point
4913 /// number with exponent of 1:
4914 ///
4915 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4916 ///
4917 /// where Op is the hexadecimal representation of floating point value.
4918 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4919   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4920                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4921   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4922                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4923   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4924 }
4925 
4926 /// GetExponent - Get the exponent:
4927 ///
4928 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4929 ///
4930 /// where Op is the hexadecimal representation of floating point value.
4931 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4932                            const TargetLowering &TLI, const SDLoc &dl) {
4933   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4934                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4935   SDValue t1 = DAG.getNode(
4936       ISD::SRL, dl, MVT::i32, t0,
4937       DAG.getConstant(23, dl,
4938                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4939   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4940                            DAG.getConstant(127, dl, MVT::i32));
4941   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4942 }
4943 
4944 /// getF32Constant - Get 32-bit floating point constant.
4945 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4946                               const SDLoc &dl) {
4947   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4948                            MVT::f32);
4949 }
4950 
4951 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4952                                        SelectionDAG &DAG) {
4953   // TODO: What fast-math-flags should be set on the floating-point nodes?
4954 
4955   //   IntegerPartOfX = ((int32_t)(t0);
4956   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4957 
4958   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4959   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4960   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4961 
4962   //   IntegerPartOfX <<= 23;
4963   IntegerPartOfX =
4964       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4965                   DAG.getConstant(23, dl,
4966                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4967                                       MVT::i32, DAG.getDataLayout())));
4968 
4969   SDValue TwoToFractionalPartOfX;
4970   if (LimitFloatPrecision <= 6) {
4971     // For floating-point precision of 6:
4972     //
4973     //   TwoToFractionalPartOfX =
4974     //     0.997535578f +
4975     //       (0.735607626f + 0.252464424f * x) * x;
4976     //
4977     // error 0.0144103317, which is 6 bits
4978     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4979                              getF32Constant(DAG, 0x3e814304, dl));
4980     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4981                              getF32Constant(DAG, 0x3f3c50c8, dl));
4982     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4983     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4984                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4985   } else if (LimitFloatPrecision <= 12) {
4986     // For floating-point precision of 12:
4987     //
4988     //   TwoToFractionalPartOfX =
4989     //     0.999892986f +
4990     //       (0.696457318f +
4991     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4992     //
4993     // error 0.000107046256, which is 13 to 14 bits
4994     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4995                              getF32Constant(DAG, 0x3da235e3, dl));
4996     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4997                              getF32Constant(DAG, 0x3e65b8f3, dl));
4998     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4999     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5000                              getF32Constant(DAG, 0x3f324b07, dl));
5001     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5002     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5003                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5004   } else { // LimitFloatPrecision <= 18
5005     // For floating-point precision of 18:
5006     //
5007     //   TwoToFractionalPartOfX =
5008     //     0.999999982f +
5009     //       (0.693148872f +
5010     //         (0.240227044f +
5011     //           (0.554906021e-1f +
5012     //             (0.961591928e-2f +
5013     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5014     // error 2.47208000*10^(-7), which is better than 18 bits
5015     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5016                              getF32Constant(DAG, 0x3924b03e, dl));
5017     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5018                              getF32Constant(DAG, 0x3ab24b87, dl));
5019     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5020     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5021                              getF32Constant(DAG, 0x3c1d8c17, dl));
5022     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5023     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5024                              getF32Constant(DAG, 0x3d634a1d, dl));
5025     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5026     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5027                              getF32Constant(DAG, 0x3e75fe14, dl));
5028     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5029     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5030                               getF32Constant(DAG, 0x3f317234, dl));
5031     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5032     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5033                                          getF32Constant(DAG, 0x3f800000, dl));
5034   }
5035 
5036   // Add the exponent into the result in integer domain.
5037   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5038   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5039                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5040 }
5041 
5042 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5043 /// limited-precision mode.
5044 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5045                          const TargetLowering &TLI, SDNodeFlags Flags) {
5046   if (Op.getValueType() == MVT::f32 &&
5047       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5048 
5049     // Put the exponent in the right bit position for later addition to the
5050     // final result:
5051     //
5052     // t0 = Op * log2(e)
5053 
5054     // TODO: What fast-math-flags should be set here?
5055     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5056                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5057     return getLimitedPrecisionExp2(t0, dl, DAG);
5058   }
5059 
5060   // No special expansion.
5061   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5062 }
5063 
5064 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5065 /// limited-precision mode.
5066 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5067                          const TargetLowering &TLI, SDNodeFlags Flags) {
5068   // TODO: What fast-math-flags should be set on the floating-point nodes?
5069 
5070   if (Op.getValueType() == MVT::f32 &&
5071       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5072     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5073 
5074     // Scale the exponent by log(2).
5075     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5076     SDValue LogOfExponent =
5077         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5078                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5079 
5080     // Get the significand and build it into a floating-point number with
5081     // exponent of 1.
5082     SDValue X = GetSignificand(DAG, Op1, dl);
5083 
5084     SDValue LogOfMantissa;
5085     if (LimitFloatPrecision <= 6) {
5086       // For floating-point precision of 6:
5087       //
5088       //   LogofMantissa =
5089       //     -1.1609546f +
5090       //       (1.4034025f - 0.23903021f * x) * x;
5091       //
5092       // error 0.0034276066, which is better than 8 bits
5093       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5094                                getF32Constant(DAG, 0xbe74c456, dl));
5095       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5096                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5097       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5098       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5099                                   getF32Constant(DAG, 0x3f949a29, dl));
5100     } else if (LimitFloatPrecision <= 12) {
5101       // For floating-point precision of 12:
5102       //
5103       //   LogOfMantissa =
5104       //     -1.7417939f +
5105       //       (2.8212026f +
5106       //         (-1.4699568f +
5107       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5108       //
5109       // error 0.000061011436, which is 14 bits
5110       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5111                                getF32Constant(DAG, 0xbd67b6d6, dl));
5112       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5113                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5114       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5115       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5116                                getF32Constant(DAG, 0x3fbc278b, dl));
5117       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5118       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5119                                getF32Constant(DAG, 0x40348e95, dl));
5120       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5121       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5122                                   getF32Constant(DAG, 0x3fdef31a, dl));
5123     } else { // LimitFloatPrecision <= 18
5124       // For floating-point precision of 18:
5125       //
5126       //   LogOfMantissa =
5127       //     -2.1072184f +
5128       //       (4.2372794f +
5129       //         (-3.7029485f +
5130       //           (2.2781945f +
5131       //             (-0.87823314f +
5132       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5133       //
5134       // error 0.0000023660568, which is better than 18 bits
5135       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5136                                getF32Constant(DAG, 0xbc91e5ac, dl));
5137       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5138                                getF32Constant(DAG, 0x3e4350aa, dl));
5139       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5140       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5141                                getF32Constant(DAG, 0x3f60d3e3, dl));
5142       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5143       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5144                                getF32Constant(DAG, 0x4011cdf0, dl));
5145       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5146       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5147                                getF32Constant(DAG, 0x406cfd1c, dl));
5148       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5149       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5150                                getF32Constant(DAG, 0x408797cb, dl));
5151       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5152       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5153                                   getF32Constant(DAG, 0x4006dcab, dl));
5154     }
5155 
5156     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5157   }
5158 
5159   // No special expansion.
5160   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5161 }
5162 
5163 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5164 /// limited-precision mode.
5165 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5166                           const TargetLowering &TLI, SDNodeFlags Flags) {
5167   // TODO: What fast-math-flags should be set on the floating-point nodes?
5168 
5169   if (Op.getValueType() == MVT::f32 &&
5170       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5171     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5172 
5173     // Get the exponent.
5174     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5175 
5176     // Get the significand and build it into a floating-point number with
5177     // exponent of 1.
5178     SDValue X = GetSignificand(DAG, Op1, dl);
5179 
5180     // Different possible minimax approximations of significand in
5181     // floating-point for various degrees of accuracy over [1,2].
5182     SDValue Log2ofMantissa;
5183     if (LimitFloatPrecision <= 6) {
5184       // For floating-point precision of 6:
5185       //
5186       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5187       //
5188       // error 0.0049451742, which is more than 7 bits
5189       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5190                                getF32Constant(DAG, 0xbeb08fe0, dl));
5191       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5192                                getF32Constant(DAG, 0x40019463, dl));
5193       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5194       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5195                                    getF32Constant(DAG, 0x3fd6633d, dl));
5196     } else if (LimitFloatPrecision <= 12) {
5197       // For floating-point precision of 12:
5198       //
5199       //   Log2ofMantissa =
5200       //     -2.51285454f +
5201       //       (4.07009056f +
5202       //         (-2.12067489f +
5203       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5204       //
5205       // error 0.0000876136000, which is better than 13 bits
5206       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5207                                getF32Constant(DAG, 0xbda7262e, dl));
5208       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5209                                getF32Constant(DAG, 0x3f25280b, dl));
5210       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5211       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5212                                getF32Constant(DAG, 0x4007b923, dl));
5213       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5214       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5215                                getF32Constant(DAG, 0x40823e2f, dl));
5216       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5217       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5218                                    getF32Constant(DAG, 0x4020d29c, dl));
5219     } else { // LimitFloatPrecision <= 18
5220       // For floating-point precision of 18:
5221       //
5222       //   Log2ofMantissa =
5223       //     -3.0400495f +
5224       //       (6.1129976f +
5225       //         (-5.3420409f +
5226       //           (3.2865683f +
5227       //             (-1.2669343f +
5228       //               (0.27515199f -
5229       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5230       //
5231       // error 0.0000018516, which is better than 18 bits
5232       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5233                                getF32Constant(DAG, 0xbcd2769e, dl));
5234       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5235                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5236       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5237       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5238                                getF32Constant(DAG, 0x3fa22ae7, dl));
5239       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5240       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5241                                getF32Constant(DAG, 0x40525723, dl));
5242       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5243       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5244                                getF32Constant(DAG, 0x40aaf200, dl));
5245       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5246       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5247                                getF32Constant(DAG, 0x40c39dad, dl));
5248       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5249       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5250                                    getF32Constant(DAG, 0x4042902c, dl));
5251     }
5252 
5253     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5254   }
5255 
5256   // No special expansion.
5257   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5258 }
5259 
5260 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5261 /// limited-precision mode.
5262 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5263                            const TargetLowering &TLI, SDNodeFlags Flags) {
5264   // TODO: What fast-math-flags should be set on the floating-point nodes?
5265 
5266   if (Op.getValueType() == MVT::f32 &&
5267       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5268     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5269 
5270     // Scale the exponent by log10(2) [0.30102999f].
5271     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5272     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5273                                         getF32Constant(DAG, 0x3e9a209a, dl));
5274 
5275     // Get the significand and build it into a floating-point number with
5276     // exponent of 1.
5277     SDValue X = GetSignificand(DAG, Op1, dl);
5278 
5279     SDValue Log10ofMantissa;
5280     if (LimitFloatPrecision <= 6) {
5281       // For floating-point precision of 6:
5282       //
5283       //   Log10ofMantissa =
5284       //     -0.50419619f +
5285       //       (0.60948995f - 0.10380950f * x) * x;
5286       //
5287       // error 0.0014886165, which is 6 bits
5288       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5289                                getF32Constant(DAG, 0xbdd49a13, dl));
5290       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5291                                getF32Constant(DAG, 0x3f1c0789, dl));
5292       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5293       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5294                                     getF32Constant(DAG, 0x3f011300, dl));
5295     } else if (LimitFloatPrecision <= 12) {
5296       // For floating-point precision of 12:
5297       //
5298       //   Log10ofMantissa =
5299       //     -0.64831180f +
5300       //       (0.91751397f +
5301       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5302       //
5303       // error 0.00019228036, which is better than 12 bits
5304       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5305                                getF32Constant(DAG, 0x3d431f31, dl));
5306       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5307                                getF32Constant(DAG, 0x3ea21fb2, dl));
5308       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5309       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5310                                getF32Constant(DAG, 0x3f6ae232, dl));
5311       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5312       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5313                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5314     } else { // LimitFloatPrecision <= 18
5315       // For floating-point precision of 18:
5316       //
5317       //   Log10ofMantissa =
5318       //     -0.84299375f +
5319       //       (1.5327582f +
5320       //         (-1.0688956f +
5321       //           (0.49102474f +
5322       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5323       //
5324       // error 0.0000037995730, which is better than 18 bits
5325       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5326                                getF32Constant(DAG, 0x3c5d51ce, dl));
5327       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5328                                getF32Constant(DAG, 0x3e00685a, dl));
5329       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5330       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5331                                getF32Constant(DAG, 0x3efb6798, dl));
5332       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5333       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5334                                getF32Constant(DAG, 0x3f88d192, dl));
5335       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5336       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5337                                getF32Constant(DAG, 0x3fc4316c, dl));
5338       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5339       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5340                                     getF32Constant(DAG, 0x3f57ce70, dl));
5341     }
5342 
5343     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5344   }
5345 
5346   // No special expansion.
5347   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5348 }
5349 
5350 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5351 /// limited-precision mode.
5352 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5353                           const TargetLowering &TLI, SDNodeFlags Flags) {
5354   if (Op.getValueType() == MVT::f32 &&
5355       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5356     return getLimitedPrecisionExp2(Op, dl, DAG);
5357 
5358   // No special expansion.
5359   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5360 }
5361 
5362 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5363 /// limited-precision mode with x == 10.0f.
5364 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5365                          SelectionDAG &DAG, const TargetLowering &TLI,
5366                          SDNodeFlags Flags) {
5367   bool IsExp10 = false;
5368   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5369       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5370     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5371       APFloat Ten(10.0f);
5372       IsExp10 = LHSC->isExactlyValue(Ten);
5373     }
5374   }
5375 
5376   // TODO: What fast-math-flags should be set on the FMUL node?
5377   if (IsExp10) {
5378     // Put the exponent in the right bit position for later addition to the
5379     // final result:
5380     //
5381     //   #define LOG2OF10 3.3219281f
5382     //   t0 = Op * LOG2OF10;
5383     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5384                              getF32Constant(DAG, 0x40549a78, dl));
5385     return getLimitedPrecisionExp2(t0, dl, DAG);
5386   }
5387 
5388   // No special expansion.
5389   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5390 }
5391 
5392 /// ExpandPowI - Expand a llvm.powi intrinsic.
5393 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5394                           SelectionDAG &DAG) {
5395   // If RHS is a constant, we can expand this out to a multiplication tree if
5396   // it's beneficial on the target, otherwise we end up lowering to a call to
5397   // __powidf2 (for example).
5398   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5399     unsigned Val = RHSC->getSExtValue();
5400 
5401     // powi(x, 0) -> 1.0
5402     if (Val == 0)
5403       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5404 
5405     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5406             Val, DAG.shouldOptForSize())) {
5407       // Get the exponent as a positive value.
5408       if ((int)Val < 0)
5409         Val = -Val;
5410       // We use the simple binary decomposition method to generate the multiply
5411       // sequence.  There are more optimal ways to do this (for example,
5412       // powi(x,15) generates one more multiply than it should), but this has
5413       // the benefit of being both really simple and much better than a libcall.
5414       SDValue Res; // Logically starts equal to 1.0
5415       SDValue CurSquare = LHS;
5416       // TODO: Intrinsics should have fast-math-flags that propagate to these
5417       // nodes.
5418       while (Val) {
5419         if (Val & 1) {
5420           if (Res.getNode())
5421             Res =
5422                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5423           else
5424             Res = CurSquare; // 1.0*CurSquare.
5425         }
5426 
5427         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5428                                 CurSquare, CurSquare);
5429         Val >>= 1;
5430       }
5431 
5432       // If the original was negative, invert the result, producing 1/(x*x*x).
5433       if (RHSC->getSExtValue() < 0)
5434         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5435                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5436       return Res;
5437     }
5438   }
5439 
5440   // Otherwise, expand to a libcall.
5441   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5442 }
5443 
5444 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5445                             SDValue LHS, SDValue RHS, SDValue Scale,
5446                             SelectionDAG &DAG, const TargetLowering &TLI) {
5447   EVT VT = LHS.getValueType();
5448   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5449   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5450   LLVMContext &Ctx = *DAG.getContext();
5451 
5452   // If the type is legal but the operation isn't, this node might survive all
5453   // the way to operation legalization. If we end up there and we do not have
5454   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5455   // node.
5456 
5457   // Coax the legalizer into expanding the node during type legalization instead
5458   // by bumping the size by one bit. This will force it to Promote, enabling the
5459   // early expansion and avoiding the need to expand later.
5460 
5461   // We don't have to do this if Scale is 0; that can always be expanded, unless
5462   // it's a saturating signed operation. Those can experience true integer
5463   // division overflow, a case which we must avoid.
5464 
5465   // FIXME: We wouldn't have to do this (or any of the early
5466   // expansion/promotion) if it was possible to expand a libcall of an
5467   // illegal type during operation legalization. But it's not, so things
5468   // get a bit hacky.
5469   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5470   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5471       (TLI.isTypeLegal(VT) ||
5472        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5473     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5474         Opcode, VT, ScaleInt);
5475     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5476       EVT PromVT;
5477       if (VT.isScalarInteger())
5478         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5479       else if (VT.isVector()) {
5480         PromVT = VT.getVectorElementType();
5481         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5482         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5483       } else
5484         llvm_unreachable("Wrong VT for DIVFIX?");
5485       if (Signed) {
5486         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5487         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5488       } else {
5489         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5490         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5491       }
5492       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5493       // For saturating operations, we need to shift up the LHS to get the
5494       // proper saturation width, and then shift down again afterwards.
5495       if (Saturating)
5496         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5497                           DAG.getConstant(1, DL, ShiftTy));
5498       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5499       if (Saturating)
5500         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5501                           DAG.getConstant(1, DL, ShiftTy));
5502       return DAG.getZExtOrTrunc(Res, DL, VT);
5503     }
5504   }
5505 
5506   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5507 }
5508 
5509 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5510 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5511 static void
5512 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5513                      const SDValue &N) {
5514   switch (N.getOpcode()) {
5515   case ISD::CopyFromReg: {
5516     SDValue Op = N.getOperand(1);
5517     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5518                       Op.getValueType().getSizeInBits());
5519     return;
5520   }
5521   case ISD::BITCAST:
5522   case ISD::AssertZext:
5523   case ISD::AssertSext:
5524   case ISD::TRUNCATE:
5525     getUnderlyingArgRegs(Regs, N.getOperand(0));
5526     return;
5527   case ISD::BUILD_PAIR:
5528   case ISD::BUILD_VECTOR:
5529   case ISD::CONCAT_VECTORS:
5530     for (SDValue Op : N->op_values())
5531       getUnderlyingArgRegs(Regs, Op);
5532     return;
5533   default:
5534     return;
5535   }
5536 }
5537 
5538 /// If the DbgValueInst is a dbg_value of a function argument, create the
5539 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5540 /// instruction selection, they will be inserted to the entry BB.
5541 /// We don't currently support this for variadic dbg_values, as they shouldn't
5542 /// appear for function arguments or in the prologue.
5543 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5544     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5545     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5546   const Argument *Arg = dyn_cast<Argument>(V);
5547   if (!Arg)
5548     return false;
5549 
5550   MachineFunction &MF = DAG.getMachineFunction();
5551   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5552 
5553   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5554   // we've been asked to pursue.
5555   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5556                               bool Indirect) {
5557     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5558       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5559       // pointing at the VReg, which will be patched up later.
5560       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5561       auto MIB = BuildMI(MF, DL, Inst);
5562       MIB.addReg(Reg);
5563       MIB.addImm(0);
5564       MIB.addMetadata(Variable);
5565       auto *NewDIExpr = FragExpr;
5566       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5567       // the DIExpression.
5568       if (Indirect)
5569         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5570       MIB.addMetadata(NewDIExpr);
5571       return MIB;
5572     } else {
5573       // Create a completely standard DBG_VALUE.
5574       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5575       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5576     }
5577   };
5578 
5579   if (Kind == FuncArgumentDbgValueKind::Value) {
5580     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5581     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5582     // the entry block.
5583     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5584     if (!IsInEntryBlock)
5585       return false;
5586 
5587     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5588     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5589     // variable that also is a param.
5590     //
5591     // Although, if we are at the top of the entry block already, we can still
5592     // emit using ArgDbgValue. This might catch some situations when the
5593     // dbg.value refers to an argument that isn't used in the entry block, so
5594     // any CopyToReg node would be optimized out and the only way to express
5595     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5596     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5597     // we should only emit as ArgDbgValue if the Variable is an argument to the
5598     // current function, and the dbg.value intrinsic is found in the entry
5599     // block.
5600     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5601         !DL->getInlinedAt();
5602     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5603     if (!IsInPrologue && !VariableIsFunctionInputArg)
5604       return false;
5605 
5606     // Here we assume that a function argument on IR level only can be used to
5607     // describe one input parameter on source level. If we for example have
5608     // source code like this
5609     //
5610     //    struct A { long x, y; };
5611     //    void foo(struct A a, long b) {
5612     //      ...
5613     //      b = a.x;
5614     //      ...
5615     //    }
5616     //
5617     // and IR like this
5618     //
5619     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5620     //  entry:
5621     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5622     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5623     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5624     //    ...
5625     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5626     //    ...
5627     //
5628     // then the last dbg.value is describing a parameter "b" using a value that
5629     // is an argument. But since we already has used %a1 to describe a parameter
5630     // we should not handle that last dbg.value here (that would result in an
5631     // incorrect hoisting of the DBG_VALUE to the function entry).
5632     // Notice that we allow one dbg.value per IR level argument, to accommodate
5633     // for the situation with fragments above.
5634     if (VariableIsFunctionInputArg) {
5635       unsigned ArgNo = Arg->getArgNo();
5636       if (ArgNo >= FuncInfo.DescribedArgs.size())
5637         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5638       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5639         return false;
5640       FuncInfo.DescribedArgs.set(ArgNo);
5641     }
5642   }
5643 
5644   bool IsIndirect = false;
5645   Optional<MachineOperand> Op;
5646   // Some arguments' frame index is recorded during argument lowering.
5647   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5648   if (FI != std::numeric_limits<int>::max())
5649     Op = MachineOperand::CreateFI(FI);
5650 
5651   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5652   if (!Op && N.getNode()) {
5653     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5654     Register Reg;
5655     if (ArgRegsAndSizes.size() == 1)
5656       Reg = ArgRegsAndSizes.front().first;
5657 
5658     if (Reg && Reg.isVirtual()) {
5659       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5660       Register PR = RegInfo.getLiveInPhysReg(Reg);
5661       if (PR)
5662         Reg = PR;
5663     }
5664     if (Reg) {
5665       Op = MachineOperand::CreateReg(Reg, false);
5666       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5667     }
5668   }
5669 
5670   if (!Op && N.getNode()) {
5671     // Check if frame index is available.
5672     SDValue LCandidate = peekThroughBitcasts(N);
5673     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5674       if (FrameIndexSDNode *FINode =
5675           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5676         Op = MachineOperand::CreateFI(FINode->getIndex());
5677   }
5678 
5679   if (!Op) {
5680     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5681     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5682                                          SplitRegs) {
5683       unsigned Offset = 0;
5684       for (const auto &RegAndSize : SplitRegs) {
5685         // If the expression is already a fragment, the current register
5686         // offset+size might extend beyond the fragment. In this case, only
5687         // the register bits that are inside the fragment are relevant.
5688         int RegFragmentSizeInBits = RegAndSize.second;
5689         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5690           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5691           // The register is entirely outside the expression fragment,
5692           // so is irrelevant for debug info.
5693           if (Offset >= ExprFragmentSizeInBits)
5694             break;
5695           // The register is partially outside the expression fragment, only
5696           // the low bits within the fragment are relevant for debug info.
5697           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5698             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5699           }
5700         }
5701 
5702         auto FragmentExpr = DIExpression::createFragmentExpression(
5703             Expr, Offset, RegFragmentSizeInBits);
5704         Offset += RegAndSize.second;
5705         // If a valid fragment expression cannot be created, the variable's
5706         // correct value cannot be determined and so it is set as Undef.
5707         if (!FragmentExpr) {
5708           SDDbgValue *SDV = DAG.getConstantDbgValue(
5709               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5710           DAG.AddDbgValue(SDV, false);
5711           continue;
5712         }
5713         MachineInstr *NewMI =
5714             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5715                              Kind != FuncArgumentDbgValueKind::Value);
5716         FuncInfo.ArgDbgValues.push_back(NewMI);
5717       }
5718     };
5719 
5720     // Check if ValueMap has reg number.
5721     DenseMap<const Value *, Register>::const_iterator
5722       VMI = FuncInfo.ValueMap.find(V);
5723     if (VMI != FuncInfo.ValueMap.end()) {
5724       const auto &TLI = DAG.getTargetLoweringInfo();
5725       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5726                        V->getType(), None);
5727       if (RFV.occupiesMultipleRegs()) {
5728         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5729         return true;
5730       }
5731 
5732       Op = MachineOperand::CreateReg(VMI->second, false);
5733       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5734     } else if (ArgRegsAndSizes.size() > 1) {
5735       // This was split due to the calling convention, and no virtual register
5736       // mapping exists for the value.
5737       splitMultiRegDbgValue(ArgRegsAndSizes);
5738       return true;
5739     }
5740   }
5741 
5742   if (!Op)
5743     return false;
5744 
5745   assert(Variable->isValidLocationForIntrinsic(DL) &&
5746          "Expected inlined-at fields to agree");
5747   MachineInstr *NewMI = nullptr;
5748 
5749   if (Op->isReg())
5750     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5751   else
5752     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5753                     Variable, Expr);
5754 
5755   // Otherwise, use ArgDbgValues.
5756   FuncInfo.ArgDbgValues.push_back(NewMI);
5757   return true;
5758 }
5759 
5760 /// Return the appropriate SDDbgValue based on N.
5761 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5762                                              DILocalVariable *Variable,
5763                                              DIExpression *Expr,
5764                                              const DebugLoc &dl,
5765                                              unsigned DbgSDNodeOrder) {
5766   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5767     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5768     // stack slot locations.
5769     //
5770     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5771     // debug values here after optimization:
5772     //
5773     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5774     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5775     //
5776     // Both describe the direct values of their associated variables.
5777     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5778                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5779   }
5780   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5781                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5782 }
5783 
5784 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5785   switch (Intrinsic) {
5786   case Intrinsic::smul_fix:
5787     return ISD::SMULFIX;
5788   case Intrinsic::umul_fix:
5789     return ISD::UMULFIX;
5790   case Intrinsic::smul_fix_sat:
5791     return ISD::SMULFIXSAT;
5792   case Intrinsic::umul_fix_sat:
5793     return ISD::UMULFIXSAT;
5794   case Intrinsic::sdiv_fix:
5795     return ISD::SDIVFIX;
5796   case Intrinsic::udiv_fix:
5797     return ISD::UDIVFIX;
5798   case Intrinsic::sdiv_fix_sat:
5799     return ISD::SDIVFIXSAT;
5800   case Intrinsic::udiv_fix_sat:
5801     return ISD::UDIVFIXSAT;
5802   default:
5803     llvm_unreachable("Unhandled fixed point intrinsic");
5804   }
5805 }
5806 
5807 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5808                                            const char *FunctionName) {
5809   assert(FunctionName && "FunctionName must not be nullptr");
5810   SDValue Callee = DAG.getExternalSymbol(
5811       FunctionName,
5812       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5813   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5814 }
5815 
5816 /// Given a @llvm.call.preallocated.setup, return the corresponding
5817 /// preallocated call.
5818 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5819   assert(cast<CallBase>(PreallocatedSetup)
5820                  ->getCalledFunction()
5821                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5822          "expected call_preallocated_setup Value");
5823   for (const auto *U : PreallocatedSetup->users()) {
5824     auto *UseCall = cast<CallBase>(U);
5825     const Function *Fn = UseCall->getCalledFunction();
5826     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5827       return UseCall;
5828     }
5829   }
5830   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5831 }
5832 
5833 /// Lower the call to the specified intrinsic function.
5834 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5835                                              unsigned Intrinsic) {
5836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5837   SDLoc sdl = getCurSDLoc();
5838   DebugLoc dl = getCurDebugLoc();
5839   SDValue Res;
5840 
5841   SDNodeFlags Flags;
5842   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5843     Flags.copyFMF(*FPOp);
5844 
5845   switch (Intrinsic) {
5846   default:
5847     // By default, turn this into a target intrinsic node.
5848     visitTargetIntrinsic(I, Intrinsic);
5849     return;
5850   case Intrinsic::vscale: {
5851     match(&I, m_VScale(DAG.getDataLayout()));
5852     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5853     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5854     return;
5855   }
5856   case Intrinsic::vastart:  visitVAStart(I); return;
5857   case Intrinsic::vaend:    visitVAEnd(I); return;
5858   case Intrinsic::vacopy:   visitVACopy(I); return;
5859   case Intrinsic::returnaddress:
5860     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5861                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5862                              getValue(I.getArgOperand(0))));
5863     return;
5864   case Intrinsic::addressofreturnaddress:
5865     setValue(&I,
5866              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5867                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5868     return;
5869   case Intrinsic::sponentry:
5870     setValue(&I,
5871              DAG.getNode(ISD::SPONENTRY, sdl,
5872                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5873     return;
5874   case Intrinsic::frameaddress:
5875     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5876                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5877                              getValue(I.getArgOperand(0))));
5878     return;
5879   case Intrinsic::read_volatile_register:
5880   case Intrinsic::read_register: {
5881     Value *Reg = I.getArgOperand(0);
5882     SDValue Chain = getRoot();
5883     SDValue RegName =
5884         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5885     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5886     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5887       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5888     setValue(&I, Res);
5889     DAG.setRoot(Res.getValue(1));
5890     return;
5891   }
5892   case Intrinsic::write_register: {
5893     Value *Reg = I.getArgOperand(0);
5894     Value *RegValue = I.getArgOperand(1);
5895     SDValue Chain = getRoot();
5896     SDValue RegName =
5897         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5898     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5899                             RegName, getValue(RegValue)));
5900     return;
5901   }
5902   case Intrinsic::memcpy: {
5903     const auto &MCI = cast<MemCpyInst>(I);
5904     SDValue Op1 = getValue(I.getArgOperand(0));
5905     SDValue Op2 = getValue(I.getArgOperand(1));
5906     SDValue Op3 = getValue(I.getArgOperand(2));
5907     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5908     Align DstAlign = MCI.getDestAlign().valueOrOne();
5909     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5910     Align Alignment = std::min(DstAlign, SrcAlign);
5911     bool isVol = MCI.isVolatile();
5912     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5913     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5914     // node.
5915     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5916     SDValue MC = DAG.getMemcpy(
5917         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5918         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5919         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5920     updateDAGForMaybeTailCall(MC);
5921     return;
5922   }
5923   case Intrinsic::memcpy_inline: {
5924     const auto &MCI = cast<MemCpyInlineInst>(I);
5925     SDValue Dst = getValue(I.getArgOperand(0));
5926     SDValue Src = getValue(I.getArgOperand(1));
5927     SDValue Size = getValue(I.getArgOperand(2));
5928     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5929     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5930     Align DstAlign = MCI.getDestAlign().valueOrOne();
5931     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5932     Align Alignment = std::min(DstAlign, SrcAlign);
5933     bool isVol = MCI.isVolatile();
5934     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5935     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5936     // node.
5937     SDValue MC = DAG.getMemcpy(
5938         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5939         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5940         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5941     updateDAGForMaybeTailCall(MC);
5942     return;
5943   }
5944   case Intrinsic::memset: {
5945     const auto &MSI = cast<MemSetInst>(I);
5946     SDValue Op1 = getValue(I.getArgOperand(0));
5947     SDValue Op2 = getValue(I.getArgOperand(1));
5948     SDValue Op3 = getValue(I.getArgOperand(2));
5949     // @llvm.memset defines 0 and 1 to both mean no alignment.
5950     Align Alignment = MSI.getDestAlign().valueOrOne();
5951     bool isVol = MSI.isVolatile();
5952     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5953     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5954     SDValue MS = DAG.getMemset(
5955         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5956         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5957     updateDAGForMaybeTailCall(MS);
5958     return;
5959   }
5960   case Intrinsic::memset_inline: {
5961     const auto &MSII = cast<MemSetInlineInst>(I);
5962     SDValue Dst = getValue(I.getArgOperand(0));
5963     SDValue Value = getValue(I.getArgOperand(1));
5964     SDValue Size = getValue(I.getArgOperand(2));
5965     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5966     // @llvm.memset defines 0 and 1 to both mean no alignment.
5967     Align DstAlign = MSII.getDestAlign().valueOrOne();
5968     bool isVol = MSII.isVolatile();
5969     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5970     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5971     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5972                                /* AlwaysInline */ true, isTC,
5973                                MachinePointerInfo(I.getArgOperand(0)),
5974                                I.getAAMetadata());
5975     updateDAGForMaybeTailCall(MC);
5976     return;
5977   }
5978   case Intrinsic::memmove: {
5979     const auto &MMI = cast<MemMoveInst>(I);
5980     SDValue Op1 = getValue(I.getArgOperand(0));
5981     SDValue Op2 = getValue(I.getArgOperand(1));
5982     SDValue Op3 = getValue(I.getArgOperand(2));
5983     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5984     Align DstAlign = MMI.getDestAlign().valueOrOne();
5985     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5986     Align Alignment = std::min(DstAlign, SrcAlign);
5987     bool isVol = MMI.isVolatile();
5988     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5989     // FIXME: Support passing different dest/src alignments to the memmove DAG
5990     // node.
5991     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5992     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5993                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5994                                 MachinePointerInfo(I.getArgOperand(1)),
5995                                 I.getAAMetadata(), AA);
5996     updateDAGForMaybeTailCall(MM);
5997     return;
5998   }
5999   case Intrinsic::memcpy_element_unordered_atomic: {
6000     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6001     SDValue Dst = getValue(MI.getRawDest());
6002     SDValue Src = getValue(MI.getRawSource());
6003     SDValue Length = getValue(MI.getLength());
6004 
6005     Type *LengthTy = MI.getLength()->getType();
6006     unsigned ElemSz = MI.getElementSizeInBytes();
6007     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6008     SDValue MC =
6009         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6010                             isTC, MachinePointerInfo(MI.getRawDest()),
6011                             MachinePointerInfo(MI.getRawSource()));
6012     updateDAGForMaybeTailCall(MC);
6013     return;
6014   }
6015   case Intrinsic::memmove_element_unordered_atomic: {
6016     auto &MI = cast<AtomicMemMoveInst>(I);
6017     SDValue Dst = getValue(MI.getRawDest());
6018     SDValue Src = getValue(MI.getRawSource());
6019     SDValue Length = getValue(MI.getLength());
6020 
6021     Type *LengthTy = MI.getLength()->getType();
6022     unsigned ElemSz = MI.getElementSizeInBytes();
6023     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6024     SDValue MC =
6025         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6026                              isTC, MachinePointerInfo(MI.getRawDest()),
6027                              MachinePointerInfo(MI.getRawSource()));
6028     updateDAGForMaybeTailCall(MC);
6029     return;
6030   }
6031   case Intrinsic::memset_element_unordered_atomic: {
6032     auto &MI = cast<AtomicMemSetInst>(I);
6033     SDValue Dst = getValue(MI.getRawDest());
6034     SDValue Val = getValue(MI.getValue());
6035     SDValue Length = getValue(MI.getLength());
6036 
6037     Type *LengthTy = MI.getLength()->getType();
6038     unsigned ElemSz = MI.getElementSizeInBytes();
6039     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6040     SDValue MC =
6041         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6042                             isTC, MachinePointerInfo(MI.getRawDest()));
6043     updateDAGForMaybeTailCall(MC);
6044     return;
6045   }
6046   case Intrinsic::call_preallocated_setup: {
6047     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6048     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6049     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6050                               getRoot(), SrcValue);
6051     setValue(&I, Res);
6052     DAG.setRoot(Res);
6053     return;
6054   }
6055   case Intrinsic::call_preallocated_arg: {
6056     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6057     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6058     SDValue Ops[3];
6059     Ops[0] = getRoot();
6060     Ops[1] = SrcValue;
6061     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6062                                    MVT::i32); // arg index
6063     SDValue Res = DAG.getNode(
6064         ISD::PREALLOCATED_ARG, sdl,
6065         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6066     setValue(&I, Res);
6067     DAG.setRoot(Res.getValue(1));
6068     return;
6069   }
6070   case Intrinsic::dbg_addr:
6071   case Intrinsic::dbg_declare: {
6072     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6073     // they are non-variadic.
6074     const auto &DI = cast<DbgVariableIntrinsic>(I);
6075     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6076     DILocalVariable *Variable = DI.getVariable();
6077     DIExpression *Expression = DI.getExpression();
6078     dropDanglingDebugInfo(Variable, Expression);
6079     assert(Variable && "Missing variable");
6080     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6081                       << "\n");
6082     // Check if address has undef value.
6083     const Value *Address = DI.getVariableLocationOp(0);
6084     if (!Address || isa<UndefValue>(Address) ||
6085         (Address->use_empty() && !isa<Argument>(Address))) {
6086       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6087                         << " (bad/undef/unused-arg address)\n");
6088       return;
6089     }
6090 
6091     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6092 
6093     // Check if this variable can be described by a frame index, typically
6094     // either as a static alloca or a byval parameter.
6095     int FI = std::numeric_limits<int>::max();
6096     if (const auto *AI =
6097             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6098       if (AI->isStaticAlloca()) {
6099         auto I = FuncInfo.StaticAllocaMap.find(AI);
6100         if (I != FuncInfo.StaticAllocaMap.end())
6101           FI = I->second;
6102       }
6103     } else if (const auto *Arg = dyn_cast<Argument>(
6104                    Address->stripInBoundsConstantOffsets())) {
6105       FI = FuncInfo.getArgumentFrameIndex(Arg);
6106     }
6107 
6108     // llvm.dbg.addr is control dependent and always generates indirect
6109     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6110     // the MachineFunction variable table.
6111     if (FI != std::numeric_limits<int>::max()) {
6112       if (Intrinsic == Intrinsic::dbg_addr) {
6113         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6114             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6115             dl, SDNodeOrder);
6116         DAG.AddDbgValue(SDV, isParameter);
6117       } else {
6118         LLVM_DEBUG(dbgs() << "Skipping " << DI
6119                           << " (variable info stashed in MF side table)\n");
6120       }
6121       return;
6122     }
6123 
6124     SDValue &N = NodeMap[Address];
6125     if (!N.getNode() && isa<Argument>(Address))
6126       // Check unused arguments map.
6127       N = UnusedArgNodeMap[Address];
6128     SDDbgValue *SDV;
6129     if (N.getNode()) {
6130       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6131         Address = BCI->getOperand(0);
6132       // Parameters are handled specially.
6133       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6134       if (isParameter && FINode) {
6135         // Byval parameter. We have a frame index at this point.
6136         SDV =
6137             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6138                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6139       } else if (isa<Argument>(Address)) {
6140         // Address is an argument, so try to emit its dbg value using
6141         // virtual register info from the FuncInfo.ValueMap.
6142         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6143                                  FuncArgumentDbgValueKind::Declare, N);
6144         return;
6145       } else {
6146         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6147                               true, dl, SDNodeOrder);
6148       }
6149       DAG.AddDbgValue(SDV, isParameter);
6150     } else {
6151       // If Address is an argument then try to emit its dbg value using
6152       // virtual register info from the FuncInfo.ValueMap.
6153       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6154                                     FuncArgumentDbgValueKind::Declare, N)) {
6155         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6156                           << " (could not emit func-arg dbg_value)\n");
6157       }
6158     }
6159     return;
6160   }
6161   case Intrinsic::dbg_label: {
6162     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6163     DILabel *Label = DI.getLabel();
6164     assert(Label && "Missing label");
6165 
6166     SDDbgLabel *SDV;
6167     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6168     DAG.AddDbgLabel(SDV);
6169     return;
6170   }
6171   case Intrinsic::dbg_value: {
6172     const DbgValueInst &DI = cast<DbgValueInst>(I);
6173     assert(DI.getVariable() && "Missing variable");
6174 
6175     DILocalVariable *Variable = DI.getVariable();
6176     DIExpression *Expression = DI.getExpression();
6177     dropDanglingDebugInfo(Variable, Expression);
6178     SmallVector<Value *, 4> Values(DI.getValues());
6179     if (Values.empty())
6180       return;
6181 
6182     if (llvm::is_contained(Values, nullptr))
6183       return;
6184 
6185     bool IsVariadic = DI.hasArgList();
6186     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6187                           SDNodeOrder, IsVariadic))
6188       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6189     return;
6190   }
6191 
6192   case Intrinsic::eh_typeid_for: {
6193     // Find the type id for the given typeinfo.
6194     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6195     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6196     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6197     setValue(&I, Res);
6198     return;
6199   }
6200 
6201   case Intrinsic::eh_return_i32:
6202   case Intrinsic::eh_return_i64:
6203     DAG.getMachineFunction().setCallsEHReturn(true);
6204     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6205                             MVT::Other,
6206                             getControlRoot(),
6207                             getValue(I.getArgOperand(0)),
6208                             getValue(I.getArgOperand(1))));
6209     return;
6210   case Intrinsic::eh_unwind_init:
6211     DAG.getMachineFunction().setCallsUnwindInit(true);
6212     return;
6213   case Intrinsic::eh_dwarf_cfa:
6214     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6215                              TLI.getPointerTy(DAG.getDataLayout()),
6216                              getValue(I.getArgOperand(0))));
6217     return;
6218   case Intrinsic::eh_sjlj_callsite: {
6219     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6220     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6221     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6222 
6223     MMI.setCurrentCallSite(CI->getZExtValue());
6224     return;
6225   }
6226   case Intrinsic::eh_sjlj_functioncontext: {
6227     // Get and store the index of the function context.
6228     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6229     AllocaInst *FnCtx =
6230       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6231     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6232     MFI.setFunctionContextIndex(FI);
6233     return;
6234   }
6235   case Intrinsic::eh_sjlj_setjmp: {
6236     SDValue Ops[2];
6237     Ops[0] = getRoot();
6238     Ops[1] = getValue(I.getArgOperand(0));
6239     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6240                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6241     setValue(&I, Op.getValue(0));
6242     DAG.setRoot(Op.getValue(1));
6243     return;
6244   }
6245   case Intrinsic::eh_sjlj_longjmp:
6246     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6247                             getRoot(), getValue(I.getArgOperand(0))));
6248     return;
6249   case Intrinsic::eh_sjlj_setup_dispatch:
6250     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6251                             getRoot()));
6252     return;
6253   case Intrinsic::masked_gather:
6254     visitMaskedGather(I);
6255     return;
6256   case Intrinsic::masked_load:
6257     visitMaskedLoad(I);
6258     return;
6259   case Intrinsic::masked_scatter:
6260     visitMaskedScatter(I);
6261     return;
6262   case Intrinsic::masked_store:
6263     visitMaskedStore(I);
6264     return;
6265   case Intrinsic::masked_expandload:
6266     visitMaskedLoad(I, true /* IsExpanding */);
6267     return;
6268   case Intrinsic::masked_compressstore:
6269     visitMaskedStore(I, true /* IsCompressing */);
6270     return;
6271   case Intrinsic::powi:
6272     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6273                             getValue(I.getArgOperand(1)), DAG));
6274     return;
6275   case Intrinsic::log:
6276     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6277     return;
6278   case Intrinsic::log2:
6279     setValue(&I,
6280              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6281     return;
6282   case Intrinsic::log10:
6283     setValue(&I,
6284              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6285     return;
6286   case Intrinsic::exp:
6287     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6288     return;
6289   case Intrinsic::exp2:
6290     setValue(&I,
6291              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6292     return;
6293   case Intrinsic::pow:
6294     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6295                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6296     return;
6297   case Intrinsic::sqrt:
6298   case Intrinsic::fabs:
6299   case Intrinsic::sin:
6300   case Intrinsic::cos:
6301   case Intrinsic::floor:
6302   case Intrinsic::ceil:
6303   case Intrinsic::trunc:
6304   case Intrinsic::rint:
6305   case Intrinsic::nearbyint:
6306   case Intrinsic::round:
6307   case Intrinsic::roundeven:
6308   case Intrinsic::canonicalize: {
6309     unsigned Opcode;
6310     switch (Intrinsic) {
6311     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6312     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6313     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6314     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6315     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6316     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6317     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6318     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6319     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6320     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6321     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6322     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6323     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6324     }
6325 
6326     setValue(&I, DAG.getNode(Opcode, sdl,
6327                              getValue(I.getArgOperand(0)).getValueType(),
6328                              getValue(I.getArgOperand(0)), Flags));
6329     return;
6330   }
6331   case Intrinsic::lround:
6332   case Intrinsic::llround:
6333   case Intrinsic::lrint:
6334   case Intrinsic::llrint: {
6335     unsigned Opcode;
6336     switch (Intrinsic) {
6337     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6338     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6339     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6340     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6341     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6342     }
6343 
6344     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6345     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6346                              getValue(I.getArgOperand(0))));
6347     return;
6348   }
6349   case Intrinsic::minnum:
6350     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6351                              getValue(I.getArgOperand(0)).getValueType(),
6352                              getValue(I.getArgOperand(0)),
6353                              getValue(I.getArgOperand(1)), Flags));
6354     return;
6355   case Intrinsic::maxnum:
6356     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6357                              getValue(I.getArgOperand(0)).getValueType(),
6358                              getValue(I.getArgOperand(0)),
6359                              getValue(I.getArgOperand(1)), Flags));
6360     return;
6361   case Intrinsic::minimum:
6362     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6363                              getValue(I.getArgOperand(0)).getValueType(),
6364                              getValue(I.getArgOperand(0)),
6365                              getValue(I.getArgOperand(1)), Flags));
6366     return;
6367   case Intrinsic::maximum:
6368     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6369                              getValue(I.getArgOperand(0)).getValueType(),
6370                              getValue(I.getArgOperand(0)),
6371                              getValue(I.getArgOperand(1)), Flags));
6372     return;
6373   case Intrinsic::copysign:
6374     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6375                              getValue(I.getArgOperand(0)).getValueType(),
6376                              getValue(I.getArgOperand(0)),
6377                              getValue(I.getArgOperand(1)), Flags));
6378     return;
6379   case Intrinsic::arithmetic_fence: {
6380     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6381                              getValue(I.getArgOperand(0)).getValueType(),
6382                              getValue(I.getArgOperand(0)), Flags));
6383     return;
6384   }
6385   case Intrinsic::fma:
6386     setValue(&I, DAG.getNode(
6387                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6388                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6389                      getValue(I.getArgOperand(2)), Flags));
6390     return;
6391 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6392   case Intrinsic::INTRINSIC:
6393 #include "llvm/IR/ConstrainedOps.def"
6394     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6395     return;
6396 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6397 #include "llvm/IR/VPIntrinsics.def"
6398     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6399     return;
6400   case Intrinsic::fptrunc_round: {
6401     // Get the last argument, the metadata and convert it to an integer in the
6402     // call
6403     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6404     Optional<RoundingMode> RoundMode =
6405         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6406 
6407     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6408 
6409     // Propagate fast-math-flags from IR to node(s).
6410     SDNodeFlags Flags;
6411     Flags.copyFMF(*cast<FPMathOperator>(&I));
6412     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6413 
6414     SDValue Result;
6415     Result = DAG.getNode(
6416         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6417         DAG.getTargetConstant((int)*RoundMode, sdl,
6418                               TLI.getPointerTy(DAG.getDataLayout())));
6419     setValue(&I, Result);
6420 
6421     return;
6422   }
6423   case Intrinsic::fmuladd: {
6424     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6425     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6426         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6427       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6428                                getValue(I.getArgOperand(0)).getValueType(),
6429                                getValue(I.getArgOperand(0)),
6430                                getValue(I.getArgOperand(1)),
6431                                getValue(I.getArgOperand(2)), Flags));
6432     } else {
6433       // TODO: Intrinsic calls should have fast-math-flags.
6434       SDValue Mul = DAG.getNode(
6435           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6436           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6437       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6438                                 getValue(I.getArgOperand(0)).getValueType(),
6439                                 Mul, getValue(I.getArgOperand(2)), Flags);
6440       setValue(&I, Add);
6441     }
6442     return;
6443   }
6444   case Intrinsic::convert_to_fp16:
6445     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6446                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6447                                          getValue(I.getArgOperand(0)),
6448                                          DAG.getTargetConstant(0, sdl,
6449                                                                MVT::i32))));
6450     return;
6451   case Intrinsic::convert_from_fp16:
6452     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6453                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6454                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6455                                          getValue(I.getArgOperand(0)))));
6456     return;
6457   case Intrinsic::fptosi_sat: {
6458     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6459     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6460                              getValue(I.getArgOperand(0)),
6461                              DAG.getValueType(VT.getScalarType())));
6462     return;
6463   }
6464   case Intrinsic::fptoui_sat: {
6465     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6466     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6467                              getValue(I.getArgOperand(0)),
6468                              DAG.getValueType(VT.getScalarType())));
6469     return;
6470   }
6471   case Intrinsic::set_rounding:
6472     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6473                       {getRoot(), getValue(I.getArgOperand(0))});
6474     setValue(&I, Res);
6475     DAG.setRoot(Res.getValue(0));
6476     return;
6477   case Intrinsic::is_fpclass: {
6478     const DataLayout DLayout = DAG.getDataLayout();
6479     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6480     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6481     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6482     MachineFunction &MF = DAG.getMachineFunction();
6483     const Function &F = MF.getFunction();
6484     SDValue Op = getValue(I.getArgOperand(0));
6485     SDNodeFlags Flags;
6486     Flags.setNoFPExcept(
6487         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6488     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6489     // expansion can use illegal types. Making expansion early allows
6490     // legalizing these types prior to selection.
6491     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6492       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6493       setValue(&I, Result);
6494       return;
6495     }
6496 
6497     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6498     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6499     setValue(&I, V);
6500     return;
6501   }
6502   case Intrinsic::pcmarker: {
6503     SDValue Tmp = getValue(I.getArgOperand(0));
6504     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6505     return;
6506   }
6507   case Intrinsic::readcyclecounter: {
6508     SDValue Op = getRoot();
6509     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6510                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6511     setValue(&I, Res);
6512     DAG.setRoot(Res.getValue(1));
6513     return;
6514   }
6515   case Intrinsic::bitreverse:
6516     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6517                              getValue(I.getArgOperand(0)).getValueType(),
6518                              getValue(I.getArgOperand(0))));
6519     return;
6520   case Intrinsic::bswap:
6521     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6522                              getValue(I.getArgOperand(0)).getValueType(),
6523                              getValue(I.getArgOperand(0))));
6524     return;
6525   case Intrinsic::cttz: {
6526     SDValue Arg = getValue(I.getArgOperand(0));
6527     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6528     EVT Ty = Arg.getValueType();
6529     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6530                              sdl, Ty, Arg));
6531     return;
6532   }
6533   case Intrinsic::ctlz: {
6534     SDValue Arg = getValue(I.getArgOperand(0));
6535     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6536     EVT Ty = Arg.getValueType();
6537     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6538                              sdl, Ty, Arg));
6539     return;
6540   }
6541   case Intrinsic::ctpop: {
6542     SDValue Arg = getValue(I.getArgOperand(0));
6543     EVT Ty = Arg.getValueType();
6544     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6545     return;
6546   }
6547   case Intrinsic::fshl:
6548   case Intrinsic::fshr: {
6549     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6550     SDValue X = getValue(I.getArgOperand(0));
6551     SDValue Y = getValue(I.getArgOperand(1));
6552     SDValue Z = getValue(I.getArgOperand(2));
6553     EVT VT = X.getValueType();
6554 
6555     if (X == Y) {
6556       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6557       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6558     } else {
6559       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6560       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6561     }
6562     return;
6563   }
6564   case Intrinsic::sadd_sat: {
6565     SDValue Op1 = getValue(I.getArgOperand(0));
6566     SDValue Op2 = getValue(I.getArgOperand(1));
6567     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6568     return;
6569   }
6570   case Intrinsic::uadd_sat: {
6571     SDValue Op1 = getValue(I.getArgOperand(0));
6572     SDValue Op2 = getValue(I.getArgOperand(1));
6573     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6574     return;
6575   }
6576   case Intrinsic::ssub_sat: {
6577     SDValue Op1 = getValue(I.getArgOperand(0));
6578     SDValue Op2 = getValue(I.getArgOperand(1));
6579     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6580     return;
6581   }
6582   case Intrinsic::usub_sat: {
6583     SDValue Op1 = getValue(I.getArgOperand(0));
6584     SDValue Op2 = getValue(I.getArgOperand(1));
6585     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6586     return;
6587   }
6588   case Intrinsic::sshl_sat: {
6589     SDValue Op1 = getValue(I.getArgOperand(0));
6590     SDValue Op2 = getValue(I.getArgOperand(1));
6591     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6592     return;
6593   }
6594   case Intrinsic::ushl_sat: {
6595     SDValue Op1 = getValue(I.getArgOperand(0));
6596     SDValue Op2 = getValue(I.getArgOperand(1));
6597     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6598     return;
6599   }
6600   case Intrinsic::smul_fix:
6601   case Intrinsic::umul_fix:
6602   case Intrinsic::smul_fix_sat:
6603   case Intrinsic::umul_fix_sat: {
6604     SDValue Op1 = getValue(I.getArgOperand(0));
6605     SDValue Op2 = getValue(I.getArgOperand(1));
6606     SDValue Op3 = getValue(I.getArgOperand(2));
6607     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6608                              Op1.getValueType(), Op1, Op2, Op3));
6609     return;
6610   }
6611   case Intrinsic::sdiv_fix:
6612   case Intrinsic::udiv_fix:
6613   case Intrinsic::sdiv_fix_sat:
6614   case Intrinsic::udiv_fix_sat: {
6615     SDValue Op1 = getValue(I.getArgOperand(0));
6616     SDValue Op2 = getValue(I.getArgOperand(1));
6617     SDValue Op3 = getValue(I.getArgOperand(2));
6618     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6619                               Op1, Op2, Op3, DAG, TLI));
6620     return;
6621   }
6622   case Intrinsic::smax: {
6623     SDValue Op1 = getValue(I.getArgOperand(0));
6624     SDValue Op2 = getValue(I.getArgOperand(1));
6625     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6626     return;
6627   }
6628   case Intrinsic::smin: {
6629     SDValue Op1 = getValue(I.getArgOperand(0));
6630     SDValue Op2 = getValue(I.getArgOperand(1));
6631     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6632     return;
6633   }
6634   case Intrinsic::umax: {
6635     SDValue Op1 = getValue(I.getArgOperand(0));
6636     SDValue Op2 = getValue(I.getArgOperand(1));
6637     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6638     return;
6639   }
6640   case Intrinsic::umin: {
6641     SDValue Op1 = getValue(I.getArgOperand(0));
6642     SDValue Op2 = getValue(I.getArgOperand(1));
6643     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6644     return;
6645   }
6646   case Intrinsic::abs: {
6647     // TODO: Preserve "int min is poison" arg in SDAG?
6648     SDValue Op1 = getValue(I.getArgOperand(0));
6649     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6650     return;
6651   }
6652   case Intrinsic::stacksave: {
6653     SDValue Op = getRoot();
6654     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6655     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6656     setValue(&I, Res);
6657     DAG.setRoot(Res.getValue(1));
6658     return;
6659   }
6660   case Intrinsic::stackrestore:
6661     Res = getValue(I.getArgOperand(0));
6662     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6663     return;
6664   case Intrinsic::get_dynamic_area_offset: {
6665     SDValue Op = getRoot();
6666     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6667     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6668     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6669     // target.
6670     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6671       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6672                          " intrinsic!");
6673     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6674                       Op);
6675     DAG.setRoot(Op);
6676     setValue(&I, Res);
6677     return;
6678   }
6679   case Intrinsic::stackguard: {
6680     MachineFunction &MF = DAG.getMachineFunction();
6681     const Module &M = *MF.getFunction().getParent();
6682     SDValue Chain = getRoot();
6683     if (TLI.useLoadStackGuardNode()) {
6684       Res = getLoadStackGuard(DAG, sdl, Chain);
6685     } else {
6686       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6687       const Value *Global = TLI.getSDagStackGuard(M);
6688       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6689       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6690                         MachinePointerInfo(Global, 0), Align,
6691                         MachineMemOperand::MOVolatile);
6692     }
6693     if (TLI.useStackGuardXorFP())
6694       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6695     DAG.setRoot(Chain);
6696     setValue(&I, Res);
6697     return;
6698   }
6699   case Intrinsic::stackprotector: {
6700     // Emit code into the DAG to store the stack guard onto the stack.
6701     MachineFunction &MF = DAG.getMachineFunction();
6702     MachineFrameInfo &MFI = MF.getFrameInfo();
6703     SDValue Src, Chain = getRoot();
6704 
6705     if (TLI.useLoadStackGuardNode())
6706       Src = getLoadStackGuard(DAG, sdl, Chain);
6707     else
6708       Src = getValue(I.getArgOperand(0));   // The guard's value.
6709 
6710     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6711 
6712     int FI = FuncInfo.StaticAllocaMap[Slot];
6713     MFI.setStackProtectorIndex(FI);
6714     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6715 
6716     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6717 
6718     // Store the stack protector onto the stack.
6719     Res = DAG.getStore(
6720         Chain, sdl, Src, FIN,
6721         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6722         MaybeAlign(), MachineMemOperand::MOVolatile);
6723     setValue(&I, Res);
6724     DAG.setRoot(Res);
6725     return;
6726   }
6727   case Intrinsic::objectsize:
6728     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6729 
6730   case Intrinsic::is_constant:
6731     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6732 
6733   case Intrinsic::annotation:
6734   case Intrinsic::ptr_annotation:
6735   case Intrinsic::launder_invariant_group:
6736   case Intrinsic::strip_invariant_group:
6737     // Drop the intrinsic, but forward the value
6738     setValue(&I, getValue(I.getOperand(0)));
6739     return;
6740 
6741   case Intrinsic::assume:
6742   case Intrinsic::experimental_noalias_scope_decl:
6743   case Intrinsic::var_annotation:
6744   case Intrinsic::sideeffect:
6745     // Discard annotate attributes, noalias scope declarations, assumptions, and
6746     // artificial side-effects.
6747     return;
6748 
6749   case Intrinsic::codeview_annotation: {
6750     // Emit a label associated with this metadata.
6751     MachineFunction &MF = DAG.getMachineFunction();
6752     MCSymbol *Label =
6753         MF.getMMI().getContext().createTempSymbol("annotation", true);
6754     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6755     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6756     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6757     DAG.setRoot(Res);
6758     return;
6759   }
6760 
6761   case Intrinsic::init_trampoline: {
6762     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6763 
6764     SDValue Ops[6];
6765     Ops[0] = getRoot();
6766     Ops[1] = getValue(I.getArgOperand(0));
6767     Ops[2] = getValue(I.getArgOperand(1));
6768     Ops[3] = getValue(I.getArgOperand(2));
6769     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6770     Ops[5] = DAG.getSrcValue(F);
6771 
6772     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6773 
6774     DAG.setRoot(Res);
6775     return;
6776   }
6777   case Intrinsic::adjust_trampoline:
6778     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6779                              TLI.getPointerTy(DAG.getDataLayout()),
6780                              getValue(I.getArgOperand(0))));
6781     return;
6782   case Intrinsic::gcroot: {
6783     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6784            "only valid in functions with gc specified, enforced by Verifier");
6785     assert(GFI && "implied by previous");
6786     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6787     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6788 
6789     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6790     GFI->addStackRoot(FI->getIndex(), TypeMap);
6791     return;
6792   }
6793   case Intrinsic::gcread:
6794   case Intrinsic::gcwrite:
6795     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6796   case Intrinsic::flt_rounds:
6797     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6798     setValue(&I, Res);
6799     DAG.setRoot(Res.getValue(1));
6800     return;
6801 
6802   case Intrinsic::expect:
6803     // Just replace __builtin_expect(exp, c) with EXP.
6804     setValue(&I, getValue(I.getArgOperand(0)));
6805     return;
6806 
6807   case Intrinsic::ubsantrap:
6808   case Intrinsic::debugtrap:
6809   case Intrinsic::trap: {
6810     StringRef TrapFuncName =
6811         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6812     if (TrapFuncName.empty()) {
6813       switch (Intrinsic) {
6814       case Intrinsic::trap:
6815         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6816         break;
6817       case Intrinsic::debugtrap:
6818         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6819         break;
6820       case Intrinsic::ubsantrap:
6821         DAG.setRoot(DAG.getNode(
6822             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6823             DAG.getTargetConstant(
6824                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6825                 MVT::i32)));
6826         break;
6827       default: llvm_unreachable("unknown trap intrinsic");
6828       }
6829       return;
6830     }
6831     TargetLowering::ArgListTy Args;
6832     if (Intrinsic == Intrinsic::ubsantrap) {
6833       Args.push_back(TargetLoweringBase::ArgListEntry());
6834       Args[0].Val = I.getArgOperand(0);
6835       Args[0].Node = getValue(Args[0].Val);
6836       Args[0].Ty = Args[0].Val->getType();
6837     }
6838 
6839     TargetLowering::CallLoweringInfo CLI(DAG);
6840     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6841         CallingConv::C, I.getType(),
6842         DAG.getExternalSymbol(TrapFuncName.data(),
6843                               TLI.getPointerTy(DAG.getDataLayout())),
6844         std::move(Args));
6845 
6846     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6847     DAG.setRoot(Result.second);
6848     return;
6849   }
6850 
6851   case Intrinsic::uadd_with_overflow:
6852   case Intrinsic::sadd_with_overflow:
6853   case Intrinsic::usub_with_overflow:
6854   case Intrinsic::ssub_with_overflow:
6855   case Intrinsic::umul_with_overflow:
6856   case Intrinsic::smul_with_overflow: {
6857     ISD::NodeType Op;
6858     switch (Intrinsic) {
6859     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6860     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6861     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6862     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6863     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6864     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6865     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6866     }
6867     SDValue Op1 = getValue(I.getArgOperand(0));
6868     SDValue Op2 = getValue(I.getArgOperand(1));
6869 
6870     EVT ResultVT = Op1.getValueType();
6871     EVT OverflowVT = MVT::i1;
6872     if (ResultVT.isVector())
6873       OverflowVT = EVT::getVectorVT(
6874           *Context, OverflowVT, ResultVT.getVectorElementCount());
6875 
6876     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6877     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6878     return;
6879   }
6880   case Intrinsic::prefetch: {
6881     SDValue Ops[5];
6882     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6883     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6884     Ops[0] = DAG.getRoot();
6885     Ops[1] = getValue(I.getArgOperand(0));
6886     Ops[2] = getValue(I.getArgOperand(1));
6887     Ops[3] = getValue(I.getArgOperand(2));
6888     Ops[4] = getValue(I.getArgOperand(3));
6889     SDValue Result = DAG.getMemIntrinsicNode(
6890         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6891         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6892         /* align */ None, Flags);
6893 
6894     // Chain the prefetch in parallell with any pending loads, to stay out of
6895     // the way of later optimizations.
6896     PendingLoads.push_back(Result);
6897     Result = getRoot();
6898     DAG.setRoot(Result);
6899     return;
6900   }
6901   case Intrinsic::lifetime_start:
6902   case Intrinsic::lifetime_end: {
6903     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6904     // Stack coloring is not enabled in O0, discard region information.
6905     if (TM.getOptLevel() == CodeGenOpt::None)
6906       return;
6907 
6908     const int64_t ObjectSize =
6909         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6910     Value *const ObjectPtr = I.getArgOperand(1);
6911     SmallVector<const Value *, 4> Allocas;
6912     getUnderlyingObjects(ObjectPtr, Allocas);
6913 
6914     for (const Value *Alloca : Allocas) {
6915       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6916 
6917       // Could not find an Alloca.
6918       if (!LifetimeObject)
6919         continue;
6920 
6921       // First check that the Alloca is static, otherwise it won't have a
6922       // valid frame index.
6923       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6924       if (SI == FuncInfo.StaticAllocaMap.end())
6925         return;
6926 
6927       const int FrameIndex = SI->second;
6928       int64_t Offset;
6929       if (GetPointerBaseWithConstantOffset(
6930               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6931         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6932       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6933                                 Offset);
6934       DAG.setRoot(Res);
6935     }
6936     return;
6937   }
6938   case Intrinsic::pseudoprobe: {
6939     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6940     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6941     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6942     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6943     DAG.setRoot(Res);
6944     return;
6945   }
6946   case Intrinsic::invariant_start:
6947     // Discard region information.
6948     setValue(&I,
6949              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6950     return;
6951   case Intrinsic::invariant_end:
6952     // Discard region information.
6953     return;
6954   case Intrinsic::clear_cache:
6955     /// FunctionName may be null.
6956     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6957       lowerCallToExternalSymbol(I, FunctionName);
6958     return;
6959   case Intrinsic::donothing:
6960   case Intrinsic::seh_try_begin:
6961   case Intrinsic::seh_scope_begin:
6962   case Intrinsic::seh_try_end:
6963   case Intrinsic::seh_scope_end:
6964     // ignore
6965     return;
6966   case Intrinsic::experimental_stackmap:
6967     visitStackmap(I);
6968     return;
6969   case Intrinsic::experimental_patchpoint_void:
6970   case Intrinsic::experimental_patchpoint_i64:
6971     visitPatchpoint(I);
6972     return;
6973   case Intrinsic::experimental_gc_statepoint:
6974     LowerStatepoint(cast<GCStatepointInst>(I));
6975     return;
6976   case Intrinsic::experimental_gc_result:
6977     visitGCResult(cast<GCResultInst>(I));
6978     return;
6979   case Intrinsic::experimental_gc_relocate:
6980     visitGCRelocate(cast<GCRelocateInst>(I));
6981     return;
6982   case Intrinsic::instrprof_cover:
6983     llvm_unreachable("instrprof failed to lower a cover");
6984   case Intrinsic::instrprof_increment:
6985     llvm_unreachable("instrprof failed to lower an increment");
6986   case Intrinsic::instrprof_value_profile:
6987     llvm_unreachable("instrprof failed to lower a value profiling call");
6988   case Intrinsic::localescape: {
6989     MachineFunction &MF = DAG.getMachineFunction();
6990     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6991 
6992     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6993     // is the same on all targets.
6994     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6995       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6996       if (isa<ConstantPointerNull>(Arg))
6997         continue; // Skip null pointers. They represent a hole in index space.
6998       AllocaInst *Slot = cast<AllocaInst>(Arg);
6999       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7000              "can only escape static allocas");
7001       int FI = FuncInfo.StaticAllocaMap[Slot];
7002       MCSymbol *FrameAllocSym =
7003           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7004               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7005       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7006               TII->get(TargetOpcode::LOCAL_ESCAPE))
7007           .addSym(FrameAllocSym)
7008           .addFrameIndex(FI);
7009     }
7010 
7011     return;
7012   }
7013 
7014   case Intrinsic::localrecover: {
7015     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7016     MachineFunction &MF = DAG.getMachineFunction();
7017 
7018     // Get the symbol that defines the frame offset.
7019     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7020     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7021     unsigned IdxVal =
7022         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7023     MCSymbol *FrameAllocSym =
7024         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7025             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7026 
7027     Value *FP = I.getArgOperand(1);
7028     SDValue FPVal = getValue(FP);
7029     EVT PtrVT = FPVal.getValueType();
7030 
7031     // Create a MCSymbol for the label to avoid any target lowering
7032     // that would make this PC relative.
7033     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7034     SDValue OffsetVal =
7035         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7036 
7037     // Add the offset to the FP.
7038     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7039     setValue(&I, Add);
7040 
7041     return;
7042   }
7043 
7044   case Intrinsic::eh_exceptionpointer:
7045   case Intrinsic::eh_exceptioncode: {
7046     // Get the exception pointer vreg, copy from it, and resize it to fit.
7047     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7048     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7049     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7050     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7051     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7052     if (Intrinsic == Intrinsic::eh_exceptioncode)
7053       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7054     setValue(&I, N);
7055     return;
7056   }
7057   case Intrinsic::xray_customevent: {
7058     // Here we want to make sure that the intrinsic behaves as if it has a
7059     // specific calling convention, and only for x86_64.
7060     // FIXME: Support other platforms later.
7061     const auto &Triple = DAG.getTarget().getTargetTriple();
7062     if (Triple.getArch() != Triple::x86_64)
7063       return;
7064 
7065     SmallVector<SDValue, 8> Ops;
7066 
7067     // We want to say that we always want the arguments in registers.
7068     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7069     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7070     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7071     SDValue Chain = getRoot();
7072     Ops.push_back(LogEntryVal);
7073     Ops.push_back(StrSizeVal);
7074     Ops.push_back(Chain);
7075 
7076     // We need to enforce the calling convention for the callsite, so that
7077     // argument ordering is enforced correctly, and that register allocation can
7078     // see that some registers may be assumed clobbered and have to preserve
7079     // them across calls to the intrinsic.
7080     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7081                                            sdl, NodeTys, Ops);
7082     SDValue patchableNode = SDValue(MN, 0);
7083     DAG.setRoot(patchableNode);
7084     setValue(&I, patchableNode);
7085     return;
7086   }
7087   case Intrinsic::xray_typedevent: {
7088     // Here we want to make sure that the intrinsic behaves as if it has a
7089     // specific calling convention, and only for x86_64.
7090     // FIXME: Support other platforms later.
7091     const auto &Triple = DAG.getTarget().getTargetTriple();
7092     if (Triple.getArch() != Triple::x86_64)
7093       return;
7094 
7095     SmallVector<SDValue, 8> Ops;
7096 
7097     // We want to say that we always want the arguments in registers.
7098     // It's unclear to me how manipulating the selection DAG here forces callers
7099     // to provide arguments in registers instead of on the stack.
7100     SDValue LogTypeId = getValue(I.getArgOperand(0));
7101     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7102     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7103     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7104     SDValue Chain = getRoot();
7105     Ops.push_back(LogTypeId);
7106     Ops.push_back(LogEntryVal);
7107     Ops.push_back(StrSizeVal);
7108     Ops.push_back(Chain);
7109 
7110     // We need to enforce the calling convention for the callsite, so that
7111     // argument ordering is enforced correctly, and that register allocation can
7112     // see that some registers may be assumed clobbered and have to preserve
7113     // them across calls to the intrinsic.
7114     MachineSDNode *MN = DAG.getMachineNode(
7115         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7116     SDValue patchableNode = SDValue(MN, 0);
7117     DAG.setRoot(patchableNode);
7118     setValue(&I, patchableNode);
7119     return;
7120   }
7121   case Intrinsic::experimental_deoptimize:
7122     LowerDeoptimizeCall(&I);
7123     return;
7124   case Intrinsic::experimental_stepvector:
7125     visitStepVector(I);
7126     return;
7127   case Intrinsic::vector_reduce_fadd:
7128   case Intrinsic::vector_reduce_fmul:
7129   case Intrinsic::vector_reduce_add:
7130   case Intrinsic::vector_reduce_mul:
7131   case Intrinsic::vector_reduce_and:
7132   case Intrinsic::vector_reduce_or:
7133   case Intrinsic::vector_reduce_xor:
7134   case Intrinsic::vector_reduce_smax:
7135   case Intrinsic::vector_reduce_smin:
7136   case Intrinsic::vector_reduce_umax:
7137   case Intrinsic::vector_reduce_umin:
7138   case Intrinsic::vector_reduce_fmax:
7139   case Intrinsic::vector_reduce_fmin:
7140     visitVectorReduce(I, Intrinsic);
7141     return;
7142 
7143   case Intrinsic::icall_branch_funnel: {
7144     SmallVector<SDValue, 16> Ops;
7145     Ops.push_back(getValue(I.getArgOperand(0)));
7146 
7147     int64_t Offset;
7148     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7149         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7150     if (!Base)
7151       report_fatal_error(
7152           "llvm.icall.branch.funnel operand must be a GlobalValue");
7153     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7154 
7155     struct BranchFunnelTarget {
7156       int64_t Offset;
7157       SDValue Target;
7158     };
7159     SmallVector<BranchFunnelTarget, 8> Targets;
7160 
7161     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7162       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7163           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7164       if (ElemBase != Base)
7165         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7166                            "to the same GlobalValue");
7167 
7168       SDValue Val = getValue(I.getArgOperand(Op + 1));
7169       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7170       if (!GA)
7171         report_fatal_error(
7172             "llvm.icall.branch.funnel operand must be a GlobalValue");
7173       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7174                                      GA->getGlobal(), sdl, Val.getValueType(),
7175                                      GA->getOffset())});
7176     }
7177     llvm::sort(Targets,
7178                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7179                  return T1.Offset < T2.Offset;
7180                });
7181 
7182     for (auto &T : Targets) {
7183       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7184       Ops.push_back(T.Target);
7185     }
7186 
7187     Ops.push_back(DAG.getRoot()); // Chain
7188     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7189                                  MVT::Other, Ops),
7190               0);
7191     DAG.setRoot(N);
7192     setValue(&I, N);
7193     HasTailCall = true;
7194     return;
7195   }
7196 
7197   case Intrinsic::wasm_landingpad_index:
7198     // Information this intrinsic contained has been transferred to
7199     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7200     // delete it now.
7201     return;
7202 
7203   case Intrinsic::aarch64_settag:
7204   case Intrinsic::aarch64_settag_zero: {
7205     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7206     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7207     SDValue Val = TSI.EmitTargetCodeForSetTag(
7208         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7209         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7210         ZeroMemory);
7211     DAG.setRoot(Val);
7212     setValue(&I, Val);
7213     return;
7214   }
7215   case Intrinsic::ptrmask: {
7216     SDValue Ptr = getValue(I.getOperand(0));
7217     SDValue Const = getValue(I.getOperand(1));
7218 
7219     EVT PtrVT = Ptr.getValueType();
7220     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7221                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7222     return;
7223   }
7224   case Intrinsic::threadlocal_address: {
7225     setValue(&I, getValue(I.getOperand(0)));
7226     return;
7227   }
7228   case Intrinsic::get_active_lane_mask: {
7229     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7230     SDValue Index = getValue(I.getOperand(0));
7231     EVT ElementVT = Index.getValueType();
7232 
7233     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7234       visitTargetIntrinsic(I, Intrinsic);
7235       return;
7236     }
7237 
7238     SDValue TripCount = getValue(I.getOperand(1));
7239     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7240 
7241     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7242     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7243     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7244     SDValue VectorInduction = DAG.getNode(
7245         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7246     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7247                                  VectorTripCount, ISD::CondCode::SETULT);
7248     setValue(&I, SetCC);
7249     return;
7250   }
7251   case Intrinsic::vector_insert: {
7252     SDValue Vec = getValue(I.getOperand(0));
7253     SDValue SubVec = getValue(I.getOperand(1));
7254     SDValue Index = getValue(I.getOperand(2));
7255 
7256     // The intrinsic's index type is i64, but the SDNode requires an index type
7257     // suitable for the target. Convert the index as required.
7258     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7259     if (Index.getValueType() != VectorIdxTy)
7260       Index = DAG.getVectorIdxConstant(
7261           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7262 
7263     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7264     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7265                              Index));
7266     return;
7267   }
7268   case Intrinsic::vector_extract: {
7269     SDValue Vec = getValue(I.getOperand(0));
7270     SDValue Index = getValue(I.getOperand(1));
7271     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7272 
7273     // The intrinsic's index type is i64, but the SDNode requires an index type
7274     // suitable for the target. Convert the index as required.
7275     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7276     if (Index.getValueType() != VectorIdxTy)
7277       Index = DAG.getVectorIdxConstant(
7278           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7279 
7280     setValue(&I,
7281              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7282     return;
7283   }
7284   case Intrinsic::experimental_vector_reverse:
7285     visitVectorReverse(I);
7286     return;
7287   case Intrinsic::experimental_vector_splice:
7288     visitVectorSplice(I);
7289     return;
7290   }
7291 }
7292 
7293 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7294     const ConstrainedFPIntrinsic &FPI) {
7295   SDLoc sdl = getCurSDLoc();
7296 
7297   // We do not need to serialize constrained FP intrinsics against
7298   // each other or against (nonvolatile) loads, so they can be
7299   // chained like loads.
7300   SDValue Chain = DAG.getRoot();
7301   SmallVector<SDValue, 4> Opers;
7302   Opers.push_back(Chain);
7303   if (FPI.isUnaryOp()) {
7304     Opers.push_back(getValue(FPI.getArgOperand(0)));
7305   } else if (FPI.isTernaryOp()) {
7306     Opers.push_back(getValue(FPI.getArgOperand(0)));
7307     Opers.push_back(getValue(FPI.getArgOperand(1)));
7308     Opers.push_back(getValue(FPI.getArgOperand(2)));
7309   } else {
7310     Opers.push_back(getValue(FPI.getArgOperand(0)));
7311     Opers.push_back(getValue(FPI.getArgOperand(1)));
7312   }
7313 
7314   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7315     assert(Result.getNode()->getNumValues() == 2);
7316 
7317     // Push node to the appropriate list so that future instructions can be
7318     // chained up correctly.
7319     SDValue OutChain = Result.getValue(1);
7320     switch (EB) {
7321     case fp::ExceptionBehavior::ebIgnore:
7322       // The only reason why ebIgnore nodes still need to be chained is that
7323       // they might depend on the current rounding mode, and therefore must
7324       // not be moved across instruction that may change that mode.
7325       [[fallthrough]];
7326     case fp::ExceptionBehavior::ebMayTrap:
7327       // These must not be moved across calls or instructions that may change
7328       // floating-point exception masks.
7329       PendingConstrainedFP.push_back(OutChain);
7330       break;
7331     case fp::ExceptionBehavior::ebStrict:
7332       // These must not be moved across calls or instructions that may change
7333       // floating-point exception masks or read floating-point exception flags.
7334       // In addition, they cannot be optimized out even if unused.
7335       PendingConstrainedFPStrict.push_back(OutChain);
7336       break;
7337     }
7338   };
7339 
7340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7341   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7342   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7343   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7344 
7345   SDNodeFlags Flags;
7346   if (EB == fp::ExceptionBehavior::ebIgnore)
7347     Flags.setNoFPExcept(true);
7348 
7349   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7350     Flags.copyFMF(*FPOp);
7351 
7352   unsigned Opcode;
7353   switch (FPI.getIntrinsicID()) {
7354   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7355 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7356   case Intrinsic::INTRINSIC:                                                   \
7357     Opcode = ISD::STRICT_##DAGN;                                               \
7358     break;
7359 #include "llvm/IR/ConstrainedOps.def"
7360   case Intrinsic::experimental_constrained_fmuladd: {
7361     Opcode = ISD::STRICT_FMA;
7362     // Break fmuladd into fmul and fadd.
7363     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7364         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7365       Opers.pop_back();
7366       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7367       pushOutChain(Mul, EB);
7368       Opcode = ISD::STRICT_FADD;
7369       Opers.clear();
7370       Opers.push_back(Mul.getValue(1));
7371       Opers.push_back(Mul.getValue(0));
7372       Opers.push_back(getValue(FPI.getArgOperand(2)));
7373     }
7374     break;
7375   }
7376   }
7377 
7378   // A few strict DAG nodes carry additional operands that are not
7379   // set up by the default code above.
7380   switch (Opcode) {
7381   default: break;
7382   case ISD::STRICT_FP_ROUND:
7383     Opers.push_back(
7384         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7385     break;
7386   case ISD::STRICT_FSETCC:
7387   case ISD::STRICT_FSETCCS: {
7388     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7389     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7390     if (TM.Options.NoNaNsFPMath)
7391       Condition = getFCmpCodeWithoutNaN(Condition);
7392     Opers.push_back(DAG.getCondCode(Condition));
7393     break;
7394   }
7395   }
7396 
7397   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7398   pushOutChain(Result, EB);
7399 
7400   SDValue FPResult = Result.getValue(0);
7401   setValue(&FPI, FPResult);
7402 }
7403 
7404 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7405   Optional<unsigned> ResOPC;
7406   switch (VPIntrin.getIntrinsicID()) {
7407 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7408   case Intrinsic::VPID:                                                        \
7409     ResOPC = ISD::VPSD;                                                        \
7410     break;
7411 #include "llvm/IR/VPIntrinsics.def"
7412   }
7413 
7414   if (!ResOPC)
7415     llvm_unreachable(
7416         "Inconsistency: no SDNode available for this VPIntrinsic!");
7417 
7418   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7419       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7420     if (VPIntrin.getFastMathFlags().allowReassoc())
7421       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7422                                                 : ISD::VP_REDUCE_FMUL;
7423   }
7424 
7425   return *ResOPC;
7426 }
7427 
7428 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7429                                       SmallVector<SDValue, 7> &OpValues) {
7430   SDLoc DL = getCurSDLoc();
7431   Value *PtrOperand = VPIntrin.getArgOperand(0);
7432   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7433   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7434   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7435   SDValue LD;
7436   bool AddToChain = true;
7437   // Do not serialize variable-length loads of constant memory with
7438   // anything.
7439   if (!Alignment)
7440     Alignment = DAG.getEVTAlign(VT);
7441   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7442   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7443   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7444   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7445       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7446       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7447   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7448                      MMO, false /*IsExpanding */);
7449   if (AddToChain)
7450     PendingLoads.push_back(LD.getValue(1));
7451   setValue(&VPIntrin, LD);
7452 }
7453 
7454 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7455                                         SmallVector<SDValue, 7> &OpValues) {
7456   SDLoc DL = getCurSDLoc();
7457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7458   Value *PtrOperand = VPIntrin.getArgOperand(0);
7459   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7460   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7461   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7462   SDValue LD;
7463   if (!Alignment)
7464     Alignment = DAG.getEVTAlign(VT.getScalarType());
7465   unsigned AS =
7466     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7467   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7468      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7469      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7470   SDValue Base, Index, Scale;
7471   ISD::MemIndexType IndexType;
7472   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7473                                     this, VPIntrin.getParent(),
7474                                     VT.getScalarStoreSize());
7475   if (!UniformBase) {
7476     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7477     Index = getValue(PtrOperand);
7478     IndexType = ISD::SIGNED_SCALED;
7479     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7480   }
7481   EVT IdxVT = Index.getValueType();
7482   EVT EltTy = IdxVT.getVectorElementType();
7483   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7484     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7485     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7486   }
7487   LD = DAG.getGatherVP(
7488       DAG.getVTList(VT, MVT::Other), VT, DL,
7489       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7490       IndexType);
7491   PendingLoads.push_back(LD.getValue(1));
7492   setValue(&VPIntrin, LD);
7493 }
7494 
7495 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7496                                        SmallVector<SDValue, 7> &OpValues) {
7497   SDLoc DL = getCurSDLoc();
7498   Value *PtrOperand = VPIntrin.getArgOperand(1);
7499   EVT VT = OpValues[0].getValueType();
7500   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7501   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7502   SDValue ST;
7503   if (!Alignment)
7504     Alignment = DAG.getEVTAlign(VT);
7505   SDValue Ptr = OpValues[1];
7506   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7507   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7508       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7509       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7510   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7511                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7512                       /* IsTruncating */ false, /*IsCompressing*/ false);
7513   DAG.setRoot(ST);
7514   setValue(&VPIntrin, ST);
7515 }
7516 
7517 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7518                                               SmallVector<SDValue, 7> &OpValues) {
7519   SDLoc DL = getCurSDLoc();
7520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7521   Value *PtrOperand = VPIntrin.getArgOperand(1);
7522   EVT VT = OpValues[0].getValueType();
7523   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7524   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7525   SDValue ST;
7526   if (!Alignment)
7527     Alignment = DAG.getEVTAlign(VT.getScalarType());
7528   unsigned AS =
7529       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7530   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7531       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7532       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7533   SDValue Base, Index, Scale;
7534   ISD::MemIndexType IndexType;
7535   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7536                                     this, VPIntrin.getParent(),
7537                                     VT.getScalarStoreSize());
7538   if (!UniformBase) {
7539     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7540     Index = getValue(PtrOperand);
7541     IndexType = ISD::SIGNED_SCALED;
7542     Scale =
7543       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7544   }
7545   EVT IdxVT = Index.getValueType();
7546   EVT EltTy = IdxVT.getVectorElementType();
7547   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7548     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7549     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7550   }
7551   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7552                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7553                          OpValues[2], OpValues[3]},
7554                         MMO, IndexType);
7555   DAG.setRoot(ST);
7556   setValue(&VPIntrin, ST);
7557 }
7558 
7559 void SelectionDAGBuilder::visitVPStridedLoad(
7560     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7561   SDLoc DL = getCurSDLoc();
7562   Value *PtrOperand = VPIntrin.getArgOperand(0);
7563   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7564   if (!Alignment)
7565     Alignment = DAG.getEVTAlign(VT.getScalarType());
7566   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7567   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7568   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7569   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7570   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7571   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7572       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7573       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7574 
7575   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7576                                     OpValues[2], OpValues[3], MMO,
7577                                     false /*IsExpanding*/);
7578 
7579   if (AddToChain)
7580     PendingLoads.push_back(LD.getValue(1));
7581   setValue(&VPIntrin, LD);
7582 }
7583 
7584 void SelectionDAGBuilder::visitVPStridedStore(
7585     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7586   SDLoc DL = getCurSDLoc();
7587   Value *PtrOperand = VPIntrin.getArgOperand(1);
7588   EVT VT = OpValues[0].getValueType();
7589   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7590   if (!Alignment)
7591     Alignment = DAG.getEVTAlign(VT.getScalarType());
7592   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7593   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7594       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7595       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7596 
7597   SDValue ST = DAG.getStridedStoreVP(
7598       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7599       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7600       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7601       /*IsCompressing*/ false);
7602 
7603   DAG.setRoot(ST);
7604   setValue(&VPIntrin, ST);
7605 }
7606 
7607 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7609   SDLoc DL = getCurSDLoc();
7610 
7611   ISD::CondCode Condition;
7612   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7613   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7614   if (IsFP) {
7615     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7616     // flags, but calls that don't return floating-point types can't be
7617     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7618     Condition = getFCmpCondCode(CondCode);
7619     if (TM.Options.NoNaNsFPMath)
7620       Condition = getFCmpCodeWithoutNaN(Condition);
7621   } else {
7622     Condition = getICmpCondCode(CondCode);
7623   }
7624 
7625   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7626   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7627   // #2 is the condition code
7628   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7629   SDValue EVL = getValue(VPIntrin.getOperand(4));
7630   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7631   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7632          "Unexpected target EVL type");
7633   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7634 
7635   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7636                                                         VPIntrin.getType());
7637   setValue(&VPIntrin,
7638            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7639 }
7640 
7641 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7642     const VPIntrinsic &VPIntrin) {
7643   SDLoc DL = getCurSDLoc();
7644   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7645 
7646   auto IID = VPIntrin.getIntrinsicID();
7647 
7648   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7649     return visitVPCmp(*CmpI);
7650 
7651   SmallVector<EVT, 4> ValueVTs;
7652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7653   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7654   SDVTList VTs = DAG.getVTList(ValueVTs);
7655 
7656   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7657 
7658   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7659   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7660          "Unexpected target EVL type");
7661 
7662   // Request operands.
7663   SmallVector<SDValue, 7> OpValues;
7664   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7665     auto Op = getValue(VPIntrin.getArgOperand(I));
7666     if (I == EVLParamPos)
7667       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7668     OpValues.push_back(Op);
7669   }
7670 
7671   switch (Opcode) {
7672   default: {
7673     SDNodeFlags SDFlags;
7674     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7675       SDFlags.copyFMF(*FPMO);
7676     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7677     setValue(&VPIntrin, Result);
7678     break;
7679   }
7680   case ISD::VP_LOAD:
7681     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7682     break;
7683   case ISD::VP_GATHER:
7684     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7685     break;
7686   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7687     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7688     break;
7689   case ISD::VP_STORE:
7690     visitVPStore(VPIntrin, OpValues);
7691     break;
7692   case ISD::VP_SCATTER:
7693     visitVPScatter(VPIntrin, OpValues);
7694     break;
7695   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7696     visitVPStridedStore(VPIntrin, OpValues);
7697     break;
7698   case ISD::VP_FMULADD: {
7699     assert(OpValues.size() == 5 && "Unexpected number of operands");
7700     SDNodeFlags SDFlags;
7701     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7702       SDFlags.copyFMF(*FPMO);
7703     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7704         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7705       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7706     } else {
7707       SDValue Mul = DAG.getNode(
7708           ISD::VP_FMUL, DL, VTs,
7709           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7710       SDValue Add =
7711           DAG.getNode(ISD::VP_FADD, DL, VTs,
7712                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7713       setValue(&VPIntrin, Add);
7714     }
7715     break;
7716   }
7717   }
7718 }
7719 
7720 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7721                                           const BasicBlock *EHPadBB,
7722                                           MCSymbol *&BeginLabel) {
7723   MachineFunction &MF = DAG.getMachineFunction();
7724   MachineModuleInfo &MMI = MF.getMMI();
7725 
7726   // Insert a label before the invoke call to mark the try range.  This can be
7727   // used to detect deletion of the invoke via the MachineModuleInfo.
7728   BeginLabel = MMI.getContext().createTempSymbol();
7729 
7730   // For SjLj, keep track of which landing pads go with which invokes
7731   // so as to maintain the ordering of pads in the LSDA.
7732   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7733   if (CallSiteIndex) {
7734     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7735     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7736 
7737     // Now that the call site is handled, stop tracking it.
7738     MMI.setCurrentCallSite(0);
7739   }
7740 
7741   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7742 }
7743 
7744 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7745                                         const BasicBlock *EHPadBB,
7746                                         MCSymbol *BeginLabel) {
7747   assert(BeginLabel && "BeginLabel should've been set");
7748 
7749   MachineFunction &MF = DAG.getMachineFunction();
7750   MachineModuleInfo &MMI = MF.getMMI();
7751 
7752   // Insert a label at the end of the invoke call to mark the try range.  This
7753   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7754   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7755   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7756 
7757   // Inform MachineModuleInfo of range.
7758   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7759   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7760   // actually use outlined funclets and their LSDA info style.
7761   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7762     assert(II && "II should've been set");
7763     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7764     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7765   } else if (!isScopedEHPersonality(Pers)) {
7766     assert(EHPadBB);
7767     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7768   }
7769 
7770   return Chain;
7771 }
7772 
7773 std::pair<SDValue, SDValue>
7774 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7775                                     const BasicBlock *EHPadBB) {
7776   MCSymbol *BeginLabel = nullptr;
7777 
7778   if (EHPadBB) {
7779     // Both PendingLoads and PendingExports must be flushed here;
7780     // this call might not return.
7781     (void)getRoot();
7782     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7783     CLI.setChain(getRoot());
7784   }
7785 
7786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7787   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7788 
7789   assert((CLI.IsTailCall || Result.second.getNode()) &&
7790          "Non-null chain expected with non-tail call!");
7791   assert((Result.second.getNode() || !Result.first.getNode()) &&
7792          "Null value expected with tail call!");
7793 
7794   if (!Result.second.getNode()) {
7795     // As a special case, a null chain means that a tail call has been emitted
7796     // and the DAG root is already updated.
7797     HasTailCall = true;
7798 
7799     // Since there's no actual continuation from this block, nothing can be
7800     // relying on us setting vregs for them.
7801     PendingExports.clear();
7802   } else {
7803     DAG.setRoot(Result.second);
7804   }
7805 
7806   if (EHPadBB) {
7807     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7808                            BeginLabel));
7809   }
7810 
7811   return Result;
7812 }
7813 
7814 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7815                                       bool isTailCall,
7816                                       bool isMustTailCall,
7817                                       const BasicBlock *EHPadBB) {
7818   auto &DL = DAG.getDataLayout();
7819   FunctionType *FTy = CB.getFunctionType();
7820   Type *RetTy = CB.getType();
7821 
7822   TargetLowering::ArgListTy Args;
7823   Args.reserve(CB.arg_size());
7824 
7825   const Value *SwiftErrorVal = nullptr;
7826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7827 
7828   if (isTailCall) {
7829     // Avoid emitting tail calls in functions with the disable-tail-calls
7830     // attribute.
7831     auto *Caller = CB.getParent()->getParent();
7832     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7833         "true" && !isMustTailCall)
7834       isTailCall = false;
7835 
7836     // We can't tail call inside a function with a swifterror argument. Lowering
7837     // does not support this yet. It would have to move into the swifterror
7838     // register before the call.
7839     if (TLI.supportSwiftError() &&
7840         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7841       isTailCall = false;
7842   }
7843 
7844   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7845     TargetLowering::ArgListEntry Entry;
7846     const Value *V = *I;
7847 
7848     // Skip empty types
7849     if (V->getType()->isEmptyTy())
7850       continue;
7851 
7852     SDValue ArgNode = getValue(V);
7853     Entry.Node = ArgNode; Entry.Ty = V->getType();
7854 
7855     Entry.setAttributes(&CB, I - CB.arg_begin());
7856 
7857     // Use swifterror virtual register as input to the call.
7858     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7859       SwiftErrorVal = V;
7860       // We find the virtual register for the actual swifterror argument.
7861       // Instead of using the Value, we use the virtual register instead.
7862       Entry.Node =
7863           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7864                           EVT(TLI.getPointerTy(DL)));
7865     }
7866 
7867     Args.push_back(Entry);
7868 
7869     // If we have an explicit sret argument that is an Instruction, (i.e., it
7870     // might point to function-local memory), we can't meaningfully tail-call.
7871     if (Entry.IsSRet && isa<Instruction>(V))
7872       isTailCall = false;
7873   }
7874 
7875   // If call site has a cfguardtarget operand bundle, create and add an
7876   // additional ArgListEntry.
7877   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7878     TargetLowering::ArgListEntry Entry;
7879     Value *V = Bundle->Inputs[0];
7880     SDValue ArgNode = getValue(V);
7881     Entry.Node = ArgNode;
7882     Entry.Ty = V->getType();
7883     Entry.IsCFGuardTarget = true;
7884     Args.push_back(Entry);
7885   }
7886 
7887   // Check if target-independent constraints permit a tail call here.
7888   // Target-dependent constraints are checked within TLI->LowerCallTo.
7889   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7890     isTailCall = false;
7891 
7892   // Disable tail calls if there is an swifterror argument. Targets have not
7893   // been updated to support tail calls.
7894   if (TLI.supportSwiftError() && SwiftErrorVal)
7895     isTailCall = false;
7896 
7897   ConstantInt *CFIType = nullptr;
7898   if (CB.isIndirectCall()) {
7899     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7900       if (!TLI.supportKCFIBundles())
7901         report_fatal_error(
7902             "Target doesn't support calls with kcfi operand bundles.");
7903       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7904       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7905     }
7906   }
7907 
7908   TargetLowering::CallLoweringInfo CLI(DAG);
7909   CLI.setDebugLoc(getCurSDLoc())
7910       .setChain(getRoot())
7911       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7912       .setTailCall(isTailCall)
7913       .setConvergent(CB.isConvergent())
7914       .setIsPreallocated(
7915           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7916       .setCFIType(CFIType);
7917   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7918 
7919   if (Result.first.getNode()) {
7920     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7921     setValue(&CB, Result.first);
7922   }
7923 
7924   // The last element of CLI.InVals has the SDValue for swifterror return.
7925   // Here we copy it to a virtual register and update SwiftErrorMap for
7926   // book-keeping.
7927   if (SwiftErrorVal && TLI.supportSwiftError()) {
7928     // Get the last element of InVals.
7929     SDValue Src = CLI.InVals.back();
7930     Register VReg =
7931         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7932     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7933     DAG.setRoot(CopyNode);
7934   }
7935 }
7936 
7937 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7938                              SelectionDAGBuilder &Builder) {
7939   // Check to see if this load can be trivially constant folded, e.g. if the
7940   // input is from a string literal.
7941   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7942     // Cast pointer to the type we really want to load.
7943     Type *LoadTy =
7944         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7945     if (LoadVT.isVector())
7946       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7947 
7948     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7949                                          PointerType::getUnqual(LoadTy));
7950 
7951     if (const Constant *LoadCst =
7952             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7953                                          LoadTy, Builder.DAG.getDataLayout()))
7954       return Builder.getValue(LoadCst);
7955   }
7956 
7957   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7958   // still constant memory, the input chain can be the entry node.
7959   SDValue Root;
7960   bool ConstantMemory = false;
7961 
7962   // Do not serialize (non-volatile) loads of constant memory with anything.
7963   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7964     Root = Builder.DAG.getEntryNode();
7965     ConstantMemory = true;
7966   } else {
7967     // Do not serialize non-volatile loads against each other.
7968     Root = Builder.DAG.getRoot();
7969   }
7970 
7971   SDValue Ptr = Builder.getValue(PtrVal);
7972   SDValue LoadVal =
7973       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7974                           MachinePointerInfo(PtrVal), Align(1));
7975 
7976   if (!ConstantMemory)
7977     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7978   return LoadVal;
7979 }
7980 
7981 /// Record the value for an instruction that produces an integer result,
7982 /// converting the type where necessary.
7983 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7984                                                   SDValue Value,
7985                                                   bool IsSigned) {
7986   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7987                                                     I.getType(), true);
7988   if (IsSigned)
7989     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7990   else
7991     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7992   setValue(&I, Value);
7993 }
7994 
7995 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7996 /// true and lower it. Otherwise return false, and it will be lowered like a
7997 /// normal call.
7998 /// The caller already checked that \p I calls the appropriate LibFunc with a
7999 /// correct prototype.
8000 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8001   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8002   const Value *Size = I.getArgOperand(2);
8003   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8004   if (CSize && CSize->getZExtValue() == 0) {
8005     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8006                                                           I.getType(), true);
8007     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8008     return true;
8009   }
8010 
8011   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8012   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8013       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8014       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8015   if (Res.first.getNode()) {
8016     processIntegerCallValue(I, Res.first, true);
8017     PendingLoads.push_back(Res.second);
8018     return true;
8019   }
8020 
8021   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8022   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8023   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8024     return false;
8025 
8026   // If the target has a fast compare for the given size, it will return a
8027   // preferred load type for that size. Require that the load VT is legal and
8028   // that the target supports unaligned loads of that type. Otherwise, return
8029   // INVALID.
8030   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8031     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8032     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8033     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8034       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8035       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8036       // TODO: Check alignment of src and dest ptrs.
8037       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8038       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8039       if (!TLI.isTypeLegal(LVT) ||
8040           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8041           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8042         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8043     }
8044 
8045     return LVT;
8046   };
8047 
8048   // This turns into unaligned loads. We only do this if the target natively
8049   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8050   // we'll only produce a small number of byte loads.
8051   MVT LoadVT;
8052   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8053   switch (NumBitsToCompare) {
8054   default:
8055     return false;
8056   case 16:
8057     LoadVT = MVT::i16;
8058     break;
8059   case 32:
8060     LoadVT = MVT::i32;
8061     break;
8062   case 64:
8063   case 128:
8064   case 256:
8065     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8066     break;
8067   }
8068 
8069   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8070     return false;
8071 
8072   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8073   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8074 
8075   // Bitcast to a wide integer type if the loads are vectors.
8076   if (LoadVT.isVector()) {
8077     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8078     LoadL = DAG.getBitcast(CmpVT, LoadL);
8079     LoadR = DAG.getBitcast(CmpVT, LoadR);
8080   }
8081 
8082   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8083   processIntegerCallValue(I, Cmp, false);
8084   return true;
8085 }
8086 
8087 /// See if we can lower a memchr call into an optimized form. If so, return
8088 /// true and lower it. Otherwise return false, and it will be lowered like a
8089 /// normal call.
8090 /// The caller already checked that \p I calls the appropriate LibFunc with a
8091 /// correct prototype.
8092 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8093   const Value *Src = I.getArgOperand(0);
8094   const Value *Char = I.getArgOperand(1);
8095   const Value *Length = I.getArgOperand(2);
8096 
8097   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8098   std::pair<SDValue, SDValue> Res =
8099     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8100                                 getValue(Src), getValue(Char), getValue(Length),
8101                                 MachinePointerInfo(Src));
8102   if (Res.first.getNode()) {
8103     setValue(&I, Res.first);
8104     PendingLoads.push_back(Res.second);
8105     return true;
8106   }
8107 
8108   return false;
8109 }
8110 
8111 /// See if we can lower a mempcpy call into an optimized form. If so, return
8112 /// true and lower it. Otherwise return false, and it will be lowered like a
8113 /// normal call.
8114 /// The caller already checked that \p I calls the appropriate LibFunc with a
8115 /// correct prototype.
8116 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8117   SDValue Dst = getValue(I.getArgOperand(0));
8118   SDValue Src = getValue(I.getArgOperand(1));
8119   SDValue Size = getValue(I.getArgOperand(2));
8120 
8121   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8122   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8123   // DAG::getMemcpy needs Alignment to be defined.
8124   Align Alignment = std::min(DstAlign, SrcAlign);
8125 
8126   bool isVol = false;
8127   SDLoc sdl = getCurSDLoc();
8128 
8129   // In the mempcpy context we need to pass in a false value for isTailCall
8130   // because the return pointer needs to be adjusted by the size of
8131   // the copied memory.
8132   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8133   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8134                              /*isTailCall=*/false,
8135                              MachinePointerInfo(I.getArgOperand(0)),
8136                              MachinePointerInfo(I.getArgOperand(1)),
8137                              I.getAAMetadata());
8138   assert(MC.getNode() != nullptr &&
8139          "** memcpy should not be lowered as TailCall in mempcpy context **");
8140   DAG.setRoot(MC);
8141 
8142   // Check if Size needs to be truncated or extended.
8143   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8144 
8145   // Adjust return pointer to point just past the last dst byte.
8146   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8147                                     Dst, Size);
8148   setValue(&I, DstPlusSize);
8149   return true;
8150 }
8151 
8152 /// See if we can lower a strcpy call into an optimized form.  If so, return
8153 /// true and lower it, otherwise return false and it will be lowered like a
8154 /// normal call.
8155 /// The caller already checked that \p I calls the appropriate LibFunc with a
8156 /// correct prototype.
8157 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8158   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8159 
8160   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8161   std::pair<SDValue, SDValue> Res =
8162     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8163                                 getValue(Arg0), getValue(Arg1),
8164                                 MachinePointerInfo(Arg0),
8165                                 MachinePointerInfo(Arg1), isStpcpy);
8166   if (Res.first.getNode()) {
8167     setValue(&I, Res.first);
8168     DAG.setRoot(Res.second);
8169     return true;
8170   }
8171 
8172   return false;
8173 }
8174 
8175 /// See if we can lower a strcmp call into an optimized form.  If so, return
8176 /// true and lower it, otherwise return false and it will be lowered like a
8177 /// normal call.
8178 /// The caller already checked that \p I calls the appropriate LibFunc with a
8179 /// correct prototype.
8180 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8181   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8182 
8183   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8184   std::pair<SDValue, SDValue> Res =
8185     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8186                                 getValue(Arg0), getValue(Arg1),
8187                                 MachinePointerInfo(Arg0),
8188                                 MachinePointerInfo(Arg1));
8189   if (Res.first.getNode()) {
8190     processIntegerCallValue(I, Res.first, true);
8191     PendingLoads.push_back(Res.second);
8192     return true;
8193   }
8194 
8195   return false;
8196 }
8197 
8198 /// See if we can lower a strlen call into an optimized form.  If so, return
8199 /// true and lower it, otherwise return false and it will be lowered like a
8200 /// normal call.
8201 /// The caller already checked that \p I calls the appropriate LibFunc with a
8202 /// correct prototype.
8203 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8204   const Value *Arg0 = I.getArgOperand(0);
8205 
8206   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8207   std::pair<SDValue, SDValue> Res =
8208     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8209                                 getValue(Arg0), MachinePointerInfo(Arg0));
8210   if (Res.first.getNode()) {
8211     processIntegerCallValue(I, Res.first, false);
8212     PendingLoads.push_back(Res.second);
8213     return true;
8214   }
8215 
8216   return false;
8217 }
8218 
8219 /// See if we can lower a strnlen call into an optimized form.  If so, return
8220 /// true and lower it, otherwise return false and it will be lowered like a
8221 /// normal call.
8222 /// The caller already checked that \p I calls the appropriate LibFunc with a
8223 /// correct prototype.
8224 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8225   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8226 
8227   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8228   std::pair<SDValue, SDValue> Res =
8229     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8230                                  getValue(Arg0), getValue(Arg1),
8231                                  MachinePointerInfo(Arg0));
8232   if (Res.first.getNode()) {
8233     processIntegerCallValue(I, Res.first, false);
8234     PendingLoads.push_back(Res.second);
8235     return true;
8236   }
8237 
8238   return false;
8239 }
8240 
8241 /// See if we can lower a unary floating-point operation into an SDNode with
8242 /// the specified Opcode.  If so, return true and lower it, otherwise return
8243 /// false and it will be lowered like a normal call.
8244 /// The caller already checked that \p I calls the appropriate LibFunc with a
8245 /// correct prototype.
8246 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8247                                               unsigned Opcode) {
8248   // We already checked this call's prototype; verify it doesn't modify errno.
8249   if (!I.onlyReadsMemory())
8250     return false;
8251 
8252   SDNodeFlags Flags;
8253   Flags.copyFMF(cast<FPMathOperator>(I));
8254 
8255   SDValue Tmp = getValue(I.getArgOperand(0));
8256   setValue(&I,
8257            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8258   return true;
8259 }
8260 
8261 /// See if we can lower a binary floating-point operation into an SDNode with
8262 /// the specified Opcode. If so, return true and lower it. Otherwise return
8263 /// false, and it will be lowered like a normal call.
8264 /// The caller already checked that \p I calls the appropriate LibFunc with a
8265 /// correct prototype.
8266 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8267                                                unsigned Opcode) {
8268   // We already checked this call's prototype; verify it doesn't modify errno.
8269   if (!I.onlyReadsMemory())
8270     return false;
8271 
8272   SDNodeFlags Flags;
8273   Flags.copyFMF(cast<FPMathOperator>(I));
8274 
8275   SDValue Tmp0 = getValue(I.getArgOperand(0));
8276   SDValue Tmp1 = getValue(I.getArgOperand(1));
8277   EVT VT = Tmp0.getValueType();
8278   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8279   return true;
8280 }
8281 
8282 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8283   // Handle inline assembly differently.
8284   if (I.isInlineAsm()) {
8285     visitInlineAsm(I);
8286     return;
8287   }
8288 
8289   if (Function *F = I.getCalledFunction()) {
8290     diagnoseDontCall(I);
8291 
8292     if (F->isDeclaration()) {
8293       // Is this an LLVM intrinsic or a target-specific intrinsic?
8294       unsigned IID = F->getIntrinsicID();
8295       if (!IID)
8296         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8297           IID = II->getIntrinsicID(F);
8298 
8299       if (IID) {
8300         visitIntrinsicCall(I, IID);
8301         return;
8302       }
8303     }
8304 
8305     // Check for well-known libc/libm calls.  If the function is internal, it
8306     // can't be a library call.  Don't do the check if marked as nobuiltin for
8307     // some reason or the call site requires strict floating point semantics.
8308     LibFunc Func;
8309     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8310         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8311         LibInfo->hasOptimizedCodeGen(Func)) {
8312       switch (Func) {
8313       default: break;
8314       case LibFunc_bcmp:
8315         if (visitMemCmpBCmpCall(I))
8316           return;
8317         break;
8318       case LibFunc_copysign:
8319       case LibFunc_copysignf:
8320       case LibFunc_copysignl:
8321         // We already checked this call's prototype; verify it doesn't modify
8322         // errno.
8323         if (I.onlyReadsMemory()) {
8324           SDValue LHS = getValue(I.getArgOperand(0));
8325           SDValue RHS = getValue(I.getArgOperand(1));
8326           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8327                                    LHS.getValueType(), LHS, RHS));
8328           return;
8329         }
8330         break;
8331       case LibFunc_fabs:
8332       case LibFunc_fabsf:
8333       case LibFunc_fabsl:
8334         if (visitUnaryFloatCall(I, ISD::FABS))
8335           return;
8336         break;
8337       case LibFunc_fmin:
8338       case LibFunc_fminf:
8339       case LibFunc_fminl:
8340         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8341           return;
8342         break;
8343       case LibFunc_fmax:
8344       case LibFunc_fmaxf:
8345       case LibFunc_fmaxl:
8346         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8347           return;
8348         break;
8349       case LibFunc_sin:
8350       case LibFunc_sinf:
8351       case LibFunc_sinl:
8352         if (visitUnaryFloatCall(I, ISD::FSIN))
8353           return;
8354         break;
8355       case LibFunc_cos:
8356       case LibFunc_cosf:
8357       case LibFunc_cosl:
8358         if (visitUnaryFloatCall(I, ISD::FCOS))
8359           return;
8360         break;
8361       case LibFunc_sqrt:
8362       case LibFunc_sqrtf:
8363       case LibFunc_sqrtl:
8364       case LibFunc_sqrt_finite:
8365       case LibFunc_sqrtf_finite:
8366       case LibFunc_sqrtl_finite:
8367         if (visitUnaryFloatCall(I, ISD::FSQRT))
8368           return;
8369         break;
8370       case LibFunc_floor:
8371       case LibFunc_floorf:
8372       case LibFunc_floorl:
8373         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8374           return;
8375         break;
8376       case LibFunc_nearbyint:
8377       case LibFunc_nearbyintf:
8378       case LibFunc_nearbyintl:
8379         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8380           return;
8381         break;
8382       case LibFunc_ceil:
8383       case LibFunc_ceilf:
8384       case LibFunc_ceill:
8385         if (visitUnaryFloatCall(I, ISD::FCEIL))
8386           return;
8387         break;
8388       case LibFunc_rint:
8389       case LibFunc_rintf:
8390       case LibFunc_rintl:
8391         if (visitUnaryFloatCall(I, ISD::FRINT))
8392           return;
8393         break;
8394       case LibFunc_round:
8395       case LibFunc_roundf:
8396       case LibFunc_roundl:
8397         if (visitUnaryFloatCall(I, ISD::FROUND))
8398           return;
8399         break;
8400       case LibFunc_trunc:
8401       case LibFunc_truncf:
8402       case LibFunc_truncl:
8403         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8404           return;
8405         break;
8406       case LibFunc_log2:
8407       case LibFunc_log2f:
8408       case LibFunc_log2l:
8409         if (visitUnaryFloatCall(I, ISD::FLOG2))
8410           return;
8411         break;
8412       case LibFunc_exp2:
8413       case LibFunc_exp2f:
8414       case LibFunc_exp2l:
8415         if (visitUnaryFloatCall(I, ISD::FEXP2))
8416           return;
8417         break;
8418       case LibFunc_memcmp:
8419         if (visitMemCmpBCmpCall(I))
8420           return;
8421         break;
8422       case LibFunc_mempcpy:
8423         if (visitMemPCpyCall(I))
8424           return;
8425         break;
8426       case LibFunc_memchr:
8427         if (visitMemChrCall(I))
8428           return;
8429         break;
8430       case LibFunc_strcpy:
8431         if (visitStrCpyCall(I, false))
8432           return;
8433         break;
8434       case LibFunc_stpcpy:
8435         if (visitStrCpyCall(I, true))
8436           return;
8437         break;
8438       case LibFunc_strcmp:
8439         if (visitStrCmpCall(I))
8440           return;
8441         break;
8442       case LibFunc_strlen:
8443         if (visitStrLenCall(I))
8444           return;
8445         break;
8446       case LibFunc_strnlen:
8447         if (visitStrNLenCall(I))
8448           return;
8449         break;
8450       }
8451     }
8452   }
8453 
8454   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8455   // have to do anything here to lower funclet bundles.
8456   // CFGuardTarget bundles are lowered in LowerCallTo.
8457   assert(!I.hasOperandBundlesOtherThan(
8458              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8459               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8460               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8461          "Cannot lower calls with arbitrary operand bundles!");
8462 
8463   SDValue Callee = getValue(I.getCalledOperand());
8464 
8465   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8466     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8467   else
8468     // Check if we can potentially perform a tail call. More detailed checking
8469     // is be done within LowerCallTo, after more information about the call is
8470     // known.
8471     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8472 }
8473 
8474 namespace {
8475 
8476 /// AsmOperandInfo - This contains information for each constraint that we are
8477 /// lowering.
8478 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8479 public:
8480   /// CallOperand - If this is the result output operand or a clobber
8481   /// this is null, otherwise it is the incoming operand to the CallInst.
8482   /// This gets modified as the asm is processed.
8483   SDValue CallOperand;
8484 
8485   /// AssignedRegs - If this is a register or register class operand, this
8486   /// contains the set of register corresponding to the operand.
8487   RegsForValue AssignedRegs;
8488 
8489   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8490     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8491   }
8492 
8493   /// Whether or not this operand accesses memory
8494   bool hasMemory(const TargetLowering &TLI) const {
8495     // Indirect operand accesses access memory.
8496     if (isIndirect)
8497       return true;
8498 
8499     for (const auto &Code : Codes)
8500       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8501         return true;
8502 
8503     return false;
8504   }
8505 };
8506 
8507 
8508 } // end anonymous namespace
8509 
8510 /// Make sure that the output operand \p OpInfo and its corresponding input
8511 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8512 /// out).
8513 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8514                                SDISelAsmOperandInfo &MatchingOpInfo,
8515                                SelectionDAG &DAG) {
8516   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8517     return;
8518 
8519   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8520   const auto &TLI = DAG.getTargetLoweringInfo();
8521 
8522   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8523       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8524                                        OpInfo.ConstraintVT);
8525   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8526       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8527                                        MatchingOpInfo.ConstraintVT);
8528   if ((OpInfo.ConstraintVT.isInteger() !=
8529        MatchingOpInfo.ConstraintVT.isInteger()) ||
8530       (MatchRC.second != InputRC.second)) {
8531     // FIXME: error out in a more elegant fashion
8532     report_fatal_error("Unsupported asm: input constraint"
8533                        " with a matching output constraint of"
8534                        " incompatible type!");
8535   }
8536   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8537 }
8538 
8539 /// Get a direct memory input to behave well as an indirect operand.
8540 /// This may introduce stores, hence the need for a \p Chain.
8541 /// \return The (possibly updated) chain.
8542 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8543                                         SDISelAsmOperandInfo &OpInfo,
8544                                         SelectionDAG &DAG) {
8545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8546 
8547   // If we don't have an indirect input, put it in the constpool if we can,
8548   // otherwise spill it to a stack slot.
8549   // TODO: This isn't quite right. We need to handle these according to
8550   // the addressing mode that the constraint wants. Also, this may take
8551   // an additional register for the computation and we don't want that
8552   // either.
8553 
8554   // If the operand is a float, integer, or vector constant, spill to a
8555   // constant pool entry to get its address.
8556   const Value *OpVal = OpInfo.CallOperandVal;
8557   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8558       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8559     OpInfo.CallOperand = DAG.getConstantPool(
8560         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8561     return Chain;
8562   }
8563 
8564   // Otherwise, create a stack slot and emit a store to it before the asm.
8565   Type *Ty = OpVal->getType();
8566   auto &DL = DAG.getDataLayout();
8567   uint64_t TySize = DL.getTypeAllocSize(Ty);
8568   MachineFunction &MF = DAG.getMachineFunction();
8569   int SSFI = MF.getFrameInfo().CreateStackObject(
8570       TySize, DL.getPrefTypeAlign(Ty), false);
8571   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8572   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8573                             MachinePointerInfo::getFixedStack(MF, SSFI),
8574                             TLI.getMemValueType(DL, Ty));
8575   OpInfo.CallOperand = StackSlot;
8576 
8577   return Chain;
8578 }
8579 
8580 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8581 /// specified operand.  We prefer to assign virtual registers, to allow the
8582 /// register allocator to handle the assignment process.  However, if the asm
8583 /// uses features that we can't model on machineinstrs, we have SDISel do the
8584 /// allocation.  This produces generally horrible, but correct, code.
8585 ///
8586 ///   OpInfo describes the operand
8587 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8588 static llvm::Optional<unsigned>
8589 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8590                      SDISelAsmOperandInfo &OpInfo,
8591                      SDISelAsmOperandInfo &RefOpInfo) {
8592   LLVMContext &Context = *DAG.getContext();
8593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8594 
8595   MachineFunction &MF = DAG.getMachineFunction();
8596   SmallVector<unsigned, 4> Regs;
8597   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8598 
8599   // No work to do for memory/address operands.
8600   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8601       OpInfo.ConstraintType == TargetLowering::C_Address)
8602     return None;
8603 
8604   // If this is a constraint for a single physreg, or a constraint for a
8605   // register class, find it.
8606   unsigned AssignedReg;
8607   const TargetRegisterClass *RC;
8608   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8609       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8610   // RC is unset only on failure. Return immediately.
8611   if (!RC)
8612     return None;
8613 
8614   // Get the actual register value type.  This is important, because the user
8615   // may have asked for (e.g.) the AX register in i32 type.  We need to
8616   // remember that AX is actually i16 to get the right extension.
8617   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8618 
8619   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8620     // If this is an FP operand in an integer register (or visa versa), or more
8621     // generally if the operand value disagrees with the register class we plan
8622     // to stick it in, fix the operand type.
8623     //
8624     // If this is an input value, the bitcast to the new type is done now.
8625     // Bitcast for output value is done at the end of visitInlineAsm().
8626     if ((OpInfo.Type == InlineAsm::isOutput ||
8627          OpInfo.Type == InlineAsm::isInput) &&
8628         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8629       // Try to convert to the first EVT that the reg class contains.  If the
8630       // types are identical size, use a bitcast to convert (e.g. two differing
8631       // vector types).  Note: output bitcast is done at the end of
8632       // visitInlineAsm().
8633       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8634         // Exclude indirect inputs while they are unsupported because the code
8635         // to perform the load is missing and thus OpInfo.CallOperand still
8636         // refers to the input address rather than the pointed-to value.
8637         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8638           OpInfo.CallOperand =
8639               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8640         OpInfo.ConstraintVT = RegVT;
8641         // If the operand is an FP value and we want it in integer registers,
8642         // use the corresponding integer type. This turns an f64 value into
8643         // i64, which can be passed with two i32 values on a 32-bit machine.
8644       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8645         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8646         if (OpInfo.Type == InlineAsm::isInput)
8647           OpInfo.CallOperand =
8648               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8649         OpInfo.ConstraintVT = VT;
8650       }
8651     }
8652   }
8653 
8654   // No need to allocate a matching input constraint since the constraint it's
8655   // matching to has already been allocated.
8656   if (OpInfo.isMatchingInputConstraint())
8657     return None;
8658 
8659   EVT ValueVT = OpInfo.ConstraintVT;
8660   if (OpInfo.ConstraintVT == MVT::Other)
8661     ValueVT = RegVT;
8662 
8663   // Initialize NumRegs.
8664   unsigned NumRegs = 1;
8665   if (OpInfo.ConstraintVT != MVT::Other)
8666     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8667 
8668   // If this is a constraint for a specific physical register, like {r17},
8669   // assign it now.
8670 
8671   // If this associated to a specific register, initialize iterator to correct
8672   // place. If virtual, make sure we have enough registers
8673 
8674   // Initialize iterator if necessary
8675   TargetRegisterClass::iterator I = RC->begin();
8676   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8677 
8678   // Do not check for single registers.
8679   if (AssignedReg) {
8680     I = std::find(I, RC->end(), AssignedReg);
8681     if (I == RC->end()) {
8682       // RC does not contain the selected register, which indicates a
8683       // mismatch between the register and the required type/bitwidth.
8684       return {AssignedReg};
8685     }
8686   }
8687 
8688   for (; NumRegs; --NumRegs, ++I) {
8689     assert(I != RC->end() && "Ran out of registers to allocate!");
8690     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8691     Regs.push_back(R);
8692   }
8693 
8694   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8695   return None;
8696 }
8697 
8698 static unsigned
8699 findMatchingInlineAsmOperand(unsigned OperandNo,
8700                              const std::vector<SDValue> &AsmNodeOperands) {
8701   // Scan until we find the definition we already emitted of this operand.
8702   unsigned CurOp = InlineAsm::Op_FirstOperand;
8703   for (; OperandNo; --OperandNo) {
8704     // Advance to the next operand.
8705     unsigned OpFlag =
8706         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8707     assert((InlineAsm::isRegDefKind(OpFlag) ||
8708             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8709             InlineAsm::isMemKind(OpFlag)) &&
8710            "Skipped past definitions?");
8711     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8712   }
8713   return CurOp;
8714 }
8715 
8716 namespace {
8717 
8718 class ExtraFlags {
8719   unsigned Flags = 0;
8720 
8721 public:
8722   explicit ExtraFlags(const CallBase &Call) {
8723     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8724     if (IA->hasSideEffects())
8725       Flags |= InlineAsm::Extra_HasSideEffects;
8726     if (IA->isAlignStack())
8727       Flags |= InlineAsm::Extra_IsAlignStack;
8728     if (Call.isConvergent())
8729       Flags |= InlineAsm::Extra_IsConvergent;
8730     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8731   }
8732 
8733   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8734     // Ideally, we would only check against memory constraints.  However, the
8735     // meaning of an Other constraint can be target-specific and we can't easily
8736     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8737     // for Other constraints as well.
8738     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8739         OpInfo.ConstraintType == TargetLowering::C_Other) {
8740       if (OpInfo.Type == InlineAsm::isInput)
8741         Flags |= InlineAsm::Extra_MayLoad;
8742       else if (OpInfo.Type == InlineAsm::isOutput)
8743         Flags |= InlineAsm::Extra_MayStore;
8744       else if (OpInfo.Type == InlineAsm::isClobber)
8745         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8746     }
8747   }
8748 
8749   unsigned get() const { return Flags; }
8750 };
8751 
8752 } // end anonymous namespace
8753 
8754 /// visitInlineAsm - Handle a call to an InlineAsm object.
8755 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8756                                          const BasicBlock *EHPadBB) {
8757   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8758 
8759   /// ConstraintOperands - Information about all of the constraints.
8760   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8761 
8762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8764       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8765 
8766   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8767   // AsmDialect, MayLoad, MayStore).
8768   bool HasSideEffect = IA->hasSideEffects();
8769   ExtraFlags ExtraInfo(Call);
8770 
8771   for (auto &T : TargetConstraints) {
8772     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8773     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8774 
8775     if (OpInfo.CallOperandVal)
8776       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8777 
8778     if (!HasSideEffect)
8779       HasSideEffect = OpInfo.hasMemory(TLI);
8780 
8781     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8782     // FIXME: Could we compute this on OpInfo rather than T?
8783 
8784     // Compute the constraint code and ConstraintType to use.
8785     TLI.ComputeConstraintToUse(T, SDValue());
8786 
8787     if (T.ConstraintType == TargetLowering::C_Immediate &&
8788         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8789       // We've delayed emitting a diagnostic like the "n" constraint because
8790       // inlining could cause an integer showing up.
8791       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8792                                           "' expects an integer constant "
8793                                           "expression");
8794 
8795     ExtraInfo.update(T);
8796   }
8797 
8798   // We won't need to flush pending loads if this asm doesn't touch
8799   // memory and is nonvolatile.
8800   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8801 
8802   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8803   if (EmitEHLabels) {
8804     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8805   }
8806   bool IsCallBr = isa<CallBrInst>(Call);
8807 
8808   if (IsCallBr || EmitEHLabels) {
8809     // If this is a callbr or invoke we need to flush pending exports since
8810     // inlineasm_br and invoke are terminators.
8811     // We need to do this before nodes are glued to the inlineasm_br node.
8812     Chain = getControlRoot();
8813   }
8814 
8815   MCSymbol *BeginLabel = nullptr;
8816   if (EmitEHLabels) {
8817     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8818   }
8819 
8820   // Second pass over the constraints: compute which constraint option to use.
8821   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8822     // If this is an output operand with a matching input operand, look up the
8823     // matching input. If their types mismatch, e.g. one is an integer, the
8824     // other is floating point, or their sizes are different, flag it as an
8825     // error.
8826     if (OpInfo.hasMatchingInput()) {
8827       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8828       patchMatchingInput(OpInfo, Input, DAG);
8829     }
8830 
8831     // Compute the constraint code and ConstraintType to use.
8832     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8833 
8834     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8835          OpInfo.Type == InlineAsm::isClobber) ||
8836         OpInfo.ConstraintType == TargetLowering::C_Address)
8837       continue;
8838 
8839     // If this is a memory input, and if the operand is not indirect, do what we
8840     // need to provide an address for the memory input.
8841     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8842         !OpInfo.isIndirect) {
8843       assert((OpInfo.isMultipleAlternative ||
8844               (OpInfo.Type == InlineAsm::isInput)) &&
8845              "Can only indirectify direct input operands!");
8846 
8847       // Memory operands really want the address of the value.
8848       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8849 
8850       // There is no longer a Value* corresponding to this operand.
8851       OpInfo.CallOperandVal = nullptr;
8852 
8853       // It is now an indirect operand.
8854       OpInfo.isIndirect = true;
8855     }
8856 
8857   }
8858 
8859   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8860   std::vector<SDValue> AsmNodeOperands;
8861   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8862   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8863       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8864 
8865   // If we have a !srcloc metadata node associated with it, we want to attach
8866   // this to the ultimately generated inline asm machineinstr.  To do this, we
8867   // pass in the third operand as this (potentially null) inline asm MDNode.
8868   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8869   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8870 
8871   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8872   // bits as operand 3.
8873   AsmNodeOperands.push_back(DAG.getTargetConstant(
8874       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8875 
8876   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8877   // this, assign virtual and physical registers for inputs and otput.
8878   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8879     // Assign Registers.
8880     SDISelAsmOperandInfo &RefOpInfo =
8881         OpInfo.isMatchingInputConstraint()
8882             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8883             : OpInfo;
8884     const auto RegError =
8885         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8886     if (RegError) {
8887       const MachineFunction &MF = DAG.getMachineFunction();
8888       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8889       const char *RegName = TRI.getName(RegError.value());
8890       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8891                                    "' allocated for constraint '" +
8892                                    Twine(OpInfo.ConstraintCode) +
8893                                    "' does not match required type");
8894       return;
8895     }
8896 
8897     auto DetectWriteToReservedRegister = [&]() {
8898       const MachineFunction &MF = DAG.getMachineFunction();
8899       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8900       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8901         if (Register::isPhysicalRegister(Reg) &&
8902             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8903           const char *RegName = TRI.getName(Reg);
8904           emitInlineAsmError(Call, "write to reserved register '" +
8905                                        Twine(RegName) + "'");
8906           return true;
8907         }
8908       }
8909       return false;
8910     };
8911     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8912             (OpInfo.Type == InlineAsm::isInput &&
8913              !OpInfo.isMatchingInputConstraint())) &&
8914            "Only address as input operand is allowed.");
8915 
8916     switch (OpInfo.Type) {
8917     case InlineAsm::isOutput:
8918       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8919         unsigned ConstraintID =
8920             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8921         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8922                "Failed to convert memory constraint code to constraint id.");
8923 
8924         // Add information to the INLINEASM node to know about this output.
8925         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8926         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8927         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8928                                                         MVT::i32));
8929         AsmNodeOperands.push_back(OpInfo.CallOperand);
8930       } else {
8931         // Otherwise, this outputs to a register (directly for C_Register /
8932         // C_RegisterClass, and a target-defined fashion for
8933         // C_Immediate/C_Other). Find a register that we can use.
8934         if (OpInfo.AssignedRegs.Regs.empty()) {
8935           emitInlineAsmError(
8936               Call, "couldn't allocate output register for constraint '" +
8937                         Twine(OpInfo.ConstraintCode) + "'");
8938           return;
8939         }
8940 
8941         if (DetectWriteToReservedRegister())
8942           return;
8943 
8944         // Add information to the INLINEASM node to know that this register is
8945         // set.
8946         OpInfo.AssignedRegs.AddInlineAsmOperands(
8947             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8948                                   : InlineAsm::Kind_RegDef,
8949             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8950       }
8951       break;
8952 
8953     case InlineAsm::isInput:
8954     case InlineAsm::isLabel: {
8955       SDValue InOperandVal = OpInfo.CallOperand;
8956 
8957       if (OpInfo.isMatchingInputConstraint()) {
8958         // If this is required to match an output register we have already set,
8959         // just use its register.
8960         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8961                                                   AsmNodeOperands);
8962         unsigned OpFlag =
8963           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8964         if (InlineAsm::isRegDefKind(OpFlag) ||
8965             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8966           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8967           if (OpInfo.isIndirect) {
8968             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8969             emitInlineAsmError(Call, "inline asm not supported yet: "
8970                                      "don't know how to handle tied "
8971                                      "indirect register inputs");
8972             return;
8973           }
8974 
8975           SmallVector<unsigned, 4> Regs;
8976           MachineFunction &MF = DAG.getMachineFunction();
8977           MachineRegisterInfo &MRI = MF.getRegInfo();
8978           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8979           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8980           Register TiedReg = R->getReg();
8981           MVT RegVT = R->getSimpleValueType(0);
8982           const TargetRegisterClass *RC =
8983               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8984               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8985                                       : TRI.getMinimalPhysRegClass(TiedReg);
8986           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8987           for (unsigned i = 0; i != NumRegs; ++i)
8988             Regs.push_back(MRI.createVirtualRegister(RC));
8989 
8990           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8991 
8992           SDLoc dl = getCurSDLoc();
8993           // Use the produced MatchedRegs object to
8994           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8995           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8996                                            true, OpInfo.getMatchedOperand(), dl,
8997                                            DAG, AsmNodeOperands);
8998           break;
8999         }
9000 
9001         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9002         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9003                "Unexpected number of operands");
9004         // Add information to the INLINEASM node to know about this input.
9005         // See InlineAsm.h isUseOperandTiedToDef.
9006         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9007         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9008                                                     OpInfo.getMatchedOperand());
9009         AsmNodeOperands.push_back(DAG.getTargetConstant(
9010             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9011         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9012         break;
9013       }
9014 
9015       // Treat indirect 'X' constraint as memory.
9016       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9017           OpInfo.isIndirect)
9018         OpInfo.ConstraintType = TargetLowering::C_Memory;
9019 
9020       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9021           OpInfo.ConstraintType == TargetLowering::C_Other) {
9022         std::vector<SDValue> Ops;
9023         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9024                                           Ops, DAG);
9025         if (Ops.empty()) {
9026           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9027             if (isa<ConstantSDNode>(InOperandVal)) {
9028               emitInlineAsmError(Call, "value out of range for constraint '" +
9029                                            Twine(OpInfo.ConstraintCode) + "'");
9030               return;
9031             }
9032 
9033           emitInlineAsmError(Call,
9034                              "invalid operand for inline asm constraint '" +
9035                                  Twine(OpInfo.ConstraintCode) + "'");
9036           return;
9037         }
9038 
9039         // Add information to the INLINEASM node to know about this input.
9040         unsigned ResOpType =
9041           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9042         AsmNodeOperands.push_back(DAG.getTargetConstant(
9043             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9044         llvm::append_range(AsmNodeOperands, Ops);
9045         break;
9046       }
9047 
9048       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9049           OpInfo.ConstraintType == TargetLowering::C_Address) {
9050         assert((OpInfo.isIndirect ||
9051                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9052                "Operand must be indirect to be a mem!");
9053         assert(InOperandVal.getValueType() ==
9054                    TLI.getPointerTy(DAG.getDataLayout()) &&
9055                "Memory operands expect pointer values");
9056 
9057         unsigned ConstraintID =
9058             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9059         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9060                "Failed to convert memory constraint code to constraint id.");
9061 
9062         // Add information to the INLINEASM node to know about this input.
9063         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9064         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9065         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9066                                                         getCurSDLoc(),
9067                                                         MVT::i32));
9068         AsmNodeOperands.push_back(InOperandVal);
9069         break;
9070       }
9071 
9072       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9073               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9074              "Unknown constraint type!");
9075 
9076       // TODO: Support this.
9077       if (OpInfo.isIndirect) {
9078         emitInlineAsmError(
9079             Call, "Don't know how to handle indirect register inputs yet "
9080                   "for constraint '" +
9081                       Twine(OpInfo.ConstraintCode) + "'");
9082         return;
9083       }
9084 
9085       // Copy the input into the appropriate registers.
9086       if (OpInfo.AssignedRegs.Regs.empty()) {
9087         emitInlineAsmError(Call,
9088                            "couldn't allocate input reg for constraint '" +
9089                                Twine(OpInfo.ConstraintCode) + "'");
9090         return;
9091       }
9092 
9093       if (DetectWriteToReservedRegister())
9094         return;
9095 
9096       SDLoc dl = getCurSDLoc();
9097 
9098       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9099                                         &Call);
9100 
9101       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9102                                                dl, DAG, AsmNodeOperands);
9103       break;
9104     }
9105     case InlineAsm::isClobber:
9106       // Add the clobbered value to the operand list, so that the register
9107       // allocator is aware that the physreg got clobbered.
9108       if (!OpInfo.AssignedRegs.Regs.empty())
9109         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9110                                                  false, 0, getCurSDLoc(), DAG,
9111                                                  AsmNodeOperands);
9112       break;
9113     }
9114   }
9115 
9116   // Finish up input operands.  Set the input chain and add the flag last.
9117   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9118   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9119 
9120   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9121   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9122                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9123   Flag = Chain.getValue(1);
9124 
9125   // Do additional work to generate outputs.
9126 
9127   SmallVector<EVT, 1> ResultVTs;
9128   SmallVector<SDValue, 1> ResultValues;
9129   SmallVector<SDValue, 8> OutChains;
9130 
9131   llvm::Type *CallResultType = Call.getType();
9132   ArrayRef<Type *> ResultTypes;
9133   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9134     ResultTypes = StructResult->elements();
9135   else if (!CallResultType->isVoidTy())
9136     ResultTypes = makeArrayRef(CallResultType);
9137 
9138   auto CurResultType = ResultTypes.begin();
9139   auto handleRegAssign = [&](SDValue V) {
9140     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9141     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9142     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9143     ++CurResultType;
9144     // If the type of the inline asm call site return value is different but has
9145     // same size as the type of the asm output bitcast it.  One example of this
9146     // is for vectors with different width / number of elements.  This can
9147     // happen for register classes that can contain multiple different value
9148     // types.  The preg or vreg allocated may not have the same VT as was
9149     // expected.
9150     //
9151     // This can also happen for a return value that disagrees with the register
9152     // class it is put in, eg. a double in a general-purpose register on a
9153     // 32-bit machine.
9154     if (ResultVT != V.getValueType() &&
9155         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9156       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9157     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9158              V.getValueType().isInteger()) {
9159       // If a result value was tied to an input value, the computed result
9160       // may have a wider width than the expected result.  Extract the
9161       // relevant portion.
9162       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9163     }
9164     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9165     ResultVTs.push_back(ResultVT);
9166     ResultValues.push_back(V);
9167   };
9168 
9169   // Deal with output operands.
9170   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9171     if (OpInfo.Type == InlineAsm::isOutput) {
9172       SDValue Val;
9173       // Skip trivial output operands.
9174       if (OpInfo.AssignedRegs.Regs.empty())
9175         continue;
9176 
9177       switch (OpInfo.ConstraintType) {
9178       case TargetLowering::C_Register:
9179       case TargetLowering::C_RegisterClass:
9180         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9181                                                   Chain, &Flag, &Call);
9182         break;
9183       case TargetLowering::C_Immediate:
9184       case TargetLowering::C_Other:
9185         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9186                                               OpInfo, DAG);
9187         break;
9188       case TargetLowering::C_Memory:
9189         break; // Already handled.
9190       case TargetLowering::C_Address:
9191         break; // Silence warning.
9192       case TargetLowering::C_Unknown:
9193         assert(false && "Unexpected unknown constraint");
9194       }
9195 
9196       // Indirect output manifest as stores. Record output chains.
9197       if (OpInfo.isIndirect) {
9198         const Value *Ptr = OpInfo.CallOperandVal;
9199         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9200         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9201                                      MachinePointerInfo(Ptr));
9202         OutChains.push_back(Store);
9203       } else {
9204         // generate CopyFromRegs to associated registers.
9205         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9206         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9207           for (const SDValue &V : Val->op_values())
9208             handleRegAssign(V);
9209         } else
9210           handleRegAssign(Val);
9211       }
9212     }
9213   }
9214 
9215   // Set results.
9216   if (!ResultValues.empty()) {
9217     assert(CurResultType == ResultTypes.end() &&
9218            "Mismatch in number of ResultTypes");
9219     assert(ResultValues.size() == ResultTypes.size() &&
9220            "Mismatch in number of output operands in asm result");
9221 
9222     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9223                             DAG.getVTList(ResultVTs), ResultValues);
9224     setValue(&Call, V);
9225   }
9226 
9227   // Collect store chains.
9228   if (!OutChains.empty())
9229     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9230 
9231   if (EmitEHLabels) {
9232     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9233   }
9234 
9235   // Only Update Root if inline assembly has a memory effect.
9236   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9237       EmitEHLabels)
9238     DAG.setRoot(Chain);
9239 }
9240 
9241 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9242                                              const Twine &Message) {
9243   LLVMContext &Ctx = *DAG.getContext();
9244   Ctx.emitError(&Call, Message);
9245 
9246   // Make sure we leave the DAG in a valid state
9247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9248   SmallVector<EVT, 1> ValueVTs;
9249   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9250 
9251   if (ValueVTs.empty())
9252     return;
9253 
9254   SmallVector<SDValue, 1> Ops;
9255   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9256     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9257 
9258   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9259 }
9260 
9261 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9262   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9263                           MVT::Other, getRoot(),
9264                           getValue(I.getArgOperand(0)),
9265                           DAG.getSrcValue(I.getArgOperand(0))));
9266 }
9267 
9268 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9270   const DataLayout &DL = DAG.getDataLayout();
9271   SDValue V = DAG.getVAArg(
9272       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9273       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9274       DL.getABITypeAlign(I.getType()).value());
9275   DAG.setRoot(V.getValue(1));
9276 
9277   if (I.getType()->isPointerTy())
9278     V = DAG.getPtrExtOrTrunc(
9279         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9280   setValue(&I, V);
9281 }
9282 
9283 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9284   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9285                           MVT::Other, getRoot(),
9286                           getValue(I.getArgOperand(0)),
9287                           DAG.getSrcValue(I.getArgOperand(0))));
9288 }
9289 
9290 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9291   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9292                           MVT::Other, getRoot(),
9293                           getValue(I.getArgOperand(0)),
9294                           getValue(I.getArgOperand(1)),
9295                           DAG.getSrcValue(I.getArgOperand(0)),
9296                           DAG.getSrcValue(I.getArgOperand(1))));
9297 }
9298 
9299 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9300                                                     const Instruction &I,
9301                                                     SDValue Op) {
9302   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9303   if (!Range)
9304     return Op;
9305 
9306   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9307   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9308     return Op;
9309 
9310   APInt Lo = CR.getUnsignedMin();
9311   if (!Lo.isMinValue())
9312     return Op;
9313 
9314   APInt Hi = CR.getUnsignedMax();
9315   unsigned Bits = std::max(Hi.getActiveBits(),
9316                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9317 
9318   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9319 
9320   SDLoc SL = getCurSDLoc();
9321 
9322   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9323                              DAG.getValueType(SmallVT));
9324   unsigned NumVals = Op.getNode()->getNumValues();
9325   if (NumVals == 1)
9326     return ZExt;
9327 
9328   SmallVector<SDValue, 4> Ops;
9329 
9330   Ops.push_back(ZExt);
9331   for (unsigned I = 1; I != NumVals; ++I)
9332     Ops.push_back(Op.getValue(I));
9333 
9334   return DAG.getMergeValues(Ops, SL);
9335 }
9336 
9337 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9338 /// the call being lowered.
9339 ///
9340 /// This is a helper for lowering intrinsics that follow a target calling
9341 /// convention or require stack pointer adjustment. Only a subset of the
9342 /// intrinsic's operands need to participate in the calling convention.
9343 void SelectionDAGBuilder::populateCallLoweringInfo(
9344     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9345     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9346     bool IsPatchPoint) {
9347   TargetLowering::ArgListTy Args;
9348   Args.reserve(NumArgs);
9349 
9350   // Populate the argument list.
9351   // Attributes for args start at offset 1, after the return attribute.
9352   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9353        ArgI != ArgE; ++ArgI) {
9354     const Value *V = Call->getOperand(ArgI);
9355 
9356     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9357 
9358     TargetLowering::ArgListEntry Entry;
9359     Entry.Node = getValue(V);
9360     Entry.Ty = V->getType();
9361     Entry.setAttributes(Call, ArgI);
9362     Args.push_back(Entry);
9363   }
9364 
9365   CLI.setDebugLoc(getCurSDLoc())
9366       .setChain(getRoot())
9367       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9368       .setDiscardResult(Call->use_empty())
9369       .setIsPatchPoint(IsPatchPoint)
9370       .setIsPreallocated(
9371           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9372 }
9373 
9374 /// Add a stack map intrinsic call's live variable operands to a stackmap
9375 /// or patchpoint target node's operand list.
9376 ///
9377 /// Constants are converted to TargetConstants purely as an optimization to
9378 /// avoid constant materialization and register allocation.
9379 ///
9380 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9381 /// generate addess computation nodes, and so FinalizeISel can convert the
9382 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9383 /// address materialization and register allocation, but may also be required
9384 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9385 /// alloca in the entry block, then the runtime may assume that the alloca's
9386 /// StackMap location can be read immediately after compilation and that the
9387 /// location is valid at any point during execution (this is similar to the
9388 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9389 /// only available in a register, then the runtime would need to trap when
9390 /// execution reaches the StackMap in order to read the alloca's location.
9391 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9392                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9393                                 SelectionDAGBuilder &Builder) {
9394   SelectionDAG &DAG = Builder.DAG;
9395   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9396     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9397 
9398     // Things on the stack are pointer-typed, meaning that they are already
9399     // legal and can be emitted directly to target nodes.
9400     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9401       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9402     } else {
9403       // Otherwise emit a target independent node to be legalised.
9404       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9405     }
9406   }
9407 }
9408 
9409 /// Lower llvm.experimental.stackmap.
9410 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9411   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9412   //                                  [live variables...])
9413 
9414   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9415 
9416   SDValue Chain, InFlag, Callee;
9417   SmallVector<SDValue, 32> Ops;
9418 
9419   SDLoc DL = getCurSDLoc();
9420   Callee = getValue(CI.getCalledOperand());
9421 
9422   // The stackmap intrinsic only records the live variables (the arguments
9423   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9424   // intrinsic, this won't be lowered to a function call. This means we don't
9425   // have to worry about calling conventions and target specific lowering code.
9426   // Instead we perform the call lowering right here.
9427   //
9428   // chain, flag = CALLSEQ_START(chain, 0, 0)
9429   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9430   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9431   //
9432   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9433   InFlag = Chain.getValue(1);
9434 
9435   // Add the STACKMAP operands, starting with DAG house-keeping.
9436   Ops.push_back(Chain);
9437   Ops.push_back(InFlag);
9438 
9439   // Add the <id>, <numShadowBytes> operands.
9440   //
9441   // These do not require legalisation, and can be emitted directly to target
9442   // constant nodes.
9443   SDValue ID = getValue(CI.getArgOperand(0));
9444   assert(ID.getValueType() == MVT::i64);
9445   SDValue IDConst = DAG.getTargetConstant(
9446       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9447   Ops.push_back(IDConst);
9448 
9449   SDValue Shad = getValue(CI.getArgOperand(1));
9450   assert(Shad.getValueType() == MVT::i32);
9451   SDValue ShadConst = DAG.getTargetConstant(
9452       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9453   Ops.push_back(ShadConst);
9454 
9455   // Add the live variables.
9456   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9457 
9458   // Create the STACKMAP node.
9459   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9460   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9461   InFlag = Chain.getValue(1);
9462 
9463   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9464 
9465   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9466 
9467   // Set the root to the target-lowered call chain.
9468   DAG.setRoot(Chain);
9469 
9470   // Inform the Frame Information that we have a stackmap in this function.
9471   FuncInfo.MF->getFrameInfo().setHasStackMap();
9472 }
9473 
9474 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9475 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9476                                           const BasicBlock *EHPadBB) {
9477   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9478   //                                                 i32 <numBytes>,
9479   //                                                 i8* <target>,
9480   //                                                 i32 <numArgs>,
9481   //                                                 [Args...],
9482   //                                                 [live variables...])
9483 
9484   CallingConv::ID CC = CB.getCallingConv();
9485   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9486   bool HasDef = !CB.getType()->isVoidTy();
9487   SDLoc dl = getCurSDLoc();
9488   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9489 
9490   // Handle immediate and symbolic callees.
9491   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9492     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9493                                    /*isTarget=*/true);
9494   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9495     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9496                                          SDLoc(SymbolicCallee),
9497                                          SymbolicCallee->getValueType(0));
9498 
9499   // Get the real number of arguments participating in the call <numArgs>
9500   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9501   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9502 
9503   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9504   // Intrinsics include all meta-operands up to but not including CC.
9505   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9506   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9507          "Not enough arguments provided to the patchpoint intrinsic");
9508 
9509   // For AnyRegCC the arguments are lowered later on manually.
9510   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9511   Type *ReturnTy =
9512       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9513 
9514   TargetLowering::CallLoweringInfo CLI(DAG);
9515   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9516                            ReturnTy, true);
9517   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9518 
9519   SDNode *CallEnd = Result.second.getNode();
9520   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9521     CallEnd = CallEnd->getOperand(0).getNode();
9522 
9523   /// Get a call instruction from the call sequence chain.
9524   /// Tail calls are not allowed.
9525   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9526          "Expected a callseq node.");
9527   SDNode *Call = CallEnd->getOperand(0).getNode();
9528   bool HasGlue = Call->getGluedNode();
9529 
9530   // Replace the target specific call node with the patchable intrinsic.
9531   SmallVector<SDValue, 8> Ops;
9532 
9533   // Push the chain.
9534   Ops.push_back(*(Call->op_begin()));
9535 
9536   // Optionally, push the glue (if any).
9537   if (HasGlue)
9538     Ops.push_back(*(Call->op_end() - 1));
9539 
9540   // Push the register mask info.
9541   if (HasGlue)
9542     Ops.push_back(*(Call->op_end() - 2));
9543   else
9544     Ops.push_back(*(Call->op_end() - 1));
9545 
9546   // Add the <id> and <numBytes> constants.
9547   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9548   Ops.push_back(DAG.getTargetConstant(
9549                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9550   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9551   Ops.push_back(DAG.getTargetConstant(
9552                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9553                   MVT::i32));
9554 
9555   // Add the callee.
9556   Ops.push_back(Callee);
9557 
9558   // Adjust <numArgs> to account for any arguments that have been passed on the
9559   // stack instead.
9560   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9561   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9562   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9563   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9564 
9565   // Add the calling convention
9566   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9567 
9568   // Add the arguments we omitted previously. The register allocator should
9569   // place these in any free register.
9570   if (IsAnyRegCC)
9571     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9572       Ops.push_back(getValue(CB.getArgOperand(i)));
9573 
9574   // Push the arguments from the call instruction.
9575   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9576   Ops.append(Call->op_begin() + 2, e);
9577 
9578   // Push live variables for the stack map.
9579   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9580 
9581   SDVTList NodeTys;
9582   if (IsAnyRegCC && HasDef) {
9583     // Create the return types based on the intrinsic definition
9584     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585     SmallVector<EVT, 3> ValueVTs;
9586     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9587     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9588 
9589     // There is always a chain and a glue type at the end
9590     ValueVTs.push_back(MVT::Other);
9591     ValueVTs.push_back(MVT::Glue);
9592     NodeTys = DAG.getVTList(ValueVTs);
9593   } else
9594     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9595 
9596   // Replace the target specific call node with a PATCHPOINT node.
9597   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9598 
9599   // Update the NodeMap.
9600   if (HasDef) {
9601     if (IsAnyRegCC)
9602       setValue(&CB, SDValue(PPV.getNode(), 0));
9603     else
9604       setValue(&CB, Result.first);
9605   }
9606 
9607   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9608   // call sequence. Furthermore the location of the chain and glue can change
9609   // when the AnyReg calling convention is used and the intrinsic returns a
9610   // value.
9611   if (IsAnyRegCC && HasDef) {
9612     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9613     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9614     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9615   } else
9616     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9617   DAG.DeleteNode(Call);
9618 
9619   // Inform the Frame Information that we have a patchpoint in this function.
9620   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9621 }
9622 
9623 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9624                                             unsigned Intrinsic) {
9625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9626   SDValue Op1 = getValue(I.getArgOperand(0));
9627   SDValue Op2;
9628   if (I.arg_size() > 1)
9629     Op2 = getValue(I.getArgOperand(1));
9630   SDLoc dl = getCurSDLoc();
9631   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9632   SDValue Res;
9633   SDNodeFlags SDFlags;
9634   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9635     SDFlags.copyFMF(*FPMO);
9636 
9637   switch (Intrinsic) {
9638   case Intrinsic::vector_reduce_fadd:
9639     if (SDFlags.hasAllowReassociation())
9640       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9641                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9642                         SDFlags);
9643     else
9644       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9645     break;
9646   case Intrinsic::vector_reduce_fmul:
9647     if (SDFlags.hasAllowReassociation())
9648       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9649                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9650                         SDFlags);
9651     else
9652       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9653     break;
9654   case Intrinsic::vector_reduce_add:
9655     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9656     break;
9657   case Intrinsic::vector_reduce_mul:
9658     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9659     break;
9660   case Intrinsic::vector_reduce_and:
9661     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9662     break;
9663   case Intrinsic::vector_reduce_or:
9664     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9665     break;
9666   case Intrinsic::vector_reduce_xor:
9667     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9668     break;
9669   case Intrinsic::vector_reduce_smax:
9670     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9671     break;
9672   case Intrinsic::vector_reduce_smin:
9673     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9674     break;
9675   case Intrinsic::vector_reduce_umax:
9676     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9677     break;
9678   case Intrinsic::vector_reduce_umin:
9679     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9680     break;
9681   case Intrinsic::vector_reduce_fmax:
9682     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9683     break;
9684   case Intrinsic::vector_reduce_fmin:
9685     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9686     break;
9687   default:
9688     llvm_unreachable("Unhandled vector reduce intrinsic");
9689   }
9690   setValue(&I, Res);
9691 }
9692 
9693 /// Returns an AttributeList representing the attributes applied to the return
9694 /// value of the given call.
9695 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9696   SmallVector<Attribute::AttrKind, 2> Attrs;
9697   if (CLI.RetSExt)
9698     Attrs.push_back(Attribute::SExt);
9699   if (CLI.RetZExt)
9700     Attrs.push_back(Attribute::ZExt);
9701   if (CLI.IsInReg)
9702     Attrs.push_back(Attribute::InReg);
9703 
9704   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9705                             Attrs);
9706 }
9707 
9708 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9709 /// implementation, which just calls LowerCall.
9710 /// FIXME: When all targets are
9711 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9712 std::pair<SDValue, SDValue>
9713 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9714   // Handle the incoming return values from the call.
9715   CLI.Ins.clear();
9716   Type *OrigRetTy = CLI.RetTy;
9717   SmallVector<EVT, 4> RetTys;
9718   SmallVector<uint64_t, 4> Offsets;
9719   auto &DL = CLI.DAG.getDataLayout();
9720   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9721 
9722   if (CLI.IsPostTypeLegalization) {
9723     // If we are lowering a libcall after legalization, split the return type.
9724     SmallVector<EVT, 4> OldRetTys;
9725     SmallVector<uint64_t, 4> OldOffsets;
9726     RetTys.swap(OldRetTys);
9727     Offsets.swap(OldOffsets);
9728 
9729     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9730       EVT RetVT = OldRetTys[i];
9731       uint64_t Offset = OldOffsets[i];
9732       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9733       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9734       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9735       RetTys.append(NumRegs, RegisterVT);
9736       for (unsigned j = 0; j != NumRegs; ++j)
9737         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9738     }
9739   }
9740 
9741   SmallVector<ISD::OutputArg, 4> Outs;
9742   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9743 
9744   bool CanLowerReturn =
9745       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9746                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9747 
9748   SDValue DemoteStackSlot;
9749   int DemoteStackIdx = -100;
9750   if (!CanLowerReturn) {
9751     // FIXME: equivalent assert?
9752     // assert(!CS.hasInAllocaArgument() &&
9753     //        "sret demotion is incompatible with inalloca");
9754     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9755     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9756     MachineFunction &MF = CLI.DAG.getMachineFunction();
9757     DemoteStackIdx =
9758         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9759     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9760                                               DL.getAllocaAddrSpace());
9761 
9762     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9763     ArgListEntry Entry;
9764     Entry.Node = DemoteStackSlot;
9765     Entry.Ty = StackSlotPtrType;
9766     Entry.IsSExt = false;
9767     Entry.IsZExt = false;
9768     Entry.IsInReg = false;
9769     Entry.IsSRet = true;
9770     Entry.IsNest = false;
9771     Entry.IsByVal = false;
9772     Entry.IsByRef = false;
9773     Entry.IsReturned = false;
9774     Entry.IsSwiftSelf = false;
9775     Entry.IsSwiftAsync = false;
9776     Entry.IsSwiftError = false;
9777     Entry.IsCFGuardTarget = false;
9778     Entry.Alignment = Alignment;
9779     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9780     CLI.NumFixedArgs += 1;
9781     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9782 
9783     // sret demotion isn't compatible with tail-calls, since the sret argument
9784     // points into the callers stack frame.
9785     CLI.IsTailCall = false;
9786   } else {
9787     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9788         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9789     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9790       ISD::ArgFlagsTy Flags;
9791       if (NeedsRegBlock) {
9792         Flags.setInConsecutiveRegs();
9793         if (I == RetTys.size() - 1)
9794           Flags.setInConsecutiveRegsLast();
9795       }
9796       EVT VT = RetTys[I];
9797       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9798                                                      CLI.CallConv, VT);
9799       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9800                                                        CLI.CallConv, VT);
9801       for (unsigned i = 0; i != NumRegs; ++i) {
9802         ISD::InputArg MyFlags;
9803         MyFlags.Flags = Flags;
9804         MyFlags.VT = RegisterVT;
9805         MyFlags.ArgVT = VT;
9806         MyFlags.Used = CLI.IsReturnValueUsed;
9807         if (CLI.RetTy->isPointerTy()) {
9808           MyFlags.Flags.setPointer();
9809           MyFlags.Flags.setPointerAddrSpace(
9810               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9811         }
9812         if (CLI.RetSExt)
9813           MyFlags.Flags.setSExt();
9814         if (CLI.RetZExt)
9815           MyFlags.Flags.setZExt();
9816         if (CLI.IsInReg)
9817           MyFlags.Flags.setInReg();
9818         CLI.Ins.push_back(MyFlags);
9819       }
9820     }
9821   }
9822 
9823   // We push in swifterror return as the last element of CLI.Ins.
9824   ArgListTy &Args = CLI.getArgs();
9825   if (supportSwiftError()) {
9826     for (const ArgListEntry &Arg : Args) {
9827       if (Arg.IsSwiftError) {
9828         ISD::InputArg MyFlags;
9829         MyFlags.VT = getPointerTy(DL);
9830         MyFlags.ArgVT = EVT(getPointerTy(DL));
9831         MyFlags.Flags.setSwiftError();
9832         CLI.Ins.push_back(MyFlags);
9833       }
9834     }
9835   }
9836 
9837   // Handle all of the outgoing arguments.
9838   CLI.Outs.clear();
9839   CLI.OutVals.clear();
9840   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9841     SmallVector<EVT, 4> ValueVTs;
9842     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9843     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9844     Type *FinalType = Args[i].Ty;
9845     if (Args[i].IsByVal)
9846       FinalType = Args[i].IndirectType;
9847     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9848         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9849     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9850          ++Value) {
9851       EVT VT = ValueVTs[Value];
9852       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9853       SDValue Op = SDValue(Args[i].Node.getNode(),
9854                            Args[i].Node.getResNo() + Value);
9855       ISD::ArgFlagsTy Flags;
9856 
9857       // Certain targets (such as MIPS), may have a different ABI alignment
9858       // for a type depending on the context. Give the target a chance to
9859       // specify the alignment it wants.
9860       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9861       Flags.setOrigAlign(OriginalAlignment);
9862 
9863       if (Args[i].Ty->isPointerTy()) {
9864         Flags.setPointer();
9865         Flags.setPointerAddrSpace(
9866             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9867       }
9868       if (Args[i].IsZExt)
9869         Flags.setZExt();
9870       if (Args[i].IsSExt)
9871         Flags.setSExt();
9872       if (Args[i].IsInReg) {
9873         // If we are using vectorcall calling convention, a structure that is
9874         // passed InReg - is surely an HVA
9875         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9876             isa<StructType>(FinalType)) {
9877           // The first value of a structure is marked
9878           if (0 == Value)
9879             Flags.setHvaStart();
9880           Flags.setHva();
9881         }
9882         // Set InReg Flag
9883         Flags.setInReg();
9884       }
9885       if (Args[i].IsSRet)
9886         Flags.setSRet();
9887       if (Args[i].IsSwiftSelf)
9888         Flags.setSwiftSelf();
9889       if (Args[i].IsSwiftAsync)
9890         Flags.setSwiftAsync();
9891       if (Args[i].IsSwiftError)
9892         Flags.setSwiftError();
9893       if (Args[i].IsCFGuardTarget)
9894         Flags.setCFGuardTarget();
9895       if (Args[i].IsByVal)
9896         Flags.setByVal();
9897       if (Args[i].IsByRef)
9898         Flags.setByRef();
9899       if (Args[i].IsPreallocated) {
9900         Flags.setPreallocated();
9901         // Set the byval flag for CCAssignFn callbacks that don't know about
9902         // preallocated.  This way we can know how many bytes we should've
9903         // allocated and how many bytes a callee cleanup function will pop.  If
9904         // we port preallocated to more targets, we'll have to add custom
9905         // preallocated handling in the various CC lowering callbacks.
9906         Flags.setByVal();
9907       }
9908       if (Args[i].IsInAlloca) {
9909         Flags.setInAlloca();
9910         // Set the byval flag for CCAssignFn callbacks that don't know about
9911         // inalloca.  This way we can know how many bytes we should've allocated
9912         // and how many bytes a callee cleanup function will pop.  If we port
9913         // inalloca to more targets, we'll have to add custom inalloca handling
9914         // in the various CC lowering callbacks.
9915         Flags.setByVal();
9916       }
9917       Align MemAlign;
9918       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9919         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9920         Flags.setByValSize(FrameSize);
9921 
9922         // info is not there but there are cases it cannot get right.
9923         if (auto MA = Args[i].Alignment)
9924           MemAlign = *MA;
9925         else
9926           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9927       } else if (auto MA = Args[i].Alignment) {
9928         MemAlign = *MA;
9929       } else {
9930         MemAlign = OriginalAlignment;
9931       }
9932       Flags.setMemAlign(MemAlign);
9933       if (Args[i].IsNest)
9934         Flags.setNest();
9935       if (NeedsRegBlock)
9936         Flags.setInConsecutiveRegs();
9937 
9938       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9939                                                  CLI.CallConv, VT);
9940       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9941                                                         CLI.CallConv, VT);
9942       SmallVector<SDValue, 4> Parts(NumParts);
9943       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9944 
9945       if (Args[i].IsSExt)
9946         ExtendKind = ISD::SIGN_EXTEND;
9947       else if (Args[i].IsZExt)
9948         ExtendKind = ISD::ZERO_EXTEND;
9949 
9950       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9951       // for now.
9952       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9953           CanLowerReturn) {
9954         assert((CLI.RetTy == Args[i].Ty ||
9955                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9956                  CLI.RetTy->getPointerAddressSpace() ==
9957                      Args[i].Ty->getPointerAddressSpace())) &&
9958                RetTys.size() == NumValues && "unexpected use of 'returned'");
9959         // Before passing 'returned' to the target lowering code, ensure that
9960         // either the register MVT and the actual EVT are the same size or that
9961         // the return value and argument are extended in the same way; in these
9962         // cases it's safe to pass the argument register value unchanged as the
9963         // return register value (although it's at the target's option whether
9964         // to do so)
9965         // TODO: allow code generation to take advantage of partially preserved
9966         // registers rather than clobbering the entire register when the
9967         // parameter extension method is not compatible with the return
9968         // extension method
9969         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9970             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9971              CLI.RetZExt == Args[i].IsZExt))
9972           Flags.setReturned();
9973       }
9974 
9975       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9976                      CLI.CallConv, ExtendKind);
9977 
9978       for (unsigned j = 0; j != NumParts; ++j) {
9979         // if it isn't first piece, alignment must be 1
9980         // For scalable vectors the scalable part is currently handled
9981         // by individual targets, so we just use the known minimum size here.
9982         ISD::OutputArg MyFlags(
9983             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9984             i < CLI.NumFixedArgs, i,
9985             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9986         if (NumParts > 1 && j == 0)
9987           MyFlags.Flags.setSplit();
9988         else if (j != 0) {
9989           MyFlags.Flags.setOrigAlign(Align(1));
9990           if (j == NumParts - 1)
9991             MyFlags.Flags.setSplitEnd();
9992         }
9993 
9994         CLI.Outs.push_back(MyFlags);
9995         CLI.OutVals.push_back(Parts[j]);
9996       }
9997 
9998       if (NeedsRegBlock && Value == NumValues - 1)
9999         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10000     }
10001   }
10002 
10003   SmallVector<SDValue, 4> InVals;
10004   CLI.Chain = LowerCall(CLI, InVals);
10005 
10006   // Update CLI.InVals to use outside of this function.
10007   CLI.InVals = InVals;
10008 
10009   // Verify that the target's LowerCall behaved as expected.
10010   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10011          "LowerCall didn't return a valid chain!");
10012   assert((!CLI.IsTailCall || InVals.empty()) &&
10013          "LowerCall emitted a return value for a tail call!");
10014   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10015          "LowerCall didn't emit the correct number of values!");
10016 
10017   // For a tail call, the return value is merely live-out and there aren't
10018   // any nodes in the DAG representing it. Return a special value to
10019   // indicate that a tail call has been emitted and no more Instructions
10020   // should be processed in the current block.
10021   if (CLI.IsTailCall) {
10022     CLI.DAG.setRoot(CLI.Chain);
10023     return std::make_pair(SDValue(), SDValue());
10024   }
10025 
10026 #ifndef NDEBUG
10027   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10028     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10029     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10030            "LowerCall emitted a value with the wrong type!");
10031   }
10032 #endif
10033 
10034   SmallVector<SDValue, 4> ReturnValues;
10035   if (!CanLowerReturn) {
10036     // The instruction result is the result of loading from the
10037     // hidden sret parameter.
10038     SmallVector<EVT, 1> PVTs;
10039     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10040 
10041     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10042     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10043     EVT PtrVT = PVTs[0];
10044 
10045     unsigned NumValues = RetTys.size();
10046     ReturnValues.resize(NumValues);
10047     SmallVector<SDValue, 4> Chains(NumValues);
10048 
10049     // An aggregate return value cannot wrap around the address space, so
10050     // offsets to its parts don't wrap either.
10051     SDNodeFlags Flags;
10052     Flags.setNoUnsignedWrap(true);
10053 
10054     MachineFunction &MF = CLI.DAG.getMachineFunction();
10055     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10056     for (unsigned i = 0; i < NumValues; ++i) {
10057       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10058                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10059                                                         PtrVT), Flags);
10060       SDValue L = CLI.DAG.getLoad(
10061           RetTys[i], CLI.DL, CLI.Chain, Add,
10062           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10063                                             DemoteStackIdx, Offsets[i]),
10064           HiddenSRetAlign);
10065       ReturnValues[i] = L;
10066       Chains[i] = L.getValue(1);
10067     }
10068 
10069     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10070   } else {
10071     // Collect the legal value parts into potentially illegal values
10072     // that correspond to the original function's return values.
10073     Optional<ISD::NodeType> AssertOp;
10074     if (CLI.RetSExt)
10075       AssertOp = ISD::AssertSext;
10076     else if (CLI.RetZExt)
10077       AssertOp = ISD::AssertZext;
10078     unsigned CurReg = 0;
10079     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10080       EVT VT = RetTys[I];
10081       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10082                                                      CLI.CallConv, VT);
10083       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10084                                                        CLI.CallConv, VT);
10085 
10086       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10087                                               NumRegs, RegisterVT, VT, nullptr,
10088                                               CLI.CallConv, AssertOp));
10089       CurReg += NumRegs;
10090     }
10091 
10092     // For a function returning void, there is no return value. We can't create
10093     // such a node, so we just return a null return value in that case. In
10094     // that case, nothing will actually look at the value.
10095     if (ReturnValues.empty())
10096       return std::make_pair(SDValue(), CLI.Chain);
10097   }
10098 
10099   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10100                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10101   return std::make_pair(Res, CLI.Chain);
10102 }
10103 
10104 /// Places new result values for the node in Results (their number
10105 /// and types must exactly match those of the original return values of
10106 /// the node), or leaves Results empty, which indicates that the node is not
10107 /// to be custom lowered after all.
10108 void TargetLowering::LowerOperationWrapper(SDNode *N,
10109                                            SmallVectorImpl<SDValue> &Results,
10110                                            SelectionDAG &DAG) const {
10111   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10112 
10113   if (!Res.getNode())
10114     return;
10115 
10116   // If the original node has one result, take the return value from
10117   // LowerOperation as is. It might not be result number 0.
10118   if (N->getNumValues() == 1) {
10119     Results.push_back(Res);
10120     return;
10121   }
10122 
10123   // If the original node has multiple results, then the return node should
10124   // have the same number of results.
10125   assert((N->getNumValues() == Res->getNumValues()) &&
10126       "Lowering returned the wrong number of results!");
10127 
10128   // Places new result values base on N result number.
10129   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10130     Results.push_back(Res.getValue(I));
10131 }
10132 
10133 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10134   llvm_unreachable("LowerOperation not implemented for this target!");
10135 }
10136 
10137 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10138                                                      unsigned Reg,
10139                                                      ISD::NodeType ExtendType) {
10140   SDValue Op = getNonRegisterValue(V);
10141   assert((Op.getOpcode() != ISD::CopyFromReg ||
10142           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10143          "Copy from a reg to the same reg!");
10144   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10145 
10146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10147   // If this is an InlineAsm we have to match the registers required, not the
10148   // notional registers required by the type.
10149 
10150   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10151                    None); // This is not an ABI copy.
10152   SDValue Chain = DAG.getEntryNode();
10153 
10154   if (ExtendType == ISD::ANY_EXTEND) {
10155     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10156     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10157       ExtendType = PreferredExtendIt->second;
10158   }
10159   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10160   PendingExports.push_back(Chain);
10161 }
10162 
10163 #include "llvm/CodeGen/SelectionDAGISel.h"
10164 
10165 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10166 /// entry block, return true.  This includes arguments used by switches, since
10167 /// the switch may expand into multiple basic blocks.
10168 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10169   // With FastISel active, we may be splitting blocks, so force creation
10170   // of virtual registers for all non-dead arguments.
10171   if (FastISel)
10172     return A->use_empty();
10173 
10174   const BasicBlock &Entry = A->getParent()->front();
10175   for (const User *U : A->users())
10176     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10177       return false;  // Use not in entry block.
10178 
10179   return true;
10180 }
10181 
10182 using ArgCopyElisionMapTy =
10183     DenseMap<const Argument *,
10184              std::pair<const AllocaInst *, const StoreInst *>>;
10185 
10186 /// Scan the entry block of the function in FuncInfo for arguments that look
10187 /// like copies into a local alloca. Record any copied arguments in
10188 /// ArgCopyElisionCandidates.
10189 static void
10190 findArgumentCopyElisionCandidates(const DataLayout &DL,
10191                                   FunctionLoweringInfo *FuncInfo,
10192                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10193   // Record the state of every static alloca used in the entry block. Argument
10194   // allocas are all used in the entry block, so we need approximately as many
10195   // entries as we have arguments.
10196   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10197   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10198   unsigned NumArgs = FuncInfo->Fn->arg_size();
10199   StaticAllocas.reserve(NumArgs * 2);
10200 
10201   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10202     if (!V)
10203       return nullptr;
10204     V = V->stripPointerCasts();
10205     const auto *AI = dyn_cast<AllocaInst>(V);
10206     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10207       return nullptr;
10208     auto Iter = StaticAllocas.insert({AI, Unknown});
10209     return &Iter.first->second;
10210   };
10211 
10212   // Look for stores of arguments to static allocas. Look through bitcasts and
10213   // GEPs to handle type coercions, as long as the alloca is fully initialized
10214   // by the store. Any non-store use of an alloca escapes it and any subsequent
10215   // unanalyzed store might write it.
10216   // FIXME: Handle structs initialized with multiple stores.
10217   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10218     // Look for stores, and handle non-store uses conservatively.
10219     const auto *SI = dyn_cast<StoreInst>(&I);
10220     if (!SI) {
10221       // We will look through cast uses, so ignore them completely.
10222       if (I.isCast())
10223         continue;
10224       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10225       // to allocas.
10226       if (I.isDebugOrPseudoInst())
10227         continue;
10228       // This is an unknown instruction. Assume it escapes or writes to all
10229       // static alloca operands.
10230       for (const Use &U : I.operands()) {
10231         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10232           *Info = StaticAllocaInfo::Clobbered;
10233       }
10234       continue;
10235     }
10236 
10237     // If the stored value is a static alloca, mark it as escaped.
10238     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10239       *Info = StaticAllocaInfo::Clobbered;
10240 
10241     // Check if the destination is a static alloca.
10242     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10243     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10244     if (!Info)
10245       continue;
10246     const AllocaInst *AI = cast<AllocaInst>(Dst);
10247 
10248     // Skip allocas that have been initialized or clobbered.
10249     if (*Info != StaticAllocaInfo::Unknown)
10250       continue;
10251 
10252     // Check if the stored value is an argument, and that this store fully
10253     // initializes the alloca.
10254     // If the argument type has padding bits we can't directly forward a pointer
10255     // as the upper bits may contain garbage.
10256     // Don't elide copies from the same argument twice.
10257     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10258     const auto *Arg = dyn_cast<Argument>(Val);
10259     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10260         Arg->getType()->isEmptyTy() ||
10261         DL.getTypeStoreSize(Arg->getType()) !=
10262             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10263         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10264         ArgCopyElisionCandidates.count(Arg)) {
10265       *Info = StaticAllocaInfo::Clobbered;
10266       continue;
10267     }
10268 
10269     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10270                       << '\n');
10271 
10272     // Mark this alloca and store for argument copy elision.
10273     *Info = StaticAllocaInfo::Elidable;
10274     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10275 
10276     // Stop scanning if we've seen all arguments. This will happen early in -O0
10277     // builds, which is useful, because -O0 builds have large entry blocks and
10278     // many allocas.
10279     if (ArgCopyElisionCandidates.size() == NumArgs)
10280       break;
10281   }
10282 }
10283 
10284 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10285 /// ArgVal is a load from a suitable fixed stack object.
10286 static void tryToElideArgumentCopy(
10287     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10288     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10289     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10290     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10291     SDValue ArgVal, bool &ArgHasUses) {
10292   // Check if this is a load from a fixed stack object.
10293   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10294   if (!LNode)
10295     return;
10296   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10297   if (!FINode)
10298     return;
10299 
10300   // Check that the fixed stack object is the right size and alignment.
10301   // Look at the alignment that the user wrote on the alloca instead of looking
10302   // at the stack object.
10303   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10304   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10305   const AllocaInst *AI = ArgCopyIter->second.first;
10306   int FixedIndex = FINode->getIndex();
10307   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10308   int OldIndex = AllocaIndex;
10309   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10310   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10311     LLVM_DEBUG(
10312         dbgs() << "  argument copy elision failed due to bad fixed stack "
10313                   "object size\n");
10314     return;
10315   }
10316   Align RequiredAlignment = AI->getAlign();
10317   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10318     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10319                          "greater than stack argument alignment ("
10320                       << DebugStr(RequiredAlignment) << " vs "
10321                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10322     return;
10323   }
10324 
10325   // Perform the elision. Delete the old stack object and replace its only use
10326   // in the variable info map. Mark the stack object as mutable.
10327   LLVM_DEBUG({
10328     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10329            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10330            << '\n';
10331   });
10332   MFI.RemoveStackObject(OldIndex);
10333   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10334   AllocaIndex = FixedIndex;
10335   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10336   Chains.push_back(ArgVal.getValue(1));
10337 
10338   // Avoid emitting code for the store implementing the copy.
10339   const StoreInst *SI = ArgCopyIter->second.second;
10340   ElidedArgCopyInstrs.insert(SI);
10341 
10342   // Check for uses of the argument again so that we can avoid exporting ArgVal
10343   // if it is't used by anything other than the store.
10344   for (const Value *U : Arg.users()) {
10345     if (U != SI) {
10346       ArgHasUses = true;
10347       break;
10348     }
10349   }
10350 }
10351 
10352 void SelectionDAGISel::LowerArguments(const Function &F) {
10353   SelectionDAG &DAG = SDB->DAG;
10354   SDLoc dl = SDB->getCurSDLoc();
10355   const DataLayout &DL = DAG.getDataLayout();
10356   SmallVector<ISD::InputArg, 16> Ins;
10357 
10358   // In Naked functions we aren't going to save any registers.
10359   if (F.hasFnAttribute(Attribute::Naked))
10360     return;
10361 
10362   if (!FuncInfo->CanLowerReturn) {
10363     // Put in an sret pointer parameter before all the other parameters.
10364     SmallVector<EVT, 1> ValueVTs;
10365     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10366                     F.getReturnType()->getPointerTo(
10367                         DAG.getDataLayout().getAllocaAddrSpace()),
10368                     ValueVTs);
10369 
10370     // NOTE: Assuming that a pointer will never break down to more than one VT
10371     // or one register.
10372     ISD::ArgFlagsTy Flags;
10373     Flags.setSRet();
10374     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10375     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10376                          ISD::InputArg::NoArgIndex, 0);
10377     Ins.push_back(RetArg);
10378   }
10379 
10380   // Look for stores of arguments to static allocas. Mark such arguments with a
10381   // flag to ask the target to give us the memory location of that argument if
10382   // available.
10383   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10384   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10385                                     ArgCopyElisionCandidates);
10386 
10387   // Set up the incoming argument description vector.
10388   for (const Argument &Arg : F.args()) {
10389     unsigned ArgNo = Arg.getArgNo();
10390     SmallVector<EVT, 4> ValueVTs;
10391     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10392     bool isArgValueUsed = !Arg.use_empty();
10393     unsigned PartBase = 0;
10394     Type *FinalType = Arg.getType();
10395     if (Arg.hasAttribute(Attribute::ByVal))
10396       FinalType = Arg.getParamByValType();
10397     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10398         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10399     for (unsigned Value = 0, NumValues = ValueVTs.size();
10400          Value != NumValues; ++Value) {
10401       EVT VT = ValueVTs[Value];
10402       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10403       ISD::ArgFlagsTy Flags;
10404 
10405 
10406       if (Arg.getType()->isPointerTy()) {
10407         Flags.setPointer();
10408         Flags.setPointerAddrSpace(
10409             cast<PointerType>(Arg.getType())->getAddressSpace());
10410       }
10411       if (Arg.hasAttribute(Attribute::ZExt))
10412         Flags.setZExt();
10413       if (Arg.hasAttribute(Attribute::SExt))
10414         Flags.setSExt();
10415       if (Arg.hasAttribute(Attribute::InReg)) {
10416         // If we are using vectorcall calling convention, a structure that is
10417         // passed InReg - is surely an HVA
10418         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10419             isa<StructType>(Arg.getType())) {
10420           // The first value of a structure is marked
10421           if (0 == Value)
10422             Flags.setHvaStart();
10423           Flags.setHva();
10424         }
10425         // Set InReg Flag
10426         Flags.setInReg();
10427       }
10428       if (Arg.hasAttribute(Attribute::StructRet))
10429         Flags.setSRet();
10430       if (Arg.hasAttribute(Attribute::SwiftSelf))
10431         Flags.setSwiftSelf();
10432       if (Arg.hasAttribute(Attribute::SwiftAsync))
10433         Flags.setSwiftAsync();
10434       if (Arg.hasAttribute(Attribute::SwiftError))
10435         Flags.setSwiftError();
10436       if (Arg.hasAttribute(Attribute::ByVal))
10437         Flags.setByVal();
10438       if (Arg.hasAttribute(Attribute::ByRef))
10439         Flags.setByRef();
10440       if (Arg.hasAttribute(Attribute::InAlloca)) {
10441         Flags.setInAlloca();
10442         // Set the byval flag for CCAssignFn callbacks that don't know about
10443         // inalloca.  This way we can know how many bytes we should've allocated
10444         // and how many bytes a callee cleanup function will pop.  If we port
10445         // inalloca to more targets, we'll have to add custom inalloca handling
10446         // in the various CC lowering callbacks.
10447         Flags.setByVal();
10448       }
10449       if (Arg.hasAttribute(Attribute::Preallocated)) {
10450         Flags.setPreallocated();
10451         // Set the byval flag for CCAssignFn callbacks that don't know about
10452         // preallocated.  This way we can know how many bytes we should've
10453         // allocated and how many bytes a callee cleanup function will pop.  If
10454         // we port preallocated to more targets, we'll have to add custom
10455         // preallocated handling in the various CC lowering callbacks.
10456         Flags.setByVal();
10457       }
10458 
10459       // Certain targets (such as MIPS), may have a different ABI alignment
10460       // for a type depending on the context. Give the target a chance to
10461       // specify the alignment it wants.
10462       const Align OriginalAlignment(
10463           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10464       Flags.setOrigAlign(OriginalAlignment);
10465 
10466       Align MemAlign;
10467       Type *ArgMemTy = nullptr;
10468       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10469           Flags.isByRef()) {
10470         if (!ArgMemTy)
10471           ArgMemTy = Arg.getPointeeInMemoryValueType();
10472 
10473         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10474 
10475         // For in-memory arguments, size and alignment should be passed from FE.
10476         // BE will guess if this info is not there but there are cases it cannot
10477         // get right.
10478         if (auto ParamAlign = Arg.getParamStackAlign())
10479           MemAlign = *ParamAlign;
10480         else if ((ParamAlign = Arg.getParamAlign()))
10481           MemAlign = *ParamAlign;
10482         else
10483           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10484         if (Flags.isByRef())
10485           Flags.setByRefSize(MemSize);
10486         else
10487           Flags.setByValSize(MemSize);
10488       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10489         MemAlign = *ParamAlign;
10490       } else {
10491         MemAlign = OriginalAlignment;
10492       }
10493       Flags.setMemAlign(MemAlign);
10494 
10495       if (Arg.hasAttribute(Attribute::Nest))
10496         Flags.setNest();
10497       if (NeedsRegBlock)
10498         Flags.setInConsecutiveRegs();
10499       if (ArgCopyElisionCandidates.count(&Arg))
10500         Flags.setCopyElisionCandidate();
10501       if (Arg.hasAttribute(Attribute::Returned))
10502         Flags.setReturned();
10503 
10504       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10505           *CurDAG->getContext(), F.getCallingConv(), VT);
10506       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10507           *CurDAG->getContext(), F.getCallingConv(), VT);
10508       for (unsigned i = 0; i != NumRegs; ++i) {
10509         // For scalable vectors, use the minimum size; individual targets
10510         // are responsible for handling scalable vector arguments and
10511         // return values.
10512         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10513                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10514         if (NumRegs > 1 && i == 0)
10515           MyFlags.Flags.setSplit();
10516         // if it isn't first piece, alignment must be 1
10517         else if (i > 0) {
10518           MyFlags.Flags.setOrigAlign(Align(1));
10519           if (i == NumRegs - 1)
10520             MyFlags.Flags.setSplitEnd();
10521         }
10522         Ins.push_back(MyFlags);
10523       }
10524       if (NeedsRegBlock && Value == NumValues - 1)
10525         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10526       PartBase += VT.getStoreSize().getKnownMinSize();
10527     }
10528   }
10529 
10530   // Call the target to set up the argument values.
10531   SmallVector<SDValue, 8> InVals;
10532   SDValue NewRoot = TLI->LowerFormalArguments(
10533       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10534 
10535   // Verify that the target's LowerFormalArguments behaved as expected.
10536   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10537          "LowerFormalArguments didn't return a valid chain!");
10538   assert(InVals.size() == Ins.size() &&
10539          "LowerFormalArguments didn't emit the correct number of values!");
10540   LLVM_DEBUG({
10541     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10542       assert(InVals[i].getNode() &&
10543              "LowerFormalArguments emitted a null value!");
10544       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10545              "LowerFormalArguments emitted a value with the wrong type!");
10546     }
10547   });
10548 
10549   // Update the DAG with the new chain value resulting from argument lowering.
10550   DAG.setRoot(NewRoot);
10551 
10552   // Set up the argument values.
10553   unsigned i = 0;
10554   if (!FuncInfo->CanLowerReturn) {
10555     // Create a virtual register for the sret pointer, and put in a copy
10556     // from the sret argument into it.
10557     SmallVector<EVT, 1> ValueVTs;
10558     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10559                     F.getReturnType()->getPointerTo(
10560                         DAG.getDataLayout().getAllocaAddrSpace()),
10561                     ValueVTs);
10562     MVT VT = ValueVTs[0].getSimpleVT();
10563     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10564     Optional<ISD::NodeType> AssertOp;
10565     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10566                                         nullptr, F.getCallingConv(), AssertOp);
10567 
10568     MachineFunction& MF = SDB->DAG.getMachineFunction();
10569     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10570     Register SRetReg =
10571         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10572     FuncInfo->DemoteRegister = SRetReg;
10573     NewRoot =
10574         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10575     DAG.setRoot(NewRoot);
10576 
10577     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10578     ++i;
10579   }
10580 
10581   SmallVector<SDValue, 4> Chains;
10582   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10583   for (const Argument &Arg : F.args()) {
10584     SmallVector<SDValue, 4> ArgValues;
10585     SmallVector<EVT, 4> ValueVTs;
10586     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10587     unsigned NumValues = ValueVTs.size();
10588     if (NumValues == 0)
10589       continue;
10590 
10591     bool ArgHasUses = !Arg.use_empty();
10592 
10593     // Elide the copying store if the target loaded this argument from a
10594     // suitable fixed stack object.
10595     if (Ins[i].Flags.isCopyElisionCandidate()) {
10596       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10597                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10598                              InVals[i], ArgHasUses);
10599     }
10600 
10601     // If this argument is unused then remember its value. It is used to generate
10602     // debugging information.
10603     bool isSwiftErrorArg =
10604         TLI->supportSwiftError() &&
10605         Arg.hasAttribute(Attribute::SwiftError);
10606     if (!ArgHasUses && !isSwiftErrorArg) {
10607       SDB->setUnusedArgValue(&Arg, InVals[i]);
10608 
10609       // Also remember any frame index for use in FastISel.
10610       if (FrameIndexSDNode *FI =
10611           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10612         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10613     }
10614 
10615     for (unsigned Val = 0; Val != NumValues; ++Val) {
10616       EVT VT = ValueVTs[Val];
10617       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10618                                                       F.getCallingConv(), VT);
10619       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10620           *CurDAG->getContext(), F.getCallingConv(), VT);
10621 
10622       // Even an apparent 'unused' swifterror argument needs to be returned. So
10623       // we do generate a copy for it that can be used on return from the
10624       // function.
10625       if (ArgHasUses || isSwiftErrorArg) {
10626         Optional<ISD::NodeType> AssertOp;
10627         if (Arg.hasAttribute(Attribute::SExt))
10628           AssertOp = ISD::AssertSext;
10629         else if (Arg.hasAttribute(Attribute::ZExt))
10630           AssertOp = ISD::AssertZext;
10631 
10632         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10633                                              PartVT, VT, nullptr,
10634                                              F.getCallingConv(), AssertOp));
10635       }
10636 
10637       i += NumParts;
10638     }
10639 
10640     // We don't need to do anything else for unused arguments.
10641     if (ArgValues.empty())
10642       continue;
10643 
10644     // Note down frame index.
10645     if (FrameIndexSDNode *FI =
10646         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10647       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10648 
10649     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10650                                      SDB->getCurSDLoc());
10651 
10652     SDB->setValue(&Arg, Res);
10653     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10654       // We want to associate the argument with the frame index, among
10655       // involved operands, that correspond to the lowest address. The
10656       // getCopyFromParts function, called earlier, is swapping the order of
10657       // the operands to BUILD_PAIR depending on endianness. The result of
10658       // that swapping is that the least significant bits of the argument will
10659       // be in the first operand of the BUILD_PAIR node, and the most
10660       // significant bits will be in the second operand.
10661       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10662       if (LoadSDNode *LNode =
10663           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10664         if (FrameIndexSDNode *FI =
10665             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10666           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10667     }
10668 
10669     // Analyses past this point are naive and don't expect an assertion.
10670     if (Res.getOpcode() == ISD::AssertZext)
10671       Res = Res.getOperand(0);
10672 
10673     // Update the SwiftErrorVRegDefMap.
10674     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10675       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10676       if (Register::isVirtualRegister(Reg))
10677         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10678                                    Reg);
10679     }
10680 
10681     // If this argument is live outside of the entry block, insert a copy from
10682     // wherever we got it to the vreg that other BB's will reference it as.
10683     if (Res.getOpcode() == ISD::CopyFromReg) {
10684       // If we can, though, try to skip creating an unnecessary vreg.
10685       // FIXME: This isn't very clean... it would be nice to make this more
10686       // general.
10687       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10688       if (Register::isVirtualRegister(Reg)) {
10689         FuncInfo->ValueMap[&Arg] = Reg;
10690         continue;
10691       }
10692     }
10693     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10694       FuncInfo->InitializeRegForValue(&Arg);
10695       SDB->CopyToExportRegsIfNeeded(&Arg);
10696     }
10697   }
10698 
10699   if (!Chains.empty()) {
10700     Chains.push_back(NewRoot);
10701     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10702   }
10703 
10704   DAG.setRoot(NewRoot);
10705 
10706   assert(i == InVals.size() && "Argument register count mismatch!");
10707 
10708   // If any argument copy elisions occurred and we have debug info, update the
10709   // stale frame indices used in the dbg.declare variable info table.
10710   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10711   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10712     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10713       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10714       if (I != ArgCopyElisionFrameIndexMap.end())
10715         VI.Slot = I->second;
10716     }
10717   }
10718 
10719   // Finally, if the target has anything special to do, allow it to do so.
10720   emitFunctionEntryCode();
10721 }
10722 
10723 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10724 /// ensure constants are generated when needed.  Remember the virtual registers
10725 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10726 /// directly add them, because expansion might result in multiple MBB's for one
10727 /// BB.  As such, the start of the BB might correspond to a different MBB than
10728 /// the end.
10729 void
10730 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10732   const Instruction *TI = LLVMBB->getTerminator();
10733 
10734   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10735 
10736   // Check PHI nodes in successors that expect a value to be available from this
10737   // block.
10738   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10739     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10740     if (!isa<PHINode>(SuccBB->begin())) continue;
10741     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10742 
10743     // If this terminator has multiple identical successors (common for
10744     // switches), only handle each succ once.
10745     if (!SuccsHandled.insert(SuccMBB).second)
10746       continue;
10747 
10748     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10749 
10750     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10751     // nodes and Machine PHI nodes, but the incoming operands have not been
10752     // emitted yet.
10753     for (const PHINode &PN : SuccBB->phis()) {
10754       // Ignore dead phi's.
10755       if (PN.use_empty())
10756         continue;
10757 
10758       // Skip empty types
10759       if (PN.getType()->isEmptyTy())
10760         continue;
10761 
10762       unsigned Reg;
10763       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10764 
10765       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10766         unsigned &RegOut = ConstantsOut[C];
10767         if (RegOut == 0) {
10768           RegOut = FuncInfo.CreateRegs(C);
10769           // We need to zero/sign extend ConstantInt phi operands to match
10770           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10771           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10772           if (auto *CI = dyn_cast<ConstantInt>(C))
10773             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10774                                                     : ISD::ZERO_EXTEND;
10775           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10776         }
10777         Reg = RegOut;
10778       } else {
10779         DenseMap<const Value *, Register>::iterator I =
10780           FuncInfo.ValueMap.find(PHIOp);
10781         if (I != FuncInfo.ValueMap.end())
10782           Reg = I->second;
10783         else {
10784           assert(isa<AllocaInst>(PHIOp) &&
10785                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10786                  "Didn't codegen value into a register!??");
10787           Reg = FuncInfo.CreateRegs(PHIOp);
10788           CopyValueToVirtualRegister(PHIOp, Reg);
10789         }
10790       }
10791 
10792       // Remember that this register needs to added to the machine PHI node as
10793       // the input for this MBB.
10794       SmallVector<EVT, 4> ValueVTs;
10795       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10796       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10797         EVT VT = ValueVTs[vti];
10798         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10799         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10800           FuncInfo.PHINodesToUpdate.push_back(
10801               std::make_pair(&*MBBI++, Reg + i));
10802         Reg += NumRegisters;
10803       }
10804     }
10805   }
10806 
10807   ConstantsOut.clear();
10808 }
10809 
10810 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10811   MachineFunction::iterator I(MBB);
10812   if (++I == FuncInfo.MF->end())
10813     return nullptr;
10814   return &*I;
10815 }
10816 
10817 /// During lowering new call nodes can be created (such as memset, etc.).
10818 /// Those will become new roots of the current DAG, but complications arise
10819 /// when they are tail calls. In such cases, the call lowering will update
10820 /// the root, but the builder still needs to know that a tail call has been
10821 /// lowered in order to avoid generating an additional return.
10822 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10823   // If the node is null, we do have a tail call.
10824   if (MaybeTC.getNode() != nullptr)
10825     DAG.setRoot(MaybeTC);
10826   else
10827     HasTailCall = true;
10828 }
10829 
10830 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10831                                         MachineBasicBlock *SwitchMBB,
10832                                         MachineBasicBlock *DefaultMBB) {
10833   MachineFunction *CurMF = FuncInfo.MF;
10834   MachineBasicBlock *NextMBB = nullptr;
10835   MachineFunction::iterator BBI(W.MBB);
10836   if (++BBI != FuncInfo.MF->end())
10837     NextMBB = &*BBI;
10838 
10839   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10840 
10841   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10842 
10843   if (Size == 2 && W.MBB == SwitchMBB) {
10844     // If any two of the cases has the same destination, and if one value
10845     // is the same as the other, but has one bit unset that the other has set,
10846     // use bit manipulation to do two compares at once.  For example:
10847     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10848     // TODO: This could be extended to merge any 2 cases in switches with 3
10849     // cases.
10850     // TODO: Handle cases where W.CaseBB != SwitchBB.
10851     CaseCluster &Small = *W.FirstCluster;
10852     CaseCluster &Big = *W.LastCluster;
10853 
10854     if (Small.Low == Small.High && Big.Low == Big.High &&
10855         Small.MBB == Big.MBB) {
10856       const APInt &SmallValue = Small.Low->getValue();
10857       const APInt &BigValue = Big.Low->getValue();
10858 
10859       // Check that there is only one bit different.
10860       APInt CommonBit = BigValue ^ SmallValue;
10861       if (CommonBit.isPowerOf2()) {
10862         SDValue CondLHS = getValue(Cond);
10863         EVT VT = CondLHS.getValueType();
10864         SDLoc DL = getCurSDLoc();
10865 
10866         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10867                                  DAG.getConstant(CommonBit, DL, VT));
10868         SDValue Cond = DAG.getSetCC(
10869             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10870             ISD::SETEQ);
10871 
10872         // Update successor info.
10873         // Both Small and Big will jump to Small.BB, so we sum up the
10874         // probabilities.
10875         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10876         if (BPI)
10877           addSuccessorWithProb(
10878               SwitchMBB, DefaultMBB,
10879               // The default destination is the first successor in IR.
10880               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10881         else
10882           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10883 
10884         // Insert the true branch.
10885         SDValue BrCond =
10886             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10887                         DAG.getBasicBlock(Small.MBB));
10888         // Insert the false branch.
10889         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10890                              DAG.getBasicBlock(DefaultMBB));
10891 
10892         DAG.setRoot(BrCond);
10893         return;
10894       }
10895     }
10896   }
10897 
10898   if (TM.getOptLevel() != CodeGenOpt::None) {
10899     // Here, we order cases by probability so the most likely case will be
10900     // checked first. However, two clusters can have the same probability in
10901     // which case their relative ordering is non-deterministic. So we use Low
10902     // as a tie-breaker as clusters are guaranteed to never overlap.
10903     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10904                [](const CaseCluster &a, const CaseCluster &b) {
10905       return a.Prob != b.Prob ?
10906              a.Prob > b.Prob :
10907              a.Low->getValue().slt(b.Low->getValue());
10908     });
10909 
10910     // Rearrange the case blocks so that the last one falls through if possible
10911     // without changing the order of probabilities.
10912     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10913       --I;
10914       if (I->Prob > W.LastCluster->Prob)
10915         break;
10916       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10917         std::swap(*I, *W.LastCluster);
10918         break;
10919       }
10920     }
10921   }
10922 
10923   // Compute total probability.
10924   BranchProbability DefaultProb = W.DefaultProb;
10925   BranchProbability UnhandledProbs = DefaultProb;
10926   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10927     UnhandledProbs += I->Prob;
10928 
10929   MachineBasicBlock *CurMBB = W.MBB;
10930   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10931     bool FallthroughUnreachable = false;
10932     MachineBasicBlock *Fallthrough;
10933     if (I == W.LastCluster) {
10934       // For the last cluster, fall through to the default destination.
10935       Fallthrough = DefaultMBB;
10936       FallthroughUnreachable = isa<UnreachableInst>(
10937           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10938     } else {
10939       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10940       CurMF->insert(BBI, Fallthrough);
10941       // Put Cond in a virtual register to make it available from the new blocks.
10942       ExportFromCurrentBlock(Cond);
10943     }
10944     UnhandledProbs -= I->Prob;
10945 
10946     switch (I->Kind) {
10947       case CC_JumpTable: {
10948         // FIXME: Optimize away range check based on pivot comparisons.
10949         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10950         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10951 
10952         // The jump block hasn't been inserted yet; insert it here.
10953         MachineBasicBlock *JumpMBB = JT->MBB;
10954         CurMF->insert(BBI, JumpMBB);
10955 
10956         auto JumpProb = I->Prob;
10957         auto FallthroughProb = UnhandledProbs;
10958 
10959         // If the default statement is a target of the jump table, we evenly
10960         // distribute the default probability to successors of CurMBB. Also
10961         // update the probability on the edge from JumpMBB to Fallthrough.
10962         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10963                                               SE = JumpMBB->succ_end();
10964              SI != SE; ++SI) {
10965           if (*SI == DefaultMBB) {
10966             JumpProb += DefaultProb / 2;
10967             FallthroughProb -= DefaultProb / 2;
10968             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10969             JumpMBB->normalizeSuccProbs();
10970             break;
10971           }
10972         }
10973 
10974         if (FallthroughUnreachable)
10975           JTH->FallthroughUnreachable = true;
10976 
10977         if (!JTH->FallthroughUnreachable)
10978           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10979         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10980         CurMBB->normalizeSuccProbs();
10981 
10982         // The jump table header will be inserted in our current block, do the
10983         // range check, and fall through to our fallthrough block.
10984         JTH->HeaderBB = CurMBB;
10985         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10986 
10987         // If we're in the right place, emit the jump table header right now.
10988         if (CurMBB == SwitchMBB) {
10989           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10990           JTH->Emitted = true;
10991         }
10992         break;
10993       }
10994       case CC_BitTests: {
10995         // FIXME: Optimize away range check based on pivot comparisons.
10996         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10997 
10998         // The bit test blocks haven't been inserted yet; insert them here.
10999         for (BitTestCase &BTC : BTB->Cases)
11000           CurMF->insert(BBI, BTC.ThisBB);
11001 
11002         // Fill in fields of the BitTestBlock.
11003         BTB->Parent = CurMBB;
11004         BTB->Default = Fallthrough;
11005 
11006         BTB->DefaultProb = UnhandledProbs;
11007         // If the cases in bit test don't form a contiguous range, we evenly
11008         // distribute the probability on the edge to Fallthrough to two
11009         // successors of CurMBB.
11010         if (!BTB->ContiguousRange) {
11011           BTB->Prob += DefaultProb / 2;
11012           BTB->DefaultProb -= DefaultProb / 2;
11013         }
11014 
11015         if (FallthroughUnreachable)
11016           BTB->FallthroughUnreachable = true;
11017 
11018         // If we're in the right place, emit the bit test header right now.
11019         if (CurMBB == SwitchMBB) {
11020           visitBitTestHeader(*BTB, SwitchMBB);
11021           BTB->Emitted = true;
11022         }
11023         break;
11024       }
11025       case CC_Range: {
11026         const Value *RHS, *LHS, *MHS;
11027         ISD::CondCode CC;
11028         if (I->Low == I->High) {
11029           // Check Cond == I->Low.
11030           CC = ISD::SETEQ;
11031           LHS = Cond;
11032           RHS=I->Low;
11033           MHS = nullptr;
11034         } else {
11035           // Check I->Low <= Cond <= I->High.
11036           CC = ISD::SETLE;
11037           LHS = I->Low;
11038           MHS = Cond;
11039           RHS = I->High;
11040         }
11041 
11042         // If Fallthrough is unreachable, fold away the comparison.
11043         if (FallthroughUnreachable)
11044           CC = ISD::SETTRUE;
11045 
11046         // The false probability is the sum of all unhandled cases.
11047         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11048                      getCurSDLoc(), I->Prob, UnhandledProbs);
11049 
11050         if (CurMBB == SwitchMBB)
11051           visitSwitchCase(CB, SwitchMBB);
11052         else
11053           SL->SwitchCases.push_back(CB);
11054 
11055         break;
11056       }
11057     }
11058     CurMBB = Fallthrough;
11059   }
11060 }
11061 
11062 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11063                                               CaseClusterIt First,
11064                                               CaseClusterIt Last) {
11065   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11066     if (X.Prob != CC.Prob)
11067       return X.Prob > CC.Prob;
11068 
11069     // Ties are broken by comparing the case value.
11070     return X.Low->getValue().slt(CC.Low->getValue());
11071   });
11072 }
11073 
11074 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11075                                         const SwitchWorkListItem &W,
11076                                         Value *Cond,
11077                                         MachineBasicBlock *SwitchMBB) {
11078   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11079          "Clusters not sorted?");
11080 
11081   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11082 
11083   // Balance the tree based on branch probabilities to create a near-optimal (in
11084   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11085   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11086   CaseClusterIt LastLeft = W.FirstCluster;
11087   CaseClusterIt FirstRight = W.LastCluster;
11088   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11089   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11090 
11091   // Move LastLeft and FirstRight towards each other from opposite directions to
11092   // find a partitioning of the clusters which balances the probability on both
11093   // sides. If LeftProb and RightProb are equal, alternate which side is
11094   // taken to ensure 0-probability nodes are distributed evenly.
11095   unsigned I = 0;
11096   while (LastLeft + 1 < FirstRight) {
11097     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11098       LeftProb += (++LastLeft)->Prob;
11099     else
11100       RightProb += (--FirstRight)->Prob;
11101     I++;
11102   }
11103 
11104   while (true) {
11105     // Our binary search tree differs from a typical BST in that ours can have up
11106     // to three values in each leaf. The pivot selection above doesn't take that
11107     // into account, which means the tree might require more nodes and be less
11108     // efficient. We compensate for this here.
11109 
11110     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11111     unsigned NumRight = W.LastCluster - FirstRight + 1;
11112 
11113     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11114       // If one side has less than 3 clusters, and the other has more than 3,
11115       // consider taking a cluster from the other side.
11116 
11117       if (NumLeft < NumRight) {
11118         // Consider moving the first cluster on the right to the left side.
11119         CaseCluster &CC = *FirstRight;
11120         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11121         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11122         if (LeftSideRank <= RightSideRank) {
11123           // Moving the cluster to the left does not demote it.
11124           ++LastLeft;
11125           ++FirstRight;
11126           continue;
11127         }
11128       } else {
11129         assert(NumRight < NumLeft);
11130         // Consider moving the last element on the left to the right side.
11131         CaseCluster &CC = *LastLeft;
11132         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11133         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11134         if (RightSideRank <= LeftSideRank) {
11135           // Moving the cluster to the right does not demot it.
11136           --LastLeft;
11137           --FirstRight;
11138           continue;
11139         }
11140       }
11141     }
11142     break;
11143   }
11144 
11145   assert(LastLeft + 1 == FirstRight);
11146   assert(LastLeft >= W.FirstCluster);
11147   assert(FirstRight <= W.LastCluster);
11148 
11149   // Use the first element on the right as pivot since we will make less-than
11150   // comparisons against it.
11151   CaseClusterIt PivotCluster = FirstRight;
11152   assert(PivotCluster > W.FirstCluster);
11153   assert(PivotCluster <= W.LastCluster);
11154 
11155   CaseClusterIt FirstLeft = W.FirstCluster;
11156   CaseClusterIt LastRight = W.LastCluster;
11157 
11158   const ConstantInt *Pivot = PivotCluster->Low;
11159 
11160   // New blocks will be inserted immediately after the current one.
11161   MachineFunction::iterator BBI(W.MBB);
11162   ++BBI;
11163 
11164   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11165   // we can branch to its destination directly if it's squeezed exactly in
11166   // between the known lower bound and Pivot - 1.
11167   MachineBasicBlock *LeftMBB;
11168   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11169       FirstLeft->Low == W.GE &&
11170       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11171     LeftMBB = FirstLeft->MBB;
11172   } else {
11173     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11174     FuncInfo.MF->insert(BBI, LeftMBB);
11175     WorkList.push_back(
11176         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11177     // Put Cond in a virtual register to make it available from the new blocks.
11178     ExportFromCurrentBlock(Cond);
11179   }
11180 
11181   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11182   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11183   // directly if RHS.High equals the current upper bound.
11184   MachineBasicBlock *RightMBB;
11185   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11186       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11187     RightMBB = FirstRight->MBB;
11188   } else {
11189     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11190     FuncInfo.MF->insert(BBI, RightMBB);
11191     WorkList.push_back(
11192         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11193     // Put Cond in a virtual register to make it available from the new blocks.
11194     ExportFromCurrentBlock(Cond);
11195   }
11196 
11197   // Create the CaseBlock record that will be used to lower the branch.
11198   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11199                getCurSDLoc(), LeftProb, RightProb);
11200 
11201   if (W.MBB == SwitchMBB)
11202     visitSwitchCase(CB, SwitchMBB);
11203   else
11204     SL->SwitchCases.push_back(CB);
11205 }
11206 
11207 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11208 // from the swith statement.
11209 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11210                                             BranchProbability PeeledCaseProb) {
11211   if (PeeledCaseProb == BranchProbability::getOne())
11212     return BranchProbability::getZero();
11213   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11214 
11215   uint32_t Numerator = CaseProb.getNumerator();
11216   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11217   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11218 }
11219 
11220 // Try to peel the top probability case if it exceeds the threshold.
11221 // Return current MachineBasicBlock for the switch statement if the peeling
11222 // does not occur.
11223 // If the peeling is performed, return the newly created MachineBasicBlock
11224 // for the peeled switch statement. Also update Clusters to remove the peeled
11225 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11226 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11227     const SwitchInst &SI, CaseClusterVector &Clusters,
11228     BranchProbability &PeeledCaseProb) {
11229   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11230   // Don't perform if there is only one cluster or optimizing for size.
11231   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11232       TM.getOptLevel() == CodeGenOpt::None ||
11233       SwitchMBB->getParent()->getFunction().hasMinSize())
11234     return SwitchMBB;
11235 
11236   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11237   unsigned PeeledCaseIndex = 0;
11238   bool SwitchPeeled = false;
11239   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11240     CaseCluster &CC = Clusters[Index];
11241     if (CC.Prob < TopCaseProb)
11242       continue;
11243     TopCaseProb = CC.Prob;
11244     PeeledCaseIndex = Index;
11245     SwitchPeeled = true;
11246   }
11247   if (!SwitchPeeled)
11248     return SwitchMBB;
11249 
11250   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11251                     << TopCaseProb << "\n");
11252 
11253   // Record the MBB for the peeled switch statement.
11254   MachineFunction::iterator BBI(SwitchMBB);
11255   ++BBI;
11256   MachineBasicBlock *PeeledSwitchMBB =
11257       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11258   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11259 
11260   ExportFromCurrentBlock(SI.getCondition());
11261   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11262   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11263                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11264   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11265 
11266   Clusters.erase(PeeledCaseIt);
11267   for (CaseCluster &CC : Clusters) {
11268     LLVM_DEBUG(
11269         dbgs() << "Scale the probablity for one cluster, before scaling: "
11270                << CC.Prob << "\n");
11271     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11272     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11273   }
11274   PeeledCaseProb = TopCaseProb;
11275   return PeeledSwitchMBB;
11276 }
11277 
11278 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11279   // Extract cases from the switch.
11280   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11281   CaseClusterVector Clusters;
11282   Clusters.reserve(SI.getNumCases());
11283   for (auto I : SI.cases()) {
11284     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11285     const ConstantInt *CaseVal = I.getCaseValue();
11286     BranchProbability Prob =
11287         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11288             : BranchProbability(1, SI.getNumCases() + 1);
11289     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11290   }
11291 
11292   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11293 
11294   // Cluster adjacent cases with the same destination. We do this at all
11295   // optimization levels because it's cheap to do and will make codegen faster
11296   // if there are many clusters.
11297   sortAndRangeify(Clusters);
11298 
11299   // The branch probablity of the peeled case.
11300   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11301   MachineBasicBlock *PeeledSwitchMBB =
11302       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11303 
11304   // If there is only the default destination, jump there directly.
11305   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11306   if (Clusters.empty()) {
11307     assert(PeeledSwitchMBB == SwitchMBB);
11308     SwitchMBB->addSuccessor(DefaultMBB);
11309     if (DefaultMBB != NextBlock(SwitchMBB)) {
11310       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11311                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11312     }
11313     return;
11314   }
11315 
11316   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11317   SL->findBitTestClusters(Clusters, &SI);
11318 
11319   LLVM_DEBUG({
11320     dbgs() << "Case clusters: ";
11321     for (const CaseCluster &C : Clusters) {
11322       if (C.Kind == CC_JumpTable)
11323         dbgs() << "JT:";
11324       if (C.Kind == CC_BitTests)
11325         dbgs() << "BT:";
11326 
11327       C.Low->getValue().print(dbgs(), true);
11328       if (C.Low != C.High) {
11329         dbgs() << '-';
11330         C.High->getValue().print(dbgs(), true);
11331       }
11332       dbgs() << ' ';
11333     }
11334     dbgs() << '\n';
11335   });
11336 
11337   assert(!Clusters.empty());
11338   SwitchWorkList WorkList;
11339   CaseClusterIt First = Clusters.begin();
11340   CaseClusterIt Last = Clusters.end() - 1;
11341   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11342   // Scale the branchprobability for DefaultMBB if the peel occurs and
11343   // DefaultMBB is not replaced.
11344   if (PeeledCaseProb != BranchProbability::getZero() &&
11345       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11346     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11347   WorkList.push_back(
11348       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11349 
11350   while (!WorkList.empty()) {
11351     SwitchWorkListItem W = WorkList.pop_back_val();
11352     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11353 
11354     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11355         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11356       // For optimized builds, lower large range as a balanced binary tree.
11357       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11358       continue;
11359     }
11360 
11361     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11362   }
11363 }
11364 
11365 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11367   auto DL = getCurSDLoc();
11368   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11369   setValue(&I, DAG.getStepVector(DL, ResultVT));
11370 }
11371 
11372 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11374   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11375 
11376   SDLoc DL = getCurSDLoc();
11377   SDValue V = getValue(I.getOperand(0));
11378   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11379 
11380   if (VT.isScalableVector()) {
11381     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11382     return;
11383   }
11384 
11385   // Use VECTOR_SHUFFLE for the fixed-length vector
11386   // to maintain existing behavior.
11387   SmallVector<int, 8> Mask;
11388   unsigned NumElts = VT.getVectorMinNumElements();
11389   for (unsigned i = 0; i != NumElts; ++i)
11390     Mask.push_back(NumElts - 1 - i);
11391 
11392   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11393 }
11394 
11395 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11396   SmallVector<EVT, 4> ValueVTs;
11397   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11398                   ValueVTs);
11399   unsigned NumValues = ValueVTs.size();
11400   if (NumValues == 0) return;
11401 
11402   SmallVector<SDValue, 4> Values(NumValues);
11403   SDValue Op = getValue(I.getOperand(0));
11404 
11405   for (unsigned i = 0; i != NumValues; ++i)
11406     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11407                             SDValue(Op.getNode(), Op.getResNo() + i));
11408 
11409   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11410                            DAG.getVTList(ValueVTs), Values));
11411 }
11412 
11413 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11415   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11416 
11417   SDLoc DL = getCurSDLoc();
11418   SDValue V1 = getValue(I.getOperand(0));
11419   SDValue V2 = getValue(I.getOperand(1));
11420   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11421 
11422   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11423   if (VT.isScalableVector()) {
11424     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11425     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11426                              DAG.getConstant(Imm, DL, IdxVT)));
11427     return;
11428   }
11429 
11430   unsigned NumElts = VT.getVectorNumElements();
11431 
11432   uint64_t Idx = (NumElts + Imm) % NumElts;
11433 
11434   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11435   SmallVector<int, 8> Mask;
11436   for (unsigned i = 0; i < NumElts; ++i)
11437     Mask.push_back(Idx + i);
11438   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11439 }
11440