xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision d4eeb02986980bf33dd56c41ceb9fc5f180c0d47)
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/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/DiagnosticInfo.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GetElementPtrTypeIterator.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/IntrinsicsAArch64.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/MC/MCSymbol.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/Transforms/Utils/Local.h"
104 #include <cstddef>
105 #include <cstring>
106 #include <iterator>
107 #include <limits>
108 #include <numeric>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       Optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
166                                 const SDValue *Parts, unsigned NumParts,
167                                 MVT PartVT, EVT ValueVT, const Value *V,
168                                 Optional<CallingConv::ID> CC = None,
169                                 Optional<ISD::NodeType> AssertOp = None) {
170   // Let the target assemble the parts if it wants to
171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173                                                    PartVT, ValueVT, CC))
174     return Val;
175 
176   if (ValueVT.isVector())
177     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178                                   CC);
179 
180   assert(NumParts > 0 && "No parts to assemble!");
181   SDValue Val = Parts[0];
182 
183   if (NumParts > 1) {
184     // Assemble the value from multiple parts.
185     if (ValueVT.isInteger()) {
186       unsigned PartBits = PartVT.getSizeInBits();
187       unsigned ValueBits = ValueVT.getSizeInBits();
188 
189       // Assemble the power of 2 part.
190       unsigned RoundParts =
191           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
201                               PartVT, HalfVT, V);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
203                               RoundParts / 2, PartVT, HalfVT, V);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi =
228             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                         TLI.getPointerTy(DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
250     }
251   }
252 
253   // There is now one part, held in Val.  Correct it to match ValueVT.
254   // PartEVT is the type of the register class that holds the value.
255   // ValueVT is the type of the inline asm operation.
256   EVT PartEVT = Val.getValueType();
257 
258   if (PartEVT == ValueVT)
259     return Val;
260 
261   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262       ValueVT.bitsLT(PartEVT)) {
263     // For an FP value in an integer part, we need to truncate to the right
264     // width first.
265     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
266     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267   }
268 
269   // Handle types that have the same size.
270   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273   // Handle types with different sizes.
274   if (PartEVT.isInteger() && ValueVT.isInteger()) {
275     if (ValueVT.bitsLT(PartEVT)) {
276       // For a truncate, see if we have any information to
277       // indicate whether the truncated bits will always be
278       // zero or sign-extension.
279       if (AssertOp.hasValue())
280         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281                           DAG.getValueType(ValueVT));
282       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283     }
284     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285   }
286 
287   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288     // FP_ROUND's are always exact here.
289     if (ValueVT.bitsLT(Val.getValueType()))
290       return DAG.getNode(
291           ISD::FP_ROUND, DL, ValueVT, Val,
292           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
293 
294     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
295   }
296 
297   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
298   // then truncating.
299   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
300       ValueVT.bitsLT(PartEVT)) {
301     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
302     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303   }
304 
305   report_fatal_error("Unknown mismatch in getCopyFromParts!");
306 }
307 
308 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
309                                               const Twine &ErrMsg) {
310   const Instruction *I = dyn_cast_or_null<Instruction>(V);
311   if (!V)
312     return Ctx.emitError(ErrMsg);
313 
314   const char *AsmError = ", possible invalid constraint for vector type";
315   if (const CallInst *CI = dyn_cast<CallInst>(I))
316     if (CI->isInlineAsm())
317       return Ctx.emitError(I, ErrMsg + AsmError);
318 
319   return Ctx.emitError(I, ErrMsg);
320 }
321 
322 /// getCopyFromPartsVector - Create a value that contains the specified legal
323 /// parts combined into the value they represent.  If the parts combine to a
324 /// type larger than ValueVT then AssertOp can be used to specify whether the
325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
326 /// ValueVT (ISD::AssertSext).
327 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
328                                       const SDValue *Parts, unsigned NumParts,
329                                       MVT PartVT, EVT ValueVT, const Value *V,
330                                       Optional<CallingConv::ID> CallConv) {
331   assert(ValueVT.isVector() && "Not a vector value");
332   assert(NumParts > 0 && "No parts to assemble!");
333   const bool IsABIRegCopy = CallConv.hasValue();
334 
335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336   SDValue Val = Parts[0];
337 
338   // Handle a multi-element vector.
339   if (NumParts > 1) {
340     EVT IntermediateVT;
341     MVT RegisterVT;
342     unsigned NumIntermediates;
343     unsigned NumRegs;
344 
345     if (IsABIRegCopy) {
346       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
347           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
348           NumIntermediates, RegisterVT);
349     } else {
350       NumRegs =
351           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
352                                      NumIntermediates, RegisterVT);
353     }
354 
355     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
356     NumParts = NumRegs; // Silence a compiler warning.
357     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
358     assert(RegisterVT.getSizeInBits() ==
359            Parts[0].getSimpleValueType().getSizeInBits() &&
360            "Part type sizes don't match!");
361 
362     // Assemble the parts into intermediate operands.
363     SmallVector<SDValue, 8> Ops(NumIntermediates);
364     if (NumIntermediates == NumParts) {
365       // If the register was not expanded, truncate or copy the value,
366       // as appropriate.
367       for (unsigned i = 0; i != NumParts; ++i)
368         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
369                                   PartVT, IntermediateVT, V, CallConv);
370     } else if (NumParts > 0) {
371       // If the intermediate type was expanded, build the intermediate
372       // operands from the parts.
373       assert(NumParts % NumIntermediates == 0 &&
374              "Must expand into a divisible number of parts!");
375       unsigned Factor = NumParts / NumIntermediates;
376       for (unsigned i = 0; i != NumIntermediates; ++i)
377         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
378                                   PartVT, IntermediateVT, V, CallConv);
379     }
380 
381     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
382     // intermediate operands.
383     EVT BuiltVectorTy =
384         IntermediateVT.isVector()
385             ? EVT::getVectorVT(
386                   *DAG.getContext(), IntermediateVT.getScalarType(),
387                   IntermediateVT.getVectorElementCount() * NumParts)
388             : EVT::getVectorVT(*DAG.getContext(),
389                                IntermediateVT.getScalarType(),
390                                NumIntermediates);
391     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
392                                                 : ISD::BUILD_VECTOR,
393                       DL, BuiltVectorTy, Ops);
394   }
395 
396   // There is now one part, held in Val.  Correct it to match ValueVT.
397   EVT PartEVT = Val.getValueType();
398 
399   if (PartEVT == ValueVT)
400     return Val;
401 
402   if (PartEVT.isVector()) {
403     // Vector/Vector bitcast.
404     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
405       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406 
407     // If the element type of the source/dest vectors are the same, but the
408     // parts vector has more elements than the value vector, then we have a
409     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
410     // elements we want.
411     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
412       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
413               ValueVT.getVectorElementCount().getKnownMinValue()) &&
414              (PartEVT.getVectorElementCount().isScalable() ==
415               ValueVT.getVectorElementCount().isScalable()) &&
416              "Cannot narrow, it would be a lossy transformation");
417       PartEVT =
418           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
419                            ValueVT.getVectorElementCount());
420       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
421                         DAG.getVectorIdxConstant(0, DL));
422       if (PartEVT == ValueVT)
423         return Val;
424     }
425 
426     // Promoted vector extract
427     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
428   }
429 
430   // Trivial bitcast if the types are the same size and the destination
431   // vector type is legal.
432   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
433       TLI.isTypeLegal(ValueVT))
434     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436   if (ValueVT.getVectorNumElements() != 1) {
437      // Certain ABIs require that vectors are passed as integers. For vectors
438      // are the same size, this is an obvious bitcast.
439      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
440        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441      } else if (ValueVT.bitsLT(PartEVT)) {
442        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
443        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
444        // Drop the extra bits.
445        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
446        return DAG.getBitcast(ValueVT, Val);
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
614                                      const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   ElementCount PartNumElts = PartVT.getVectorElementCount();
620   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
621 
622   // We only support widening vectors with equivalent element types and
623   // fixed/scalable properties. If a target needs to widen a fixed-length type
624   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
625   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
626       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
627       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
628     return SDValue();
629 
630   // Widening a scalable vector to another scalable vector is done by inserting
631   // the vector into a larger undef one.
632   if (PartNumElts.isScalable())
633     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
634                        Val, DAG.getVectorIdxConstant(0, DL));
635 
636   EVT ElementVT = PartVT.getVectorElementType();
637   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
638   // undef elements.
639   SmallVector<SDValue, 16> Ops;
640   DAG.ExtractVectorElements(Val, Ops);
641   SDValue EltUndef = DAG.getUNDEF(ElementVT);
642   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
643 
644   // FIXME: Use CONCAT for 2x -> 4x.
645   return DAG.getBuildVector(PartVT, DL, Ops);
646 }
647 
648 /// getCopyToPartsVector - Create a series of nodes that contain the specified
649 /// value split into legal parts.
650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
651                                  SDValue Val, SDValue *Parts, unsigned NumParts,
652                                  MVT PartVT, const Value *V,
653                                  Optional<CallingConv::ID> CallConv) {
654   EVT ValueVT = Val.getValueType();
655   assert(ValueVT.isVector() && "Not a vector");
656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657   const bool IsABIRegCopy = CallConv.hasValue();
658 
659   if (NumParts == 1) {
660     EVT PartEVT = PartVT;
661     if (PartEVT == ValueVT) {
662       // Nothing to do.
663     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
664       // Bitconvert vector->vector case.
665       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
666     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
667       Val = Widened;
668     } else if (PartVT.isVector() &&
669                PartEVT.getVectorElementType().bitsGE(
670                    ValueVT.getVectorElementType()) &&
671                PartEVT.getVectorElementCount() ==
672                    ValueVT.getVectorElementCount()) {
673 
674       // Promoted vector extract
675       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676     } else if (PartEVT.isVector() &&
677                PartEVT.getVectorElementType() !=
678                    ValueVT.getVectorElementType() &&
679                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
680                    TargetLowering::TypeWidenVector) {
681       // Combination of widening and promotion.
682       EVT WidenVT =
683           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
684                            PartVT.getVectorElementCount());
685       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
686       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorElementCount().isScalar()) {
689         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
690                           DAG.getVectorIdxConstant(0, DL));
691       } else {
692         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
693         assert(PartVT.getFixedSizeInBits() > ValueSize &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
696         Val = DAG.getBitcast(IntermediateType, Val);
697         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698       }
699     }
700 
701     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
702     Parts[0] = Val;
703     return;
704   }
705 
706   // Handle a multi-element vector.
707   EVT IntermediateVT;
708   MVT RegisterVT;
709   unsigned NumIntermediates;
710   unsigned NumRegs;
711   if (IsABIRegCopy) {
712     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
713         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
714         NumIntermediates, RegisterVT);
715   } else {
716     NumRegs =
717         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
718                                    NumIntermediates, RegisterVT);
719   }
720 
721   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
722   NumParts = NumRegs; // Silence a compiler warning.
723   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
724 
725   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
726          "Mixing scalable and fixed vectors when copying in parts");
727 
728   Optional<ElementCount> DestEltCnt;
729 
730   if (IntermediateVT.isVector())
731     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
732   else
733     DestEltCnt = ElementCount::getFixed(NumIntermediates);
734 
735   EVT BuiltVectorTy = EVT::getVectorVT(
736       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
737 
738   if (ValueVT == BuiltVectorTy) {
739     // Nothing to do.
740   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
741     // Bitconvert vector->vector case.
742     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743   } else {
744     if (BuiltVectorTy.getVectorElementType().bitsGT(
745             ValueVT.getVectorElementType())) {
746       // Integer promotion.
747       ValueVT = EVT::getVectorVT(*DAG.getContext(),
748                                  BuiltVectorTy.getVectorElementType(),
749                                  ValueVT.getVectorElementCount());
750       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
751     }
752 
753     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
754       Val = Widened;
755     }
756   }
757 
758   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
759 
760   // Split the vector into intermediate operands.
761   SmallVector<SDValue, 8> Ops(NumIntermediates);
762   for (unsigned i = 0; i != NumIntermediates; ++i) {
763     if (IntermediateVT.isVector()) {
764       // This does something sensible for scalable vectors - see the
765       // definition of EXTRACT_SUBVECTOR for further details.
766       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
767       Ops[i] =
768           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770     } else {
771       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772                            DAG.getVectorIdxConstant(i, DL));
773     }
774   }
775 
776   // Split the intermediate operands into legal parts.
777   if (NumParts == NumIntermediates) {
778     // If the register was not expanded, promote or copy the value,
779     // as appropriate.
780     for (unsigned i = 0; i != NumParts; ++i)
781       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782   } else if (NumParts > 0) {
783     // If the intermediate type was expanded, split each the value into
784     // legal parts.
785     assert(NumIntermediates != 0 && "division by zero");
786     assert(NumParts % NumIntermediates == 0 &&
787            "Must expand into a divisible number of parts!");
788     unsigned Factor = NumParts / NumIntermediates;
789     for (unsigned i = 0; i != NumIntermediates; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791                      CallConv);
792   }
793 }
794 
795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
796                            EVT valuevt, Optional<CallingConv::ID> CC)
797     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798       RegCount(1, regs.size()), CallConv(CC) {}
799 
800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
801                            const DataLayout &DL, unsigned Reg, Type *Ty,
802                            Optional<CallingConv::ID> CC) {
803   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805   CallConv = CC;
806 
807   for (EVT ValueVT : ValueVTs) {
808     unsigned NumRegs =
809         isABIMangled()
810             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811             : TLI.getNumRegisters(Context, ValueVT);
812     MVT RegisterVT =
813         isABIMangled()
814             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815             : TLI.getRegisterType(Context, ValueVT);
816     for (unsigned i = 0; i != NumRegs; ++i)
817       Regs.push_back(Reg + i);
818     RegVTs.push_back(RegisterVT);
819     RegCount.push_back(NumRegs);
820     Reg += NumRegs;
821   }
822 }
823 
824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
825                                       FunctionLoweringInfo &FuncInfo,
826                                       const SDLoc &dl, SDValue &Chain,
827                                       SDValue *Flag, const Value *V) const {
828   // A Value with type {} or [0 x %t] needs no registers.
829   if (ValueVTs.empty())
830     return SDValue();
831 
832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834   // Assemble the legal parts into the final values.
835   SmallVector<SDValue, 4> Values(ValueVTs.size());
836   SmallVector<SDValue, 8> Parts;
837   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838     // Copy the legal parts from the registers.
839     EVT ValueVT = ValueVTs[Value];
840     unsigned NumRegs = RegCount[Value];
841     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842                                           *DAG.getContext(),
843                                           CallConv.getValue(), RegVTs[Value])
844                                     : RegVTs[Value];
845 
846     Parts.resize(NumRegs);
847     for (unsigned i = 0; i != NumRegs; ++i) {
848       SDValue P;
849       if (!Flag) {
850         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851       } else {
852         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853         *Flag = P.getValue(2);
854       }
855 
856       Chain = P.getValue(1);
857       Parts[i] = P;
858 
859       // If the source register was virtual and if we know something about it,
860       // add an assert node.
861       if (!Register::isVirtualRegister(Regs[Part + i]) ||
862           !RegisterVT.isInteger())
863         continue;
864 
865       const FunctionLoweringInfo::LiveOutInfo *LOI =
866         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867       if (!LOI)
868         continue;
869 
870       unsigned RegSize = RegisterVT.getScalarSizeInBits();
871       unsigned NumSignBits = LOI->NumSignBits;
872       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874       if (NumZeroBits == RegSize) {
875         // The current value is a zero.
876         // Explicitly express that as it would be easier for
877         // optimizations to kick in.
878         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879         continue;
880       }
881 
882       // FIXME: We capture more information than the dag can represent.  For
883       // now, just use the tightest assertzext/assertsext possible.
884       bool isSExt;
885       EVT FromVT(MVT::Other);
886       if (NumZeroBits) {
887         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888         isSExt = false;
889       } else if (NumSignBits > 1) {
890         FromVT =
891             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892         isSExt = true;
893       } else {
894         continue;
895       }
896       // Add an assertion node.
897       assert(FromVT != MVT::Other);
898       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899                              RegisterVT, P, DAG.getValueType(FromVT));
900     }
901 
902     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903                                      RegisterVT, ValueVT, V, CallConv);
904     Part += NumRegs;
905     Parts.clear();
906   }
907 
908   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
912                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913                                  const Value *V,
914                                  ISD::NodeType PreferredExtendType) const {
915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916   ISD::NodeType ExtendKind = PreferredExtendType;
917 
918   // Get the list of the values's legal parts.
919   unsigned NumRegs = Regs.size();
920   SmallVector<SDValue, 8> Parts(NumRegs);
921   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922     unsigned NumParts = RegCount[Value];
923 
924     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925                                           *DAG.getContext(),
926                                           CallConv.getValue(), RegVTs[Value])
927                                     : RegVTs[Value];
928 
929     // We need to zero extend constants that are liveout to match assumptions
930     // in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
931     if (ExtendKind == ISD::ANY_EXTEND &&
932         (TLI.isZExtFree(Val, RegisterVT) || isa<ConstantSDNode>(Val)))
933       ExtendKind = ISD::ZERO_EXTEND;
934 
935     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
936                    NumParts, RegisterVT, V, CallConv, ExtendKind);
937     Part += NumParts;
938   }
939 
940   // Copy the parts into the registers.
941   SmallVector<SDValue, 8> Chains(NumRegs);
942   for (unsigned i = 0; i != NumRegs; ++i) {
943     SDValue Part;
944     if (!Flag) {
945       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
946     } else {
947       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
948       *Flag = Part.getValue(1);
949     }
950 
951     Chains[i] = Part.getValue(0);
952   }
953 
954   if (NumRegs == 1 || Flag)
955     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
956     // flagged to it. That is the CopyToReg nodes and the user are considered
957     // a single scheduling unit. If we create a TokenFactor and return it as
958     // chain, then the TokenFactor is both a predecessor (operand) of the
959     // user as well as a successor (the TF operands are flagged to the user).
960     // c1, f1 = CopyToReg
961     // c2, f2 = CopyToReg
962     // c3     = TokenFactor c1, c2
963     // ...
964     //        = op c3, ..., f2
965     Chain = Chains[NumRegs-1];
966   else
967     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
968 }
969 
970 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
971                                         unsigned MatchingIdx, const SDLoc &dl,
972                                         SelectionDAG &DAG,
973                                         std::vector<SDValue> &Ops) const {
974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
975 
976   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
977   if (HasMatching)
978     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
979   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
980     // Put the register class of the virtual registers in the flag word.  That
981     // way, later passes can recompute register class constraints for inline
982     // assembly as well as normal instructions.
983     // Don't do this for tied operands that can use the regclass information
984     // from the def.
985     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
986     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
987     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
988   }
989 
990   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
991   Ops.push_back(Res);
992 
993   if (Code == InlineAsm::Kind_Clobber) {
994     // Clobbers should always have a 1:1 mapping with registers, and may
995     // reference registers that have illegal (e.g. vector) types. Hence, we
996     // shouldn't try to apply any sort of splitting logic to them.
997     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
998            "No 1:1 mapping from clobbers to regs?");
999     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1000     (void)SP;
1001     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1002       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1003       assert(
1004           (Regs[I] != SP ||
1005            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1006           "If we clobbered the stack pointer, MFI should know about it.");
1007     }
1008     return;
1009   }
1010 
1011   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1012     MVT RegisterVT = RegVTs[Value];
1013     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1014                                            RegisterVT);
1015     for (unsigned i = 0; i != NumRegs; ++i) {
1016       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1017       unsigned TheReg = Regs[Reg++];
1018       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1019     }
1020   }
1021 }
1022 
1023 SmallVector<std::pair<unsigned, TypeSize>, 4>
1024 RegsForValue::getRegsAndSizes() const {
1025   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1026   unsigned I = 0;
1027   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1028     unsigned RegCount = std::get<0>(CountAndVT);
1029     MVT RegisterVT = std::get<1>(CountAndVT);
1030     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1031     for (unsigned E = I + RegCount; I != E; ++I)
1032       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1033   }
1034   return OutVec;
1035 }
1036 
1037 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1038                                const TargetLibraryInfo *li) {
1039   AA = aa;
1040   GFI = gfi;
1041   LibInfo = li;
1042   Context = DAG.getContext();
1043   LPadToCallSiteMap.clear();
1044   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1045 }
1046 
1047 void SelectionDAGBuilder::clear() {
1048   NodeMap.clear();
1049   UnusedArgNodeMap.clear();
1050   PendingLoads.clear();
1051   PendingExports.clear();
1052   PendingConstrainedFP.clear();
1053   PendingConstrainedFPStrict.clear();
1054   CurInst = nullptr;
1055   HasTailCall = false;
1056   SDNodeOrder = LowestSDNodeOrder;
1057   StatepointLowering.clear();
1058 }
1059 
1060 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1061   DanglingDebugInfoMap.clear();
1062 }
1063 
1064 // Update DAG root to include dependencies on Pending chains.
1065 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1066   SDValue Root = DAG.getRoot();
1067 
1068   if (Pending.empty())
1069     return Root;
1070 
1071   // Add current root to PendingChains, unless we already indirectly
1072   // depend on it.
1073   if (Root.getOpcode() != ISD::EntryToken) {
1074     unsigned i = 0, e = Pending.size();
1075     for (; i != e; ++i) {
1076       assert(Pending[i].getNode()->getNumOperands() > 1);
1077       if (Pending[i].getNode()->getOperand(0) == Root)
1078         break;  // Don't add the root if we already indirectly depend on it.
1079     }
1080 
1081     if (i == e)
1082       Pending.push_back(Root);
1083   }
1084 
1085   if (Pending.size() == 1)
1086     Root = Pending[0];
1087   else
1088     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1089 
1090   DAG.setRoot(Root);
1091   Pending.clear();
1092   return Root;
1093 }
1094 
1095 SDValue SelectionDAGBuilder::getMemoryRoot() {
1096   return updateRoot(PendingLoads);
1097 }
1098 
1099 SDValue SelectionDAGBuilder::getRoot() {
1100   // Chain up all pending constrained intrinsics together with all
1101   // pending loads, by simply appending them to PendingLoads and
1102   // then calling getMemoryRoot().
1103   PendingLoads.reserve(PendingLoads.size() +
1104                        PendingConstrainedFP.size() +
1105                        PendingConstrainedFPStrict.size());
1106   PendingLoads.append(PendingConstrainedFP.begin(),
1107                       PendingConstrainedFP.end());
1108   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1109                       PendingConstrainedFPStrict.end());
1110   PendingConstrainedFP.clear();
1111   PendingConstrainedFPStrict.clear();
1112   return getMemoryRoot();
1113 }
1114 
1115 SDValue SelectionDAGBuilder::getControlRoot() {
1116   // We need to emit pending fpexcept.strict constrained intrinsics,
1117   // so append them to the PendingExports list.
1118   PendingExports.append(PendingConstrainedFPStrict.begin(),
1119                         PendingConstrainedFPStrict.end());
1120   PendingConstrainedFPStrict.clear();
1121   return updateRoot(PendingExports);
1122 }
1123 
1124 void SelectionDAGBuilder::visit(const Instruction &I) {
1125   // Set up outgoing PHI node register values before emitting the terminator.
1126   if (I.isTerminator()) {
1127     HandlePHINodesInSuccessorBlocks(I.getParent());
1128   }
1129 
1130   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1131   if (!isa<DbgInfoIntrinsic>(I))
1132     ++SDNodeOrder;
1133 
1134   CurInst = &I;
1135 
1136   visit(I.getOpcode(), I);
1137 
1138   if (!I.isTerminator() && !HasTailCall &&
1139       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1140     CopyToExportRegsIfNeeded(&I);
1141 
1142   CurInst = nullptr;
1143 }
1144 
1145 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1146   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1147 }
1148 
1149 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1150   // Note: this doesn't use InstVisitor, because it has to work with
1151   // ConstantExpr's in addition to instructions.
1152   switch (Opcode) {
1153   default: llvm_unreachable("Unknown instruction type encountered!");
1154     // Build the switch statement using the Instruction.def file.
1155 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1156     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1157 #include "llvm/IR/Instruction.def"
1158   }
1159 }
1160 
1161 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1162                                                DebugLoc DL, unsigned Order) {
1163   // We treat variadic dbg_values differently at this stage.
1164   if (DI->hasArgList()) {
1165     // For variadic dbg_values we will now insert an undef.
1166     // FIXME: We can potentially recover these!
1167     SmallVector<SDDbgOperand, 2> Locs;
1168     for (const Value *V : DI->getValues()) {
1169       auto Undef = UndefValue::get(V->getType());
1170       Locs.push_back(SDDbgOperand::fromConst(Undef));
1171     }
1172     SDDbgValue *SDV = DAG.getDbgValueList(
1173         DI->getVariable(), DI->getExpression(), Locs, {},
1174         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1175     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1176   } else {
1177     // TODO: Dangling debug info will eventually either be resolved or produce
1178     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1179     // between the original dbg.value location and its resolved DBG_VALUE,
1180     // which we should ideally fill with an extra Undef DBG_VALUE.
1181     assert(DI->getNumVariableLocationOps() == 1 &&
1182            "DbgValueInst without an ArgList should have a single location "
1183            "operand.");
1184     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1185   }
1186 }
1187 
1188 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1189                                                 const DIExpression *Expr) {
1190   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1191     const DbgValueInst *DI = DDI.getDI();
1192     DIVariable *DanglingVariable = DI->getVariable();
1193     DIExpression *DanglingExpr = DI->getExpression();
1194     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1195       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1196       return true;
1197     }
1198     return false;
1199   };
1200 
1201   for (auto &DDIMI : DanglingDebugInfoMap) {
1202     DanglingDebugInfoVector &DDIV = DDIMI.second;
1203 
1204     // If debug info is to be dropped, run it through final checks to see
1205     // whether it can be salvaged.
1206     for (auto &DDI : DDIV)
1207       if (isMatchingDbgValue(DDI))
1208         salvageUnresolvedDbgValue(DDI);
1209 
1210     erase_if(DDIV, isMatchingDbgValue);
1211   }
1212 }
1213 
1214 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1215 // generate the debug data structures now that we've seen its definition.
1216 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1217                                                    SDValue Val) {
1218   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1219   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1220     return;
1221 
1222   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1223   for (auto &DDI : DDIV) {
1224     const DbgValueInst *DI = DDI.getDI();
1225     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1226     assert(DI && "Ill-formed DanglingDebugInfo");
1227     DebugLoc dl = DDI.getdl();
1228     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1229     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1230     DILocalVariable *Variable = DI->getVariable();
1231     DIExpression *Expr = DI->getExpression();
1232     assert(Variable->isValidLocationForIntrinsic(dl) &&
1233            "Expected inlined-at fields to agree");
1234     SDDbgValue *SDV;
1235     if (Val.getNode()) {
1236       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1237       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1238       // we couldn't resolve it directly when examining the DbgValue intrinsic
1239       // in the first place we should not be more successful here). Unless we
1240       // have some test case that prove this to be correct we should avoid
1241       // calling EmitFuncArgumentDbgValue here.
1242       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1243         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1244                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1245         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1246         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1247         // inserted after the definition of Val when emitting the instructions
1248         // after ISel. An alternative could be to teach
1249         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1250         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1251                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1252                    << ValSDNodeOrder << "\n");
1253         SDV = getDbgValue(Val, Variable, Expr, dl,
1254                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1255         DAG.AddDbgValue(SDV, false);
1256       } else
1257         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1258                           << "in EmitFuncArgumentDbgValue\n");
1259     } else {
1260       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1261       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1262       auto SDV =
1263           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1264       DAG.AddDbgValue(SDV, false);
1265     }
1266   }
1267   DDIV.clear();
1268 }
1269 
1270 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1271   // TODO: For the variadic implementation, instead of only checking the fail
1272   // state of `handleDebugValue`, we need know specifically which values were
1273   // invalid, so that we attempt to salvage only those values when processing
1274   // a DIArgList.
1275   assert(!DDI.getDI()->hasArgList() &&
1276          "Not implemented for variadic dbg_values");
1277   Value *V = DDI.getDI()->getValue(0);
1278   DILocalVariable *Var = DDI.getDI()->getVariable();
1279   DIExpression *Expr = DDI.getDI()->getExpression();
1280   DebugLoc DL = DDI.getdl();
1281   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1282   unsigned SDOrder = DDI.getSDNodeOrder();
1283   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1284   // that DW_OP_stack_value is desired.
1285   assert(isa<DbgValueInst>(DDI.getDI()));
1286   bool StackValue = true;
1287 
1288   // Can this Value can be encoded without any further work?
1289   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1290     return;
1291 
1292   // Attempt to salvage back through as many instructions as possible. Bail if
1293   // a non-instruction is seen, such as a constant expression or global
1294   // variable. FIXME: Further work could recover those too.
1295   while (isa<Instruction>(V)) {
1296     Instruction &VAsInst = *cast<Instruction>(V);
1297     // Temporary "0", awaiting real implementation.
1298     SmallVector<uint64_t, 16> Ops;
1299     SmallVector<Value *, 4> AdditionalValues;
1300     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1301                              AdditionalValues);
1302     // If we cannot salvage any further, and haven't yet found a suitable debug
1303     // expression, bail out.
1304     if (!V)
1305       break;
1306 
1307     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1308     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1309     // here for variadic dbg_values, remove that condition.
1310     if (!AdditionalValues.empty())
1311       break;
1312 
1313     // New value and expr now represent this debuginfo.
1314     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1315 
1316     // Some kind of simplification occurred: check whether the operand of the
1317     // salvaged debug expression can be encoded in this DAG.
1318     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1319                          /*IsVariadic=*/false)) {
1320       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1321                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1322       return;
1323     }
1324   }
1325 
1326   // This was the final opportunity to salvage this debug information, and it
1327   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1328   // any earlier variable location.
1329   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1330   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1331   DAG.AddDbgValue(SDV, false);
1332 
1333   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1334                     << "\n");
1335   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1336                     << "\n");
1337 }
1338 
1339 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1340                                            DILocalVariable *Var,
1341                                            DIExpression *Expr, DebugLoc dl,
1342                                            DebugLoc InstDL, unsigned Order,
1343                                            bool IsVariadic) {
1344   if (Values.empty())
1345     return true;
1346   SmallVector<SDDbgOperand> LocationOps;
1347   SmallVector<SDNode *> Dependencies;
1348   for (const Value *V : Values) {
1349     // Constant value.
1350     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1351         isa<ConstantPointerNull>(V)) {
1352       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1353       continue;
1354     }
1355 
1356     // If the Value is a frame index, we can create a FrameIndex debug value
1357     // without relying on the DAG at all.
1358     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1359       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1360       if (SI != FuncInfo.StaticAllocaMap.end()) {
1361         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1362         continue;
1363       }
1364     }
1365 
1366     // Do not use getValue() in here; we don't want to generate code at
1367     // this point if it hasn't been done yet.
1368     SDValue N = NodeMap[V];
1369     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1370       N = UnusedArgNodeMap[V];
1371     if (N.getNode()) {
1372       // Only emit func arg dbg value for non-variadic dbg.values for now.
1373       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1374         return true;
1375       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1376         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1377         // describe stack slot locations.
1378         //
1379         // Consider "int x = 0; int *px = &x;". There are two kinds of
1380         // interesting debug values here after optimization:
1381         //
1382         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1383         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1384         //
1385         // Both describe the direct values of their associated variables.
1386         Dependencies.push_back(N.getNode());
1387         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1388         continue;
1389       }
1390       LocationOps.emplace_back(
1391           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1392       continue;
1393     }
1394 
1395     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1396     // Special rules apply for the first dbg.values of parameter variables in a
1397     // function. Identify them by the fact they reference Argument Values, that
1398     // they're parameters, and they are parameters of the current function. We
1399     // need to let them dangle until they get an SDNode.
1400     bool IsParamOfFunc =
1401         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1402     if (IsParamOfFunc)
1403       return false;
1404 
1405     // The value is not used in this block yet (or it would have an SDNode).
1406     // We still want the value to appear for the user if possible -- if it has
1407     // an associated VReg, we can refer to that instead.
1408     auto VMI = FuncInfo.ValueMap.find(V);
1409     if (VMI != FuncInfo.ValueMap.end()) {
1410       unsigned Reg = VMI->second;
1411       // If this is a PHI node, it may be split up into several MI PHI nodes
1412       // (in FunctionLoweringInfo::set).
1413       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1414                        V->getType(), None);
1415       if (RFV.occupiesMultipleRegs()) {
1416         // FIXME: We could potentially support variadic dbg_values here.
1417         if (IsVariadic)
1418           return false;
1419         unsigned Offset = 0;
1420         unsigned BitsToDescribe = 0;
1421         if (auto VarSize = Var->getSizeInBits())
1422           BitsToDescribe = *VarSize;
1423         if (auto Fragment = Expr->getFragmentInfo())
1424           BitsToDescribe = Fragment->SizeInBits;
1425         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1426           // Bail out if all bits are described already.
1427           if (Offset >= BitsToDescribe)
1428             break;
1429           // TODO: handle scalable vectors.
1430           unsigned RegisterSize = RegAndSize.second;
1431           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1432                                       ? BitsToDescribe - Offset
1433                                       : RegisterSize;
1434           auto FragmentExpr = DIExpression::createFragmentExpression(
1435               Expr, Offset, FragmentSize);
1436           if (!FragmentExpr)
1437             continue;
1438           SDDbgValue *SDV = DAG.getVRegDbgValue(
1439               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1440           DAG.AddDbgValue(SDV, false);
1441           Offset += RegisterSize;
1442         }
1443         return true;
1444       }
1445       // We can use simple vreg locations for variadic dbg_values as well.
1446       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1447       continue;
1448     }
1449     // We failed to create a SDDbgOperand for V.
1450     return false;
1451   }
1452 
1453   // We have created a SDDbgOperand for each Value in Values.
1454   // Should use Order instead of SDNodeOrder?
1455   assert(!LocationOps.empty());
1456   SDDbgValue *SDV =
1457       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1458                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1459   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1460   return true;
1461 }
1462 
1463 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1464   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1465   for (auto &Pair : DanglingDebugInfoMap)
1466     for (auto &DDI : Pair.second)
1467       salvageUnresolvedDbgValue(DDI);
1468   clearDanglingDebugInfo();
1469 }
1470 
1471 /// getCopyFromRegs - If there was virtual register allocated for the value V
1472 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1473 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1474   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1475   SDValue Result;
1476 
1477   if (It != FuncInfo.ValueMap.end()) {
1478     Register InReg = It->second;
1479 
1480     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1481                      DAG.getDataLayout(), InReg, Ty,
1482                      None); // This is not an ABI copy.
1483     SDValue Chain = DAG.getEntryNode();
1484     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1485                                  V);
1486     resolveDanglingDebugInfo(V, Result);
1487   }
1488 
1489   return Result;
1490 }
1491 
1492 /// getValue - Return an SDValue for the given Value.
1493 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1494   // If we already have an SDValue for this value, use it. It's important
1495   // to do this first, so that we don't create a CopyFromReg if we already
1496   // have a regular SDValue.
1497   SDValue &N = NodeMap[V];
1498   if (N.getNode()) return N;
1499 
1500   // If there's a virtual register allocated and initialized for this
1501   // value, use it.
1502   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1503     return copyFromReg;
1504 
1505   // Otherwise create a new SDValue and remember it.
1506   SDValue Val = getValueImpl(V);
1507   NodeMap[V] = Val;
1508   resolveDanglingDebugInfo(V, Val);
1509   return Val;
1510 }
1511 
1512 /// getNonRegisterValue - Return an SDValue for the given Value, but
1513 /// don't look in FuncInfo.ValueMap for a virtual register.
1514 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1515   // If we already have an SDValue for this value, use it.
1516   SDValue &N = NodeMap[V];
1517   if (N.getNode()) {
1518     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1519       // Remove the debug location from the node as the node is about to be used
1520       // in a location which may differ from the original debug location.  This
1521       // is relevant to Constant and ConstantFP nodes because they can appear
1522       // as constant expressions inside PHI nodes.
1523       N->setDebugLoc(DebugLoc());
1524     }
1525     return N;
1526   }
1527 
1528   // Otherwise create a new SDValue and remember it.
1529   SDValue Val = getValueImpl(V);
1530   NodeMap[V] = Val;
1531   resolveDanglingDebugInfo(V, Val);
1532   return Val;
1533 }
1534 
1535 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1536 /// Create an SDValue for the given value.
1537 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1539 
1540   if (const Constant *C = dyn_cast<Constant>(V)) {
1541     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1542 
1543     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1544       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1545 
1546     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1547       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1548 
1549     if (isa<ConstantPointerNull>(C)) {
1550       unsigned AS = V->getType()->getPointerAddressSpace();
1551       return DAG.getConstant(0, getCurSDLoc(),
1552                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1553     }
1554 
1555     if (match(C, m_VScale(DAG.getDataLayout())))
1556       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1557 
1558     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1559       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1560 
1561     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1562       return DAG.getUNDEF(VT);
1563 
1564     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1565       visit(CE->getOpcode(), *CE);
1566       SDValue N1 = NodeMap[V];
1567       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1568       return N1;
1569     }
1570 
1571     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1572       SmallVector<SDValue, 4> Constants;
1573       for (const Use &U : C->operands()) {
1574         SDNode *Val = getValue(U).getNode();
1575         // If the operand is an empty aggregate, there are no values.
1576         if (!Val) continue;
1577         // Add each leaf value from the operand to the Constants list
1578         // to form a flattened list of all the values.
1579         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1580           Constants.push_back(SDValue(Val, i));
1581       }
1582 
1583       return DAG.getMergeValues(Constants, getCurSDLoc());
1584     }
1585 
1586     if (const ConstantDataSequential *CDS =
1587           dyn_cast<ConstantDataSequential>(C)) {
1588       SmallVector<SDValue, 4> Ops;
1589       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1590         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1591         // Add each leaf value from the operand to the Constants list
1592         // to form a flattened list of all the values.
1593         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1594           Ops.push_back(SDValue(Val, i));
1595       }
1596 
1597       if (isa<ArrayType>(CDS->getType()))
1598         return DAG.getMergeValues(Ops, getCurSDLoc());
1599       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1600     }
1601 
1602     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1603       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1604              "Unknown struct or array constant!");
1605 
1606       SmallVector<EVT, 4> ValueVTs;
1607       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1608       unsigned NumElts = ValueVTs.size();
1609       if (NumElts == 0)
1610         return SDValue(); // empty struct
1611       SmallVector<SDValue, 4> Constants(NumElts);
1612       for (unsigned i = 0; i != NumElts; ++i) {
1613         EVT EltVT = ValueVTs[i];
1614         if (isa<UndefValue>(C))
1615           Constants[i] = DAG.getUNDEF(EltVT);
1616         else if (EltVT.isFloatingPoint())
1617           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1618         else
1619           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1620       }
1621 
1622       return DAG.getMergeValues(Constants, getCurSDLoc());
1623     }
1624 
1625     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1626       return DAG.getBlockAddress(BA, VT);
1627 
1628     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1629       return getValue(Equiv->getGlobalValue());
1630 
1631     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1632       return getValue(NC->getGlobalValue());
1633 
1634     VectorType *VecTy = cast<VectorType>(V->getType());
1635 
1636     // Now that we know the number and type of the elements, get that number of
1637     // elements into the Ops array based on what kind of constant it is.
1638     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1639       SmallVector<SDValue, 16> Ops;
1640       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1641       for (unsigned i = 0; i != NumElements; ++i)
1642         Ops.push_back(getValue(CV->getOperand(i)));
1643 
1644       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1645     } else if (isa<ConstantAggregateZero>(C)) {
1646       EVT EltVT =
1647           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1648 
1649       SDValue Op;
1650       if (EltVT.isFloatingPoint())
1651         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1652       else
1653         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1654 
1655       if (isa<ScalableVectorType>(VecTy))
1656         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1657       else {
1658         SmallVector<SDValue, 16> Ops;
1659         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1660         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1661       }
1662     }
1663     llvm_unreachable("Unknown vector constant");
1664   }
1665 
1666   // If this is a static alloca, generate it as the frameindex instead of
1667   // computation.
1668   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1669     DenseMap<const AllocaInst*, int>::iterator SI =
1670       FuncInfo.StaticAllocaMap.find(AI);
1671     if (SI != FuncInfo.StaticAllocaMap.end())
1672       return DAG.getFrameIndex(SI->second,
1673                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1674   }
1675 
1676   // If this is an instruction which fast-isel has deferred, select it now.
1677   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1678     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1679 
1680     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1681                      Inst->getType(), None);
1682     SDValue Chain = DAG.getEntryNode();
1683     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1684   }
1685 
1686   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1687     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1688   }
1689   if (const auto *BB = dyn_cast<BasicBlock>(V))
1690     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1691   llvm_unreachable("Can't get register for value!");
1692 }
1693 
1694 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1695   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1696   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1697   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1698   bool IsSEH = isAsynchronousEHPersonality(Pers);
1699   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1700   if (!IsSEH)
1701     CatchPadMBB->setIsEHScopeEntry();
1702   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1703   if (IsMSVCCXX || IsCoreCLR)
1704     CatchPadMBB->setIsEHFuncletEntry();
1705 }
1706 
1707 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1708   // Update machine-CFG edge.
1709   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1710   FuncInfo.MBB->addSuccessor(TargetMBB);
1711   TargetMBB->setIsEHCatchretTarget(true);
1712   DAG.getMachineFunction().setHasEHCatchret(true);
1713 
1714   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1715   bool IsSEH = isAsynchronousEHPersonality(Pers);
1716   if (IsSEH) {
1717     // If this is not a fall-through branch or optimizations are switched off,
1718     // emit the branch.
1719     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1720         TM.getOptLevel() == CodeGenOpt::None)
1721       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1722                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1723     return;
1724   }
1725 
1726   // Figure out the funclet membership for the catchret's successor.
1727   // This will be used by the FuncletLayout pass to determine how to order the
1728   // BB's.
1729   // A 'catchret' returns to the outer scope's color.
1730   Value *ParentPad = I.getCatchSwitchParentPad();
1731   const BasicBlock *SuccessorColor;
1732   if (isa<ConstantTokenNone>(ParentPad))
1733     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1734   else
1735     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1736   assert(SuccessorColor && "No parent funclet for catchret!");
1737   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1738   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1739 
1740   // Create the terminator node.
1741   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1742                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1743                             DAG.getBasicBlock(SuccessorColorMBB));
1744   DAG.setRoot(Ret);
1745 }
1746 
1747 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1748   // Don't emit any special code for the cleanuppad instruction. It just marks
1749   // the start of an EH scope/funclet.
1750   FuncInfo.MBB->setIsEHScopeEntry();
1751   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1752   if (Pers != EHPersonality::Wasm_CXX) {
1753     FuncInfo.MBB->setIsEHFuncletEntry();
1754     FuncInfo.MBB->setIsCleanupFuncletEntry();
1755   }
1756 }
1757 
1758 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1759 // not match, it is OK to add only the first unwind destination catchpad to the
1760 // successors, because there will be at least one invoke instruction within the
1761 // catch scope that points to the next unwind destination, if one exists, so
1762 // CFGSort cannot mess up with BB sorting order.
1763 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1764 // call within them, and catchpads only consisting of 'catch (...)' have a
1765 // '__cxa_end_catch' call within them, both of which generate invokes in case
1766 // the next unwind destination exists, i.e., the next unwind destination is not
1767 // the caller.)
1768 //
1769 // Having at most one EH pad successor is also simpler and helps later
1770 // transformations.
1771 //
1772 // For example,
1773 // current:
1774 //   invoke void @foo to ... unwind label %catch.dispatch
1775 // catch.dispatch:
1776 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1777 // catch.start:
1778 //   ...
1779 //   ... in this BB or some other child BB dominated by this BB there will be an
1780 //   invoke that points to 'next' BB as an unwind destination
1781 //
1782 // next: ; We don't need to add this to 'current' BB's successor
1783 //   ...
1784 static void findWasmUnwindDestinations(
1785     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1786     BranchProbability Prob,
1787     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1788         &UnwindDests) {
1789   while (EHPadBB) {
1790     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1791     if (isa<CleanupPadInst>(Pad)) {
1792       // Stop on cleanup pads.
1793       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1794       UnwindDests.back().first->setIsEHScopeEntry();
1795       break;
1796     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1797       // Add the catchpad handlers to the possible destinations. We don't
1798       // continue to the unwind destination of the catchswitch for wasm.
1799       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1800         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1801         UnwindDests.back().first->setIsEHScopeEntry();
1802       }
1803       break;
1804     } else {
1805       continue;
1806     }
1807   }
1808 }
1809 
1810 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1811 /// many places it could ultimately go. In the IR, we have a single unwind
1812 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1813 /// This function skips over imaginary basic blocks that hold catchswitch
1814 /// instructions, and finds all the "real" machine
1815 /// basic block destinations. As those destinations may not be successors of
1816 /// EHPadBB, here we also calculate the edge probability to those destinations.
1817 /// The passed-in Prob is the edge probability to EHPadBB.
1818 static void findUnwindDestinations(
1819     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1820     BranchProbability Prob,
1821     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1822         &UnwindDests) {
1823   EHPersonality Personality =
1824     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1825   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1826   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1827   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1828   bool IsSEH = isAsynchronousEHPersonality(Personality);
1829 
1830   if (IsWasmCXX) {
1831     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1832     assert(UnwindDests.size() <= 1 &&
1833            "There should be at most one unwind destination for wasm");
1834     return;
1835   }
1836 
1837   while (EHPadBB) {
1838     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1839     BasicBlock *NewEHPadBB = nullptr;
1840     if (isa<LandingPadInst>(Pad)) {
1841       // Stop on landingpads. They are not funclets.
1842       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1843       break;
1844     } else if (isa<CleanupPadInst>(Pad)) {
1845       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1846       // personalities.
1847       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1848       UnwindDests.back().first->setIsEHScopeEntry();
1849       UnwindDests.back().first->setIsEHFuncletEntry();
1850       break;
1851     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1852       // Add the catchpad handlers to the possible destinations.
1853       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1854         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1855         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1856         if (IsMSVCCXX || IsCoreCLR)
1857           UnwindDests.back().first->setIsEHFuncletEntry();
1858         if (!IsSEH)
1859           UnwindDests.back().first->setIsEHScopeEntry();
1860       }
1861       NewEHPadBB = CatchSwitch->getUnwindDest();
1862     } else {
1863       continue;
1864     }
1865 
1866     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1867     if (BPI && NewEHPadBB)
1868       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1869     EHPadBB = NewEHPadBB;
1870   }
1871 }
1872 
1873 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1874   // Update successor info.
1875   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1876   auto UnwindDest = I.getUnwindDest();
1877   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1878   BranchProbability UnwindDestProb =
1879       (BPI && UnwindDest)
1880           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1881           : BranchProbability::getZero();
1882   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1883   for (auto &UnwindDest : UnwindDests) {
1884     UnwindDest.first->setIsEHPad();
1885     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1886   }
1887   FuncInfo.MBB->normalizeSuccProbs();
1888 
1889   // Create the terminator node.
1890   SDValue Ret =
1891       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1892   DAG.setRoot(Ret);
1893 }
1894 
1895 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1896   report_fatal_error("visitCatchSwitch not yet implemented!");
1897 }
1898 
1899 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1900   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1901   auto &DL = DAG.getDataLayout();
1902   SDValue Chain = getControlRoot();
1903   SmallVector<ISD::OutputArg, 8> Outs;
1904   SmallVector<SDValue, 8> OutVals;
1905 
1906   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1907   // lower
1908   //
1909   //   %val = call <ty> @llvm.experimental.deoptimize()
1910   //   ret <ty> %val
1911   //
1912   // differently.
1913   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1914     LowerDeoptimizingReturn();
1915     return;
1916   }
1917 
1918   if (!FuncInfo.CanLowerReturn) {
1919     unsigned DemoteReg = FuncInfo.DemoteRegister;
1920     const Function *F = I.getParent()->getParent();
1921 
1922     // Emit a store of the return value through the virtual register.
1923     // Leave Outs empty so that LowerReturn won't try to load return
1924     // registers the usual way.
1925     SmallVector<EVT, 1> PtrValueVTs;
1926     ComputeValueVTs(TLI, DL,
1927                     F->getReturnType()->getPointerTo(
1928                         DAG.getDataLayout().getAllocaAddrSpace()),
1929                     PtrValueVTs);
1930 
1931     SDValue RetPtr =
1932         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1933     SDValue RetOp = getValue(I.getOperand(0));
1934 
1935     SmallVector<EVT, 4> ValueVTs, MemVTs;
1936     SmallVector<uint64_t, 4> Offsets;
1937     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1938                     &Offsets);
1939     unsigned NumValues = ValueVTs.size();
1940 
1941     SmallVector<SDValue, 4> Chains(NumValues);
1942     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1943     for (unsigned i = 0; i != NumValues; ++i) {
1944       // An aggregate return value cannot wrap around the address space, so
1945       // offsets to its parts don't wrap either.
1946       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1947                                            TypeSize::Fixed(Offsets[i]));
1948 
1949       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1950       if (MemVTs[i] != ValueVTs[i])
1951         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1952       Chains[i] = DAG.getStore(
1953           Chain, getCurSDLoc(), Val,
1954           // FIXME: better loc info would be nice.
1955           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1956           commonAlignment(BaseAlign, Offsets[i]));
1957     }
1958 
1959     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1960                         MVT::Other, Chains);
1961   } else if (I.getNumOperands() != 0) {
1962     SmallVector<EVT, 4> ValueVTs;
1963     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1964     unsigned NumValues = ValueVTs.size();
1965     if (NumValues) {
1966       SDValue RetOp = getValue(I.getOperand(0));
1967 
1968       const Function *F = I.getParent()->getParent();
1969 
1970       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1971           I.getOperand(0)->getType(), F->getCallingConv(),
1972           /*IsVarArg*/ false, DL);
1973 
1974       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1975       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1976         ExtendKind = ISD::SIGN_EXTEND;
1977       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1978         ExtendKind = ISD::ZERO_EXTEND;
1979 
1980       LLVMContext &Context = F->getContext();
1981       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1982 
1983       for (unsigned j = 0; j != NumValues; ++j) {
1984         EVT VT = ValueVTs[j];
1985 
1986         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1987           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1988 
1989         CallingConv::ID CC = F->getCallingConv();
1990 
1991         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1992         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1993         SmallVector<SDValue, 4> Parts(NumParts);
1994         getCopyToParts(DAG, getCurSDLoc(),
1995                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1996                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1997 
1998         // 'inreg' on function refers to return value
1999         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2000         if (RetInReg)
2001           Flags.setInReg();
2002 
2003         if (I.getOperand(0)->getType()->isPointerTy()) {
2004           Flags.setPointer();
2005           Flags.setPointerAddrSpace(
2006               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2007         }
2008 
2009         if (NeedsRegBlock) {
2010           Flags.setInConsecutiveRegs();
2011           if (j == NumValues - 1)
2012             Flags.setInConsecutiveRegsLast();
2013         }
2014 
2015         // Propagate extension type if any
2016         if (ExtendKind == ISD::SIGN_EXTEND)
2017           Flags.setSExt();
2018         else if (ExtendKind == ISD::ZERO_EXTEND)
2019           Flags.setZExt();
2020 
2021         for (unsigned i = 0; i < NumParts; ++i) {
2022           Outs.push_back(ISD::OutputArg(Flags,
2023                                         Parts[i].getValueType().getSimpleVT(),
2024                                         VT, /*isfixed=*/true, 0, 0));
2025           OutVals.push_back(Parts[i]);
2026         }
2027       }
2028     }
2029   }
2030 
2031   // Push in swifterror virtual register as the last element of Outs. This makes
2032   // sure swifterror virtual register will be returned in the swifterror
2033   // physical register.
2034   const Function *F = I.getParent()->getParent();
2035   if (TLI.supportSwiftError() &&
2036       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2037     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2038     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2039     Flags.setSwiftError();
2040     Outs.push_back(ISD::OutputArg(
2041         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2042         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2043     // Create SDNode for the swifterror virtual register.
2044     OutVals.push_back(
2045         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2046                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2047                         EVT(TLI.getPointerTy(DL))));
2048   }
2049 
2050   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2051   CallingConv::ID CallConv =
2052     DAG.getMachineFunction().getFunction().getCallingConv();
2053   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2054       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2055 
2056   // Verify that the target's LowerReturn behaved as expected.
2057   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2058          "LowerReturn didn't return a valid chain!");
2059 
2060   // Update the DAG with the new chain value resulting from return lowering.
2061   DAG.setRoot(Chain);
2062 }
2063 
2064 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2065 /// created for it, emit nodes to copy the value into the virtual
2066 /// registers.
2067 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2068   // Skip empty types
2069   if (V->getType()->isEmptyTy())
2070     return;
2071 
2072   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2073   if (VMI != FuncInfo.ValueMap.end()) {
2074     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2075     CopyValueToVirtualRegister(V, VMI->second);
2076   }
2077 }
2078 
2079 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2080 /// the current basic block, add it to ValueMap now so that we'll get a
2081 /// CopyTo/FromReg.
2082 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2083   // No need to export constants.
2084   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2085 
2086   // Already exported?
2087   if (FuncInfo.isExportedInst(V)) return;
2088 
2089   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2090   CopyValueToVirtualRegister(V, Reg);
2091 }
2092 
2093 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2094                                                      const BasicBlock *FromBB) {
2095   // The operands of the setcc have to be in this block.  We don't know
2096   // how to export them from some other block.
2097   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2098     // Can export from current BB.
2099     if (VI->getParent() == FromBB)
2100       return true;
2101 
2102     // Is already exported, noop.
2103     return FuncInfo.isExportedInst(V);
2104   }
2105 
2106   // If this is an argument, we can export it if the BB is the entry block or
2107   // if it is already exported.
2108   if (isa<Argument>(V)) {
2109     if (FromBB->isEntryBlock())
2110       return true;
2111 
2112     // Otherwise, can only export this if it is already exported.
2113     return FuncInfo.isExportedInst(V);
2114   }
2115 
2116   // Otherwise, constants can always be exported.
2117   return true;
2118 }
2119 
2120 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2121 BranchProbability
2122 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2123                                         const MachineBasicBlock *Dst) const {
2124   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2125   const BasicBlock *SrcBB = Src->getBasicBlock();
2126   const BasicBlock *DstBB = Dst->getBasicBlock();
2127   if (!BPI) {
2128     // If BPI is not available, set the default probability as 1 / N, where N is
2129     // the number of successors.
2130     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2131     return BranchProbability(1, SuccSize);
2132   }
2133   return BPI->getEdgeProbability(SrcBB, DstBB);
2134 }
2135 
2136 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2137                                                MachineBasicBlock *Dst,
2138                                                BranchProbability Prob) {
2139   if (!FuncInfo.BPI)
2140     Src->addSuccessorWithoutProb(Dst);
2141   else {
2142     if (Prob.isUnknown())
2143       Prob = getEdgeProbability(Src, Dst);
2144     Src->addSuccessor(Dst, Prob);
2145   }
2146 }
2147 
2148 static bool InBlock(const Value *V, const BasicBlock *BB) {
2149   if (const Instruction *I = dyn_cast<Instruction>(V))
2150     return I->getParent() == BB;
2151   return true;
2152 }
2153 
2154 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2155 /// This function emits a branch and is used at the leaves of an OR or an
2156 /// AND operator tree.
2157 void
2158 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2159                                                   MachineBasicBlock *TBB,
2160                                                   MachineBasicBlock *FBB,
2161                                                   MachineBasicBlock *CurBB,
2162                                                   MachineBasicBlock *SwitchBB,
2163                                                   BranchProbability TProb,
2164                                                   BranchProbability FProb,
2165                                                   bool InvertCond) {
2166   const BasicBlock *BB = CurBB->getBasicBlock();
2167 
2168   // If the leaf of the tree is a comparison, merge the condition into
2169   // the caseblock.
2170   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2171     // The operands of the cmp have to be in this block.  We don't know
2172     // how to export them from some other block.  If this is the first block
2173     // of the sequence, no exporting is needed.
2174     if (CurBB == SwitchBB ||
2175         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2176          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2177       ISD::CondCode Condition;
2178       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2179         ICmpInst::Predicate Pred =
2180             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2181         Condition = getICmpCondCode(Pred);
2182       } else {
2183         const FCmpInst *FC = cast<FCmpInst>(Cond);
2184         FCmpInst::Predicate Pred =
2185             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2186         Condition = getFCmpCondCode(Pred);
2187         if (TM.Options.NoNaNsFPMath)
2188           Condition = getFCmpCodeWithoutNaN(Condition);
2189       }
2190 
2191       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2192                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2193       SL->SwitchCases.push_back(CB);
2194       return;
2195     }
2196   }
2197 
2198   // Create a CaseBlock record representing this branch.
2199   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2200   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2201                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2202   SL->SwitchCases.push_back(CB);
2203 }
2204 
2205 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2206                                                MachineBasicBlock *TBB,
2207                                                MachineBasicBlock *FBB,
2208                                                MachineBasicBlock *CurBB,
2209                                                MachineBasicBlock *SwitchBB,
2210                                                Instruction::BinaryOps Opc,
2211                                                BranchProbability TProb,
2212                                                BranchProbability FProb,
2213                                                bool InvertCond) {
2214   // Skip over not part of the tree and remember to invert op and operands at
2215   // next level.
2216   Value *NotCond;
2217   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2218       InBlock(NotCond, CurBB->getBasicBlock())) {
2219     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2220                          !InvertCond);
2221     return;
2222   }
2223 
2224   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2225   const Value *BOpOp0, *BOpOp1;
2226   // Compute the effective opcode for Cond, taking into account whether it needs
2227   // to be inverted, e.g.
2228   //   and (not (or A, B)), C
2229   // gets lowered as
2230   //   and (and (not A, not B), C)
2231   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2232   if (BOp) {
2233     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2234                ? Instruction::And
2235                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2236                       ? Instruction::Or
2237                       : (Instruction::BinaryOps)0);
2238     if (InvertCond) {
2239       if (BOpc == Instruction::And)
2240         BOpc = Instruction::Or;
2241       else if (BOpc == Instruction::Or)
2242         BOpc = Instruction::And;
2243     }
2244   }
2245 
2246   // If this node is not part of the or/and tree, emit it as a branch.
2247   // Note that all nodes in the tree should have same opcode.
2248   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2249   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2250       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2251       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2252     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2253                                  TProb, FProb, InvertCond);
2254     return;
2255   }
2256 
2257   //  Create TmpBB after CurBB.
2258   MachineFunction::iterator BBI(CurBB);
2259   MachineFunction &MF = DAG.getMachineFunction();
2260   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2261   CurBB->getParent()->insert(++BBI, TmpBB);
2262 
2263   if (Opc == Instruction::Or) {
2264     // Codegen X | Y as:
2265     // BB1:
2266     //   jmp_if_X TBB
2267     //   jmp TmpBB
2268     // TmpBB:
2269     //   jmp_if_Y TBB
2270     //   jmp FBB
2271     //
2272 
2273     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2274     // The requirement is that
2275     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2276     //     = TrueProb for original BB.
2277     // Assuming the original probabilities are A and B, one choice is to set
2278     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2279     // A/(1+B) and 2B/(1+B). This choice assumes that
2280     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2281     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2282     // TmpBB, but the math is more complicated.
2283 
2284     auto NewTrueProb = TProb / 2;
2285     auto NewFalseProb = TProb / 2 + FProb;
2286     // Emit the LHS condition.
2287     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2288                          NewFalseProb, InvertCond);
2289 
2290     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2291     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2292     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2293     // Emit the RHS condition into TmpBB.
2294     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2295                          Probs[1], InvertCond);
2296   } else {
2297     assert(Opc == Instruction::And && "Unknown merge op!");
2298     // Codegen X & Y as:
2299     // BB1:
2300     //   jmp_if_X TmpBB
2301     //   jmp FBB
2302     // TmpBB:
2303     //   jmp_if_Y TBB
2304     //   jmp FBB
2305     //
2306     //  This requires creation of TmpBB after CurBB.
2307 
2308     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2309     // The requirement is that
2310     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2311     //     = FalseProb for original BB.
2312     // Assuming the original probabilities are A and B, one choice is to set
2313     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2314     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2315     // TrueProb for BB1 * FalseProb for TmpBB.
2316 
2317     auto NewTrueProb = TProb + FProb / 2;
2318     auto NewFalseProb = FProb / 2;
2319     // Emit the LHS condition.
2320     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2321                          NewFalseProb, InvertCond);
2322 
2323     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2324     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2325     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2326     // Emit the RHS condition into TmpBB.
2327     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2328                          Probs[1], InvertCond);
2329   }
2330 }
2331 
2332 /// If the set of cases should be emitted as a series of branches, return true.
2333 /// If we should emit this as a bunch of and/or'd together conditions, return
2334 /// false.
2335 bool
2336 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2337   if (Cases.size() != 2) return true;
2338 
2339   // If this is two comparisons of the same values or'd or and'd together, they
2340   // will get folded into a single comparison, so don't emit two blocks.
2341   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2342        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2343       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2344        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2345     return false;
2346   }
2347 
2348   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2349   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2350   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2351       Cases[0].CC == Cases[1].CC &&
2352       isa<Constant>(Cases[0].CmpRHS) &&
2353       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2354     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2355       return false;
2356     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2357       return false;
2358   }
2359 
2360   return true;
2361 }
2362 
2363 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2364   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2365 
2366   // Update machine-CFG edges.
2367   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2368 
2369   if (I.isUnconditional()) {
2370     // Update machine-CFG edges.
2371     BrMBB->addSuccessor(Succ0MBB);
2372 
2373     // If this is not a fall-through branch or optimizations are switched off,
2374     // emit the branch.
2375     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2376       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2377                               MVT::Other, getControlRoot(),
2378                               DAG.getBasicBlock(Succ0MBB)));
2379 
2380     return;
2381   }
2382 
2383   // If this condition is one of the special cases we handle, do special stuff
2384   // now.
2385   const Value *CondVal = I.getCondition();
2386   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2387 
2388   // If this is a series of conditions that are or'd or and'd together, emit
2389   // this as a sequence of branches instead of setcc's with and/or operations.
2390   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2391   // unpredictable branches, and vector extracts because those jumps are likely
2392   // expensive for any target), this should improve performance.
2393   // For example, instead of something like:
2394   //     cmp A, B
2395   //     C = seteq
2396   //     cmp D, E
2397   //     F = setle
2398   //     or C, F
2399   //     jnz foo
2400   // Emit:
2401   //     cmp A, B
2402   //     je foo
2403   //     cmp D, E
2404   //     jle foo
2405   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2406   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2407       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2408     Value *Vec;
2409     const Value *BOp0, *BOp1;
2410     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2411     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2412       Opcode = Instruction::And;
2413     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2414       Opcode = Instruction::Or;
2415 
2416     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2417                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2418       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2419                            getEdgeProbability(BrMBB, Succ0MBB),
2420                            getEdgeProbability(BrMBB, Succ1MBB),
2421                            /*InvertCond=*/false);
2422       // If the compares in later blocks need to use values not currently
2423       // exported from this block, export them now.  This block should always
2424       // be the first entry.
2425       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2426 
2427       // Allow some cases to be rejected.
2428       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2429         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2430           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2431           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2432         }
2433 
2434         // Emit the branch for this block.
2435         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2436         SL->SwitchCases.erase(SL->SwitchCases.begin());
2437         return;
2438       }
2439 
2440       // Okay, we decided not to do this, remove any inserted MBB's and clear
2441       // SwitchCases.
2442       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2443         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2444 
2445       SL->SwitchCases.clear();
2446     }
2447   }
2448 
2449   // Create a CaseBlock record representing this branch.
2450   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2451                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2452 
2453   // Use visitSwitchCase to actually insert the fast branch sequence for this
2454   // cond branch.
2455   visitSwitchCase(CB, BrMBB);
2456 }
2457 
2458 /// visitSwitchCase - Emits the necessary code to represent a single node in
2459 /// the binary search tree resulting from lowering a switch instruction.
2460 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2461                                           MachineBasicBlock *SwitchBB) {
2462   SDValue Cond;
2463   SDValue CondLHS = getValue(CB.CmpLHS);
2464   SDLoc dl = CB.DL;
2465 
2466   if (CB.CC == ISD::SETTRUE) {
2467     // Branch or fall through to TrueBB.
2468     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2469     SwitchBB->normalizeSuccProbs();
2470     if (CB.TrueBB != NextBlock(SwitchBB)) {
2471       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2472                               DAG.getBasicBlock(CB.TrueBB)));
2473     }
2474     return;
2475   }
2476 
2477   auto &TLI = DAG.getTargetLoweringInfo();
2478   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2479 
2480   // Build the setcc now.
2481   if (!CB.CmpMHS) {
2482     // Fold "(X == true)" to X and "(X == false)" to !X to
2483     // handle common cases produced by branch lowering.
2484     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2485         CB.CC == ISD::SETEQ)
2486       Cond = CondLHS;
2487     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2488              CB.CC == ISD::SETEQ) {
2489       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2490       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2491     } else {
2492       SDValue CondRHS = getValue(CB.CmpRHS);
2493 
2494       // If a pointer's DAG type is larger than its memory type then the DAG
2495       // values are zero-extended. This breaks signed comparisons so truncate
2496       // back to the underlying type before doing the compare.
2497       if (CondLHS.getValueType() != MemVT) {
2498         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2499         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2500       }
2501       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2502     }
2503   } else {
2504     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2505 
2506     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2507     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2508 
2509     SDValue CmpOp = getValue(CB.CmpMHS);
2510     EVT VT = CmpOp.getValueType();
2511 
2512     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2513       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2514                           ISD::SETLE);
2515     } else {
2516       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2517                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2518       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2519                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2520     }
2521   }
2522 
2523   // Update successor info
2524   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2525   // TrueBB and FalseBB are always different unless the incoming IR is
2526   // degenerate. This only happens when running llc on weird IR.
2527   if (CB.TrueBB != CB.FalseBB)
2528     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2529   SwitchBB->normalizeSuccProbs();
2530 
2531   // If the lhs block is the next block, invert the condition so that we can
2532   // fall through to the lhs instead of the rhs block.
2533   if (CB.TrueBB == NextBlock(SwitchBB)) {
2534     std::swap(CB.TrueBB, CB.FalseBB);
2535     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2536     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2537   }
2538 
2539   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2540                                MVT::Other, getControlRoot(), Cond,
2541                                DAG.getBasicBlock(CB.TrueBB));
2542 
2543   // Insert the false branch. Do this even if it's a fall through branch,
2544   // this makes it easier to do DAG optimizations which require inverting
2545   // the branch condition.
2546   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2547                        DAG.getBasicBlock(CB.FalseBB));
2548 
2549   DAG.setRoot(BrCond);
2550 }
2551 
2552 /// visitJumpTable - Emit JumpTable node in the current MBB
2553 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2554   // Emit the code for the jump table
2555   assert(JT.Reg != -1U && "Should lower JT Header first!");
2556   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2557   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2558                                      JT.Reg, PTy);
2559   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2560   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2561                                     MVT::Other, Index.getValue(1),
2562                                     Table, Index);
2563   DAG.setRoot(BrJumpTable);
2564 }
2565 
2566 /// visitJumpTableHeader - This function emits necessary code to produce index
2567 /// in the JumpTable from switch case.
2568 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2569                                                JumpTableHeader &JTH,
2570                                                MachineBasicBlock *SwitchBB) {
2571   SDLoc dl = getCurSDLoc();
2572 
2573   // Subtract the lowest switch case value from the value being switched on.
2574   SDValue SwitchOp = getValue(JTH.SValue);
2575   EVT VT = SwitchOp.getValueType();
2576   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2577                             DAG.getConstant(JTH.First, dl, VT));
2578 
2579   // The SDNode we just created, which holds the value being switched on minus
2580   // the smallest case value, needs to be copied to a virtual register so it
2581   // can be used as an index into the jump table in a subsequent basic block.
2582   // This value may be smaller or larger than the target's pointer type, and
2583   // therefore require extension or truncating.
2584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2585   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2586 
2587   unsigned JumpTableReg =
2588       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2589   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2590                                     JumpTableReg, SwitchOp);
2591   JT.Reg = JumpTableReg;
2592 
2593   if (!JTH.FallthroughUnreachable) {
2594     // Emit the range check for the jump table, and branch to the default block
2595     // for the switch statement if the value being switched on exceeds the
2596     // largest case in the switch.
2597     SDValue CMP = DAG.getSetCC(
2598         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2599                                    Sub.getValueType()),
2600         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2601 
2602     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2603                                  MVT::Other, CopyTo, CMP,
2604                                  DAG.getBasicBlock(JT.Default));
2605 
2606     // Avoid emitting unnecessary branches to the next block.
2607     if (JT.MBB != NextBlock(SwitchBB))
2608       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2609                            DAG.getBasicBlock(JT.MBB));
2610 
2611     DAG.setRoot(BrCond);
2612   } else {
2613     // Avoid emitting unnecessary branches to the next block.
2614     if (JT.MBB != NextBlock(SwitchBB))
2615       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2616                               DAG.getBasicBlock(JT.MBB)));
2617     else
2618       DAG.setRoot(CopyTo);
2619   }
2620 }
2621 
2622 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2623 /// variable if there exists one.
2624 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2625                                  SDValue &Chain) {
2626   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2627   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2628   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2629   MachineFunction &MF = DAG.getMachineFunction();
2630   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2631   MachineSDNode *Node =
2632       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2633   if (Global) {
2634     MachinePointerInfo MPInfo(Global);
2635     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2636                  MachineMemOperand::MODereferenceable;
2637     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2638         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2639     DAG.setNodeMemRefs(Node, {MemRef});
2640   }
2641   if (PtrTy != PtrMemTy)
2642     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2643   return SDValue(Node, 0);
2644 }
2645 
2646 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2647 /// tail spliced into a stack protector check success bb.
2648 ///
2649 /// For a high level explanation of how this fits into the stack protector
2650 /// generation see the comment on the declaration of class
2651 /// StackProtectorDescriptor.
2652 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2653                                                   MachineBasicBlock *ParentBB) {
2654 
2655   // First create the loads to the guard/stack slot for the comparison.
2656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2657   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2658   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2659 
2660   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2661   int FI = MFI.getStackProtectorIndex();
2662 
2663   SDValue Guard;
2664   SDLoc dl = getCurSDLoc();
2665   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2666   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2667   Align Align =
2668       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2669 
2670   // Generate code to load the content of the guard slot.
2671   SDValue GuardVal = DAG.getLoad(
2672       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2673       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2674       MachineMemOperand::MOVolatile);
2675 
2676   if (TLI.useStackGuardXorFP())
2677     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2678 
2679   // Retrieve guard check function, nullptr if instrumentation is inlined.
2680   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2681     // The target provides a guard check function to validate the guard value.
2682     // Generate a call to that function with the content of the guard slot as
2683     // argument.
2684     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2685     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2686 
2687     TargetLowering::ArgListTy Args;
2688     TargetLowering::ArgListEntry Entry;
2689     Entry.Node = GuardVal;
2690     Entry.Ty = FnTy->getParamType(0);
2691     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2692       Entry.IsInReg = true;
2693     Args.push_back(Entry);
2694 
2695     TargetLowering::CallLoweringInfo CLI(DAG);
2696     CLI.setDebugLoc(getCurSDLoc())
2697         .setChain(DAG.getEntryNode())
2698         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2699                    getValue(GuardCheckFn), std::move(Args));
2700 
2701     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2702     DAG.setRoot(Result.second);
2703     return;
2704   }
2705 
2706   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2707   // Otherwise, emit a volatile load to retrieve the stack guard value.
2708   SDValue Chain = DAG.getEntryNode();
2709   if (TLI.useLoadStackGuardNode()) {
2710     Guard = getLoadStackGuard(DAG, dl, Chain);
2711   } else {
2712     const Value *IRGuard = TLI.getSDagStackGuard(M);
2713     SDValue GuardPtr = getValue(IRGuard);
2714 
2715     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2716                         MachinePointerInfo(IRGuard, 0), Align,
2717                         MachineMemOperand::MOVolatile);
2718   }
2719 
2720   // Perform the comparison via a getsetcc.
2721   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2722                                                         *DAG.getContext(),
2723                                                         Guard.getValueType()),
2724                              Guard, GuardVal, ISD::SETNE);
2725 
2726   // If the guard/stackslot do not equal, branch to failure MBB.
2727   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2728                                MVT::Other, GuardVal.getOperand(0),
2729                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2730   // Otherwise branch to success MBB.
2731   SDValue Br = DAG.getNode(ISD::BR, dl,
2732                            MVT::Other, BrCond,
2733                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2734 
2735   DAG.setRoot(Br);
2736 }
2737 
2738 /// Codegen the failure basic block for a stack protector check.
2739 ///
2740 /// A failure stack protector machine basic block consists simply of a call to
2741 /// __stack_chk_fail().
2742 ///
2743 /// For a high level explanation of how this fits into the stack protector
2744 /// generation see the comment on the declaration of class
2745 /// StackProtectorDescriptor.
2746 void
2747 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2749   TargetLowering::MakeLibCallOptions CallOptions;
2750   CallOptions.setDiscardResult(true);
2751   SDValue Chain =
2752       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2753                       None, CallOptions, getCurSDLoc()).second;
2754   // On PS4, the "return address" must still be within the calling function,
2755   // even if it's at the very end, so emit an explicit TRAP here.
2756   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2757   if (TM.getTargetTriple().isPS4CPU())
2758     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2759   // WebAssembly needs an unreachable instruction after a non-returning call,
2760   // because the function return type can be different from __stack_chk_fail's
2761   // return type (void).
2762   if (TM.getTargetTriple().isWasm())
2763     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2764 
2765   DAG.setRoot(Chain);
2766 }
2767 
2768 /// visitBitTestHeader - This function emits necessary code to produce value
2769 /// suitable for "bit tests"
2770 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2771                                              MachineBasicBlock *SwitchBB) {
2772   SDLoc dl = getCurSDLoc();
2773 
2774   // Subtract the minimum value.
2775   SDValue SwitchOp = getValue(B.SValue);
2776   EVT VT = SwitchOp.getValueType();
2777   SDValue RangeSub =
2778       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2779 
2780   // Determine the type of the test operands.
2781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2782   bool UsePtrType = false;
2783   if (!TLI.isTypeLegal(VT)) {
2784     UsePtrType = true;
2785   } else {
2786     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2787       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2788         // Switch table case range are encoded into series of masks.
2789         // Just use pointer type, it's guaranteed to fit.
2790         UsePtrType = true;
2791         break;
2792       }
2793   }
2794   SDValue Sub = RangeSub;
2795   if (UsePtrType) {
2796     VT = TLI.getPointerTy(DAG.getDataLayout());
2797     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2798   }
2799 
2800   B.RegVT = VT.getSimpleVT();
2801   B.Reg = FuncInfo.CreateReg(B.RegVT);
2802   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2803 
2804   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2805 
2806   if (!B.FallthroughUnreachable)
2807     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2808   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2809   SwitchBB->normalizeSuccProbs();
2810 
2811   SDValue Root = CopyTo;
2812   if (!B.FallthroughUnreachable) {
2813     // Conditional branch to the default block.
2814     SDValue RangeCmp = DAG.getSetCC(dl,
2815         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2816                                RangeSub.getValueType()),
2817         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2818         ISD::SETUGT);
2819 
2820     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2821                        DAG.getBasicBlock(B.Default));
2822   }
2823 
2824   // Avoid emitting unnecessary branches to the next block.
2825   if (MBB != NextBlock(SwitchBB))
2826     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2827 
2828   DAG.setRoot(Root);
2829 }
2830 
2831 /// visitBitTestCase - this function produces one "bit test"
2832 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2833                                            MachineBasicBlock* NextMBB,
2834                                            BranchProbability BranchProbToNext,
2835                                            unsigned Reg,
2836                                            BitTestCase &B,
2837                                            MachineBasicBlock *SwitchBB) {
2838   SDLoc dl = getCurSDLoc();
2839   MVT VT = BB.RegVT;
2840   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2841   SDValue Cmp;
2842   unsigned PopCount = countPopulation(B.Mask);
2843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2844   if (PopCount == 1) {
2845     // Testing for a single bit; just compare the shift count with what it
2846     // would need to be to shift a 1 bit in that position.
2847     Cmp = DAG.getSetCC(
2848         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2849         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2850         ISD::SETEQ);
2851   } else if (PopCount == BB.Range) {
2852     // There is only one zero bit in the range, test for it directly.
2853     Cmp = DAG.getSetCC(
2854         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2855         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2856         ISD::SETNE);
2857   } else {
2858     // Make desired shift
2859     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2860                                     DAG.getConstant(1, dl, VT), ShiftOp);
2861 
2862     // Emit bit tests and jumps
2863     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2864                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2865     Cmp = DAG.getSetCC(
2866         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2867         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2868   }
2869 
2870   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2871   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2872   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2873   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2874   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2875   // one as they are relative probabilities (and thus work more like weights),
2876   // and hence we need to normalize them to let the sum of them become one.
2877   SwitchBB->normalizeSuccProbs();
2878 
2879   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2880                               MVT::Other, getControlRoot(),
2881                               Cmp, DAG.getBasicBlock(B.TargetBB));
2882 
2883   // Avoid emitting unnecessary branches to the next block.
2884   if (NextMBB != NextBlock(SwitchBB))
2885     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2886                         DAG.getBasicBlock(NextMBB));
2887 
2888   DAG.setRoot(BrAnd);
2889 }
2890 
2891 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2892   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2893 
2894   // Retrieve successors. Look through artificial IR level blocks like
2895   // catchswitch for successors.
2896   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2897   const BasicBlock *EHPadBB = I.getSuccessor(1);
2898 
2899   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2900   // have to do anything here to lower funclet bundles.
2901   assert(!I.hasOperandBundlesOtherThan(
2902              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2903               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2904               LLVMContext::OB_cfguardtarget,
2905               LLVMContext::OB_clang_arc_attachedcall}) &&
2906          "Cannot lower invokes with arbitrary operand bundles yet!");
2907 
2908   const Value *Callee(I.getCalledOperand());
2909   const Function *Fn = dyn_cast<Function>(Callee);
2910   if (isa<InlineAsm>(Callee))
2911     visitInlineAsm(I, EHPadBB);
2912   else if (Fn && Fn->isIntrinsic()) {
2913     switch (Fn->getIntrinsicID()) {
2914     default:
2915       llvm_unreachable("Cannot invoke this intrinsic");
2916     case Intrinsic::donothing:
2917       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2918     case Intrinsic::seh_try_begin:
2919     case Intrinsic::seh_scope_begin:
2920     case Intrinsic::seh_try_end:
2921     case Intrinsic::seh_scope_end:
2922       break;
2923     case Intrinsic::experimental_patchpoint_void:
2924     case Intrinsic::experimental_patchpoint_i64:
2925       visitPatchpoint(I, EHPadBB);
2926       break;
2927     case Intrinsic::experimental_gc_statepoint:
2928       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2929       break;
2930     case Intrinsic::wasm_rethrow: {
2931       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2932       // special because it can be invoked, so we manually lower it to a DAG
2933       // node here.
2934       SmallVector<SDValue, 8> Ops;
2935       Ops.push_back(getRoot()); // inchain
2936       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2937       Ops.push_back(
2938           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2939                                 TLI.getPointerTy(DAG.getDataLayout())));
2940       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2941       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2942       break;
2943     }
2944     }
2945   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2946     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2947     // Eventually we will support lowering the @llvm.experimental.deoptimize
2948     // intrinsic, and right now there are no plans to support other intrinsics
2949     // with deopt state.
2950     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2951   } else {
2952     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2953   }
2954 
2955   // If the value of the invoke is used outside of its defining block, make it
2956   // available as a virtual register.
2957   // We already took care of the exported value for the statepoint instruction
2958   // during call to the LowerStatepoint.
2959   if (!isa<GCStatepointInst>(I)) {
2960     CopyToExportRegsIfNeeded(&I);
2961   }
2962 
2963   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2964   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2965   BranchProbability EHPadBBProb =
2966       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2967           : BranchProbability::getZero();
2968   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2969 
2970   // Update successor info.
2971   addSuccessorWithProb(InvokeMBB, Return);
2972   for (auto &UnwindDest : UnwindDests) {
2973     UnwindDest.first->setIsEHPad();
2974     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2975   }
2976   InvokeMBB->normalizeSuccProbs();
2977 
2978   // Drop into normal successor.
2979   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2980                           DAG.getBasicBlock(Return)));
2981 }
2982 
2983 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2984   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2985 
2986   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2987   // have to do anything here to lower funclet bundles.
2988   assert(!I.hasOperandBundlesOtherThan(
2989              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2990          "Cannot lower callbrs with arbitrary operand bundles yet!");
2991 
2992   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2993   visitInlineAsm(I);
2994   CopyToExportRegsIfNeeded(&I);
2995 
2996   // Retrieve successors.
2997   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2998 
2999   // Update successor info.
3000   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3001   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3002     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
3003     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3004     Target->setIsInlineAsmBrIndirectTarget();
3005   }
3006   CallBrMBB->normalizeSuccProbs();
3007 
3008   // Drop into default successor.
3009   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3010                           MVT::Other, getControlRoot(),
3011                           DAG.getBasicBlock(Return)));
3012 }
3013 
3014 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3015   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3016 }
3017 
3018 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3019   assert(FuncInfo.MBB->isEHPad() &&
3020          "Call to landingpad not in landing pad!");
3021 
3022   // If there aren't registers to copy the values into (e.g., during SjLj
3023   // exceptions), then don't bother to create these DAG nodes.
3024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3025   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3026   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3027       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3028     return;
3029 
3030   // If landingpad's return type is token type, we don't create DAG nodes
3031   // for its exception pointer and selector value. The extraction of exception
3032   // pointer or selector value from token type landingpads is not currently
3033   // supported.
3034   if (LP.getType()->isTokenTy())
3035     return;
3036 
3037   SmallVector<EVT, 2> ValueVTs;
3038   SDLoc dl = getCurSDLoc();
3039   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3040   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3041 
3042   // Get the two live-in registers as SDValues. The physregs have already been
3043   // copied into virtual registers.
3044   SDValue Ops[2];
3045   if (FuncInfo.ExceptionPointerVirtReg) {
3046     Ops[0] = DAG.getZExtOrTrunc(
3047         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3048                            FuncInfo.ExceptionPointerVirtReg,
3049                            TLI.getPointerTy(DAG.getDataLayout())),
3050         dl, ValueVTs[0]);
3051   } else {
3052     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3053   }
3054   Ops[1] = DAG.getZExtOrTrunc(
3055       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3056                          FuncInfo.ExceptionSelectorVirtReg,
3057                          TLI.getPointerTy(DAG.getDataLayout())),
3058       dl, ValueVTs[1]);
3059 
3060   // Merge into one.
3061   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3062                             DAG.getVTList(ValueVTs), Ops);
3063   setValue(&LP, Res);
3064 }
3065 
3066 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3067                                            MachineBasicBlock *Last) {
3068   // Update JTCases.
3069   for (JumpTableBlock &JTB : SL->JTCases)
3070     if (JTB.first.HeaderBB == First)
3071       JTB.first.HeaderBB = Last;
3072 
3073   // Update BitTestCases.
3074   for (BitTestBlock &BTB : SL->BitTestCases)
3075     if (BTB.Parent == First)
3076       BTB.Parent = Last;
3077 }
3078 
3079 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3080   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3081 
3082   // Update machine-CFG edges with unique successors.
3083   SmallSet<BasicBlock*, 32> Done;
3084   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3085     BasicBlock *BB = I.getSuccessor(i);
3086     bool Inserted = Done.insert(BB).second;
3087     if (!Inserted)
3088         continue;
3089 
3090     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3091     addSuccessorWithProb(IndirectBrMBB, Succ);
3092   }
3093   IndirectBrMBB->normalizeSuccProbs();
3094 
3095   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3096                           MVT::Other, getControlRoot(),
3097                           getValue(I.getAddress())));
3098 }
3099 
3100 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3101   if (!DAG.getTarget().Options.TrapUnreachable)
3102     return;
3103 
3104   // We may be able to ignore unreachable behind a noreturn call.
3105   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3106     const BasicBlock &BB = *I.getParent();
3107     if (&I != &BB.front()) {
3108       BasicBlock::const_iterator PredI =
3109         std::prev(BasicBlock::const_iterator(&I));
3110       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3111         if (Call->doesNotReturn())
3112           return;
3113       }
3114     }
3115   }
3116 
3117   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3118 }
3119 
3120 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3121   SDNodeFlags Flags;
3122   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3123     Flags.copyFMF(*FPOp);
3124 
3125   SDValue Op = getValue(I.getOperand(0));
3126   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3127                                     Op, Flags);
3128   setValue(&I, UnNodeValue);
3129 }
3130 
3131 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3132   SDNodeFlags Flags;
3133   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3134     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3135     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3136   }
3137   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3138     Flags.setExact(ExactOp->isExact());
3139   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3140     Flags.copyFMF(*FPOp);
3141 
3142   SDValue Op1 = getValue(I.getOperand(0));
3143   SDValue Op2 = getValue(I.getOperand(1));
3144   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3145                                      Op1, Op2, Flags);
3146   setValue(&I, BinNodeValue);
3147 }
3148 
3149 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3150   SDValue Op1 = getValue(I.getOperand(0));
3151   SDValue Op2 = getValue(I.getOperand(1));
3152 
3153   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3154       Op1.getValueType(), DAG.getDataLayout());
3155 
3156   // Coerce the shift amount to the right type if we can.
3157   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3158     unsigned ShiftSize = ShiftTy.getSizeInBits();
3159     unsigned Op2Size = Op2.getValueSizeInBits();
3160     SDLoc DL = getCurSDLoc();
3161 
3162     // If the operand is smaller than the shift count type, promote it.
3163     if (ShiftSize > Op2Size)
3164       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3165 
3166     // If the operand is larger than the shift count type but the shift
3167     // count type has enough bits to represent any shift value, truncate
3168     // it now. This is a common case and it exposes the truncate to
3169     // optimization early.
3170     else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3171       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3172     // Otherwise we'll need to temporarily settle for some other convenient
3173     // type.  Type legalization will make adjustments once the shiftee is split.
3174     else
3175       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3176   }
3177 
3178   bool nuw = false;
3179   bool nsw = false;
3180   bool exact = false;
3181 
3182   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3183 
3184     if (const OverflowingBinaryOperator *OFBinOp =
3185             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3186       nuw = OFBinOp->hasNoUnsignedWrap();
3187       nsw = OFBinOp->hasNoSignedWrap();
3188     }
3189     if (const PossiblyExactOperator *ExactOp =
3190             dyn_cast<const PossiblyExactOperator>(&I))
3191       exact = ExactOp->isExact();
3192   }
3193   SDNodeFlags Flags;
3194   Flags.setExact(exact);
3195   Flags.setNoSignedWrap(nsw);
3196   Flags.setNoUnsignedWrap(nuw);
3197   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3198                             Flags);
3199   setValue(&I, Res);
3200 }
3201 
3202 void SelectionDAGBuilder::visitSDiv(const User &I) {
3203   SDValue Op1 = getValue(I.getOperand(0));
3204   SDValue Op2 = getValue(I.getOperand(1));
3205 
3206   SDNodeFlags Flags;
3207   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3208                  cast<PossiblyExactOperator>(&I)->isExact());
3209   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3210                            Op2, Flags));
3211 }
3212 
3213 void SelectionDAGBuilder::visitICmp(const User &I) {
3214   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3215   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3216     predicate = IC->getPredicate();
3217   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3218     predicate = ICmpInst::Predicate(IC->getPredicate());
3219   SDValue Op1 = getValue(I.getOperand(0));
3220   SDValue Op2 = getValue(I.getOperand(1));
3221   ISD::CondCode Opcode = getICmpCondCode(predicate);
3222 
3223   auto &TLI = DAG.getTargetLoweringInfo();
3224   EVT MemVT =
3225       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3226 
3227   // If a pointer's DAG type is larger than its memory type then the DAG values
3228   // are zero-extended. This breaks signed comparisons so truncate back to the
3229   // underlying type before doing the compare.
3230   if (Op1.getValueType() != MemVT) {
3231     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3232     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3233   }
3234 
3235   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3236                                                         I.getType());
3237   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3238 }
3239 
3240 void SelectionDAGBuilder::visitFCmp(const User &I) {
3241   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3242   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3243     predicate = FC->getPredicate();
3244   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3245     predicate = FCmpInst::Predicate(FC->getPredicate());
3246   SDValue Op1 = getValue(I.getOperand(0));
3247   SDValue Op2 = getValue(I.getOperand(1));
3248 
3249   ISD::CondCode Condition = getFCmpCondCode(predicate);
3250   auto *FPMO = cast<FPMathOperator>(&I);
3251   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3252     Condition = getFCmpCodeWithoutNaN(Condition);
3253 
3254   SDNodeFlags Flags;
3255   Flags.copyFMF(*FPMO);
3256   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3257 
3258   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3259                                                         I.getType());
3260   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3261 }
3262 
3263 // Check if the condition of the select has one use or two users that are both
3264 // selects with the same condition.
3265 static bool hasOnlySelectUsers(const Value *Cond) {
3266   return llvm::all_of(Cond->users(), [](const Value *V) {
3267     return isa<SelectInst>(V);
3268   });
3269 }
3270 
3271 void SelectionDAGBuilder::visitSelect(const User &I) {
3272   SmallVector<EVT, 4> ValueVTs;
3273   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3274                   ValueVTs);
3275   unsigned NumValues = ValueVTs.size();
3276   if (NumValues == 0) return;
3277 
3278   SmallVector<SDValue, 4> Values(NumValues);
3279   SDValue Cond     = getValue(I.getOperand(0));
3280   SDValue LHSVal   = getValue(I.getOperand(1));
3281   SDValue RHSVal   = getValue(I.getOperand(2));
3282   SmallVector<SDValue, 1> BaseOps(1, Cond);
3283   ISD::NodeType OpCode =
3284       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3285 
3286   bool IsUnaryAbs = false;
3287   bool Negate = false;
3288 
3289   SDNodeFlags Flags;
3290   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3291     Flags.copyFMF(*FPOp);
3292 
3293   // Min/max matching is only viable if all output VTs are the same.
3294   if (is_splat(ValueVTs)) {
3295     EVT VT = ValueVTs[0];
3296     LLVMContext &Ctx = *DAG.getContext();
3297     auto &TLI = DAG.getTargetLoweringInfo();
3298 
3299     // We care about the legality of the operation after it has been type
3300     // legalized.
3301     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3302       VT = TLI.getTypeToTransformTo(Ctx, VT);
3303 
3304     // If the vselect is legal, assume we want to leave this as a vector setcc +
3305     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3306     // min/max is legal on the scalar type.
3307     bool UseScalarMinMax = VT.isVector() &&
3308       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3309 
3310     Value *LHS, *RHS;
3311     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3312     ISD::NodeType Opc = ISD::DELETED_NODE;
3313     switch (SPR.Flavor) {
3314     case SPF_UMAX:    Opc = ISD::UMAX; break;
3315     case SPF_UMIN:    Opc = ISD::UMIN; break;
3316     case SPF_SMAX:    Opc = ISD::SMAX; break;
3317     case SPF_SMIN:    Opc = ISD::SMIN; break;
3318     case SPF_FMINNUM:
3319       switch (SPR.NaNBehavior) {
3320       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3321       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3322       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3323       case SPNB_RETURNS_ANY: {
3324         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3325           Opc = ISD::FMINNUM;
3326         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3327           Opc = ISD::FMINIMUM;
3328         else if (UseScalarMinMax)
3329           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3330             ISD::FMINNUM : ISD::FMINIMUM;
3331         break;
3332       }
3333       }
3334       break;
3335     case SPF_FMAXNUM:
3336       switch (SPR.NaNBehavior) {
3337       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3338       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3339       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3340       case SPNB_RETURNS_ANY:
3341 
3342         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3343           Opc = ISD::FMAXNUM;
3344         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3345           Opc = ISD::FMAXIMUM;
3346         else if (UseScalarMinMax)
3347           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3348             ISD::FMAXNUM : ISD::FMAXIMUM;
3349         break;
3350       }
3351       break;
3352     case SPF_NABS:
3353       Negate = true;
3354       LLVM_FALLTHROUGH;
3355     case SPF_ABS:
3356       IsUnaryAbs = true;
3357       Opc = ISD::ABS;
3358       break;
3359     default: break;
3360     }
3361 
3362     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3363         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3364          (UseScalarMinMax &&
3365           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3366         // If the underlying comparison instruction is used by any other
3367         // instruction, the consumed instructions won't be destroyed, so it is
3368         // not profitable to convert to a min/max.
3369         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3370       OpCode = Opc;
3371       LHSVal = getValue(LHS);
3372       RHSVal = getValue(RHS);
3373       BaseOps.clear();
3374     }
3375 
3376     if (IsUnaryAbs) {
3377       OpCode = Opc;
3378       LHSVal = getValue(LHS);
3379       BaseOps.clear();
3380     }
3381   }
3382 
3383   if (IsUnaryAbs) {
3384     for (unsigned i = 0; i != NumValues; ++i) {
3385       SDLoc dl = getCurSDLoc();
3386       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3387       Values[i] =
3388           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3389       if (Negate)
3390         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3391                                 Values[i]);
3392     }
3393   } else {
3394     for (unsigned i = 0; i != NumValues; ++i) {
3395       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3396       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3397       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3398       Values[i] = DAG.getNode(
3399           OpCode, getCurSDLoc(),
3400           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3401     }
3402   }
3403 
3404   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3405                            DAG.getVTList(ValueVTs), Values));
3406 }
3407 
3408 void SelectionDAGBuilder::visitTrunc(const User &I) {
3409   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3410   SDValue N = getValue(I.getOperand(0));
3411   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3412                                                         I.getType());
3413   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3414 }
3415 
3416 void SelectionDAGBuilder::visitZExt(const User &I) {
3417   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3418   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3419   SDValue N = getValue(I.getOperand(0));
3420   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3421                                                         I.getType());
3422   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3423 }
3424 
3425 void SelectionDAGBuilder::visitSExt(const User &I) {
3426   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3427   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3428   SDValue N = getValue(I.getOperand(0));
3429   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3430                                                         I.getType());
3431   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3432 }
3433 
3434 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3435   // FPTrunc is never a no-op cast, no need to check
3436   SDValue N = getValue(I.getOperand(0));
3437   SDLoc dl = getCurSDLoc();
3438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3439   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3440   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3441                            DAG.getTargetConstant(
3442                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3443 }
3444 
3445 void SelectionDAGBuilder::visitFPExt(const User &I) {
3446   // FPExt is never a no-op cast, no need to check
3447   SDValue N = getValue(I.getOperand(0));
3448   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3449                                                         I.getType());
3450   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3451 }
3452 
3453 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3454   // FPToUI is never a no-op cast, no need to check
3455   SDValue N = getValue(I.getOperand(0));
3456   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3457                                                         I.getType());
3458   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3459 }
3460 
3461 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3462   // FPToSI is never a no-op cast, no need to check
3463   SDValue N = getValue(I.getOperand(0));
3464   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3465                                                         I.getType());
3466   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3467 }
3468 
3469 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3470   // UIToFP is never a no-op cast, no need to check
3471   SDValue N = getValue(I.getOperand(0));
3472   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3473                                                         I.getType());
3474   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3475 }
3476 
3477 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3478   // SIToFP is never a no-op cast, no need to check
3479   SDValue N = getValue(I.getOperand(0));
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3483 }
3484 
3485 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3486   // What to do depends on the size of the integer and the size of the pointer.
3487   // We can either truncate, zero extend, or no-op, accordingly.
3488   SDValue N = getValue(I.getOperand(0));
3489   auto &TLI = DAG.getTargetLoweringInfo();
3490   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3491                                                         I.getType());
3492   EVT PtrMemVT =
3493       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3494   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3495   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3496   setValue(&I, N);
3497 }
3498 
3499 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3500   // What to do depends on the size of the integer and the size of the pointer.
3501   // We can either truncate, zero extend, or no-op, accordingly.
3502   SDValue N = getValue(I.getOperand(0));
3503   auto &TLI = DAG.getTargetLoweringInfo();
3504   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3505   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3506   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3507   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3508   setValue(&I, N);
3509 }
3510 
3511 void SelectionDAGBuilder::visitBitCast(const User &I) {
3512   SDValue N = getValue(I.getOperand(0));
3513   SDLoc dl = getCurSDLoc();
3514   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3515                                                         I.getType());
3516 
3517   // BitCast assures us that source and destination are the same size so this is
3518   // either a BITCAST or a no-op.
3519   if (DestVT != N.getValueType())
3520     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3521                              DestVT, N)); // convert types.
3522   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3523   // might fold any kind of constant expression to an integer constant and that
3524   // is not what we are looking for. Only recognize a bitcast of a genuine
3525   // constant integer as an opaque constant.
3526   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3527     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3528                                  /*isOpaque*/true));
3529   else
3530     setValue(&I, N);            // noop cast.
3531 }
3532 
3533 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3535   const Value *SV = I.getOperand(0);
3536   SDValue N = getValue(SV);
3537   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3538 
3539   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3540   unsigned DestAS = I.getType()->getPointerAddressSpace();
3541 
3542   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3543     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3544 
3545   setValue(&I, N);
3546 }
3547 
3548 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3550   SDValue InVec = getValue(I.getOperand(0));
3551   SDValue InVal = getValue(I.getOperand(1));
3552   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3553                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3554   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3555                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3556                            InVec, InVal, InIdx));
3557 }
3558 
3559 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3561   SDValue InVec = getValue(I.getOperand(0));
3562   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3563                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3564   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3565                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3566                            InVec, InIdx));
3567 }
3568 
3569 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3570   SDValue Src1 = getValue(I.getOperand(0));
3571   SDValue Src2 = getValue(I.getOperand(1));
3572   ArrayRef<int> Mask;
3573   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3574     Mask = SVI->getShuffleMask();
3575   else
3576     Mask = cast<ConstantExpr>(I).getShuffleMask();
3577   SDLoc DL = getCurSDLoc();
3578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3579   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3580   EVT SrcVT = Src1.getValueType();
3581 
3582   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3583       VT.isScalableVector()) {
3584     // Canonical splat form of first element of first input vector.
3585     SDValue FirstElt =
3586         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3587                     DAG.getVectorIdxConstant(0, DL));
3588     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3589     return;
3590   }
3591 
3592   // For now, we only handle splats for scalable vectors.
3593   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3594   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3595   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3596 
3597   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3598   unsigned MaskNumElts = Mask.size();
3599 
3600   if (SrcNumElts == MaskNumElts) {
3601     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3602     return;
3603   }
3604 
3605   // Normalize the shuffle vector since mask and vector length don't match.
3606   if (SrcNumElts < MaskNumElts) {
3607     // Mask is longer than the source vectors. We can use concatenate vector to
3608     // make the mask and vectors lengths match.
3609 
3610     if (MaskNumElts % SrcNumElts == 0) {
3611       // Mask length is a multiple of the source vector length.
3612       // Check if the shuffle is some kind of concatenation of the input
3613       // vectors.
3614       unsigned NumConcat = MaskNumElts / SrcNumElts;
3615       bool IsConcat = true;
3616       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3617       for (unsigned i = 0; i != MaskNumElts; ++i) {
3618         int Idx = Mask[i];
3619         if (Idx < 0)
3620           continue;
3621         // Ensure the indices in each SrcVT sized piece are sequential and that
3622         // the same source is used for the whole piece.
3623         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3624             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3625              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3626           IsConcat = false;
3627           break;
3628         }
3629         // Remember which source this index came from.
3630         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3631       }
3632 
3633       // The shuffle is concatenating multiple vectors together. Just emit
3634       // a CONCAT_VECTORS operation.
3635       if (IsConcat) {
3636         SmallVector<SDValue, 8> ConcatOps;
3637         for (auto Src : ConcatSrcs) {
3638           if (Src < 0)
3639             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3640           else if (Src == 0)
3641             ConcatOps.push_back(Src1);
3642           else
3643             ConcatOps.push_back(Src2);
3644         }
3645         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3646         return;
3647       }
3648     }
3649 
3650     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3651     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3652     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3653                                     PaddedMaskNumElts);
3654 
3655     // Pad both vectors with undefs to make them the same length as the mask.
3656     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3657 
3658     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3659     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3660     MOps1[0] = Src1;
3661     MOps2[0] = Src2;
3662 
3663     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3664     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3665 
3666     // Readjust mask for new input vector length.
3667     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3668     for (unsigned i = 0; i != MaskNumElts; ++i) {
3669       int Idx = Mask[i];
3670       if (Idx >= (int)SrcNumElts)
3671         Idx -= SrcNumElts - PaddedMaskNumElts;
3672       MappedOps[i] = Idx;
3673     }
3674 
3675     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3676 
3677     // If the concatenated vector was padded, extract a subvector with the
3678     // correct number of elements.
3679     if (MaskNumElts != PaddedMaskNumElts)
3680       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3681                            DAG.getVectorIdxConstant(0, DL));
3682 
3683     setValue(&I, Result);
3684     return;
3685   }
3686 
3687   if (SrcNumElts > MaskNumElts) {
3688     // Analyze the access pattern of the vector to see if we can extract
3689     // two subvectors and do the shuffle.
3690     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3691     bool CanExtract = true;
3692     for (int Idx : Mask) {
3693       unsigned Input = 0;
3694       if (Idx < 0)
3695         continue;
3696 
3697       if (Idx >= (int)SrcNumElts) {
3698         Input = 1;
3699         Idx -= SrcNumElts;
3700       }
3701 
3702       // If all the indices come from the same MaskNumElts sized portion of
3703       // the sources we can use extract. Also make sure the extract wouldn't
3704       // extract past the end of the source.
3705       int NewStartIdx = alignDown(Idx, MaskNumElts);
3706       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3707           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3708         CanExtract = false;
3709       // Make sure we always update StartIdx as we use it to track if all
3710       // elements are undef.
3711       StartIdx[Input] = NewStartIdx;
3712     }
3713 
3714     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3715       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3716       return;
3717     }
3718     if (CanExtract) {
3719       // Extract appropriate subvector and generate a vector shuffle
3720       for (unsigned Input = 0; Input < 2; ++Input) {
3721         SDValue &Src = Input == 0 ? Src1 : Src2;
3722         if (StartIdx[Input] < 0)
3723           Src = DAG.getUNDEF(VT);
3724         else {
3725           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3726                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3727         }
3728       }
3729 
3730       // Calculate new mask.
3731       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3732       for (int &Idx : MappedOps) {
3733         if (Idx >= (int)SrcNumElts)
3734           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3735         else if (Idx >= 0)
3736           Idx -= StartIdx[0];
3737       }
3738 
3739       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3740       return;
3741     }
3742   }
3743 
3744   // We can't use either concat vectors or extract subvectors so fall back to
3745   // replacing the shuffle with extract and build vector.
3746   // to insert and build vector.
3747   EVT EltVT = VT.getVectorElementType();
3748   SmallVector<SDValue,8> Ops;
3749   for (int Idx : Mask) {
3750     SDValue Res;
3751 
3752     if (Idx < 0) {
3753       Res = DAG.getUNDEF(EltVT);
3754     } else {
3755       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3756       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3757 
3758       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3759                         DAG.getVectorIdxConstant(Idx, DL));
3760     }
3761 
3762     Ops.push_back(Res);
3763   }
3764 
3765   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3766 }
3767 
3768 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3769   ArrayRef<unsigned> Indices;
3770   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3771     Indices = IV->getIndices();
3772   else
3773     Indices = cast<ConstantExpr>(&I)->getIndices();
3774 
3775   const Value *Op0 = I.getOperand(0);
3776   const Value *Op1 = I.getOperand(1);
3777   Type *AggTy = I.getType();
3778   Type *ValTy = Op1->getType();
3779   bool IntoUndef = isa<UndefValue>(Op0);
3780   bool FromUndef = isa<UndefValue>(Op1);
3781 
3782   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3783 
3784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3785   SmallVector<EVT, 4> AggValueVTs;
3786   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3787   SmallVector<EVT, 4> ValValueVTs;
3788   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3789 
3790   unsigned NumAggValues = AggValueVTs.size();
3791   unsigned NumValValues = ValValueVTs.size();
3792   SmallVector<SDValue, 4> Values(NumAggValues);
3793 
3794   // Ignore an insertvalue that produces an empty object
3795   if (!NumAggValues) {
3796     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3797     return;
3798   }
3799 
3800   SDValue Agg = getValue(Op0);
3801   unsigned i = 0;
3802   // Copy the beginning value(s) from the original aggregate.
3803   for (; i != LinearIndex; ++i)
3804     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3805                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3806   // Copy values from the inserted value(s).
3807   if (NumValValues) {
3808     SDValue Val = getValue(Op1);
3809     for (; i != LinearIndex + NumValValues; ++i)
3810       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3811                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3812   }
3813   // Copy remaining value(s) from the original aggregate.
3814   for (; i != NumAggValues; ++i)
3815     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3816                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3817 
3818   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3819                            DAG.getVTList(AggValueVTs), Values));
3820 }
3821 
3822 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3823   ArrayRef<unsigned> Indices;
3824   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3825     Indices = EV->getIndices();
3826   else
3827     Indices = cast<ConstantExpr>(&I)->getIndices();
3828 
3829   const Value *Op0 = I.getOperand(0);
3830   Type *AggTy = Op0->getType();
3831   Type *ValTy = I.getType();
3832   bool OutOfUndef = isa<UndefValue>(Op0);
3833 
3834   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3835 
3836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3837   SmallVector<EVT, 4> ValValueVTs;
3838   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3839 
3840   unsigned NumValValues = ValValueVTs.size();
3841 
3842   // Ignore a extractvalue that produces an empty object
3843   if (!NumValValues) {
3844     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3845     return;
3846   }
3847 
3848   SmallVector<SDValue, 4> Values(NumValValues);
3849 
3850   SDValue Agg = getValue(Op0);
3851   // Copy out the selected value(s).
3852   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3853     Values[i - LinearIndex] =
3854       OutOfUndef ?
3855         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3856         SDValue(Agg.getNode(), Agg.getResNo() + i);
3857 
3858   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3859                            DAG.getVTList(ValValueVTs), Values));
3860 }
3861 
3862 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3863   Value *Op0 = I.getOperand(0);
3864   // Note that the pointer operand may be a vector of pointers. Take the scalar
3865   // element which holds a pointer.
3866   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3867   SDValue N = getValue(Op0);
3868   SDLoc dl = getCurSDLoc();
3869   auto &TLI = DAG.getTargetLoweringInfo();
3870 
3871   // Normalize Vector GEP - all scalar operands should be converted to the
3872   // splat vector.
3873   bool IsVectorGEP = I.getType()->isVectorTy();
3874   ElementCount VectorElementCount =
3875       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3876                   : ElementCount::getFixed(0);
3877 
3878   if (IsVectorGEP && !N.getValueType().isVector()) {
3879     LLVMContext &Context = *DAG.getContext();
3880     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3881     if (VectorElementCount.isScalable())
3882       N = DAG.getSplatVector(VT, dl, N);
3883     else
3884       N = DAG.getSplatBuildVector(VT, dl, N);
3885   }
3886 
3887   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3888        GTI != E; ++GTI) {
3889     const Value *Idx = GTI.getOperand();
3890     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3891       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3892       if (Field) {
3893         // N = N + Offset
3894         uint64_t Offset =
3895             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3896 
3897         // In an inbounds GEP with an offset that is nonnegative even when
3898         // interpreted as signed, assume there is no unsigned overflow.
3899         SDNodeFlags Flags;
3900         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3901           Flags.setNoUnsignedWrap(true);
3902 
3903         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3904                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3905       }
3906     } else {
3907       // IdxSize is the width of the arithmetic according to IR semantics.
3908       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3909       // (and fix up the result later).
3910       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3911       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3912       TypeSize ElementSize =
3913           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3914       // We intentionally mask away the high bits here; ElementSize may not
3915       // fit in IdxTy.
3916       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3917       bool ElementScalable = ElementSize.isScalable();
3918 
3919       // If this is a scalar constant or a splat vector of constants,
3920       // handle it quickly.
3921       const auto *C = dyn_cast<Constant>(Idx);
3922       if (C && isa<VectorType>(C->getType()))
3923         C = C->getSplatValue();
3924 
3925       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3926       if (CI && CI->isZero())
3927         continue;
3928       if (CI && !ElementScalable) {
3929         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3930         LLVMContext &Context = *DAG.getContext();
3931         SDValue OffsVal;
3932         if (IsVectorGEP)
3933           OffsVal = DAG.getConstant(
3934               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3935         else
3936           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3937 
3938         // In an inbounds GEP with an offset that is nonnegative even when
3939         // interpreted as signed, assume there is no unsigned overflow.
3940         SDNodeFlags Flags;
3941         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3942           Flags.setNoUnsignedWrap(true);
3943 
3944         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3945 
3946         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3947         continue;
3948       }
3949 
3950       // N = N + Idx * ElementMul;
3951       SDValue IdxN = getValue(Idx);
3952 
3953       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3954         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3955                                   VectorElementCount);
3956         if (VectorElementCount.isScalable())
3957           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3958         else
3959           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3960       }
3961 
3962       // If the index is smaller or larger than intptr_t, truncate or extend
3963       // it.
3964       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3965 
3966       if (ElementScalable) {
3967         EVT VScaleTy = N.getValueType().getScalarType();
3968         SDValue VScale = DAG.getNode(
3969             ISD::VSCALE, dl, VScaleTy,
3970             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3971         if (IsVectorGEP)
3972           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3973         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3974       } else {
3975         // If this is a multiply by a power of two, turn it into a shl
3976         // immediately.  This is a very common case.
3977         if (ElementMul != 1) {
3978           if (ElementMul.isPowerOf2()) {
3979             unsigned Amt = ElementMul.logBase2();
3980             IdxN = DAG.getNode(ISD::SHL, dl,
3981                                N.getValueType(), IdxN,
3982                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3983           } else {
3984             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3985                                             IdxN.getValueType());
3986             IdxN = DAG.getNode(ISD::MUL, dl,
3987                                N.getValueType(), IdxN, Scale);
3988           }
3989         }
3990       }
3991 
3992       N = DAG.getNode(ISD::ADD, dl,
3993                       N.getValueType(), N, IdxN);
3994     }
3995   }
3996 
3997   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3998   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3999   if (IsVectorGEP) {
4000     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4001     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4002   }
4003 
4004   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4005     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4006 
4007   setValue(&I, N);
4008 }
4009 
4010 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4011   // If this is a fixed sized alloca in the entry block of the function,
4012   // allocate it statically on the stack.
4013   if (FuncInfo.StaticAllocaMap.count(&I))
4014     return;   // getValue will auto-populate this.
4015 
4016   SDLoc dl = getCurSDLoc();
4017   Type *Ty = I.getAllocatedType();
4018   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4019   auto &DL = DAG.getDataLayout();
4020   TypeSize TySize = DL.getTypeAllocSize(Ty);
4021   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4022 
4023   SDValue AllocSize = getValue(I.getArraySize());
4024 
4025   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4026   if (AllocSize.getValueType() != IntPtr)
4027     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4028 
4029   if (TySize.isScalable())
4030     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4031                             DAG.getVScale(dl, IntPtr,
4032                                           APInt(IntPtr.getScalarSizeInBits(),
4033                                                 TySize.getKnownMinValue())));
4034   else
4035     AllocSize =
4036         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4037                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4038 
4039   // Handle alignment.  If the requested alignment is less than or equal to
4040   // the stack alignment, ignore it.  If the size is greater than or equal to
4041   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4042   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4043   if (*Alignment <= StackAlign)
4044     Alignment = None;
4045 
4046   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4047   // Round the size of the allocation up to the stack alignment size
4048   // by add SA-1 to the size. This doesn't overflow because we're computing
4049   // an address inside an alloca.
4050   SDNodeFlags Flags;
4051   Flags.setNoUnsignedWrap(true);
4052   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4053                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4054 
4055   // Mask out the low bits for alignment purposes.
4056   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4057                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4058 
4059   SDValue Ops[] = {
4060       getRoot(), AllocSize,
4061       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4062   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4063   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4064   setValue(&I, DSA);
4065   DAG.setRoot(DSA.getValue(1));
4066 
4067   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4068 }
4069 
4070 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4071   if (I.isAtomic())
4072     return visitAtomicLoad(I);
4073 
4074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4075   const Value *SV = I.getOperand(0);
4076   if (TLI.supportSwiftError()) {
4077     // Swifterror values can come from either a function parameter with
4078     // swifterror attribute or an alloca with swifterror attribute.
4079     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4080       if (Arg->hasSwiftErrorAttr())
4081         return visitLoadFromSwiftError(I);
4082     }
4083 
4084     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4085       if (Alloca->isSwiftError())
4086         return visitLoadFromSwiftError(I);
4087     }
4088   }
4089 
4090   SDValue Ptr = getValue(SV);
4091 
4092   Type *Ty = I.getType();
4093   Align Alignment = I.getAlign();
4094 
4095   AAMDNodes AAInfo = I.getAAMetadata();
4096   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4097 
4098   SmallVector<EVT, 4> ValueVTs, MemVTs;
4099   SmallVector<uint64_t, 4> Offsets;
4100   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4101   unsigned NumValues = ValueVTs.size();
4102   if (NumValues == 0)
4103     return;
4104 
4105   bool isVolatile = I.isVolatile();
4106 
4107   SDValue Root;
4108   bool ConstantMemory = false;
4109   if (isVolatile)
4110     // Serialize volatile loads with other side effects.
4111     Root = getRoot();
4112   else if (NumValues > MaxParallelChains)
4113     Root = getMemoryRoot();
4114   else if (AA &&
4115            AA->pointsToConstantMemory(MemoryLocation(
4116                SV,
4117                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4118                AAInfo))) {
4119     // Do not serialize (non-volatile) loads of constant memory with anything.
4120     Root = DAG.getEntryNode();
4121     ConstantMemory = true;
4122   } else {
4123     // Do not serialize non-volatile loads against each other.
4124     Root = DAG.getRoot();
4125   }
4126 
4127   SDLoc dl = getCurSDLoc();
4128 
4129   if (isVolatile)
4130     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4131 
4132   // An aggregate load cannot wrap around the address space, so offsets to its
4133   // parts don't wrap either.
4134   SDNodeFlags Flags;
4135   Flags.setNoUnsignedWrap(true);
4136 
4137   SmallVector<SDValue, 4> Values(NumValues);
4138   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4139   EVT PtrVT = Ptr.getValueType();
4140 
4141   MachineMemOperand::Flags MMOFlags
4142     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4143 
4144   unsigned ChainI = 0;
4145   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4146     // Serializing loads here may result in excessive register pressure, and
4147     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4148     // could recover a bit by hoisting nodes upward in the chain by recognizing
4149     // they are side-effect free or do not alias. The optimizer should really
4150     // avoid this case by converting large object/array copies to llvm.memcpy
4151     // (MaxParallelChains should always remain as failsafe).
4152     if (ChainI == MaxParallelChains) {
4153       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4154       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4155                                   makeArrayRef(Chains.data(), ChainI));
4156       Root = Chain;
4157       ChainI = 0;
4158     }
4159     SDValue A = DAG.getNode(ISD::ADD, dl,
4160                             PtrVT, Ptr,
4161                             DAG.getConstant(Offsets[i], dl, PtrVT),
4162                             Flags);
4163 
4164     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4165                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4166                             MMOFlags, AAInfo, Ranges);
4167     Chains[ChainI] = L.getValue(1);
4168 
4169     if (MemVTs[i] != ValueVTs[i])
4170       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4171 
4172     Values[i] = L;
4173   }
4174 
4175   if (!ConstantMemory) {
4176     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4177                                 makeArrayRef(Chains.data(), ChainI));
4178     if (isVolatile)
4179       DAG.setRoot(Chain);
4180     else
4181       PendingLoads.push_back(Chain);
4182   }
4183 
4184   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4185                            DAG.getVTList(ValueVTs), Values));
4186 }
4187 
4188 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4189   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4190          "call visitStoreToSwiftError when backend supports swifterror");
4191 
4192   SmallVector<EVT, 4> ValueVTs;
4193   SmallVector<uint64_t, 4> Offsets;
4194   const Value *SrcV = I.getOperand(0);
4195   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4196                   SrcV->getType(), ValueVTs, &Offsets);
4197   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4198          "expect a single EVT for swifterror");
4199 
4200   SDValue Src = getValue(SrcV);
4201   // Create a virtual register, then update the virtual register.
4202   Register VReg =
4203       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4204   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4205   // Chain can be getRoot or getControlRoot.
4206   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4207                                       SDValue(Src.getNode(), Src.getResNo()));
4208   DAG.setRoot(CopyNode);
4209 }
4210 
4211 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4212   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4213          "call visitLoadFromSwiftError when backend supports swifterror");
4214 
4215   assert(!I.isVolatile() &&
4216          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4217          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4218          "Support volatile, non temporal, invariant for load_from_swift_error");
4219 
4220   const Value *SV = I.getOperand(0);
4221   Type *Ty = I.getType();
4222   assert(
4223       (!AA ||
4224        !AA->pointsToConstantMemory(MemoryLocation(
4225            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4226            I.getAAMetadata()))) &&
4227       "load_from_swift_error should not be constant memory");
4228 
4229   SmallVector<EVT, 4> ValueVTs;
4230   SmallVector<uint64_t, 4> Offsets;
4231   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4232                   ValueVTs, &Offsets);
4233   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4234          "expect a single EVT for swifterror");
4235 
4236   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4237   SDValue L = DAG.getCopyFromReg(
4238       getRoot(), getCurSDLoc(),
4239       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4240 
4241   setValue(&I, L);
4242 }
4243 
4244 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4245   if (I.isAtomic())
4246     return visitAtomicStore(I);
4247 
4248   const Value *SrcV = I.getOperand(0);
4249   const Value *PtrV = I.getOperand(1);
4250 
4251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4252   if (TLI.supportSwiftError()) {
4253     // Swifterror values can come from either a function parameter with
4254     // swifterror attribute or an alloca with swifterror attribute.
4255     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4256       if (Arg->hasSwiftErrorAttr())
4257         return visitStoreToSwiftError(I);
4258     }
4259 
4260     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4261       if (Alloca->isSwiftError())
4262         return visitStoreToSwiftError(I);
4263     }
4264   }
4265 
4266   SmallVector<EVT, 4> ValueVTs, MemVTs;
4267   SmallVector<uint64_t, 4> Offsets;
4268   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4269                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4270   unsigned NumValues = ValueVTs.size();
4271   if (NumValues == 0)
4272     return;
4273 
4274   // Get the lowered operands. Note that we do this after
4275   // checking if NumResults is zero, because with zero results
4276   // the operands won't have values in the map.
4277   SDValue Src = getValue(SrcV);
4278   SDValue Ptr = getValue(PtrV);
4279 
4280   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4281   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4282   SDLoc dl = getCurSDLoc();
4283   Align Alignment = I.getAlign();
4284   AAMDNodes AAInfo = I.getAAMetadata();
4285 
4286   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4287 
4288   // An aggregate load cannot wrap around the address space, so offsets to its
4289   // parts don't wrap either.
4290   SDNodeFlags Flags;
4291   Flags.setNoUnsignedWrap(true);
4292 
4293   unsigned ChainI = 0;
4294   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4295     // See visitLoad comments.
4296     if (ChainI == MaxParallelChains) {
4297       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4298                                   makeArrayRef(Chains.data(), ChainI));
4299       Root = Chain;
4300       ChainI = 0;
4301     }
4302     SDValue Add =
4303         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4304     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4305     if (MemVTs[i] != ValueVTs[i])
4306       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4307     SDValue St =
4308         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4309                      Alignment, MMOFlags, AAInfo);
4310     Chains[ChainI] = St;
4311   }
4312 
4313   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4314                                   makeArrayRef(Chains.data(), ChainI));
4315   DAG.setRoot(StoreNode);
4316 }
4317 
4318 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4319                                            bool IsCompressing) {
4320   SDLoc sdl = getCurSDLoc();
4321 
4322   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4323                                MaybeAlign &Alignment) {
4324     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4325     Src0 = I.getArgOperand(0);
4326     Ptr = I.getArgOperand(1);
4327     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4328     Mask = I.getArgOperand(3);
4329   };
4330   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4331                                     MaybeAlign &Alignment) {
4332     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4333     Src0 = I.getArgOperand(0);
4334     Ptr = I.getArgOperand(1);
4335     Mask = I.getArgOperand(2);
4336     Alignment = None;
4337   };
4338 
4339   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4340   MaybeAlign Alignment;
4341   if (IsCompressing)
4342     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4343   else
4344     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4345 
4346   SDValue Ptr = getValue(PtrOperand);
4347   SDValue Src0 = getValue(Src0Operand);
4348   SDValue Mask = getValue(MaskOperand);
4349   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4350 
4351   EVT VT = Src0.getValueType();
4352   if (!Alignment)
4353     Alignment = DAG.getEVTAlign(VT);
4354 
4355   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4356       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4357       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4358   SDValue StoreNode =
4359       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4360                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4361   DAG.setRoot(StoreNode);
4362   setValue(&I, StoreNode);
4363 }
4364 
4365 // Get a uniform base for the Gather/Scatter intrinsic.
4366 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4367 // We try to represent it as a base pointer + vector of indices.
4368 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4369 // The first operand of the GEP may be a single pointer or a vector of pointers
4370 // Example:
4371 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4372 //  or
4373 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4374 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4375 //
4376 // When the first GEP operand is a single pointer - it is the uniform base we
4377 // are looking for. If first operand of the GEP is a splat vector - we
4378 // extract the splat value and use it as a uniform base.
4379 // In all other cases the function returns 'false'.
4380 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4381                            ISD::MemIndexType &IndexType, SDValue &Scale,
4382                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4383   SelectionDAG& DAG = SDB->DAG;
4384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4385   const DataLayout &DL = DAG.getDataLayout();
4386 
4387   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4388 
4389   // Handle splat constant pointer.
4390   if (auto *C = dyn_cast<Constant>(Ptr)) {
4391     C = C->getSplatValue();
4392     if (!C)
4393       return false;
4394 
4395     Base = SDB->getValue(C);
4396 
4397     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4398     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4399     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4400     IndexType = ISD::SIGNED_SCALED;
4401     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4402     return true;
4403   }
4404 
4405   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4406   if (!GEP || GEP->getParent() != CurBB)
4407     return false;
4408 
4409   if (GEP->getNumOperands() != 2)
4410     return false;
4411 
4412   const Value *BasePtr = GEP->getPointerOperand();
4413   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4414 
4415   // Make sure the base is scalar and the index is a vector.
4416   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4417     return false;
4418 
4419   Base = SDB->getValue(BasePtr);
4420   Index = SDB->getValue(IndexVal);
4421   IndexType = ISD::SIGNED_SCALED;
4422   Scale = DAG.getTargetConstant(
4423               DL.getTypeAllocSize(GEP->getResultElementType()),
4424               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4425   return true;
4426 }
4427 
4428 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4429   SDLoc sdl = getCurSDLoc();
4430 
4431   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4432   const Value *Ptr = I.getArgOperand(1);
4433   SDValue Src0 = getValue(I.getArgOperand(0));
4434   SDValue Mask = getValue(I.getArgOperand(3));
4435   EVT VT = Src0.getValueType();
4436   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4437                         ->getMaybeAlignValue()
4438                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4440 
4441   SDValue Base;
4442   SDValue Index;
4443   ISD::MemIndexType IndexType;
4444   SDValue Scale;
4445   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4446                                     I.getParent());
4447 
4448   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4449   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4450       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4451       // TODO: Make MachineMemOperands aware of scalable
4452       // vectors.
4453       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4454   if (!UniformBase) {
4455     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4456     Index = getValue(Ptr);
4457     IndexType = ISD::SIGNED_UNSCALED;
4458     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4459   }
4460 
4461   EVT IdxVT = Index.getValueType();
4462   EVT EltTy = IdxVT.getVectorElementType();
4463   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4464     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4465     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4466   }
4467 
4468   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4469   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4470                                          Ops, MMO, IndexType, false);
4471   DAG.setRoot(Scatter);
4472   setValue(&I, Scatter);
4473 }
4474 
4475 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4476   SDLoc sdl = getCurSDLoc();
4477 
4478   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4479                               MaybeAlign &Alignment) {
4480     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4481     Ptr = I.getArgOperand(0);
4482     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4483     Mask = I.getArgOperand(2);
4484     Src0 = I.getArgOperand(3);
4485   };
4486   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4487                                  MaybeAlign &Alignment) {
4488     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4489     Ptr = I.getArgOperand(0);
4490     Alignment = None;
4491     Mask = I.getArgOperand(1);
4492     Src0 = I.getArgOperand(2);
4493   };
4494 
4495   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4496   MaybeAlign Alignment;
4497   if (IsExpanding)
4498     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4499   else
4500     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4501 
4502   SDValue Ptr = getValue(PtrOperand);
4503   SDValue Src0 = getValue(Src0Operand);
4504   SDValue Mask = getValue(MaskOperand);
4505   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4506 
4507   EVT VT = Src0.getValueType();
4508   if (!Alignment)
4509     Alignment = DAG.getEVTAlign(VT);
4510 
4511   AAMDNodes AAInfo = I.getAAMetadata();
4512   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4513 
4514   // Do not serialize masked loads of constant memory with anything.
4515   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4516   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4517 
4518   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4519 
4520   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4521       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4522       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4523 
4524   SDValue Load =
4525       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4526                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4527   if (AddToChain)
4528     PendingLoads.push_back(Load.getValue(1));
4529   setValue(&I, Load);
4530 }
4531 
4532 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4533   SDLoc sdl = getCurSDLoc();
4534 
4535   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4536   const Value *Ptr = I.getArgOperand(0);
4537   SDValue Src0 = getValue(I.getArgOperand(3));
4538   SDValue Mask = getValue(I.getArgOperand(2));
4539 
4540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4541   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4542   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4543                         ->getMaybeAlignValue()
4544                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4545 
4546   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4547 
4548   SDValue Root = DAG.getRoot();
4549   SDValue Base;
4550   SDValue Index;
4551   ISD::MemIndexType IndexType;
4552   SDValue Scale;
4553   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4554                                     I.getParent());
4555   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4556   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4557       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4558       // TODO: Make MachineMemOperands aware of scalable
4559       // vectors.
4560       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4561 
4562   if (!UniformBase) {
4563     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4564     Index = getValue(Ptr);
4565     IndexType = ISD::SIGNED_UNSCALED;
4566     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4567   }
4568 
4569   EVT IdxVT = Index.getValueType();
4570   EVT EltTy = IdxVT.getVectorElementType();
4571   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4572     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4573     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4574   }
4575 
4576   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4577   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4578                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4579 
4580   PendingLoads.push_back(Gather.getValue(1));
4581   setValue(&I, Gather);
4582 }
4583 
4584 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4585   SDLoc dl = getCurSDLoc();
4586   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4587   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4588   SyncScope::ID SSID = I.getSyncScopeID();
4589 
4590   SDValue InChain = getRoot();
4591 
4592   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4593   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4594 
4595   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4596   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4597 
4598   MachineFunction &MF = DAG.getMachineFunction();
4599   MachineMemOperand *MMO = MF.getMachineMemOperand(
4600       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4601       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4602       FailureOrdering);
4603 
4604   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4605                                    dl, MemVT, VTs, InChain,
4606                                    getValue(I.getPointerOperand()),
4607                                    getValue(I.getCompareOperand()),
4608                                    getValue(I.getNewValOperand()), MMO);
4609 
4610   SDValue OutChain = L.getValue(2);
4611 
4612   setValue(&I, L);
4613   DAG.setRoot(OutChain);
4614 }
4615 
4616 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4617   SDLoc dl = getCurSDLoc();
4618   ISD::NodeType NT;
4619   switch (I.getOperation()) {
4620   default: llvm_unreachable("Unknown atomicrmw operation");
4621   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4622   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4623   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4624   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4625   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4626   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4627   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4628   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4629   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4630   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4631   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4632   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4633   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4634   }
4635   AtomicOrdering Ordering = I.getOrdering();
4636   SyncScope::ID SSID = I.getSyncScopeID();
4637 
4638   SDValue InChain = getRoot();
4639 
4640   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4642   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4643 
4644   MachineFunction &MF = DAG.getMachineFunction();
4645   MachineMemOperand *MMO = MF.getMachineMemOperand(
4646       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4647       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4648 
4649   SDValue L =
4650     DAG.getAtomic(NT, dl, MemVT, InChain,
4651                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4652                   MMO);
4653 
4654   SDValue OutChain = L.getValue(1);
4655 
4656   setValue(&I, L);
4657   DAG.setRoot(OutChain);
4658 }
4659 
4660 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4661   SDLoc dl = getCurSDLoc();
4662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4663   SDValue Ops[3];
4664   Ops[0] = getRoot();
4665   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4666                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4667   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4668                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4669   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4670 }
4671 
4672 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4673   SDLoc dl = getCurSDLoc();
4674   AtomicOrdering Order = I.getOrdering();
4675   SyncScope::ID SSID = I.getSyncScopeID();
4676 
4677   SDValue InChain = getRoot();
4678 
4679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4680   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4681   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4682 
4683   if (!TLI.supportsUnalignedAtomics() &&
4684       I.getAlignment() < MemVT.getSizeInBits() / 8)
4685     report_fatal_error("Cannot generate unaligned atomic load");
4686 
4687   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4688 
4689   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4690       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4691       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4692 
4693   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4694 
4695   SDValue Ptr = getValue(I.getPointerOperand());
4696 
4697   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4698     // TODO: Once this is better exercised by tests, it should be merged with
4699     // the normal path for loads to prevent future divergence.
4700     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4701     if (MemVT != VT)
4702       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4703 
4704     setValue(&I, L);
4705     SDValue OutChain = L.getValue(1);
4706     if (!I.isUnordered())
4707       DAG.setRoot(OutChain);
4708     else
4709       PendingLoads.push_back(OutChain);
4710     return;
4711   }
4712 
4713   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4714                             Ptr, MMO);
4715 
4716   SDValue OutChain = L.getValue(1);
4717   if (MemVT != VT)
4718     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4719 
4720   setValue(&I, L);
4721   DAG.setRoot(OutChain);
4722 }
4723 
4724 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4725   SDLoc dl = getCurSDLoc();
4726 
4727   AtomicOrdering Ordering = I.getOrdering();
4728   SyncScope::ID SSID = I.getSyncScopeID();
4729 
4730   SDValue InChain = getRoot();
4731 
4732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4733   EVT MemVT =
4734       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4735 
4736   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4737     report_fatal_error("Cannot generate unaligned atomic store");
4738 
4739   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4740 
4741   MachineFunction &MF = DAG.getMachineFunction();
4742   MachineMemOperand *MMO = MF.getMachineMemOperand(
4743       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4744       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4745 
4746   SDValue Val = getValue(I.getValueOperand());
4747   if (Val.getValueType() != MemVT)
4748     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4749   SDValue Ptr = getValue(I.getPointerOperand());
4750 
4751   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4752     // TODO: Once this is better exercised by tests, it should be merged with
4753     // the normal path for stores to prevent future divergence.
4754     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4755     DAG.setRoot(S);
4756     return;
4757   }
4758   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4759                                    Ptr, Val, MMO);
4760 
4761 
4762   DAG.setRoot(OutChain);
4763 }
4764 
4765 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4766 /// node.
4767 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4768                                                unsigned Intrinsic) {
4769   // Ignore the callsite's attributes. A specific call site may be marked with
4770   // readnone, but the lowering code will expect the chain based on the
4771   // definition.
4772   const Function *F = I.getCalledFunction();
4773   bool HasChain = !F->doesNotAccessMemory();
4774   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4775 
4776   // Build the operand list.
4777   SmallVector<SDValue, 8> Ops;
4778   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4779     if (OnlyLoad) {
4780       // We don't need to serialize loads against other loads.
4781       Ops.push_back(DAG.getRoot());
4782     } else {
4783       Ops.push_back(getRoot());
4784     }
4785   }
4786 
4787   // Info is set by getTgtMemInstrinsic
4788   TargetLowering::IntrinsicInfo Info;
4789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4790   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4791                                                DAG.getMachineFunction(),
4792                                                Intrinsic);
4793 
4794   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4795   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4796       Info.opc == ISD::INTRINSIC_W_CHAIN)
4797     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4798                                         TLI.getPointerTy(DAG.getDataLayout())));
4799 
4800   // Add all operands of the call to the operand list.
4801   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4802     const Value *Arg = I.getArgOperand(i);
4803     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4804       Ops.push_back(getValue(Arg));
4805       continue;
4806     }
4807 
4808     // Use TargetConstant instead of a regular constant for immarg.
4809     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4810     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4811       assert(CI->getBitWidth() <= 64 &&
4812              "large intrinsic immediates not handled");
4813       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4814     } else {
4815       Ops.push_back(
4816           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4817     }
4818   }
4819 
4820   SmallVector<EVT, 4> ValueVTs;
4821   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4822 
4823   if (HasChain)
4824     ValueVTs.push_back(MVT::Other);
4825 
4826   SDVTList VTs = DAG.getVTList(ValueVTs);
4827 
4828   // Propagate fast-math-flags from IR to node(s).
4829   SDNodeFlags Flags;
4830   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4831     Flags.copyFMF(*FPMO);
4832   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4833 
4834   // Create the node.
4835   SDValue Result;
4836   if (IsTgtIntrinsic) {
4837     // This is target intrinsic that touches memory
4838     Result =
4839         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4840                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4841                                 Info.align, Info.flags, Info.size,
4842                                 I.getAAMetadata());
4843   } else if (!HasChain) {
4844     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4845   } else if (!I.getType()->isVoidTy()) {
4846     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4847   } else {
4848     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4849   }
4850 
4851   if (HasChain) {
4852     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4853     if (OnlyLoad)
4854       PendingLoads.push_back(Chain);
4855     else
4856       DAG.setRoot(Chain);
4857   }
4858 
4859   if (!I.getType()->isVoidTy()) {
4860     if (!isa<VectorType>(I.getType()))
4861       Result = lowerRangeToAssertZExt(DAG, I, Result);
4862 
4863     MaybeAlign Alignment = I.getRetAlign();
4864     if (!Alignment)
4865       Alignment = F->getAttributes().getRetAlignment();
4866     // Insert `assertalign` node if there's an alignment.
4867     if (InsertAssertAlign && Alignment) {
4868       Result =
4869           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4870     }
4871 
4872     setValue(&I, Result);
4873   }
4874 }
4875 
4876 /// GetSignificand - Get the significand and build it into a floating-point
4877 /// number with exponent of 1:
4878 ///
4879 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4880 ///
4881 /// where Op is the hexadecimal representation of floating point value.
4882 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4883   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4884                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4885   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4886                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4887   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4888 }
4889 
4890 /// GetExponent - Get the exponent:
4891 ///
4892 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4893 ///
4894 /// where Op is the hexadecimal representation of floating point value.
4895 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4896                            const TargetLowering &TLI, const SDLoc &dl) {
4897   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4898                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4899   SDValue t1 = DAG.getNode(
4900       ISD::SRL, dl, MVT::i32, t0,
4901       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4902   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4903                            DAG.getConstant(127, dl, MVT::i32));
4904   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4905 }
4906 
4907 /// getF32Constant - Get 32-bit floating point constant.
4908 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4909                               const SDLoc &dl) {
4910   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4911                            MVT::f32);
4912 }
4913 
4914 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4915                                        SelectionDAG &DAG) {
4916   // TODO: What fast-math-flags should be set on the floating-point nodes?
4917 
4918   //   IntegerPartOfX = ((int32_t)(t0);
4919   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4920 
4921   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4922   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4923   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4924 
4925   //   IntegerPartOfX <<= 23;
4926   IntegerPartOfX = DAG.getNode(
4927       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4928       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4929                                   DAG.getDataLayout())));
4930 
4931   SDValue TwoToFractionalPartOfX;
4932   if (LimitFloatPrecision <= 6) {
4933     // For floating-point precision of 6:
4934     //
4935     //   TwoToFractionalPartOfX =
4936     //     0.997535578f +
4937     //       (0.735607626f + 0.252464424f * x) * x;
4938     //
4939     // error 0.0144103317, which is 6 bits
4940     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4941                              getF32Constant(DAG, 0x3e814304, dl));
4942     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4943                              getF32Constant(DAG, 0x3f3c50c8, dl));
4944     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4945     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4946                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4947   } else if (LimitFloatPrecision <= 12) {
4948     // For floating-point precision of 12:
4949     //
4950     //   TwoToFractionalPartOfX =
4951     //     0.999892986f +
4952     //       (0.696457318f +
4953     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4954     //
4955     // error 0.000107046256, which is 13 to 14 bits
4956     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4957                              getF32Constant(DAG, 0x3da235e3, dl));
4958     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4959                              getF32Constant(DAG, 0x3e65b8f3, dl));
4960     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4961     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4962                              getF32Constant(DAG, 0x3f324b07, dl));
4963     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4964     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4965                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4966   } else { // LimitFloatPrecision <= 18
4967     // For floating-point precision of 18:
4968     //
4969     //   TwoToFractionalPartOfX =
4970     //     0.999999982f +
4971     //       (0.693148872f +
4972     //         (0.240227044f +
4973     //           (0.554906021e-1f +
4974     //             (0.961591928e-2f +
4975     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4976     // error 2.47208000*10^(-7), which is better than 18 bits
4977     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4978                              getF32Constant(DAG, 0x3924b03e, dl));
4979     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4980                              getF32Constant(DAG, 0x3ab24b87, dl));
4981     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4982     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4983                              getF32Constant(DAG, 0x3c1d8c17, dl));
4984     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4985     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4986                              getF32Constant(DAG, 0x3d634a1d, dl));
4987     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4988     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4989                              getF32Constant(DAG, 0x3e75fe14, dl));
4990     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4991     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4992                               getF32Constant(DAG, 0x3f317234, dl));
4993     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4994     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4995                                          getF32Constant(DAG, 0x3f800000, dl));
4996   }
4997 
4998   // Add the exponent into the result in integer domain.
4999   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5000   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5001                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5002 }
5003 
5004 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5005 /// limited-precision mode.
5006 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5007                          const TargetLowering &TLI, SDNodeFlags Flags) {
5008   if (Op.getValueType() == MVT::f32 &&
5009       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5010 
5011     // Put the exponent in the right bit position for later addition to the
5012     // final result:
5013     //
5014     // t0 = Op * log2(e)
5015 
5016     // TODO: What fast-math-flags should be set here?
5017     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5018                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5019     return getLimitedPrecisionExp2(t0, dl, DAG);
5020   }
5021 
5022   // No special expansion.
5023   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5024 }
5025 
5026 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5027 /// limited-precision mode.
5028 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5029                          const TargetLowering &TLI, SDNodeFlags Flags) {
5030   // TODO: What fast-math-flags should be set on the floating-point nodes?
5031 
5032   if (Op.getValueType() == MVT::f32 &&
5033       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5034     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5035 
5036     // Scale the exponent by log(2).
5037     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5038     SDValue LogOfExponent =
5039         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5040                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5041 
5042     // Get the significand and build it into a floating-point number with
5043     // exponent of 1.
5044     SDValue X = GetSignificand(DAG, Op1, dl);
5045 
5046     SDValue LogOfMantissa;
5047     if (LimitFloatPrecision <= 6) {
5048       // For floating-point precision of 6:
5049       //
5050       //   LogofMantissa =
5051       //     -1.1609546f +
5052       //       (1.4034025f - 0.23903021f * x) * x;
5053       //
5054       // error 0.0034276066, which is better than 8 bits
5055       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5056                                getF32Constant(DAG, 0xbe74c456, dl));
5057       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5058                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5059       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5060       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5061                                   getF32Constant(DAG, 0x3f949a29, dl));
5062     } else if (LimitFloatPrecision <= 12) {
5063       // For floating-point precision of 12:
5064       //
5065       //   LogOfMantissa =
5066       //     -1.7417939f +
5067       //       (2.8212026f +
5068       //         (-1.4699568f +
5069       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5070       //
5071       // error 0.000061011436, which is 14 bits
5072       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5073                                getF32Constant(DAG, 0xbd67b6d6, dl));
5074       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5075                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5076       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5077       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5078                                getF32Constant(DAG, 0x3fbc278b, dl));
5079       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5080       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5081                                getF32Constant(DAG, 0x40348e95, dl));
5082       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5083       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5084                                   getF32Constant(DAG, 0x3fdef31a, dl));
5085     } else { // LimitFloatPrecision <= 18
5086       // For floating-point precision of 18:
5087       //
5088       //   LogOfMantissa =
5089       //     -2.1072184f +
5090       //       (4.2372794f +
5091       //         (-3.7029485f +
5092       //           (2.2781945f +
5093       //             (-0.87823314f +
5094       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5095       //
5096       // error 0.0000023660568, which is better than 18 bits
5097       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5098                                getF32Constant(DAG, 0xbc91e5ac, dl));
5099       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5100                                getF32Constant(DAG, 0x3e4350aa, dl));
5101       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5102       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5103                                getF32Constant(DAG, 0x3f60d3e3, dl));
5104       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5105       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5106                                getF32Constant(DAG, 0x4011cdf0, dl));
5107       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5108       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5109                                getF32Constant(DAG, 0x406cfd1c, dl));
5110       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5111       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5112                                getF32Constant(DAG, 0x408797cb, dl));
5113       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5114       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5115                                   getF32Constant(DAG, 0x4006dcab, dl));
5116     }
5117 
5118     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5119   }
5120 
5121   // No special expansion.
5122   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5123 }
5124 
5125 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5126 /// limited-precision mode.
5127 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5128                           const TargetLowering &TLI, SDNodeFlags Flags) {
5129   // TODO: What fast-math-flags should be set on the floating-point nodes?
5130 
5131   if (Op.getValueType() == MVT::f32 &&
5132       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5133     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5134 
5135     // Get the exponent.
5136     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5137 
5138     // Get the significand and build it into a floating-point number with
5139     // exponent of 1.
5140     SDValue X = GetSignificand(DAG, Op1, dl);
5141 
5142     // Different possible minimax approximations of significand in
5143     // floating-point for various degrees of accuracy over [1,2].
5144     SDValue Log2ofMantissa;
5145     if (LimitFloatPrecision <= 6) {
5146       // For floating-point precision of 6:
5147       //
5148       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5149       //
5150       // error 0.0049451742, which is more than 7 bits
5151       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5152                                getF32Constant(DAG, 0xbeb08fe0, dl));
5153       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5154                                getF32Constant(DAG, 0x40019463, dl));
5155       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5156       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5157                                    getF32Constant(DAG, 0x3fd6633d, dl));
5158     } else if (LimitFloatPrecision <= 12) {
5159       // For floating-point precision of 12:
5160       //
5161       //   Log2ofMantissa =
5162       //     -2.51285454f +
5163       //       (4.07009056f +
5164       //         (-2.12067489f +
5165       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5166       //
5167       // error 0.0000876136000, which is better than 13 bits
5168       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5169                                getF32Constant(DAG, 0xbda7262e, dl));
5170       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5171                                getF32Constant(DAG, 0x3f25280b, dl));
5172       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5173       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5174                                getF32Constant(DAG, 0x4007b923, dl));
5175       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5176       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5177                                getF32Constant(DAG, 0x40823e2f, dl));
5178       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5179       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5180                                    getF32Constant(DAG, 0x4020d29c, dl));
5181     } else { // LimitFloatPrecision <= 18
5182       // For floating-point precision of 18:
5183       //
5184       //   Log2ofMantissa =
5185       //     -3.0400495f +
5186       //       (6.1129976f +
5187       //         (-5.3420409f +
5188       //           (3.2865683f +
5189       //             (-1.2669343f +
5190       //               (0.27515199f -
5191       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5192       //
5193       // error 0.0000018516, which is better than 18 bits
5194       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5195                                getF32Constant(DAG, 0xbcd2769e, dl));
5196       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5197                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5198       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5199       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5200                                getF32Constant(DAG, 0x3fa22ae7, dl));
5201       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5202       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5203                                getF32Constant(DAG, 0x40525723, dl));
5204       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5205       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5206                                getF32Constant(DAG, 0x40aaf200, dl));
5207       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5208       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5209                                getF32Constant(DAG, 0x40c39dad, dl));
5210       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5211       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5212                                    getF32Constant(DAG, 0x4042902c, dl));
5213     }
5214 
5215     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5216   }
5217 
5218   // No special expansion.
5219   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5220 }
5221 
5222 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5223 /// limited-precision mode.
5224 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5225                            const TargetLowering &TLI, SDNodeFlags Flags) {
5226   // TODO: What fast-math-flags should be set on the floating-point nodes?
5227 
5228   if (Op.getValueType() == MVT::f32 &&
5229       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5230     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5231 
5232     // Scale the exponent by log10(2) [0.30102999f].
5233     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5234     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5235                                         getF32Constant(DAG, 0x3e9a209a, dl));
5236 
5237     // Get the significand and build it into a floating-point number with
5238     // exponent of 1.
5239     SDValue X = GetSignificand(DAG, Op1, dl);
5240 
5241     SDValue Log10ofMantissa;
5242     if (LimitFloatPrecision <= 6) {
5243       // For floating-point precision of 6:
5244       //
5245       //   Log10ofMantissa =
5246       //     -0.50419619f +
5247       //       (0.60948995f - 0.10380950f * x) * x;
5248       //
5249       // error 0.0014886165, which is 6 bits
5250       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5251                                getF32Constant(DAG, 0xbdd49a13, dl));
5252       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5253                                getF32Constant(DAG, 0x3f1c0789, dl));
5254       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5255       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5256                                     getF32Constant(DAG, 0x3f011300, dl));
5257     } else if (LimitFloatPrecision <= 12) {
5258       // For floating-point precision of 12:
5259       //
5260       //   Log10ofMantissa =
5261       //     -0.64831180f +
5262       //       (0.91751397f +
5263       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5264       //
5265       // error 0.00019228036, which is better than 12 bits
5266       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5267                                getF32Constant(DAG, 0x3d431f31, dl));
5268       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5269                                getF32Constant(DAG, 0x3ea21fb2, dl));
5270       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5271       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5272                                getF32Constant(DAG, 0x3f6ae232, dl));
5273       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5274       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5275                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5276     } else { // LimitFloatPrecision <= 18
5277       // For floating-point precision of 18:
5278       //
5279       //   Log10ofMantissa =
5280       //     -0.84299375f +
5281       //       (1.5327582f +
5282       //         (-1.0688956f +
5283       //           (0.49102474f +
5284       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5285       //
5286       // error 0.0000037995730, which is better than 18 bits
5287       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5288                                getF32Constant(DAG, 0x3c5d51ce, dl));
5289       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5290                                getF32Constant(DAG, 0x3e00685a, dl));
5291       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5292       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5293                                getF32Constant(DAG, 0x3efb6798, dl));
5294       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5295       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5296                                getF32Constant(DAG, 0x3f88d192, dl));
5297       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5298       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5299                                getF32Constant(DAG, 0x3fc4316c, dl));
5300       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5301       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5302                                     getF32Constant(DAG, 0x3f57ce70, dl));
5303     }
5304 
5305     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5306   }
5307 
5308   // No special expansion.
5309   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5310 }
5311 
5312 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5313 /// limited-precision mode.
5314 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5315                           const TargetLowering &TLI, SDNodeFlags Flags) {
5316   if (Op.getValueType() == MVT::f32 &&
5317       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5318     return getLimitedPrecisionExp2(Op, dl, DAG);
5319 
5320   // No special expansion.
5321   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5322 }
5323 
5324 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5325 /// limited-precision mode with x == 10.0f.
5326 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5327                          SelectionDAG &DAG, const TargetLowering &TLI,
5328                          SDNodeFlags Flags) {
5329   bool IsExp10 = false;
5330   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5331       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5332     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5333       APFloat Ten(10.0f);
5334       IsExp10 = LHSC->isExactlyValue(Ten);
5335     }
5336   }
5337 
5338   // TODO: What fast-math-flags should be set on the FMUL node?
5339   if (IsExp10) {
5340     // Put the exponent in the right bit position for later addition to the
5341     // final result:
5342     //
5343     //   #define LOG2OF10 3.3219281f
5344     //   t0 = Op * LOG2OF10;
5345     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5346                              getF32Constant(DAG, 0x40549a78, dl));
5347     return getLimitedPrecisionExp2(t0, dl, DAG);
5348   }
5349 
5350   // No special expansion.
5351   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5352 }
5353 
5354 /// ExpandPowI - Expand a llvm.powi intrinsic.
5355 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5356                           SelectionDAG &DAG) {
5357   // If RHS is a constant, we can expand this out to a multiplication tree,
5358   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5359   // optimizing for size, we only want to do this if the expansion would produce
5360   // a small number of multiplies, otherwise we do the full expansion.
5361   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5362     // Get the exponent as a positive value.
5363     unsigned Val = RHSC->getSExtValue();
5364     if ((int)Val < 0) Val = -Val;
5365 
5366     // powi(x, 0) -> 1.0
5367     if (Val == 0)
5368       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5369 
5370     bool OptForSize = DAG.shouldOptForSize();
5371     if (!OptForSize ||
5372         // If optimizing for size, don't insert too many multiplies.
5373         // This inserts up to 5 multiplies.
5374         countPopulation(Val) + Log2_32(Val) < 7) {
5375       // We use the simple binary decomposition method to generate the multiply
5376       // sequence.  There are more optimal ways to do this (for example,
5377       // powi(x,15) generates one more multiply than it should), but this has
5378       // the benefit of being both really simple and much better than a libcall.
5379       SDValue Res;  // Logically starts equal to 1.0
5380       SDValue CurSquare = LHS;
5381       // TODO: Intrinsics should have fast-math-flags that propagate to these
5382       // nodes.
5383       while (Val) {
5384         if (Val & 1) {
5385           if (Res.getNode())
5386             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5387           else
5388             Res = CurSquare;  // 1.0*CurSquare.
5389         }
5390 
5391         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5392                                 CurSquare, CurSquare);
5393         Val >>= 1;
5394       }
5395 
5396       // If the original was negative, invert the result, producing 1/(x*x*x).
5397       if (RHSC->getSExtValue() < 0)
5398         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5399                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5400       return Res;
5401     }
5402   }
5403 
5404   // Otherwise, expand to a libcall.
5405   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5406 }
5407 
5408 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5409                             SDValue LHS, SDValue RHS, SDValue Scale,
5410                             SelectionDAG &DAG, const TargetLowering &TLI) {
5411   EVT VT = LHS.getValueType();
5412   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5413   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5414   LLVMContext &Ctx = *DAG.getContext();
5415 
5416   // If the type is legal but the operation isn't, this node might survive all
5417   // the way to operation legalization. If we end up there and we do not have
5418   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5419   // node.
5420 
5421   // Coax the legalizer into expanding the node during type legalization instead
5422   // by bumping the size by one bit. This will force it to Promote, enabling the
5423   // early expansion and avoiding the need to expand later.
5424 
5425   // We don't have to do this if Scale is 0; that can always be expanded, unless
5426   // it's a saturating signed operation. Those can experience true integer
5427   // division overflow, a case which we must avoid.
5428 
5429   // FIXME: We wouldn't have to do this (or any of the early
5430   // expansion/promotion) if it was possible to expand a libcall of an
5431   // illegal type during operation legalization. But it's not, so things
5432   // get a bit hacky.
5433   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5434   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5435       (TLI.isTypeLegal(VT) ||
5436        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5437     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5438         Opcode, VT, ScaleInt);
5439     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5440       EVT PromVT;
5441       if (VT.isScalarInteger())
5442         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5443       else if (VT.isVector()) {
5444         PromVT = VT.getVectorElementType();
5445         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5446         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5447       } else
5448         llvm_unreachable("Wrong VT for DIVFIX?");
5449       if (Signed) {
5450         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5451         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5452       } else {
5453         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5454         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5455       }
5456       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5457       // For saturating operations, we need to shift up the LHS to get the
5458       // proper saturation width, and then shift down again afterwards.
5459       if (Saturating)
5460         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5461                           DAG.getConstant(1, DL, ShiftTy));
5462       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5463       if (Saturating)
5464         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5465                           DAG.getConstant(1, DL, ShiftTy));
5466       return DAG.getZExtOrTrunc(Res, DL, VT);
5467     }
5468   }
5469 
5470   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5471 }
5472 
5473 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5474 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5475 static void
5476 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5477                      const SDValue &N) {
5478   switch (N.getOpcode()) {
5479   case ISD::CopyFromReg: {
5480     SDValue Op = N.getOperand(1);
5481     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5482                       Op.getValueType().getSizeInBits());
5483     return;
5484   }
5485   case ISD::BITCAST:
5486   case ISD::AssertZext:
5487   case ISD::AssertSext:
5488   case ISD::TRUNCATE:
5489     getUnderlyingArgRegs(Regs, N.getOperand(0));
5490     return;
5491   case ISD::BUILD_PAIR:
5492   case ISD::BUILD_VECTOR:
5493   case ISD::CONCAT_VECTORS:
5494     for (SDValue Op : N->op_values())
5495       getUnderlyingArgRegs(Regs, Op);
5496     return;
5497   default:
5498     return;
5499   }
5500 }
5501 
5502 /// If the DbgValueInst is a dbg_value of a function argument, create the
5503 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5504 /// instruction selection, they will be inserted to the entry BB.
5505 /// We don't currently support this for variadic dbg_values, as they shouldn't
5506 /// appear for function arguments or in the prologue.
5507 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5508     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5509     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5510   const Argument *Arg = dyn_cast<Argument>(V);
5511   if (!Arg)
5512     return false;
5513 
5514   MachineFunction &MF = DAG.getMachineFunction();
5515   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5516 
5517   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5518   // we've been asked to pursue.
5519   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5520                               bool Indirect) {
5521     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5522       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5523       // pointing at the VReg, which will be patched up later.
5524       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5525       auto MIB = BuildMI(MF, DL, Inst);
5526       MIB.addReg(Reg);
5527       MIB.addImm(0);
5528       MIB.addMetadata(Variable);
5529       auto *NewDIExpr = FragExpr;
5530       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5531       // the DIExpression.
5532       if (Indirect)
5533         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5534       MIB.addMetadata(NewDIExpr);
5535       return MIB;
5536     } else {
5537       // Create a completely standard DBG_VALUE.
5538       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5539       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5540     }
5541   };
5542 
5543   if (!IsDbgDeclare) {
5544     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5545     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5546     // the entry block.
5547     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5548     if (!IsInEntryBlock)
5549       return false;
5550 
5551     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5552     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5553     // variable that also is a param.
5554     //
5555     // Although, if we are at the top of the entry block already, we can still
5556     // emit using ArgDbgValue. This might catch some situations when the
5557     // dbg.value refers to an argument that isn't used in the entry block, so
5558     // any CopyToReg node would be optimized out and the only way to express
5559     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5560     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5561     // we should only emit as ArgDbgValue if the Variable is an argument to the
5562     // current function, and the dbg.value intrinsic is found in the entry
5563     // block.
5564     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5565         !DL->getInlinedAt();
5566     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5567     if (!IsInPrologue && !VariableIsFunctionInputArg)
5568       return false;
5569 
5570     // Here we assume that a function argument on IR level only can be used to
5571     // describe one input parameter on source level. If we for example have
5572     // source code like this
5573     //
5574     //    struct A { long x, y; };
5575     //    void foo(struct A a, long b) {
5576     //      ...
5577     //      b = a.x;
5578     //      ...
5579     //    }
5580     //
5581     // and IR like this
5582     //
5583     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5584     //  entry:
5585     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5586     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5587     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5588     //    ...
5589     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5590     //    ...
5591     //
5592     // then the last dbg.value is describing a parameter "b" using a value that
5593     // is an argument. But since we already has used %a1 to describe a parameter
5594     // we should not handle that last dbg.value here (that would result in an
5595     // incorrect hoisting of the DBG_VALUE to the function entry).
5596     // Notice that we allow one dbg.value per IR level argument, to accommodate
5597     // for the situation with fragments above.
5598     if (VariableIsFunctionInputArg) {
5599       unsigned ArgNo = Arg->getArgNo();
5600       if (ArgNo >= FuncInfo.DescribedArgs.size())
5601         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5602       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5603         return false;
5604       FuncInfo.DescribedArgs.set(ArgNo);
5605     }
5606   }
5607 
5608   bool IsIndirect = false;
5609   Optional<MachineOperand> Op;
5610   // Some arguments' frame index is recorded during argument lowering.
5611   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5612   if (FI != std::numeric_limits<int>::max())
5613     Op = MachineOperand::CreateFI(FI);
5614 
5615   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5616   if (!Op && N.getNode()) {
5617     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5618     Register Reg;
5619     if (ArgRegsAndSizes.size() == 1)
5620       Reg = ArgRegsAndSizes.front().first;
5621 
5622     if (Reg && Reg.isVirtual()) {
5623       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5624       Register PR = RegInfo.getLiveInPhysReg(Reg);
5625       if (PR)
5626         Reg = PR;
5627     }
5628     if (Reg) {
5629       Op = MachineOperand::CreateReg(Reg, false);
5630       IsIndirect = IsDbgDeclare;
5631     }
5632   }
5633 
5634   if (!Op && N.getNode()) {
5635     // Check if frame index is available.
5636     SDValue LCandidate = peekThroughBitcasts(N);
5637     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5638       if (FrameIndexSDNode *FINode =
5639           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5640         Op = MachineOperand::CreateFI(FINode->getIndex());
5641   }
5642 
5643   if (!Op) {
5644     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5645     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5646                                          SplitRegs) {
5647       unsigned Offset = 0;
5648       for (const auto &RegAndSize : SplitRegs) {
5649         // If the expression is already a fragment, the current register
5650         // offset+size might extend beyond the fragment. In this case, only
5651         // the register bits that are inside the fragment are relevant.
5652         int RegFragmentSizeInBits = RegAndSize.second;
5653         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5654           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5655           // The register is entirely outside the expression fragment,
5656           // so is irrelevant for debug info.
5657           if (Offset >= ExprFragmentSizeInBits)
5658             break;
5659           // The register is partially outside the expression fragment, only
5660           // the low bits within the fragment are relevant for debug info.
5661           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5662             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5663           }
5664         }
5665 
5666         auto FragmentExpr = DIExpression::createFragmentExpression(
5667             Expr, Offset, RegFragmentSizeInBits);
5668         Offset += RegAndSize.second;
5669         // If a valid fragment expression cannot be created, the variable's
5670         // correct value cannot be determined and so it is set as Undef.
5671         if (!FragmentExpr) {
5672           SDDbgValue *SDV = DAG.getConstantDbgValue(
5673               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5674           DAG.AddDbgValue(SDV, false);
5675           continue;
5676         }
5677         MachineInstr *NewMI =
5678             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5679         FuncInfo.ArgDbgValues.push_back(NewMI);
5680       }
5681     };
5682 
5683     // Check if ValueMap has reg number.
5684     DenseMap<const Value *, Register>::const_iterator
5685       VMI = FuncInfo.ValueMap.find(V);
5686     if (VMI != FuncInfo.ValueMap.end()) {
5687       const auto &TLI = DAG.getTargetLoweringInfo();
5688       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5689                        V->getType(), None);
5690       if (RFV.occupiesMultipleRegs()) {
5691         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5692         return true;
5693       }
5694 
5695       Op = MachineOperand::CreateReg(VMI->second, false);
5696       IsIndirect = IsDbgDeclare;
5697     } else if (ArgRegsAndSizes.size() > 1) {
5698       // This was split due to the calling convention, and no virtual register
5699       // mapping exists for the value.
5700       splitMultiRegDbgValue(ArgRegsAndSizes);
5701       return true;
5702     }
5703   }
5704 
5705   if (!Op)
5706     return false;
5707 
5708   assert(Variable->isValidLocationForIntrinsic(DL) &&
5709          "Expected inlined-at fields to agree");
5710   MachineInstr *NewMI = nullptr;
5711 
5712   if (Op->isReg())
5713     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5714   else
5715     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5716                     Variable, Expr);
5717 
5718   FuncInfo.ArgDbgValues.push_back(NewMI);
5719   return true;
5720 }
5721 
5722 /// Return the appropriate SDDbgValue based on N.
5723 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5724                                              DILocalVariable *Variable,
5725                                              DIExpression *Expr,
5726                                              const DebugLoc &dl,
5727                                              unsigned DbgSDNodeOrder) {
5728   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5729     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5730     // stack slot locations.
5731     //
5732     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5733     // debug values here after optimization:
5734     //
5735     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5736     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5737     //
5738     // Both describe the direct values of their associated variables.
5739     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5740                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5741   }
5742   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5743                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5744 }
5745 
5746 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5747   switch (Intrinsic) {
5748   case Intrinsic::smul_fix:
5749     return ISD::SMULFIX;
5750   case Intrinsic::umul_fix:
5751     return ISD::UMULFIX;
5752   case Intrinsic::smul_fix_sat:
5753     return ISD::SMULFIXSAT;
5754   case Intrinsic::umul_fix_sat:
5755     return ISD::UMULFIXSAT;
5756   case Intrinsic::sdiv_fix:
5757     return ISD::SDIVFIX;
5758   case Intrinsic::udiv_fix:
5759     return ISD::UDIVFIX;
5760   case Intrinsic::sdiv_fix_sat:
5761     return ISD::SDIVFIXSAT;
5762   case Intrinsic::udiv_fix_sat:
5763     return ISD::UDIVFIXSAT;
5764   default:
5765     llvm_unreachable("Unhandled fixed point intrinsic");
5766   }
5767 }
5768 
5769 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5770                                            const char *FunctionName) {
5771   assert(FunctionName && "FunctionName must not be nullptr");
5772   SDValue Callee = DAG.getExternalSymbol(
5773       FunctionName,
5774       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5775   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5776 }
5777 
5778 /// Given a @llvm.call.preallocated.setup, return the corresponding
5779 /// preallocated call.
5780 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5781   assert(cast<CallBase>(PreallocatedSetup)
5782                  ->getCalledFunction()
5783                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5784          "expected call_preallocated_setup Value");
5785   for (auto *U : PreallocatedSetup->users()) {
5786     auto *UseCall = cast<CallBase>(U);
5787     const Function *Fn = UseCall->getCalledFunction();
5788     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5789       return UseCall;
5790     }
5791   }
5792   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5793 }
5794 
5795 /// Lower the call to the specified intrinsic function.
5796 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5797                                              unsigned Intrinsic) {
5798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5799   SDLoc sdl = getCurSDLoc();
5800   DebugLoc dl = getCurDebugLoc();
5801   SDValue Res;
5802 
5803   SDNodeFlags Flags;
5804   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5805     Flags.copyFMF(*FPOp);
5806 
5807   switch (Intrinsic) {
5808   default:
5809     // By default, turn this into a target intrinsic node.
5810     visitTargetIntrinsic(I, Intrinsic);
5811     return;
5812   case Intrinsic::vscale: {
5813     match(&I, m_VScale(DAG.getDataLayout()));
5814     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5815     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5816     return;
5817   }
5818   case Intrinsic::vastart:  visitVAStart(I); return;
5819   case Intrinsic::vaend:    visitVAEnd(I); return;
5820   case Intrinsic::vacopy:   visitVACopy(I); return;
5821   case Intrinsic::returnaddress:
5822     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5823                              TLI.getPointerTy(DAG.getDataLayout()),
5824                              getValue(I.getArgOperand(0))));
5825     return;
5826   case Intrinsic::addressofreturnaddress:
5827     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5828                              TLI.getPointerTy(DAG.getDataLayout())));
5829     return;
5830   case Intrinsic::sponentry:
5831     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5832                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5833     return;
5834   case Intrinsic::frameaddress:
5835     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5836                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5837                              getValue(I.getArgOperand(0))));
5838     return;
5839   case Intrinsic::read_volatile_register:
5840   case Intrinsic::read_register: {
5841     Value *Reg = I.getArgOperand(0);
5842     SDValue Chain = getRoot();
5843     SDValue RegName =
5844         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5845     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5846     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5847       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5848     setValue(&I, Res);
5849     DAG.setRoot(Res.getValue(1));
5850     return;
5851   }
5852   case Intrinsic::write_register: {
5853     Value *Reg = I.getArgOperand(0);
5854     Value *RegValue = I.getArgOperand(1);
5855     SDValue Chain = getRoot();
5856     SDValue RegName =
5857         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5858     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5859                             RegName, getValue(RegValue)));
5860     return;
5861   }
5862   case Intrinsic::memcpy: {
5863     const auto &MCI = cast<MemCpyInst>(I);
5864     SDValue Op1 = getValue(I.getArgOperand(0));
5865     SDValue Op2 = getValue(I.getArgOperand(1));
5866     SDValue Op3 = getValue(I.getArgOperand(2));
5867     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5868     Align DstAlign = MCI.getDestAlign().valueOrOne();
5869     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5870     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5871     bool isVol = MCI.isVolatile();
5872     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5873     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5874     // node.
5875     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5876     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5877                                /* AlwaysInline */ false, isTC,
5878                                MachinePointerInfo(I.getArgOperand(0)),
5879                                MachinePointerInfo(I.getArgOperand(1)),
5880                                I.getAAMetadata());
5881     updateDAGForMaybeTailCall(MC);
5882     return;
5883   }
5884   case Intrinsic::memcpy_inline: {
5885     const auto &MCI = cast<MemCpyInlineInst>(I);
5886     SDValue Dst = getValue(I.getArgOperand(0));
5887     SDValue Src = getValue(I.getArgOperand(1));
5888     SDValue Size = getValue(I.getArgOperand(2));
5889     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5890     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5891     Align DstAlign = MCI.getDestAlign().valueOrOne();
5892     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5893     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5894     bool isVol = MCI.isVolatile();
5895     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5896     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5897     // node.
5898     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5899                                /* AlwaysInline */ true, isTC,
5900                                MachinePointerInfo(I.getArgOperand(0)),
5901                                MachinePointerInfo(I.getArgOperand(1)),
5902                                I.getAAMetadata());
5903     updateDAGForMaybeTailCall(MC);
5904     return;
5905   }
5906   case Intrinsic::memset: {
5907     const auto &MSI = cast<MemSetInst>(I);
5908     SDValue Op1 = getValue(I.getArgOperand(0));
5909     SDValue Op2 = getValue(I.getArgOperand(1));
5910     SDValue Op3 = getValue(I.getArgOperand(2));
5911     // @llvm.memset defines 0 and 1 to both mean no alignment.
5912     Align Alignment = MSI.getDestAlign().valueOrOne();
5913     bool isVol = MSI.isVolatile();
5914     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5915     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5916     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5917                                MachinePointerInfo(I.getArgOperand(0)),
5918                                I.getAAMetadata());
5919     updateDAGForMaybeTailCall(MS);
5920     return;
5921   }
5922   case Intrinsic::memmove: {
5923     const auto &MMI = cast<MemMoveInst>(I);
5924     SDValue Op1 = getValue(I.getArgOperand(0));
5925     SDValue Op2 = getValue(I.getArgOperand(1));
5926     SDValue Op3 = getValue(I.getArgOperand(2));
5927     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5928     Align DstAlign = MMI.getDestAlign().valueOrOne();
5929     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5930     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5931     bool isVol = MMI.isVolatile();
5932     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5933     // FIXME: Support passing different dest/src alignments to the memmove DAG
5934     // node.
5935     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5936     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5937                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5938                                 MachinePointerInfo(I.getArgOperand(1)),
5939                                 I.getAAMetadata());
5940     updateDAGForMaybeTailCall(MM);
5941     return;
5942   }
5943   case Intrinsic::memcpy_element_unordered_atomic: {
5944     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5945     SDValue Dst = getValue(MI.getRawDest());
5946     SDValue Src = getValue(MI.getRawSource());
5947     SDValue Length = getValue(MI.getLength());
5948 
5949     unsigned DstAlign = MI.getDestAlignment();
5950     unsigned SrcAlign = MI.getSourceAlignment();
5951     Type *LengthTy = MI.getLength()->getType();
5952     unsigned ElemSz = MI.getElementSizeInBytes();
5953     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5954     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5955                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5956                                      MachinePointerInfo(MI.getRawDest()),
5957                                      MachinePointerInfo(MI.getRawSource()));
5958     updateDAGForMaybeTailCall(MC);
5959     return;
5960   }
5961   case Intrinsic::memmove_element_unordered_atomic: {
5962     auto &MI = cast<AtomicMemMoveInst>(I);
5963     SDValue Dst = getValue(MI.getRawDest());
5964     SDValue Src = getValue(MI.getRawSource());
5965     SDValue Length = getValue(MI.getLength());
5966 
5967     unsigned DstAlign = MI.getDestAlignment();
5968     unsigned SrcAlign = MI.getSourceAlignment();
5969     Type *LengthTy = MI.getLength()->getType();
5970     unsigned ElemSz = MI.getElementSizeInBytes();
5971     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5972     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5973                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5974                                       MachinePointerInfo(MI.getRawDest()),
5975                                       MachinePointerInfo(MI.getRawSource()));
5976     updateDAGForMaybeTailCall(MC);
5977     return;
5978   }
5979   case Intrinsic::memset_element_unordered_atomic: {
5980     auto &MI = cast<AtomicMemSetInst>(I);
5981     SDValue Dst = getValue(MI.getRawDest());
5982     SDValue Val = getValue(MI.getValue());
5983     SDValue Length = getValue(MI.getLength());
5984 
5985     unsigned DstAlign = MI.getDestAlignment();
5986     Type *LengthTy = MI.getLength()->getType();
5987     unsigned ElemSz = MI.getElementSizeInBytes();
5988     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5989     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5990                                      LengthTy, ElemSz, isTC,
5991                                      MachinePointerInfo(MI.getRawDest()));
5992     updateDAGForMaybeTailCall(MC);
5993     return;
5994   }
5995   case Intrinsic::call_preallocated_setup: {
5996     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5997     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5998     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5999                               getRoot(), SrcValue);
6000     setValue(&I, Res);
6001     DAG.setRoot(Res);
6002     return;
6003   }
6004   case Intrinsic::call_preallocated_arg: {
6005     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6006     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6007     SDValue Ops[3];
6008     Ops[0] = getRoot();
6009     Ops[1] = SrcValue;
6010     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6011                                    MVT::i32); // arg index
6012     SDValue Res = DAG.getNode(
6013         ISD::PREALLOCATED_ARG, sdl,
6014         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6015     setValue(&I, Res);
6016     DAG.setRoot(Res.getValue(1));
6017     return;
6018   }
6019   case Intrinsic::dbg_addr:
6020   case Intrinsic::dbg_declare: {
6021     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6022     // they are non-variadic.
6023     const auto &DI = cast<DbgVariableIntrinsic>(I);
6024     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6025     DILocalVariable *Variable = DI.getVariable();
6026     DIExpression *Expression = DI.getExpression();
6027     dropDanglingDebugInfo(Variable, Expression);
6028     assert(Variable && "Missing variable");
6029     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6030                       << "\n");
6031     // Check if address has undef value.
6032     const Value *Address = DI.getVariableLocationOp(0);
6033     if (!Address || isa<UndefValue>(Address) ||
6034         (Address->use_empty() && !isa<Argument>(Address))) {
6035       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6036                         << " (bad/undef/unused-arg address)\n");
6037       return;
6038     }
6039 
6040     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6041 
6042     // Check if this variable can be described by a frame index, typically
6043     // either as a static alloca or a byval parameter.
6044     int FI = std::numeric_limits<int>::max();
6045     if (const auto *AI =
6046             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6047       if (AI->isStaticAlloca()) {
6048         auto I = FuncInfo.StaticAllocaMap.find(AI);
6049         if (I != FuncInfo.StaticAllocaMap.end())
6050           FI = I->second;
6051       }
6052     } else if (const auto *Arg = dyn_cast<Argument>(
6053                    Address->stripInBoundsConstantOffsets())) {
6054       FI = FuncInfo.getArgumentFrameIndex(Arg);
6055     }
6056 
6057     // llvm.dbg.addr is control dependent and always generates indirect
6058     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6059     // the MachineFunction variable table.
6060     if (FI != std::numeric_limits<int>::max()) {
6061       if (Intrinsic == Intrinsic::dbg_addr) {
6062         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6063             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6064             dl, SDNodeOrder);
6065         DAG.AddDbgValue(SDV, isParameter);
6066       } else {
6067         LLVM_DEBUG(dbgs() << "Skipping " << DI
6068                           << " (variable info stashed in MF side table)\n");
6069       }
6070       return;
6071     }
6072 
6073     SDValue &N = NodeMap[Address];
6074     if (!N.getNode() && isa<Argument>(Address))
6075       // Check unused arguments map.
6076       N = UnusedArgNodeMap[Address];
6077     SDDbgValue *SDV;
6078     if (N.getNode()) {
6079       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6080         Address = BCI->getOperand(0);
6081       // Parameters are handled specially.
6082       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6083       if (isParameter && FINode) {
6084         // Byval parameter. We have a frame index at this point.
6085         SDV =
6086             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6087                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6088       } else if (isa<Argument>(Address)) {
6089         // Address is an argument, so try to emit its dbg value using
6090         // virtual register info from the FuncInfo.ValueMap.
6091         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6092         return;
6093       } else {
6094         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6095                               true, dl, SDNodeOrder);
6096       }
6097       DAG.AddDbgValue(SDV, isParameter);
6098     } else {
6099       // If Address is an argument then try to emit its dbg value using
6100       // virtual register info from the FuncInfo.ValueMap.
6101       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6102                                     N)) {
6103         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6104                           << " (could not emit func-arg dbg_value)\n");
6105       }
6106     }
6107     return;
6108   }
6109   case Intrinsic::dbg_label: {
6110     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6111     DILabel *Label = DI.getLabel();
6112     assert(Label && "Missing label");
6113 
6114     SDDbgLabel *SDV;
6115     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6116     DAG.AddDbgLabel(SDV);
6117     return;
6118   }
6119   case Intrinsic::dbg_value: {
6120     const DbgValueInst &DI = cast<DbgValueInst>(I);
6121     assert(DI.getVariable() && "Missing variable");
6122 
6123     DILocalVariable *Variable = DI.getVariable();
6124     DIExpression *Expression = DI.getExpression();
6125     dropDanglingDebugInfo(Variable, Expression);
6126     SmallVector<Value *, 4> Values(DI.getValues());
6127     if (Values.empty())
6128       return;
6129 
6130     if (llvm::is_contained(Values, nullptr))
6131       return;
6132 
6133     bool IsVariadic = DI.hasArgList();
6134     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6135                           SDNodeOrder, IsVariadic))
6136       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6137     return;
6138   }
6139 
6140   case Intrinsic::eh_typeid_for: {
6141     // Find the type id for the given typeinfo.
6142     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6143     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6144     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6145     setValue(&I, Res);
6146     return;
6147   }
6148 
6149   case Intrinsic::eh_return_i32:
6150   case Intrinsic::eh_return_i64:
6151     DAG.getMachineFunction().setCallsEHReturn(true);
6152     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6153                             MVT::Other,
6154                             getControlRoot(),
6155                             getValue(I.getArgOperand(0)),
6156                             getValue(I.getArgOperand(1))));
6157     return;
6158   case Intrinsic::eh_unwind_init:
6159     DAG.getMachineFunction().setCallsUnwindInit(true);
6160     return;
6161   case Intrinsic::eh_dwarf_cfa:
6162     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6163                              TLI.getPointerTy(DAG.getDataLayout()),
6164                              getValue(I.getArgOperand(0))));
6165     return;
6166   case Intrinsic::eh_sjlj_callsite: {
6167     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6168     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6169     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6170     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6171 
6172     MMI.setCurrentCallSite(CI->getZExtValue());
6173     return;
6174   }
6175   case Intrinsic::eh_sjlj_functioncontext: {
6176     // Get and store the index of the function context.
6177     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6178     AllocaInst *FnCtx =
6179       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6180     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6181     MFI.setFunctionContextIndex(FI);
6182     return;
6183   }
6184   case Intrinsic::eh_sjlj_setjmp: {
6185     SDValue Ops[2];
6186     Ops[0] = getRoot();
6187     Ops[1] = getValue(I.getArgOperand(0));
6188     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6189                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6190     setValue(&I, Op.getValue(0));
6191     DAG.setRoot(Op.getValue(1));
6192     return;
6193   }
6194   case Intrinsic::eh_sjlj_longjmp:
6195     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6196                             getRoot(), getValue(I.getArgOperand(0))));
6197     return;
6198   case Intrinsic::eh_sjlj_setup_dispatch:
6199     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6200                             getRoot()));
6201     return;
6202   case Intrinsic::masked_gather:
6203     visitMaskedGather(I);
6204     return;
6205   case Intrinsic::masked_load:
6206     visitMaskedLoad(I);
6207     return;
6208   case Intrinsic::masked_scatter:
6209     visitMaskedScatter(I);
6210     return;
6211   case Intrinsic::masked_store:
6212     visitMaskedStore(I);
6213     return;
6214   case Intrinsic::masked_expandload:
6215     visitMaskedLoad(I, true /* IsExpanding */);
6216     return;
6217   case Intrinsic::masked_compressstore:
6218     visitMaskedStore(I, true /* IsCompressing */);
6219     return;
6220   case Intrinsic::powi:
6221     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6222                             getValue(I.getArgOperand(1)), DAG));
6223     return;
6224   case Intrinsic::log:
6225     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6226     return;
6227   case Intrinsic::log2:
6228     setValue(&I,
6229              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6230     return;
6231   case Intrinsic::log10:
6232     setValue(&I,
6233              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6234     return;
6235   case Intrinsic::exp:
6236     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6237     return;
6238   case Intrinsic::exp2:
6239     setValue(&I,
6240              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6241     return;
6242   case Intrinsic::pow:
6243     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6244                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6245     return;
6246   case Intrinsic::sqrt:
6247   case Intrinsic::fabs:
6248   case Intrinsic::sin:
6249   case Intrinsic::cos:
6250   case Intrinsic::floor:
6251   case Intrinsic::ceil:
6252   case Intrinsic::trunc:
6253   case Intrinsic::rint:
6254   case Intrinsic::nearbyint:
6255   case Intrinsic::round:
6256   case Intrinsic::roundeven:
6257   case Intrinsic::canonicalize: {
6258     unsigned Opcode;
6259     switch (Intrinsic) {
6260     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6261     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6262     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6263     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6264     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6265     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6266     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6267     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6268     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6269     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6270     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6271     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6272     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6273     }
6274 
6275     setValue(&I, DAG.getNode(Opcode, sdl,
6276                              getValue(I.getArgOperand(0)).getValueType(),
6277                              getValue(I.getArgOperand(0)), Flags));
6278     return;
6279   }
6280   case Intrinsic::lround:
6281   case Intrinsic::llround:
6282   case Intrinsic::lrint:
6283   case Intrinsic::llrint: {
6284     unsigned Opcode;
6285     switch (Intrinsic) {
6286     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6287     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6288     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6289     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6290     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6291     }
6292 
6293     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6294     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6295                              getValue(I.getArgOperand(0))));
6296     return;
6297   }
6298   case Intrinsic::minnum:
6299     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6300                              getValue(I.getArgOperand(0)).getValueType(),
6301                              getValue(I.getArgOperand(0)),
6302                              getValue(I.getArgOperand(1)), Flags));
6303     return;
6304   case Intrinsic::maxnum:
6305     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6306                              getValue(I.getArgOperand(0)).getValueType(),
6307                              getValue(I.getArgOperand(0)),
6308                              getValue(I.getArgOperand(1)), Flags));
6309     return;
6310   case Intrinsic::minimum:
6311     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6312                              getValue(I.getArgOperand(0)).getValueType(),
6313                              getValue(I.getArgOperand(0)),
6314                              getValue(I.getArgOperand(1)), Flags));
6315     return;
6316   case Intrinsic::maximum:
6317     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6318                              getValue(I.getArgOperand(0)).getValueType(),
6319                              getValue(I.getArgOperand(0)),
6320                              getValue(I.getArgOperand(1)), Flags));
6321     return;
6322   case Intrinsic::copysign:
6323     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6324                              getValue(I.getArgOperand(0)).getValueType(),
6325                              getValue(I.getArgOperand(0)),
6326                              getValue(I.getArgOperand(1)), Flags));
6327     return;
6328   case Intrinsic::arithmetic_fence: {
6329     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6330                              getValue(I.getArgOperand(0)).getValueType(),
6331                              getValue(I.getArgOperand(0)), Flags));
6332     return;
6333   }
6334   case Intrinsic::fma:
6335     setValue(&I, DAG.getNode(
6336                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6337                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6338                      getValue(I.getArgOperand(2)), Flags));
6339     return;
6340 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6341   case Intrinsic::INTRINSIC:
6342 #include "llvm/IR/ConstrainedOps.def"
6343     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6344     return;
6345 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6346 #include "llvm/IR/VPIntrinsics.def"
6347     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6348     return;
6349   case Intrinsic::fmuladd: {
6350     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6351     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6352         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6353       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6354                                getValue(I.getArgOperand(0)).getValueType(),
6355                                getValue(I.getArgOperand(0)),
6356                                getValue(I.getArgOperand(1)),
6357                                getValue(I.getArgOperand(2)), Flags));
6358     } else {
6359       // TODO: Intrinsic calls should have fast-math-flags.
6360       SDValue Mul = DAG.getNode(
6361           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6362           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6363       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6364                                 getValue(I.getArgOperand(0)).getValueType(),
6365                                 Mul, getValue(I.getArgOperand(2)), Flags);
6366       setValue(&I, Add);
6367     }
6368     return;
6369   }
6370   case Intrinsic::convert_to_fp16:
6371     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6372                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6373                                          getValue(I.getArgOperand(0)),
6374                                          DAG.getTargetConstant(0, sdl,
6375                                                                MVT::i32))));
6376     return;
6377   case Intrinsic::convert_from_fp16:
6378     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6379                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6380                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6381                                          getValue(I.getArgOperand(0)))));
6382     return;
6383   case Intrinsic::fptosi_sat: {
6384     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6385     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6386                              getValue(I.getArgOperand(0)),
6387                              DAG.getValueType(VT.getScalarType())));
6388     return;
6389   }
6390   case Intrinsic::fptoui_sat: {
6391     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6392     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6393                              getValue(I.getArgOperand(0)),
6394                              DAG.getValueType(VT.getScalarType())));
6395     return;
6396   }
6397   case Intrinsic::set_rounding:
6398     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6399                       {getRoot(), getValue(I.getArgOperand(0))});
6400     setValue(&I, Res);
6401     DAG.setRoot(Res.getValue(0));
6402     return;
6403   case Intrinsic::pcmarker: {
6404     SDValue Tmp = getValue(I.getArgOperand(0));
6405     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6406     return;
6407   }
6408   case Intrinsic::readcyclecounter: {
6409     SDValue Op = getRoot();
6410     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6411                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6412     setValue(&I, Res);
6413     DAG.setRoot(Res.getValue(1));
6414     return;
6415   }
6416   case Intrinsic::bitreverse:
6417     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6418                              getValue(I.getArgOperand(0)).getValueType(),
6419                              getValue(I.getArgOperand(0))));
6420     return;
6421   case Intrinsic::bswap:
6422     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6423                              getValue(I.getArgOperand(0)).getValueType(),
6424                              getValue(I.getArgOperand(0))));
6425     return;
6426   case Intrinsic::cttz: {
6427     SDValue Arg = getValue(I.getArgOperand(0));
6428     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6429     EVT Ty = Arg.getValueType();
6430     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6431                              sdl, Ty, Arg));
6432     return;
6433   }
6434   case Intrinsic::ctlz: {
6435     SDValue Arg = getValue(I.getArgOperand(0));
6436     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6437     EVT Ty = Arg.getValueType();
6438     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6439                              sdl, Ty, Arg));
6440     return;
6441   }
6442   case Intrinsic::ctpop: {
6443     SDValue Arg = getValue(I.getArgOperand(0));
6444     EVT Ty = Arg.getValueType();
6445     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6446     return;
6447   }
6448   case Intrinsic::fshl:
6449   case Intrinsic::fshr: {
6450     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6451     SDValue X = getValue(I.getArgOperand(0));
6452     SDValue Y = getValue(I.getArgOperand(1));
6453     SDValue Z = getValue(I.getArgOperand(2));
6454     EVT VT = X.getValueType();
6455 
6456     if (X == Y) {
6457       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6458       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6459     } else {
6460       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6461       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6462     }
6463     return;
6464   }
6465   case Intrinsic::sadd_sat: {
6466     SDValue Op1 = getValue(I.getArgOperand(0));
6467     SDValue Op2 = getValue(I.getArgOperand(1));
6468     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6469     return;
6470   }
6471   case Intrinsic::uadd_sat: {
6472     SDValue Op1 = getValue(I.getArgOperand(0));
6473     SDValue Op2 = getValue(I.getArgOperand(1));
6474     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6475     return;
6476   }
6477   case Intrinsic::ssub_sat: {
6478     SDValue Op1 = getValue(I.getArgOperand(0));
6479     SDValue Op2 = getValue(I.getArgOperand(1));
6480     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6481     return;
6482   }
6483   case Intrinsic::usub_sat: {
6484     SDValue Op1 = getValue(I.getArgOperand(0));
6485     SDValue Op2 = getValue(I.getArgOperand(1));
6486     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6487     return;
6488   }
6489   case Intrinsic::sshl_sat: {
6490     SDValue Op1 = getValue(I.getArgOperand(0));
6491     SDValue Op2 = getValue(I.getArgOperand(1));
6492     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6493     return;
6494   }
6495   case Intrinsic::ushl_sat: {
6496     SDValue Op1 = getValue(I.getArgOperand(0));
6497     SDValue Op2 = getValue(I.getArgOperand(1));
6498     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6499     return;
6500   }
6501   case Intrinsic::smul_fix:
6502   case Intrinsic::umul_fix:
6503   case Intrinsic::smul_fix_sat:
6504   case Intrinsic::umul_fix_sat: {
6505     SDValue Op1 = getValue(I.getArgOperand(0));
6506     SDValue Op2 = getValue(I.getArgOperand(1));
6507     SDValue Op3 = getValue(I.getArgOperand(2));
6508     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6509                              Op1.getValueType(), Op1, Op2, Op3));
6510     return;
6511   }
6512   case Intrinsic::sdiv_fix:
6513   case Intrinsic::udiv_fix:
6514   case Intrinsic::sdiv_fix_sat:
6515   case Intrinsic::udiv_fix_sat: {
6516     SDValue Op1 = getValue(I.getArgOperand(0));
6517     SDValue Op2 = getValue(I.getArgOperand(1));
6518     SDValue Op3 = getValue(I.getArgOperand(2));
6519     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6520                               Op1, Op2, Op3, DAG, TLI));
6521     return;
6522   }
6523   case Intrinsic::smax: {
6524     SDValue Op1 = getValue(I.getArgOperand(0));
6525     SDValue Op2 = getValue(I.getArgOperand(1));
6526     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6527     return;
6528   }
6529   case Intrinsic::smin: {
6530     SDValue Op1 = getValue(I.getArgOperand(0));
6531     SDValue Op2 = getValue(I.getArgOperand(1));
6532     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6533     return;
6534   }
6535   case Intrinsic::umax: {
6536     SDValue Op1 = getValue(I.getArgOperand(0));
6537     SDValue Op2 = getValue(I.getArgOperand(1));
6538     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6539     return;
6540   }
6541   case Intrinsic::umin: {
6542     SDValue Op1 = getValue(I.getArgOperand(0));
6543     SDValue Op2 = getValue(I.getArgOperand(1));
6544     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6545     return;
6546   }
6547   case Intrinsic::abs: {
6548     // TODO: Preserve "int min is poison" arg in SDAG?
6549     SDValue Op1 = getValue(I.getArgOperand(0));
6550     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6551     return;
6552   }
6553   case Intrinsic::stacksave: {
6554     SDValue Op = getRoot();
6555     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6556     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6557     setValue(&I, Res);
6558     DAG.setRoot(Res.getValue(1));
6559     return;
6560   }
6561   case Intrinsic::stackrestore:
6562     Res = getValue(I.getArgOperand(0));
6563     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6564     return;
6565   case Intrinsic::get_dynamic_area_offset: {
6566     SDValue Op = getRoot();
6567     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6568     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6569     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6570     // target.
6571     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6572       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6573                          " intrinsic!");
6574     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6575                       Op);
6576     DAG.setRoot(Op);
6577     setValue(&I, Res);
6578     return;
6579   }
6580   case Intrinsic::stackguard: {
6581     MachineFunction &MF = DAG.getMachineFunction();
6582     const Module &M = *MF.getFunction().getParent();
6583     SDValue Chain = getRoot();
6584     if (TLI.useLoadStackGuardNode()) {
6585       Res = getLoadStackGuard(DAG, sdl, Chain);
6586     } else {
6587       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6588       const Value *Global = TLI.getSDagStackGuard(M);
6589       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6590       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6591                         MachinePointerInfo(Global, 0), Align,
6592                         MachineMemOperand::MOVolatile);
6593     }
6594     if (TLI.useStackGuardXorFP())
6595       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6596     DAG.setRoot(Chain);
6597     setValue(&I, Res);
6598     return;
6599   }
6600   case Intrinsic::stackprotector: {
6601     // Emit code into the DAG to store the stack guard onto the stack.
6602     MachineFunction &MF = DAG.getMachineFunction();
6603     MachineFrameInfo &MFI = MF.getFrameInfo();
6604     SDValue Src, Chain = getRoot();
6605 
6606     if (TLI.useLoadStackGuardNode())
6607       Src = getLoadStackGuard(DAG, sdl, Chain);
6608     else
6609       Src = getValue(I.getArgOperand(0));   // The guard's value.
6610 
6611     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6612 
6613     int FI = FuncInfo.StaticAllocaMap[Slot];
6614     MFI.setStackProtectorIndex(FI);
6615     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6616 
6617     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6618 
6619     // Store the stack protector onto the stack.
6620     Res = DAG.getStore(
6621         Chain, sdl, Src, FIN,
6622         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6623         MaybeAlign(), MachineMemOperand::MOVolatile);
6624     setValue(&I, Res);
6625     DAG.setRoot(Res);
6626     return;
6627   }
6628   case Intrinsic::objectsize:
6629     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6630 
6631   case Intrinsic::is_constant:
6632     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6633 
6634   case Intrinsic::annotation:
6635   case Intrinsic::ptr_annotation:
6636   case Intrinsic::launder_invariant_group:
6637   case Intrinsic::strip_invariant_group:
6638     // Drop the intrinsic, but forward the value
6639     setValue(&I, getValue(I.getOperand(0)));
6640     return;
6641 
6642   case Intrinsic::assume:
6643   case Intrinsic::experimental_noalias_scope_decl:
6644   case Intrinsic::var_annotation:
6645   case Intrinsic::sideeffect:
6646     // Discard annotate attributes, noalias scope declarations, assumptions, and
6647     // artificial side-effects.
6648     return;
6649 
6650   case Intrinsic::codeview_annotation: {
6651     // Emit a label associated with this metadata.
6652     MachineFunction &MF = DAG.getMachineFunction();
6653     MCSymbol *Label =
6654         MF.getMMI().getContext().createTempSymbol("annotation", true);
6655     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6656     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6657     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6658     DAG.setRoot(Res);
6659     return;
6660   }
6661 
6662   case Intrinsic::init_trampoline: {
6663     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6664 
6665     SDValue Ops[6];
6666     Ops[0] = getRoot();
6667     Ops[1] = getValue(I.getArgOperand(0));
6668     Ops[2] = getValue(I.getArgOperand(1));
6669     Ops[3] = getValue(I.getArgOperand(2));
6670     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6671     Ops[5] = DAG.getSrcValue(F);
6672 
6673     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6674 
6675     DAG.setRoot(Res);
6676     return;
6677   }
6678   case Intrinsic::adjust_trampoline:
6679     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6680                              TLI.getPointerTy(DAG.getDataLayout()),
6681                              getValue(I.getArgOperand(0))));
6682     return;
6683   case Intrinsic::gcroot: {
6684     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6685            "only valid in functions with gc specified, enforced by Verifier");
6686     assert(GFI && "implied by previous");
6687     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6688     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6689 
6690     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6691     GFI->addStackRoot(FI->getIndex(), TypeMap);
6692     return;
6693   }
6694   case Intrinsic::gcread:
6695   case Intrinsic::gcwrite:
6696     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6697   case Intrinsic::flt_rounds:
6698     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6699     setValue(&I, Res);
6700     DAG.setRoot(Res.getValue(1));
6701     return;
6702 
6703   case Intrinsic::expect:
6704     // Just replace __builtin_expect(exp, c) with EXP.
6705     setValue(&I, getValue(I.getArgOperand(0)));
6706     return;
6707 
6708   case Intrinsic::ubsantrap:
6709   case Intrinsic::debugtrap:
6710   case Intrinsic::trap: {
6711     StringRef TrapFuncName =
6712         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6713     if (TrapFuncName.empty()) {
6714       switch (Intrinsic) {
6715       case Intrinsic::trap:
6716         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6717         break;
6718       case Intrinsic::debugtrap:
6719         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6720         break;
6721       case Intrinsic::ubsantrap:
6722         DAG.setRoot(DAG.getNode(
6723             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6724             DAG.getTargetConstant(
6725                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6726                 MVT::i32)));
6727         break;
6728       default: llvm_unreachable("unknown trap intrinsic");
6729       }
6730       return;
6731     }
6732     TargetLowering::ArgListTy Args;
6733     if (Intrinsic == Intrinsic::ubsantrap) {
6734       Args.push_back(TargetLoweringBase::ArgListEntry());
6735       Args[0].Val = I.getArgOperand(0);
6736       Args[0].Node = getValue(Args[0].Val);
6737       Args[0].Ty = Args[0].Val->getType();
6738     }
6739 
6740     TargetLowering::CallLoweringInfo CLI(DAG);
6741     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6742         CallingConv::C, I.getType(),
6743         DAG.getExternalSymbol(TrapFuncName.data(),
6744                               TLI.getPointerTy(DAG.getDataLayout())),
6745         std::move(Args));
6746 
6747     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6748     DAG.setRoot(Result.second);
6749     return;
6750   }
6751 
6752   case Intrinsic::uadd_with_overflow:
6753   case Intrinsic::sadd_with_overflow:
6754   case Intrinsic::usub_with_overflow:
6755   case Intrinsic::ssub_with_overflow:
6756   case Intrinsic::umul_with_overflow:
6757   case Intrinsic::smul_with_overflow: {
6758     ISD::NodeType Op;
6759     switch (Intrinsic) {
6760     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6761     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6762     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6763     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6764     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6765     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6766     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6767     }
6768     SDValue Op1 = getValue(I.getArgOperand(0));
6769     SDValue Op2 = getValue(I.getArgOperand(1));
6770 
6771     EVT ResultVT = Op1.getValueType();
6772     EVT OverflowVT = MVT::i1;
6773     if (ResultVT.isVector())
6774       OverflowVT = EVT::getVectorVT(
6775           *Context, OverflowVT, ResultVT.getVectorElementCount());
6776 
6777     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6778     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6779     return;
6780   }
6781   case Intrinsic::prefetch: {
6782     SDValue Ops[5];
6783     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6784     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6785     Ops[0] = DAG.getRoot();
6786     Ops[1] = getValue(I.getArgOperand(0));
6787     Ops[2] = getValue(I.getArgOperand(1));
6788     Ops[3] = getValue(I.getArgOperand(2));
6789     Ops[4] = getValue(I.getArgOperand(3));
6790     SDValue Result = DAG.getMemIntrinsicNode(
6791         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6792         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6793         /* align */ None, Flags);
6794 
6795     // Chain the prefetch in parallell with any pending loads, to stay out of
6796     // the way of later optimizations.
6797     PendingLoads.push_back(Result);
6798     Result = getRoot();
6799     DAG.setRoot(Result);
6800     return;
6801   }
6802   case Intrinsic::lifetime_start:
6803   case Intrinsic::lifetime_end: {
6804     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6805     // Stack coloring is not enabled in O0, discard region information.
6806     if (TM.getOptLevel() == CodeGenOpt::None)
6807       return;
6808 
6809     const int64_t ObjectSize =
6810         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6811     Value *const ObjectPtr = I.getArgOperand(1);
6812     SmallVector<const Value *, 4> Allocas;
6813     getUnderlyingObjects(ObjectPtr, Allocas);
6814 
6815     for (const Value *Alloca : Allocas) {
6816       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6817 
6818       // Could not find an Alloca.
6819       if (!LifetimeObject)
6820         continue;
6821 
6822       // First check that the Alloca is static, otherwise it won't have a
6823       // valid frame index.
6824       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6825       if (SI == FuncInfo.StaticAllocaMap.end())
6826         return;
6827 
6828       const int FrameIndex = SI->second;
6829       int64_t Offset;
6830       if (GetPointerBaseWithConstantOffset(
6831               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6832         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6833       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6834                                 Offset);
6835       DAG.setRoot(Res);
6836     }
6837     return;
6838   }
6839   case Intrinsic::pseudoprobe: {
6840     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6841     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6842     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6843     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6844     DAG.setRoot(Res);
6845     return;
6846   }
6847   case Intrinsic::invariant_start:
6848     // Discard region information.
6849     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6850     return;
6851   case Intrinsic::invariant_end:
6852     // Discard region information.
6853     return;
6854   case Intrinsic::clear_cache:
6855     /// FunctionName may be null.
6856     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6857       lowerCallToExternalSymbol(I, FunctionName);
6858     return;
6859   case Intrinsic::donothing:
6860   case Intrinsic::seh_try_begin:
6861   case Intrinsic::seh_scope_begin:
6862   case Intrinsic::seh_try_end:
6863   case Intrinsic::seh_scope_end:
6864     // ignore
6865     return;
6866   case Intrinsic::experimental_stackmap:
6867     visitStackmap(I);
6868     return;
6869   case Intrinsic::experimental_patchpoint_void:
6870   case Intrinsic::experimental_patchpoint_i64:
6871     visitPatchpoint(I);
6872     return;
6873   case Intrinsic::experimental_gc_statepoint:
6874     LowerStatepoint(cast<GCStatepointInst>(I));
6875     return;
6876   case Intrinsic::experimental_gc_result:
6877     visitGCResult(cast<GCResultInst>(I));
6878     return;
6879   case Intrinsic::experimental_gc_relocate:
6880     visitGCRelocate(cast<GCRelocateInst>(I));
6881     return;
6882   case Intrinsic::instrprof_cover:
6883     llvm_unreachable("instrprof failed to lower a cover");
6884   case Intrinsic::instrprof_increment:
6885     llvm_unreachable("instrprof failed to lower an increment");
6886   case Intrinsic::instrprof_value_profile:
6887     llvm_unreachable("instrprof failed to lower a value profiling call");
6888   case Intrinsic::localescape: {
6889     MachineFunction &MF = DAG.getMachineFunction();
6890     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6891 
6892     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6893     // is the same on all targets.
6894     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6895       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6896       if (isa<ConstantPointerNull>(Arg))
6897         continue; // Skip null pointers. They represent a hole in index space.
6898       AllocaInst *Slot = cast<AllocaInst>(Arg);
6899       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6900              "can only escape static allocas");
6901       int FI = FuncInfo.StaticAllocaMap[Slot];
6902       MCSymbol *FrameAllocSym =
6903           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6904               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6905       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6906               TII->get(TargetOpcode::LOCAL_ESCAPE))
6907           .addSym(FrameAllocSym)
6908           .addFrameIndex(FI);
6909     }
6910 
6911     return;
6912   }
6913 
6914   case Intrinsic::localrecover: {
6915     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6916     MachineFunction &MF = DAG.getMachineFunction();
6917 
6918     // Get the symbol that defines the frame offset.
6919     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6920     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6921     unsigned IdxVal =
6922         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6923     MCSymbol *FrameAllocSym =
6924         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6925             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6926 
6927     Value *FP = I.getArgOperand(1);
6928     SDValue FPVal = getValue(FP);
6929     EVT PtrVT = FPVal.getValueType();
6930 
6931     // Create a MCSymbol for the label to avoid any target lowering
6932     // that would make this PC relative.
6933     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6934     SDValue OffsetVal =
6935         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6936 
6937     // Add the offset to the FP.
6938     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6939     setValue(&I, Add);
6940 
6941     return;
6942   }
6943 
6944   case Intrinsic::eh_exceptionpointer:
6945   case Intrinsic::eh_exceptioncode: {
6946     // Get the exception pointer vreg, copy from it, and resize it to fit.
6947     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6948     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6949     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6950     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6951     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6952     if (Intrinsic == Intrinsic::eh_exceptioncode)
6953       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6954     setValue(&I, N);
6955     return;
6956   }
6957   case Intrinsic::xray_customevent: {
6958     // Here we want to make sure that the intrinsic behaves as if it has a
6959     // specific calling convention, and only for x86_64.
6960     // FIXME: Support other platforms later.
6961     const auto &Triple = DAG.getTarget().getTargetTriple();
6962     if (Triple.getArch() != Triple::x86_64)
6963       return;
6964 
6965     SmallVector<SDValue, 8> Ops;
6966 
6967     // We want to say that we always want the arguments in registers.
6968     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6969     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6970     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6971     SDValue Chain = getRoot();
6972     Ops.push_back(LogEntryVal);
6973     Ops.push_back(StrSizeVal);
6974     Ops.push_back(Chain);
6975 
6976     // We need to enforce the calling convention for the callsite, so that
6977     // argument ordering is enforced correctly, and that register allocation can
6978     // see that some registers may be assumed clobbered and have to preserve
6979     // them across calls to the intrinsic.
6980     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6981                                            sdl, NodeTys, Ops);
6982     SDValue patchableNode = SDValue(MN, 0);
6983     DAG.setRoot(patchableNode);
6984     setValue(&I, patchableNode);
6985     return;
6986   }
6987   case Intrinsic::xray_typedevent: {
6988     // Here we want to make sure that the intrinsic behaves as if it has a
6989     // specific calling convention, and only for x86_64.
6990     // FIXME: Support other platforms later.
6991     const auto &Triple = DAG.getTarget().getTargetTriple();
6992     if (Triple.getArch() != Triple::x86_64)
6993       return;
6994 
6995     SmallVector<SDValue, 8> Ops;
6996 
6997     // We want to say that we always want the arguments in registers.
6998     // It's unclear to me how manipulating the selection DAG here forces callers
6999     // to provide arguments in registers instead of on the stack.
7000     SDValue LogTypeId = getValue(I.getArgOperand(0));
7001     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7002     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7003     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7004     SDValue Chain = getRoot();
7005     Ops.push_back(LogTypeId);
7006     Ops.push_back(LogEntryVal);
7007     Ops.push_back(StrSizeVal);
7008     Ops.push_back(Chain);
7009 
7010     // We need to enforce the calling convention for the callsite, so that
7011     // argument ordering is enforced correctly, and that register allocation can
7012     // see that some registers may be assumed clobbered and have to preserve
7013     // them across calls to the intrinsic.
7014     MachineSDNode *MN = DAG.getMachineNode(
7015         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7016     SDValue patchableNode = SDValue(MN, 0);
7017     DAG.setRoot(patchableNode);
7018     setValue(&I, patchableNode);
7019     return;
7020   }
7021   case Intrinsic::experimental_deoptimize:
7022     LowerDeoptimizeCall(&I);
7023     return;
7024   case Intrinsic::experimental_stepvector:
7025     visitStepVector(I);
7026     return;
7027   case Intrinsic::vector_reduce_fadd:
7028   case Intrinsic::vector_reduce_fmul:
7029   case Intrinsic::vector_reduce_add:
7030   case Intrinsic::vector_reduce_mul:
7031   case Intrinsic::vector_reduce_and:
7032   case Intrinsic::vector_reduce_or:
7033   case Intrinsic::vector_reduce_xor:
7034   case Intrinsic::vector_reduce_smax:
7035   case Intrinsic::vector_reduce_smin:
7036   case Intrinsic::vector_reduce_umax:
7037   case Intrinsic::vector_reduce_umin:
7038   case Intrinsic::vector_reduce_fmax:
7039   case Intrinsic::vector_reduce_fmin:
7040     visitVectorReduce(I, Intrinsic);
7041     return;
7042 
7043   case Intrinsic::icall_branch_funnel: {
7044     SmallVector<SDValue, 16> Ops;
7045     Ops.push_back(getValue(I.getArgOperand(0)));
7046 
7047     int64_t Offset;
7048     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7049         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7050     if (!Base)
7051       report_fatal_error(
7052           "llvm.icall.branch.funnel operand must be a GlobalValue");
7053     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7054 
7055     struct BranchFunnelTarget {
7056       int64_t Offset;
7057       SDValue Target;
7058     };
7059     SmallVector<BranchFunnelTarget, 8> Targets;
7060 
7061     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7062       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7063           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7064       if (ElemBase != Base)
7065         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7066                            "to the same GlobalValue");
7067 
7068       SDValue Val = getValue(I.getArgOperand(Op + 1));
7069       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7070       if (!GA)
7071         report_fatal_error(
7072             "llvm.icall.branch.funnel operand must be a GlobalValue");
7073       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7074                                      GA->getGlobal(), sdl, Val.getValueType(),
7075                                      GA->getOffset())});
7076     }
7077     llvm::sort(Targets,
7078                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7079                  return T1.Offset < T2.Offset;
7080                });
7081 
7082     for (auto &T : Targets) {
7083       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7084       Ops.push_back(T.Target);
7085     }
7086 
7087     Ops.push_back(DAG.getRoot()); // Chain
7088     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7089                                  MVT::Other, Ops),
7090               0);
7091     DAG.setRoot(N);
7092     setValue(&I, N);
7093     HasTailCall = true;
7094     return;
7095   }
7096 
7097   case Intrinsic::wasm_landingpad_index:
7098     // Information this intrinsic contained has been transferred to
7099     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7100     // delete it now.
7101     return;
7102 
7103   case Intrinsic::aarch64_settag:
7104   case Intrinsic::aarch64_settag_zero: {
7105     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7106     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7107     SDValue Val = TSI.EmitTargetCodeForSetTag(
7108         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7109         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7110         ZeroMemory);
7111     DAG.setRoot(Val);
7112     setValue(&I, Val);
7113     return;
7114   }
7115   case Intrinsic::ptrmask: {
7116     SDValue Ptr = getValue(I.getOperand(0));
7117     SDValue Const = getValue(I.getOperand(1));
7118 
7119     EVT PtrVT = Ptr.getValueType();
7120     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7121                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7122     return;
7123   }
7124   case Intrinsic::get_active_lane_mask: {
7125     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7126     SDValue Index = getValue(I.getOperand(0));
7127     EVT ElementVT = Index.getValueType();
7128 
7129     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7130       visitTargetIntrinsic(I, Intrinsic);
7131       return;
7132     }
7133 
7134     SDValue TripCount = getValue(I.getOperand(1));
7135     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7136 
7137     SDValue VectorIndex, VectorTripCount;
7138     if (VecTy.isScalableVector()) {
7139       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7140       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7141     } else {
7142       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7143       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7144     }
7145     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7146     SDValue VectorInduction = DAG.getNode(
7147         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7148     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7149                                  VectorTripCount, ISD::CondCode::SETULT);
7150     setValue(&I, SetCC);
7151     return;
7152   }
7153   case Intrinsic::experimental_vector_insert: {
7154     SDValue Vec = getValue(I.getOperand(0));
7155     SDValue SubVec = getValue(I.getOperand(1));
7156     SDValue Index = getValue(I.getOperand(2));
7157 
7158     // The intrinsic's index type is i64, but the SDNode requires an index type
7159     // suitable for the target. Convert the index as required.
7160     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7161     if (Index.getValueType() != VectorIdxTy)
7162       Index = DAG.getVectorIdxConstant(
7163           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7164 
7165     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7166     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7167                              Index));
7168     return;
7169   }
7170   case Intrinsic::experimental_vector_extract: {
7171     SDValue Vec = getValue(I.getOperand(0));
7172     SDValue Index = getValue(I.getOperand(1));
7173     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7174 
7175     // The intrinsic's index type is i64, but the SDNode requires an index type
7176     // suitable for the target. Convert the index as required.
7177     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7178     if (Index.getValueType() != VectorIdxTy)
7179       Index = DAG.getVectorIdxConstant(
7180           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7181 
7182     setValue(&I,
7183              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7184     return;
7185   }
7186   case Intrinsic::experimental_vector_reverse:
7187     visitVectorReverse(I);
7188     return;
7189   case Intrinsic::experimental_vector_splice:
7190     visitVectorSplice(I);
7191     return;
7192   }
7193 }
7194 
7195 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7196     const ConstrainedFPIntrinsic &FPI) {
7197   SDLoc sdl = getCurSDLoc();
7198 
7199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7200   SmallVector<EVT, 4> ValueVTs;
7201   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7202   ValueVTs.push_back(MVT::Other); // Out chain
7203 
7204   // We do not need to serialize constrained FP intrinsics against
7205   // each other or against (nonvolatile) loads, so they can be
7206   // chained like loads.
7207   SDValue Chain = DAG.getRoot();
7208   SmallVector<SDValue, 4> Opers;
7209   Opers.push_back(Chain);
7210   if (FPI.isUnaryOp()) {
7211     Opers.push_back(getValue(FPI.getArgOperand(0)));
7212   } else if (FPI.isTernaryOp()) {
7213     Opers.push_back(getValue(FPI.getArgOperand(0)));
7214     Opers.push_back(getValue(FPI.getArgOperand(1)));
7215     Opers.push_back(getValue(FPI.getArgOperand(2)));
7216   } else {
7217     Opers.push_back(getValue(FPI.getArgOperand(0)));
7218     Opers.push_back(getValue(FPI.getArgOperand(1)));
7219   }
7220 
7221   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7222     assert(Result.getNode()->getNumValues() == 2);
7223 
7224     // Push node to the appropriate list so that future instructions can be
7225     // chained up correctly.
7226     SDValue OutChain = Result.getValue(1);
7227     switch (EB) {
7228     case fp::ExceptionBehavior::ebIgnore:
7229       // The only reason why ebIgnore nodes still need to be chained is that
7230       // they might depend on the current rounding mode, and therefore must
7231       // not be moved across instruction that may change that mode.
7232       LLVM_FALLTHROUGH;
7233     case fp::ExceptionBehavior::ebMayTrap:
7234       // These must not be moved across calls or instructions that may change
7235       // floating-point exception masks.
7236       PendingConstrainedFP.push_back(OutChain);
7237       break;
7238     case fp::ExceptionBehavior::ebStrict:
7239       // These must not be moved across calls or instructions that may change
7240       // floating-point exception masks or read floating-point exception flags.
7241       // In addition, they cannot be optimized out even if unused.
7242       PendingConstrainedFPStrict.push_back(OutChain);
7243       break;
7244     }
7245   };
7246 
7247   SDVTList VTs = DAG.getVTList(ValueVTs);
7248   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7249 
7250   SDNodeFlags Flags;
7251   if (EB == fp::ExceptionBehavior::ebIgnore)
7252     Flags.setNoFPExcept(true);
7253 
7254   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7255     Flags.copyFMF(*FPOp);
7256 
7257   unsigned Opcode;
7258   switch (FPI.getIntrinsicID()) {
7259   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7260 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7261   case Intrinsic::INTRINSIC:                                                   \
7262     Opcode = ISD::STRICT_##DAGN;                                               \
7263     break;
7264 #include "llvm/IR/ConstrainedOps.def"
7265   case Intrinsic::experimental_constrained_fmuladd: {
7266     Opcode = ISD::STRICT_FMA;
7267     // Break fmuladd into fmul and fadd.
7268     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7269         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7270                                         ValueVTs[0])) {
7271       Opers.pop_back();
7272       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7273       pushOutChain(Mul, EB);
7274       Opcode = ISD::STRICT_FADD;
7275       Opers.clear();
7276       Opers.push_back(Mul.getValue(1));
7277       Opers.push_back(Mul.getValue(0));
7278       Opers.push_back(getValue(FPI.getArgOperand(2)));
7279     }
7280     break;
7281   }
7282   }
7283 
7284   // A few strict DAG nodes carry additional operands that are not
7285   // set up by the default code above.
7286   switch (Opcode) {
7287   default: break;
7288   case ISD::STRICT_FP_ROUND:
7289     Opers.push_back(
7290         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7291     break;
7292   case ISD::STRICT_FSETCC:
7293   case ISD::STRICT_FSETCCS: {
7294     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7295     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7296     if (TM.Options.NoNaNsFPMath)
7297       Condition = getFCmpCodeWithoutNaN(Condition);
7298     Opers.push_back(DAG.getCondCode(Condition));
7299     break;
7300   }
7301   }
7302 
7303   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7304   pushOutChain(Result, EB);
7305 
7306   SDValue FPResult = Result.getValue(0);
7307   setValue(&FPI, FPResult);
7308 }
7309 
7310 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7311   Optional<unsigned> ResOPC;
7312   switch (VPIntrin.getIntrinsicID()) {
7313 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7314 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7315 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7316 #include "llvm/IR/VPIntrinsics.def"
7317   }
7318 
7319   if (!ResOPC.hasValue())
7320     llvm_unreachable(
7321         "Inconsistency: no SDNode available for this VPIntrinsic!");
7322 
7323   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7324       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7325     if (VPIntrin.getFastMathFlags().allowReassoc())
7326       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7327                                                 : ISD::VP_REDUCE_FMUL;
7328   }
7329 
7330   return ResOPC.getValue();
7331 }
7332 
7333 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7334                                             SmallVector<SDValue, 7> &OpValues,
7335                                             bool IsGather) {
7336   SDLoc DL = getCurSDLoc();
7337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7338   Value *PtrOperand = VPIntrin.getArgOperand(0);
7339   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7340   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7341   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7342   SDValue LD;
7343   bool AddToChain = true;
7344   if (!IsGather) {
7345     // Do not serialize variable-length loads of constant memory with
7346     // anything.
7347     if (!Alignment)
7348       Alignment = DAG.getEVTAlign(VT);
7349     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7350     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7351     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7352     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7353         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7354         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7355     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7356                        MMO, false /*IsExpanding */);
7357   } else {
7358     if (!Alignment)
7359       Alignment = DAG.getEVTAlign(VT.getScalarType());
7360     unsigned AS =
7361         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7362     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7363         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7364         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7365     SDValue Base, Index, Scale;
7366     ISD::MemIndexType IndexType;
7367     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7368                                       this, VPIntrin.getParent());
7369     if (!UniformBase) {
7370       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7371       Index = getValue(PtrOperand);
7372       IndexType = ISD::SIGNED_UNSCALED;
7373       Scale =
7374           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7375     }
7376     EVT IdxVT = Index.getValueType();
7377     EVT EltTy = IdxVT.getVectorElementType();
7378     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7379       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7380       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7381     }
7382     LD = DAG.getGatherVP(
7383         DAG.getVTList(VT, MVT::Other), VT, DL,
7384         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7385         IndexType);
7386   }
7387   if (AddToChain)
7388     PendingLoads.push_back(LD.getValue(1));
7389   setValue(&VPIntrin, LD);
7390 }
7391 
7392 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7393                                               SmallVector<SDValue, 7> &OpValues,
7394                                               bool IsScatter) {
7395   SDLoc DL = getCurSDLoc();
7396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7397   Value *PtrOperand = VPIntrin.getArgOperand(1);
7398   EVT VT = OpValues[0].getValueType();
7399   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7400   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7401   SDValue ST;
7402   if (!IsScatter) {
7403     if (!Alignment)
7404       Alignment = DAG.getEVTAlign(VT);
7405     SDValue Ptr = OpValues[1];
7406     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7407     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7408         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7409         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7410     ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7411                         OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7412                         /* IsTruncating */ false, /*IsCompressing*/ false);
7413   } else {
7414     if (!Alignment)
7415       Alignment = DAG.getEVTAlign(VT.getScalarType());
7416     unsigned AS =
7417         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7418     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7419         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7420         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7421     SDValue Base, Index, Scale;
7422     ISD::MemIndexType IndexType;
7423     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7424                                       this, VPIntrin.getParent());
7425     if (!UniformBase) {
7426       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7427       Index = getValue(PtrOperand);
7428       IndexType = ISD::SIGNED_UNSCALED;
7429       Scale =
7430           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7431     }
7432     EVT IdxVT = Index.getValueType();
7433     EVT EltTy = IdxVT.getVectorElementType();
7434     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7435       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7436       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7437     }
7438     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7439                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7440                            OpValues[2], OpValues[3]},
7441                           MMO, IndexType);
7442   }
7443   DAG.setRoot(ST);
7444   setValue(&VPIntrin, ST);
7445 }
7446 
7447 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7448     const VPIntrinsic &VPIntrin) {
7449   SDLoc DL = getCurSDLoc();
7450   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7451 
7452   SmallVector<EVT, 4> ValueVTs;
7453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7454   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7455   SDVTList VTs = DAG.getVTList(ValueVTs);
7456 
7457   auto EVLParamPos =
7458       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7459 
7460   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7461   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7462          "Unexpected target EVL type");
7463 
7464   // Request operands.
7465   SmallVector<SDValue, 7> OpValues;
7466   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7467     auto Op = getValue(VPIntrin.getArgOperand(I));
7468     if (I == EVLParamPos)
7469       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7470     OpValues.push_back(Op);
7471   }
7472 
7473   switch (Opcode) {
7474   default: {
7475     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7476     setValue(&VPIntrin, Result);
7477     break;
7478   }
7479   case ISD::VP_LOAD:
7480   case ISD::VP_GATHER:
7481     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7482                       Opcode == ISD::VP_GATHER);
7483     break;
7484   case ISD::VP_STORE:
7485   case ISD::VP_SCATTER:
7486     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7487     break;
7488   }
7489 }
7490 
7491 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7492                                           const BasicBlock *EHPadBB,
7493                                           MCSymbol *&BeginLabel) {
7494   MachineFunction &MF = DAG.getMachineFunction();
7495   MachineModuleInfo &MMI = MF.getMMI();
7496 
7497   // Insert a label before the invoke call to mark the try range.  This can be
7498   // used to detect deletion of the invoke via the MachineModuleInfo.
7499   BeginLabel = MMI.getContext().createTempSymbol();
7500 
7501   // For SjLj, keep track of which landing pads go with which invokes
7502   // so as to maintain the ordering of pads in the LSDA.
7503   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7504   if (CallSiteIndex) {
7505     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7506     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7507 
7508     // Now that the call site is handled, stop tracking it.
7509     MMI.setCurrentCallSite(0);
7510   }
7511 
7512   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7513 }
7514 
7515 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7516                                         const BasicBlock *EHPadBB,
7517                                         MCSymbol *BeginLabel) {
7518   assert(BeginLabel && "BeginLabel should've been set");
7519 
7520   MachineFunction &MF = DAG.getMachineFunction();
7521   MachineModuleInfo &MMI = MF.getMMI();
7522 
7523   // Insert a label at the end of the invoke call to mark the try range.  This
7524   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7525   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7526   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7527 
7528   // Inform MachineModuleInfo of range.
7529   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7530   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7531   // actually use outlined funclets and their LSDA info style.
7532   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7533     assert(II && "II should've been set");
7534     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7535     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7536   } else if (!isScopedEHPersonality(Pers)) {
7537     assert(EHPadBB);
7538     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7539   }
7540 
7541   return Chain;
7542 }
7543 
7544 std::pair<SDValue, SDValue>
7545 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7546                                     const BasicBlock *EHPadBB) {
7547   MCSymbol *BeginLabel = nullptr;
7548 
7549   if (EHPadBB) {
7550     // Both PendingLoads and PendingExports must be flushed here;
7551     // this call might not return.
7552     (void)getRoot();
7553     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7554     CLI.setChain(getRoot());
7555   }
7556 
7557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7558   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7559 
7560   assert((CLI.IsTailCall || Result.second.getNode()) &&
7561          "Non-null chain expected with non-tail call!");
7562   assert((Result.second.getNode() || !Result.first.getNode()) &&
7563          "Null value expected with tail call!");
7564 
7565   if (!Result.second.getNode()) {
7566     // As a special case, a null chain means that a tail call has been emitted
7567     // and the DAG root is already updated.
7568     HasTailCall = true;
7569 
7570     // Since there's no actual continuation from this block, nothing can be
7571     // relying on us setting vregs for them.
7572     PendingExports.clear();
7573   } else {
7574     DAG.setRoot(Result.second);
7575   }
7576 
7577   if (EHPadBB) {
7578     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7579                            BeginLabel));
7580   }
7581 
7582   return Result;
7583 }
7584 
7585 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7586                                       bool isTailCall,
7587                                       bool isMustTailCall,
7588                                       const BasicBlock *EHPadBB) {
7589   auto &DL = DAG.getDataLayout();
7590   FunctionType *FTy = CB.getFunctionType();
7591   Type *RetTy = CB.getType();
7592 
7593   TargetLowering::ArgListTy Args;
7594   Args.reserve(CB.arg_size());
7595 
7596   const Value *SwiftErrorVal = nullptr;
7597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7598 
7599   if (isTailCall) {
7600     // Avoid emitting tail calls in functions with the disable-tail-calls
7601     // attribute.
7602     auto *Caller = CB.getParent()->getParent();
7603     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7604         "true" && !isMustTailCall)
7605       isTailCall = false;
7606 
7607     // We can't tail call inside a function with a swifterror argument. Lowering
7608     // does not support this yet. It would have to move into the swifterror
7609     // register before the call.
7610     if (TLI.supportSwiftError() &&
7611         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7612       isTailCall = false;
7613   }
7614 
7615   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7616     TargetLowering::ArgListEntry Entry;
7617     const Value *V = *I;
7618 
7619     // Skip empty types
7620     if (V->getType()->isEmptyTy())
7621       continue;
7622 
7623     SDValue ArgNode = getValue(V);
7624     Entry.Node = ArgNode; Entry.Ty = V->getType();
7625 
7626     Entry.setAttributes(&CB, I - CB.arg_begin());
7627 
7628     // Use swifterror virtual register as input to the call.
7629     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7630       SwiftErrorVal = V;
7631       // We find the virtual register for the actual swifterror argument.
7632       // Instead of using the Value, we use the virtual register instead.
7633       Entry.Node =
7634           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7635                           EVT(TLI.getPointerTy(DL)));
7636     }
7637 
7638     Args.push_back(Entry);
7639 
7640     // If we have an explicit sret argument that is an Instruction, (i.e., it
7641     // might point to function-local memory), we can't meaningfully tail-call.
7642     if (Entry.IsSRet && isa<Instruction>(V))
7643       isTailCall = false;
7644   }
7645 
7646   // If call site has a cfguardtarget operand bundle, create and add an
7647   // additional ArgListEntry.
7648   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7649     TargetLowering::ArgListEntry Entry;
7650     Value *V = Bundle->Inputs[0];
7651     SDValue ArgNode = getValue(V);
7652     Entry.Node = ArgNode;
7653     Entry.Ty = V->getType();
7654     Entry.IsCFGuardTarget = true;
7655     Args.push_back(Entry);
7656   }
7657 
7658   // Check if target-independent constraints permit a tail call here.
7659   // Target-dependent constraints are checked within TLI->LowerCallTo.
7660   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7661     isTailCall = false;
7662 
7663   // Disable tail calls if there is an swifterror argument. Targets have not
7664   // been updated to support tail calls.
7665   if (TLI.supportSwiftError() && SwiftErrorVal)
7666     isTailCall = false;
7667 
7668   TargetLowering::CallLoweringInfo CLI(DAG);
7669   CLI.setDebugLoc(getCurSDLoc())
7670       .setChain(getRoot())
7671       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7672       .setTailCall(isTailCall)
7673       .setConvergent(CB.isConvergent())
7674       .setIsPreallocated(
7675           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7676   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7677 
7678   if (Result.first.getNode()) {
7679     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7680     setValue(&CB, Result.first);
7681   }
7682 
7683   // The last element of CLI.InVals has the SDValue for swifterror return.
7684   // Here we copy it to a virtual register and update SwiftErrorMap for
7685   // book-keeping.
7686   if (SwiftErrorVal && TLI.supportSwiftError()) {
7687     // Get the last element of InVals.
7688     SDValue Src = CLI.InVals.back();
7689     Register VReg =
7690         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7691     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7692     DAG.setRoot(CopyNode);
7693   }
7694 }
7695 
7696 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7697                              SelectionDAGBuilder &Builder) {
7698   // Check to see if this load can be trivially constant folded, e.g. if the
7699   // input is from a string literal.
7700   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7701     // Cast pointer to the type we really want to load.
7702     Type *LoadTy =
7703         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7704     if (LoadVT.isVector())
7705       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7706 
7707     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7708                                          PointerType::getUnqual(LoadTy));
7709 
7710     if (const Constant *LoadCst =
7711             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7712                                          LoadTy, Builder.DAG.getDataLayout()))
7713       return Builder.getValue(LoadCst);
7714   }
7715 
7716   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7717   // still constant memory, the input chain can be the entry node.
7718   SDValue Root;
7719   bool ConstantMemory = false;
7720 
7721   // Do not serialize (non-volatile) loads of constant memory with anything.
7722   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7723     Root = Builder.DAG.getEntryNode();
7724     ConstantMemory = true;
7725   } else {
7726     // Do not serialize non-volatile loads against each other.
7727     Root = Builder.DAG.getRoot();
7728   }
7729 
7730   SDValue Ptr = Builder.getValue(PtrVal);
7731   SDValue LoadVal =
7732       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7733                           MachinePointerInfo(PtrVal), Align(1));
7734 
7735   if (!ConstantMemory)
7736     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7737   return LoadVal;
7738 }
7739 
7740 /// Record the value for an instruction that produces an integer result,
7741 /// converting the type where necessary.
7742 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7743                                                   SDValue Value,
7744                                                   bool IsSigned) {
7745   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7746                                                     I.getType(), true);
7747   if (IsSigned)
7748     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7749   else
7750     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7751   setValue(&I, Value);
7752 }
7753 
7754 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7755 /// true and lower it. Otherwise return false, and it will be lowered like a
7756 /// normal call.
7757 /// The caller already checked that \p I calls the appropriate LibFunc with a
7758 /// correct prototype.
7759 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7760   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7761   const Value *Size = I.getArgOperand(2);
7762   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7763   if (CSize && CSize->getZExtValue() == 0) {
7764     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7765                                                           I.getType(), true);
7766     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7767     return true;
7768   }
7769 
7770   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7771   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7772       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7773       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7774   if (Res.first.getNode()) {
7775     processIntegerCallValue(I, Res.first, true);
7776     PendingLoads.push_back(Res.second);
7777     return true;
7778   }
7779 
7780   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7781   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7782   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7783     return false;
7784 
7785   // If the target has a fast compare for the given size, it will return a
7786   // preferred load type for that size. Require that the load VT is legal and
7787   // that the target supports unaligned loads of that type. Otherwise, return
7788   // INVALID.
7789   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7790     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7791     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7792     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7793       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7794       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7795       // TODO: Check alignment of src and dest ptrs.
7796       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7797       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7798       if (!TLI.isTypeLegal(LVT) ||
7799           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7800           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7801         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7802     }
7803 
7804     return LVT;
7805   };
7806 
7807   // This turns into unaligned loads. We only do this if the target natively
7808   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7809   // we'll only produce a small number of byte loads.
7810   MVT LoadVT;
7811   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7812   switch (NumBitsToCompare) {
7813   default:
7814     return false;
7815   case 16:
7816     LoadVT = MVT::i16;
7817     break;
7818   case 32:
7819     LoadVT = MVT::i32;
7820     break;
7821   case 64:
7822   case 128:
7823   case 256:
7824     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7825     break;
7826   }
7827 
7828   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7829     return false;
7830 
7831   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7832   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7833 
7834   // Bitcast to a wide integer type if the loads are vectors.
7835   if (LoadVT.isVector()) {
7836     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7837     LoadL = DAG.getBitcast(CmpVT, LoadL);
7838     LoadR = DAG.getBitcast(CmpVT, LoadR);
7839   }
7840 
7841   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7842   processIntegerCallValue(I, Cmp, false);
7843   return true;
7844 }
7845 
7846 /// See if we can lower a memchr call into an optimized form. If so, return
7847 /// true and lower it. Otherwise return false, and it will be lowered like a
7848 /// normal call.
7849 /// The caller already checked that \p I calls the appropriate LibFunc with a
7850 /// correct prototype.
7851 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7852   const Value *Src = I.getArgOperand(0);
7853   const Value *Char = I.getArgOperand(1);
7854   const Value *Length = I.getArgOperand(2);
7855 
7856   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7857   std::pair<SDValue, SDValue> Res =
7858     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7859                                 getValue(Src), getValue(Char), getValue(Length),
7860                                 MachinePointerInfo(Src));
7861   if (Res.first.getNode()) {
7862     setValue(&I, Res.first);
7863     PendingLoads.push_back(Res.second);
7864     return true;
7865   }
7866 
7867   return false;
7868 }
7869 
7870 /// See if we can lower a mempcpy call into an optimized form. If so, return
7871 /// true and lower it. Otherwise return false, and it will be lowered like a
7872 /// normal call.
7873 /// The caller already checked that \p I calls the appropriate LibFunc with a
7874 /// correct prototype.
7875 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7876   SDValue Dst = getValue(I.getArgOperand(0));
7877   SDValue Src = getValue(I.getArgOperand(1));
7878   SDValue Size = getValue(I.getArgOperand(2));
7879 
7880   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7881   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7882   // DAG::getMemcpy needs Alignment to be defined.
7883   Align Alignment = std::min(DstAlign, SrcAlign);
7884 
7885   bool isVol = false;
7886   SDLoc sdl = getCurSDLoc();
7887 
7888   // In the mempcpy context we need to pass in a false value for isTailCall
7889   // because the return pointer needs to be adjusted by the size of
7890   // the copied memory.
7891   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7892   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7893                              /*isTailCall=*/false,
7894                              MachinePointerInfo(I.getArgOperand(0)),
7895                              MachinePointerInfo(I.getArgOperand(1)),
7896                              I.getAAMetadata());
7897   assert(MC.getNode() != nullptr &&
7898          "** memcpy should not be lowered as TailCall in mempcpy context **");
7899   DAG.setRoot(MC);
7900 
7901   // Check if Size needs to be truncated or extended.
7902   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7903 
7904   // Adjust return pointer to point just past the last dst byte.
7905   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7906                                     Dst, Size);
7907   setValue(&I, DstPlusSize);
7908   return true;
7909 }
7910 
7911 /// See if we can lower a strcpy call into an optimized form.  If so, return
7912 /// true and lower it, otherwise return false and it will be lowered like a
7913 /// normal call.
7914 /// The caller already checked that \p I calls the appropriate LibFunc with a
7915 /// correct prototype.
7916 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7917   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7918 
7919   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7920   std::pair<SDValue, SDValue> Res =
7921     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7922                                 getValue(Arg0), getValue(Arg1),
7923                                 MachinePointerInfo(Arg0),
7924                                 MachinePointerInfo(Arg1), isStpcpy);
7925   if (Res.first.getNode()) {
7926     setValue(&I, Res.first);
7927     DAG.setRoot(Res.second);
7928     return true;
7929   }
7930 
7931   return false;
7932 }
7933 
7934 /// See if we can lower a strcmp call into an optimized form.  If so, return
7935 /// true and lower it, otherwise return false and it will be lowered like a
7936 /// normal call.
7937 /// The caller already checked that \p I calls the appropriate LibFunc with a
7938 /// correct prototype.
7939 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7940   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7941 
7942   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7943   std::pair<SDValue, SDValue> Res =
7944     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7945                                 getValue(Arg0), getValue(Arg1),
7946                                 MachinePointerInfo(Arg0),
7947                                 MachinePointerInfo(Arg1));
7948   if (Res.first.getNode()) {
7949     processIntegerCallValue(I, Res.first, true);
7950     PendingLoads.push_back(Res.second);
7951     return true;
7952   }
7953 
7954   return false;
7955 }
7956 
7957 /// See if we can lower a strlen call into an optimized form.  If so, return
7958 /// true and lower it, otherwise return false and it will be lowered like a
7959 /// normal call.
7960 /// The caller already checked that \p I calls the appropriate LibFunc with a
7961 /// correct prototype.
7962 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7963   const Value *Arg0 = I.getArgOperand(0);
7964 
7965   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7966   std::pair<SDValue, SDValue> Res =
7967     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7968                                 getValue(Arg0), MachinePointerInfo(Arg0));
7969   if (Res.first.getNode()) {
7970     processIntegerCallValue(I, Res.first, false);
7971     PendingLoads.push_back(Res.second);
7972     return true;
7973   }
7974 
7975   return false;
7976 }
7977 
7978 /// See if we can lower a strnlen call into an optimized form.  If so, return
7979 /// true and lower it, otherwise return false and it will be lowered like a
7980 /// normal call.
7981 /// The caller already checked that \p I calls the appropriate LibFunc with a
7982 /// correct prototype.
7983 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7984   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7985 
7986   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7987   std::pair<SDValue, SDValue> Res =
7988     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7989                                  getValue(Arg0), getValue(Arg1),
7990                                  MachinePointerInfo(Arg0));
7991   if (Res.first.getNode()) {
7992     processIntegerCallValue(I, Res.first, false);
7993     PendingLoads.push_back(Res.second);
7994     return true;
7995   }
7996 
7997   return false;
7998 }
7999 
8000 /// See if we can lower a unary floating-point operation into an SDNode with
8001 /// the specified Opcode.  If so, return true and lower it, otherwise return
8002 /// false and it will be lowered like a normal call.
8003 /// The caller already checked that \p I calls the appropriate LibFunc with a
8004 /// correct prototype.
8005 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8006                                               unsigned Opcode) {
8007   // We already checked this call's prototype; verify it doesn't modify errno.
8008   if (!I.onlyReadsMemory())
8009     return false;
8010 
8011   SDNodeFlags Flags;
8012   Flags.copyFMF(cast<FPMathOperator>(I));
8013 
8014   SDValue Tmp = getValue(I.getArgOperand(0));
8015   setValue(&I,
8016            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8017   return true;
8018 }
8019 
8020 /// See if we can lower a binary floating-point operation into an SDNode with
8021 /// the specified Opcode. If so, return true and lower it. Otherwise return
8022 /// false, and it will be lowered like a normal call.
8023 /// The caller already checked that \p I calls the appropriate LibFunc with a
8024 /// correct prototype.
8025 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8026                                                unsigned Opcode) {
8027   // We already checked this call's prototype; verify it doesn't modify errno.
8028   if (!I.onlyReadsMemory())
8029     return false;
8030 
8031   SDNodeFlags Flags;
8032   Flags.copyFMF(cast<FPMathOperator>(I));
8033 
8034   SDValue Tmp0 = getValue(I.getArgOperand(0));
8035   SDValue Tmp1 = getValue(I.getArgOperand(1));
8036   EVT VT = Tmp0.getValueType();
8037   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8038   return true;
8039 }
8040 
8041 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8042   // Handle inline assembly differently.
8043   if (I.isInlineAsm()) {
8044     visitInlineAsm(I);
8045     return;
8046   }
8047 
8048   if (Function *F = I.getCalledFunction()) {
8049     diagnoseDontCall(I);
8050 
8051     if (F->isDeclaration()) {
8052       // Is this an LLVM intrinsic or a target-specific intrinsic?
8053       unsigned IID = F->getIntrinsicID();
8054       if (!IID)
8055         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8056           IID = II->getIntrinsicID(F);
8057 
8058       if (IID) {
8059         visitIntrinsicCall(I, IID);
8060         return;
8061       }
8062     }
8063 
8064     // Check for well-known libc/libm calls.  If the function is internal, it
8065     // can't be a library call.  Don't do the check if marked as nobuiltin for
8066     // some reason or the call site requires strict floating point semantics.
8067     LibFunc Func;
8068     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8069         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8070         LibInfo->hasOptimizedCodeGen(Func)) {
8071       switch (Func) {
8072       default: break;
8073       case LibFunc_bcmp:
8074         if (visitMemCmpBCmpCall(I))
8075           return;
8076         break;
8077       case LibFunc_copysign:
8078       case LibFunc_copysignf:
8079       case LibFunc_copysignl:
8080         // We already checked this call's prototype; verify it doesn't modify
8081         // errno.
8082         if (I.onlyReadsMemory()) {
8083           SDValue LHS = getValue(I.getArgOperand(0));
8084           SDValue RHS = getValue(I.getArgOperand(1));
8085           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8086                                    LHS.getValueType(), LHS, RHS));
8087           return;
8088         }
8089         break;
8090       case LibFunc_fabs:
8091       case LibFunc_fabsf:
8092       case LibFunc_fabsl:
8093         if (visitUnaryFloatCall(I, ISD::FABS))
8094           return;
8095         break;
8096       case LibFunc_fmin:
8097       case LibFunc_fminf:
8098       case LibFunc_fminl:
8099         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8100           return;
8101         break;
8102       case LibFunc_fmax:
8103       case LibFunc_fmaxf:
8104       case LibFunc_fmaxl:
8105         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8106           return;
8107         break;
8108       case LibFunc_sin:
8109       case LibFunc_sinf:
8110       case LibFunc_sinl:
8111         if (visitUnaryFloatCall(I, ISD::FSIN))
8112           return;
8113         break;
8114       case LibFunc_cos:
8115       case LibFunc_cosf:
8116       case LibFunc_cosl:
8117         if (visitUnaryFloatCall(I, ISD::FCOS))
8118           return;
8119         break;
8120       case LibFunc_sqrt:
8121       case LibFunc_sqrtf:
8122       case LibFunc_sqrtl:
8123       case LibFunc_sqrt_finite:
8124       case LibFunc_sqrtf_finite:
8125       case LibFunc_sqrtl_finite:
8126         if (visitUnaryFloatCall(I, ISD::FSQRT))
8127           return;
8128         break;
8129       case LibFunc_floor:
8130       case LibFunc_floorf:
8131       case LibFunc_floorl:
8132         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8133           return;
8134         break;
8135       case LibFunc_nearbyint:
8136       case LibFunc_nearbyintf:
8137       case LibFunc_nearbyintl:
8138         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8139           return;
8140         break;
8141       case LibFunc_ceil:
8142       case LibFunc_ceilf:
8143       case LibFunc_ceill:
8144         if (visitUnaryFloatCall(I, ISD::FCEIL))
8145           return;
8146         break;
8147       case LibFunc_rint:
8148       case LibFunc_rintf:
8149       case LibFunc_rintl:
8150         if (visitUnaryFloatCall(I, ISD::FRINT))
8151           return;
8152         break;
8153       case LibFunc_round:
8154       case LibFunc_roundf:
8155       case LibFunc_roundl:
8156         if (visitUnaryFloatCall(I, ISD::FROUND))
8157           return;
8158         break;
8159       case LibFunc_trunc:
8160       case LibFunc_truncf:
8161       case LibFunc_truncl:
8162         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8163           return;
8164         break;
8165       case LibFunc_log2:
8166       case LibFunc_log2f:
8167       case LibFunc_log2l:
8168         if (visitUnaryFloatCall(I, ISD::FLOG2))
8169           return;
8170         break;
8171       case LibFunc_exp2:
8172       case LibFunc_exp2f:
8173       case LibFunc_exp2l:
8174         if (visitUnaryFloatCall(I, ISD::FEXP2))
8175           return;
8176         break;
8177       case LibFunc_memcmp:
8178         if (visitMemCmpBCmpCall(I))
8179           return;
8180         break;
8181       case LibFunc_mempcpy:
8182         if (visitMemPCpyCall(I))
8183           return;
8184         break;
8185       case LibFunc_memchr:
8186         if (visitMemChrCall(I))
8187           return;
8188         break;
8189       case LibFunc_strcpy:
8190         if (visitStrCpyCall(I, false))
8191           return;
8192         break;
8193       case LibFunc_stpcpy:
8194         if (visitStrCpyCall(I, true))
8195           return;
8196         break;
8197       case LibFunc_strcmp:
8198         if (visitStrCmpCall(I))
8199           return;
8200         break;
8201       case LibFunc_strlen:
8202         if (visitStrLenCall(I))
8203           return;
8204         break;
8205       case LibFunc_strnlen:
8206         if (visitStrNLenCall(I))
8207           return;
8208         break;
8209       }
8210     }
8211   }
8212 
8213   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8214   // have to do anything here to lower funclet bundles.
8215   // CFGuardTarget bundles are lowered in LowerCallTo.
8216   assert(!I.hasOperandBundlesOtherThan(
8217              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8218               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8219               LLVMContext::OB_clang_arc_attachedcall}) &&
8220          "Cannot lower calls with arbitrary operand bundles!");
8221 
8222   SDValue Callee = getValue(I.getCalledOperand());
8223 
8224   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8225     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8226   else
8227     // Check if we can potentially perform a tail call. More detailed checking
8228     // is be done within LowerCallTo, after more information about the call is
8229     // known.
8230     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8231 }
8232 
8233 namespace {
8234 
8235 /// AsmOperandInfo - This contains information for each constraint that we are
8236 /// lowering.
8237 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8238 public:
8239   /// CallOperand - If this is the result output operand or a clobber
8240   /// this is null, otherwise it is the incoming operand to the CallInst.
8241   /// This gets modified as the asm is processed.
8242   SDValue CallOperand;
8243 
8244   /// AssignedRegs - If this is a register or register class operand, this
8245   /// contains the set of register corresponding to the operand.
8246   RegsForValue AssignedRegs;
8247 
8248   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8249     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8250   }
8251 
8252   /// Whether or not this operand accesses memory
8253   bool hasMemory(const TargetLowering &TLI) const {
8254     // Indirect operand accesses access memory.
8255     if (isIndirect)
8256       return true;
8257 
8258     for (const auto &Code : Codes)
8259       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8260         return true;
8261 
8262     return false;
8263   }
8264 
8265   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8266   /// corresponds to.  If there is no Value* for this operand, it returns
8267   /// MVT::Other.
8268   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8269                            const DataLayout &DL,
8270                            llvm::Type *ParamElemType) const {
8271     if (!CallOperandVal) return MVT::Other;
8272 
8273     if (isa<BasicBlock>(CallOperandVal))
8274       return TLI.getProgramPointerTy(DL);
8275 
8276     llvm::Type *OpTy = CallOperandVal->getType();
8277 
8278     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8279     // If this is an indirect operand, the operand is a pointer to the
8280     // accessed type.
8281     if (isIndirect) {
8282       OpTy = ParamElemType;
8283       assert(OpTy && "Indirect opernad must have elementtype attribute");
8284     }
8285 
8286     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8287     if (StructType *STy = dyn_cast<StructType>(OpTy))
8288       if (STy->getNumElements() == 1)
8289         OpTy = STy->getElementType(0);
8290 
8291     // If OpTy is not a single value, it may be a struct/union that we
8292     // can tile with integers.
8293     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8294       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8295       switch (BitSize) {
8296       default: break;
8297       case 1:
8298       case 8:
8299       case 16:
8300       case 32:
8301       case 64:
8302       case 128:
8303         OpTy = IntegerType::get(Context, BitSize);
8304         break;
8305       }
8306     }
8307 
8308     return TLI.getAsmOperandValueType(DL, OpTy, true);
8309   }
8310 };
8311 
8312 
8313 } // end anonymous namespace
8314 
8315 /// Make sure that the output operand \p OpInfo and its corresponding input
8316 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8317 /// out).
8318 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8319                                SDISelAsmOperandInfo &MatchingOpInfo,
8320                                SelectionDAG &DAG) {
8321   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8322     return;
8323 
8324   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8325   const auto &TLI = DAG.getTargetLoweringInfo();
8326 
8327   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8328       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8329                                        OpInfo.ConstraintVT);
8330   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8331       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8332                                        MatchingOpInfo.ConstraintVT);
8333   if ((OpInfo.ConstraintVT.isInteger() !=
8334        MatchingOpInfo.ConstraintVT.isInteger()) ||
8335       (MatchRC.second != InputRC.second)) {
8336     // FIXME: error out in a more elegant fashion
8337     report_fatal_error("Unsupported asm: input constraint"
8338                        " with a matching output constraint of"
8339                        " incompatible type!");
8340   }
8341   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8342 }
8343 
8344 /// Get a direct memory input to behave well as an indirect operand.
8345 /// This may introduce stores, hence the need for a \p Chain.
8346 /// \return The (possibly updated) chain.
8347 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8348                                         SDISelAsmOperandInfo &OpInfo,
8349                                         SelectionDAG &DAG) {
8350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8351 
8352   // If we don't have an indirect input, put it in the constpool if we can,
8353   // otherwise spill it to a stack slot.
8354   // TODO: This isn't quite right. We need to handle these according to
8355   // the addressing mode that the constraint wants. Also, this may take
8356   // an additional register for the computation and we don't want that
8357   // either.
8358 
8359   // If the operand is a float, integer, or vector constant, spill to a
8360   // constant pool entry to get its address.
8361   const Value *OpVal = OpInfo.CallOperandVal;
8362   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8363       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8364     OpInfo.CallOperand = DAG.getConstantPool(
8365         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8366     return Chain;
8367   }
8368 
8369   // Otherwise, create a stack slot and emit a store to it before the asm.
8370   Type *Ty = OpVal->getType();
8371   auto &DL = DAG.getDataLayout();
8372   uint64_t TySize = DL.getTypeAllocSize(Ty);
8373   MachineFunction &MF = DAG.getMachineFunction();
8374   int SSFI = MF.getFrameInfo().CreateStackObject(
8375       TySize, DL.getPrefTypeAlign(Ty), false);
8376   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8377   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8378                             MachinePointerInfo::getFixedStack(MF, SSFI),
8379                             TLI.getMemValueType(DL, Ty));
8380   OpInfo.CallOperand = StackSlot;
8381 
8382   return Chain;
8383 }
8384 
8385 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8386 /// specified operand.  We prefer to assign virtual registers, to allow the
8387 /// register allocator to handle the assignment process.  However, if the asm
8388 /// uses features that we can't model on machineinstrs, we have SDISel do the
8389 /// allocation.  This produces generally horrible, but correct, code.
8390 ///
8391 ///   OpInfo describes the operand
8392 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8393 static llvm::Optional<unsigned>
8394 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8395                      SDISelAsmOperandInfo &OpInfo,
8396                      SDISelAsmOperandInfo &RefOpInfo) {
8397   LLVMContext &Context = *DAG.getContext();
8398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8399 
8400   MachineFunction &MF = DAG.getMachineFunction();
8401   SmallVector<unsigned, 4> Regs;
8402   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8403 
8404   // No work to do for memory operations.
8405   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8406     return None;
8407 
8408   // If this is a constraint for a single physreg, or a constraint for a
8409   // register class, find it.
8410   unsigned AssignedReg;
8411   const TargetRegisterClass *RC;
8412   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8413       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8414   // RC is unset only on failure. Return immediately.
8415   if (!RC)
8416     return None;
8417 
8418   // Get the actual register value type.  This is important, because the user
8419   // may have asked for (e.g.) the AX register in i32 type.  We need to
8420   // remember that AX is actually i16 to get the right extension.
8421   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8422 
8423   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8424     // If this is an FP operand in an integer register (or visa versa), or more
8425     // generally if the operand value disagrees with the register class we plan
8426     // to stick it in, fix the operand type.
8427     //
8428     // If this is an input value, the bitcast to the new type is done now.
8429     // Bitcast for output value is done at the end of visitInlineAsm().
8430     if ((OpInfo.Type == InlineAsm::isOutput ||
8431          OpInfo.Type == InlineAsm::isInput) &&
8432         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8433       // Try to convert to the first EVT that the reg class contains.  If the
8434       // types are identical size, use a bitcast to convert (e.g. two differing
8435       // vector types).  Note: output bitcast is done at the end of
8436       // visitInlineAsm().
8437       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8438         // Exclude indirect inputs while they are unsupported because the code
8439         // to perform the load is missing and thus OpInfo.CallOperand still
8440         // refers to the input address rather than the pointed-to value.
8441         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8442           OpInfo.CallOperand =
8443               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8444         OpInfo.ConstraintVT = RegVT;
8445         // If the operand is an FP value and we want it in integer registers,
8446         // use the corresponding integer type. This turns an f64 value into
8447         // i64, which can be passed with two i32 values on a 32-bit machine.
8448       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8449         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8450         if (OpInfo.Type == InlineAsm::isInput)
8451           OpInfo.CallOperand =
8452               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8453         OpInfo.ConstraintVT = VT;
8454       }
8455     }
8456   }
8457 
8458   // No need to allocate a matching input constraint since the constraint it's
8459   // matching to has already been allocated.
8460   if (OpInfo.isMatchingInputConstraint())
8461     return None;
8462 
8463   EVT ValueVT = OpInfo.ConstraintVT;
8464   if (OpInfo.ConstraintVT == MVT::Other)
8465     ValueVT = RegVT;
8466 
8467   // Initialize NumRegs.
8468   unsigned NumRegs = 1;
8469   if (OpInfo.ConstraintVT != MVT::Other)
8470     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8471 
8472   // If this is a constraint for a specific physical register, like {r17},
8473   // assign it now.
8474 
8475   // If this associated to a specific register, initialize iterator to correct
8476   // place. If virtual, make sure we have enough registers
8477 
8478   // Initialize iterator if necessary
8479   TargetRegisterClass::iterator I = RC->begin();
8480   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8481 
8482   // Do not check for single registers.
8483   if (AssignedReg) {
8484     I = std::find(I, RC->end(), AssignedReg);
8485     if (I == RC->end()) {
8486       // RC does not contain the selected register, which indicates a
8487       // mismatch between the register and the required type/bitwidth.
8488       return {AssignedReg};
8489     }
8490   }
8491 
8492   for (; NumRegs; --NumRegs, ++I) {
8493     assert(I != RC->end() && "Ran out of registers to allocate!");
8494     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8495     Regs.push_back(R);
8496   }
8497 
8498   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8499   return None;
8500 }
8501 
8502 static unsigned
8503 findMatchingInlineAsmOperand(unsigned OperandNo,
8504                              const std::vector<SDValue> &AsmNodeOperands) {
8505   // Scan until we find the definition we already emitted of this operand.
8506   unsigned CurOp = InlineAsm::Op_FirstOperand;
8507   for (; OperandNo; --OperandNo) {
8508     // Advance to the next operand.
8509     unsigned OpFlag =
8510         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8511     assert((InlineAsm::isRegDefKind(OpFlag) ||
8512             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8513             InlineAsm::isMemKind(OpFlag)) &&
8514            "Skipped past definitions?");
8515     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8516   }
8517   return CurOp;
8518 }
8519 
8520 namespace {
8521 
8522 class ExtraFlags {
8523   unsigned Flags = 0;
8524 
8525 public:
8526   explicit ExtraFlags(const CallBase &Call) {
8527     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8528     if (IA->hasSideEffects())
8529       Flags |= InlineAsm::Extra_HasSideEffects;
8530     if (IA->isAlignStack())
8531       Flags |= InlineAsm::Extra_IsAlignStack;
8532     if (Call.isConvergent())
8533       Flags |= InlineAsm::Extra_IsConvergent;
8534     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8535   }
8536 
8537   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8538     // Ideally, we would only check against memory constraints.  However, the
8539     // meaning of an Other constraint can be target-specific and we can't easily
8540     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8541     // for Other constraints as well.
8542     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8543         OpInfo.ConstraintType == TargetLowering::C_Other) {
8544       if (OpInfo.Type == InlineAsm::isInput)
8545         Flags |= InlineAsm::Extra_MayLoad;
8546       else if (OpInfo.Type == InlineAsm::isOutput)
8547         Flags |= InlineAsm::Extra_MayStore;
8548       else if (OpInfo.Type == InlineAsm::isClobber)
8549         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8550     }
8551   }
8552 
8553   unsigned get() const { return Flags; }
8554 };
8555 
8556 } // end anonymous namespace
8557 
8558 /// visitInlineAsm - Handle a call to an InlineAsm object.
8559 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8560                                          const BasicBlock *EHPadBB) {
8561   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8562 
8563   /// ConstraintOperands - Information about all of the constraints.
8564   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8565 
8566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8567   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8568       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8569 
8570   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8571   // AsmDialect, MayLoad, MayStore).
8572   bool HasSideEffect = IA->hasSideEffects();
8573   ExtraFlags ExtraInfo(Call);
8574 
8575   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8576   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8577   for (auto &T : TargetConstraints) {
8578     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8579     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8580 
8581     // Compute the value type for each operand.
8582     if (OpInfo.hasArg()) {
8583       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
8584       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8585       Type *ParamElemTy = Call.getAttributes().getParamElementType(ArgNo);
8586       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8587                                            DAG.getDataLayout(), ParamElemTy);
8588       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8589       ArgNo++;
8590     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8591       // The return value of the call is this value.  As such, there is no
8592       // corresponding argument.
8593       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8594       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8595         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8596             DAG.getDataLayout(), STy->getElementType(ResNo));
8597       } else {
8598         assert(ResNo == 0 && "Asm only has one result!");
8599         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8600             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8601       }
8602       ++ResNo;
8603     } else {
8604       OpInfo.ConstraintVT = MVT::Other;
8605     }
8606 
8607     if (!HasSideEffect)
8608       HasSideEffect = OpInfo.hasMemory(TLI);
8609 
8610     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8611     // FIXME: Could we compute this on OpInfo rather than T?
8612 
8613     // Compute the constraint code and ConstraintType to use.
8614     TLI.ComputeConstraintToUse(T, SDValue());
8615 
8616     if (T.ConstraintType == TargetLowering::C_Immediate &&
8617         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8618       // We've delayed emitting a diagnostic like the "n" constraint because
8619       // inlining could cause an integer showing up.
8620       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8621                                           "' expects an integer constant "
8622                                           "expression");
8623 
8624     ExtraInfo.update(T);
8625   }
8626 
8627   // We won't need to flush pending loads if this asm doesn't touch
8628   // memory and is nonvolatile.
8629   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8630 
8631   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8632   if (EmitEHLabels) {
8633     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8634   }
8635   bool IsCallBr = isa<CallBrInst>(Call);
8636 
8637   if (IsCallBr || EmitEHLabels) {
8638     // If this is a callbr or invoke we need to flush pending exports since
8639     // inlineasm_br and invoke are terminators.
8640     // We need to do this before nodes are glued to the inlineasm_br node.
8641     Chain = getControlRoot();
8642   }
8643 
8644   MCSymbol *BeginLabel = nullptr;
8645   if (EmitEHLabels) {
8646     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8647   }
8648 
8649   // Second pass over the constraints: compute which constraint option to use.
8650   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8651     // If this is an output operand with a matching input operand, look up the
8652     // matching input. If their types mismatch, e.g. one is an integer, the
8653     // other is floating point, or their sizes are different, flag it as an
8654     // error.
8655     if (OpInfo.hasMatchingInput()) {
8656       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8657       patchMatchingInput(OpInfo, Input, DAG);
8658     }
8659 
8660     // Compute the constraint code and ConstraintType to use.
8661     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8662 
8663     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8664         OpInfo.Type == InlineAsm::isClobber)
8665       continue;
8666 
8667     // If this is a memory input, and if the operand is not indirect, do what we
8668     // need to provide an address for the memory input.
8669     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8670         !OpInfo.isIndirect) {
8671       assert((OpInfo.isMultipleAlternative ||
8672               (OpInfo.Type == InlineAsm::isInput)) &&
8673              "Can only indirectify direct input operands!");
8674 
8675       // Memory operands really want the address of the value.
8676       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8677 
8678       // There is no longer a Value* corresponding to this operand.
8679       OpInfo.CallOperandVal = nullptr;
8680 
8681       // It is now an indirect operand.
8682       OpInfo.isIndirect = true;
8683     }
8684 
8685   }
8686 
8687   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8688   std::vector<SDValue> AsmNodeOperands;
8689   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8690   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8691       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8692 
8693   // If we have a !srcloc metadata node associated with it, we want to attach
8694   // this to the ultimately generated inline asm machineinstr.  To do this, we
8695   // pass in the third operand as this (potentially null) inline asm MDNode.
8696   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8697   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8698 
8699   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8700   // bits as operand 3.
8701   AsmNodeOperands.push_back(DAG.getTargetConstant(
8702       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8703 
8704   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8705   // this, assign virtual and physical registers for inputs and otput.
8706   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8707     // Assign Registers.
8708     SDISelAsmOperandInfo &RefOpInfo =
8709         OpInfo.isMatchingInputConstraint()
8710             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8711             : OpInfo;
8712     const auto RegError =
8713         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8714     if (RegError.hasValue()) {
8715       const MachineFunction &MF = DAG.getMachineFunction();
8716       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8717       const char *RegName = TRI.getName(RegError.getValue());
8718       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8719                                    "' allocated for constraint '" +
8720                                    Twine(OpInfo.ConstraintCode) +
8721                                    "' does not match required type");
8722       return;
8723     }
8724 
8725     auto DetectWriteToReservedRegister = [&]() {
8726       const MachineFunction &MF = DAG.getMachineFunction();
8727       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8728       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8729         if (Register::isPhysicalRegister(Reg) &&
8730             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8731           const char *RegName = TRI.getName(Reg);
8732           emitInlineAsmError(Call, "write to reserved register '" +
8733                                        Twine(RegName) + "'");
8734           return true;
8735         }
8736       }
8737       return false;
8738     };
8739 
8740     switch (OpInfo.Type) {
8741     case InlineAsm::isOutput:
8742       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8743         unsigned ConstraintID =
8744             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8745         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8746                "Failed to convert memory constraint code to constraint id.");
8747 
8748         // Add information to the INLINEASM node to know about this output.
8749         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8750         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8751         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8752                                                         MVT::i32));
8753         AsmNodeOperands.push_back(OpInfo.CallOperand);
8754       } else {
8755         // Otherwise, this outputs to a register (directly for C_Register /
8756         // C_RegisterClass, and a target-defined fashion for
8757         // C_Immediate/C_Other). Find a register that we can use.
8758         if (OpInfo.AssignedRegs.Regs.empty()) {
8759           emitInlineAsmError(
8760               Call, "couldn't allocate output register for constraint '" +
8761                         Twine(OpInfo.ConstraintCode) + "'");
8762           return;
8763         }
8764 
8765         if (DetectWriteToReservedRegister())
8766           return;
8767 
8768         // Add information to the INLINEASM node to know that this register is
8769         // set.
8770         OpInfo.AssignedRegs.AddInlineAsmOperands(
8771             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8772                                   : InlineAsm::Kind_RegDef,
8773             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8774       }
8775       break;
8776 
8777     case InlineAsm::isInput: {
8778       SDValue InOperandVal = OpInfo.CallOperand;
8779 
8780       if (OpInfo.isMatchingInputConstraint()) {
8781         // If this is required to match an output register we have already set,
8782         // just use its register.
8783         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8784                                                   AsmNodeOperands);
8785         unsigned OpFlag =
8786           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8787         if (InlineAsm::isRegDefKind(OpFlag) ||
8788             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8789           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8790           if (OpInfo.isIndirect) {
8791             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8792             emitInlineAsmError(Call, "inline asm not supported yet: "
8793                                      "don't know how to handle tied "
8794                                      "indirect register inputs");
8795             return;
8796           }
8797 
8798           SmallVector<unsigned, 4> Regs;
8799           MachineFunction &MF = DAG.getMachineFunction();
8800           MachineRegisterInfo &MRI = MF.getRegInfo();
8801           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8802           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8803           Register TiedReg = R->getReg();
8804           MVT RegVT = R->getSimpleValueType(0);
8805           const TargetRegisterClass *RC =
8806               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8807               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8808                                       : TRI.getMinimalPhysRegClass(TiedReg);
8809           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8810           for (unsigned i = 0; i != NumRegs; ++i)
8811             Regs.push_back(MRI.createVirtualRegister(RC));
8812 
8813           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8814 
8815           SDLoc dl = getCurSDLoc();
8816           // Use the produced MatchedRegs object to
8817           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8818           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8819                                            true, OpInfo.getMatchedOperand(), dl,
8820                                            DAG, AsmNodeOperands);
8821           break;
8822         }
8823 
8824         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8825         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8826                "Unexpected number of operands");
8827         // Add information to the INLINEASM node to know about this input.
8828         // See InlineAsm.h isUseOperandTiedToDef.
8829         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8830         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8831                                                     OpInfo.getMatchedOperand());
8832         AsmNodeOperands.push_back(DAG.getTargetConstant(
8833             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8834         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8835         break;
8836       }
8837 
8838       // Treat indirect 'X' constraint as memory.
8839       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8840           OpInfo.isIndirect)
8841         OpInfo.ConstraintType = TargetLowering::C_Memory;
8842 
8843       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8844           OpInfo.ConstraintType == TargetLowering::C_Other) {
8845         std::vector<SDValue> Ops;
8846         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8847                                           Ops, DAG);
8848         if (Ops.empty()) {
8849           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8850             if (isa<ConstantSDNode>(InOperandVal)) {
8851               emitInlineAsmError(Call, "value out of range for constraint '" +
8852                                            Twine(OpInfo.ConstraintCode) + "'");
8853               return;
8854             }
8855 
8856           emitInlineAsmError(Call,
8857                              "invalid operand for inline asm constraint '" +
8858                                  Twine(OpInfo.ConstraintCode) + "'");
8859           return;
8860         }
8861 
8862         // Add information to the INLINEASM node to know about this input.
8863         unsigned ResOpType =
8864           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8865         AsmNodeOperands.push_back(DAG.getTargetConstant(
8866             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8867         llvm::append_range(AsmNodeOperands, Ops);
8868         break;
8869       }
8870 
8871       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8872         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8873         assert(InOperandVal.getValueType() ==
8874                    TLI.getPointerTy(DAG.getDataLayout()) &&
8875                "Memory operands expect pointer values");
8876 
8877         unsigned ConstraintID =
8878             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8879         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8880                "Failed to convert memory constraint code to constraint id.");
8881 
8882         // Add information to the INLINEASM node to know about this input.
8883         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8884         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8885         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8886                                                         getCurSDLoc(),
8887                                                         MVT::i32));
8888         AsmNodeOperands.push_back(InOperandVal);
8889         break;
8890       }
8891 
8892       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8893               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8894              "Unknown constraint type!");
8895 
8896       // TODO: Support this.
8897       if (OpInfo.isIndirect) {
8898         emitInlineAsmError(
8899             Call, "Don't know how to handle indirect register inputs yet "
8900                   "for constraint '" +
8901                       Twine(OpInfo.ConstraintCode) + "'");
8902         return;
8903       }
8904 
8905       // Copy the input into the appropriate registers.
8906       if (OpInfo.AssignedRegs.Regs.empty()) {
8907         emitInlineAsmError(Call,
8908                            "couldn't allocate input reg for constraint '" +
8909                                Twine(OpInfo.ConstraintCode) + "'");
8910         return;
8911       }
8912 
8913       if (DetectWriteToReservedRegister())
8914         return;
8915 
8916       SDLoc dl = getCurSDLoc();
8917 
8918       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8919                                         &Call);
8920 
8921       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8922                                                dl, DAG, AsmNodeOperands);
8923       break;
8924     }
8925     case InlineAsm::isClobber:
8926       // Add the clobbered value to the operand list, so that the register
8927       // allocator is aware that the physreg got clobbered.
8928       if (!OpInfo.AssignedRegs.Regs.empty())
8929         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8930                                                  false, 0, getCurSDLoc(), DAG,
8931                                                  AsmNodeOperands);
8932       break;
8933     }
8934   }
8935 
8936   // Finish up input operands.  Set the input chain and add the flag last.
8937   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8938   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8939 
8940   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8941   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8942                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8943   Flag = Chain.getValue(1);
8944 
8945   // Do additional work to generate outputs.
8946 
8947   SmallVector<EVT, 1> ResultVTs;
8948   SmallVector<SDValue, 1> ResultValues;
8949   SmallVector<SDValue, 8> OutChains;
8950 
8951   llvm::Type *CallResultType = Call.getType();
8952   ArrayRef<Type *> ResultTypes;
8953   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8954     ResultTypes = StructResult->elements();
8955   else if (!CallResultType->isVoidTy())
8956     ResultTypes = makeArrayRef(CallResultType);
8957 
8958   auto CurResultType = ResultTypes.begin();
8959   auto handleRegAssign = [&](SDValue V) {
8960     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8961     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8962     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8963     ++CurResultType;
8964     // If the type of the inline asm call site return value is different but has
8965     // same size as the type of the asm output bitcast it.  One example of this
8966     // is for vectors with different width / number of elements.  This can
8967     // happen for register classes that can contain multiple different value
8968     // types.  The preg or vreg allocated may not have the same VT as was
8969     // expected.
8970     //
8971     // This can also happen for a return value that disagrees with the register
8972     // class it is put in, eg. a double in a general-purpose register on a
8973     // 32-bit machine.
8974     if (ResultVT != V.getValueType() &&
8975         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8976       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8977     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8978              V.getValueType().isInteger()) {
8979       // If a result value was tied to an input value, the computed result
8980       // may have a wider width than the expected result.  Extract the
8981       // relevant portion.
8982       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8983     }
8984     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8985     ResultVTs.push_back(ResultVT);
8986     ResultValues.push_back(V);
8987   };
8988 
8989   // Deal with output operands.
8990   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8991     if (OpInfo.Type == InlineAsm::isOutput) {
8992       SDValue Val;
8993       // Skip trivial output operands.
8994       if (OpInfo.AssignedRegs.Regs.empty())
8995         continue;
8996 
8997       switch (OpInfo.ConstraintType) {
8998       case TargetLowering::C_Register:
8999       case TargetLowering::C_RegisterClass:
9000         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9001                                                   Chain, &Flag, &Call);
9002         break;
9003       case TargetLowering::C_Immediate:
9004       case TargetLowering::C_Other:
9005         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9006                                               OpInfo, DAG);
9007         break;
9008       case TargetLowering::C_Memory:
9009         break; // Already handled.
9010       case TargetLowering::C_Unknown:
9011         assert(false && "Unexpected unknown constraint");
9012       }
9013 
9014       // Indirect output manifest as stores. Record output chains.
9015       if (OpInfo.isIndirect) {
9016         const Value *Ptr = OpInfo.CallOperandVal;
9017         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9018         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9019                                      MachinePointerInfo(Ptr));
9020         OutChains.push_back(Store);
9021       } else {
9022         // generate CopyFromRegs to associated registers.
9023         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9024         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9025           for (const SDValue &V : Val->op_values())
9026             handleRegAssign(V);
9027         } else
9028           handleRegAssign(Val);
9029       }
9030     }
9031   }
9032 
9033   // Set results.
9034   if (!ResultValues.empty()) {
9035     assert(CurResultType == ResultTypes.end() &&
9036            "Mismatch in number of ResultTypes");
9037     assert(ResultValues.size() == ResultTypes.size() &&
9038            "Mismatch in number of output operands in asm result");
9039 
9040     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9041                             DAG.getVTList(ResultVTs), ResultValues);
9042     setValue(&Call, V);
9043   }
9044 
9045   // Collect store chains.
9046   if (!OutChains.empty())
9047     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9048 
9049   if (EmitEHLabels) {
9050     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9051   }
9052 
9053   // Only Update Root if inline assembly has a memory effect.
9054   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9055       EmitEHLabels)
9056     DAG.setRoot(Chain);
9057 }
9058 
9059 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9060                                              const Twine &Message) {
9061   LLVMContext &Ctx = *DAG.getContext();
9062   Ctx.emitError(&Call, Message);
9063 
9064   // Make sure we leave the DAG in a valid state
9065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9066   SmallVector<EVT, 1> ValueVTs;
9067   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9068 
9069   if (ValueVTs.empty())
9070     return;
9071 
9072   SmallVector<SDValue, 1> Ops;
9073   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9074     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9075 
9076   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9077 }
9078 
9079 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9080   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9081                           MVT::Other, getRoot(),
9082                           getValue(I.getArgOperand(0)),
9083                           DAG.getSrcValue(I.getArgOperand(0))));
9084 }
9085 
9086 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9088   const DataLayout &DL = DAG.getDataLayout();
9089   SDValue V = DAG.getVAArg(
9090       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9091       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9092       DL.getABITypeAlign(I.getType()).value());
9093   DAG.setRoot(V.getValue(1));
9094 
9095   if (I.getType()->isPointerTy())
9096     V = DAG.getPtrExtOrTrunc(
9097         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9098   setValue(&I, V);
9099 }
9100 
9101 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9102   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9103                           MVT::Other, getRoot(),
9104                           getValue(I.getArgOperand(0)),
9105                           DAG.getSrcValue(I.getArgOperand(0))));
9106 }
9107 
9108 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9109   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9110                           MVT::Other, getRoot(),
9111                           getValue(I.getArgOperand(0)),
9112                           getValue(I.getArgOperand(1)),
9113                           DAG.getSrcValue(I.getArgOperand(0)),
9114                           DAG.getSrcValue(I.getArgOperand(1))));
9115 }
9116 
9117 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9118                                                     const Instruction &I,
9119                                                     SDValue Op) {
9120   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9121   if (!Range)
9122     return Op;
9123 
9124   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9125   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9126     return Op;
9127 
9128   APInt Lo = CR.getUnsignedMin();
9129   if (!Lo.isMinValue())
9130     return Op;
9131 
9132   APInt Hi = CR.getUnsignedMax();
9133   unsigned Bits = std::max(Hi.getActiveBits(),
9134                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9135 
9136   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9137 
9138   SDLoc SL = getCurSDLoc();
9139 
9140   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9141                              DAG.getValueType(SmallVT));
9142   unsigned NumVals = Op.getNode()->getNumValues();
9143   if (NumVals == 1)
9144     return ZExt;
9145 
9146   SmallVector<SDValue, 4> Ops;
9147 
9148   Ops.push_back(ZExt);
9149   for (unsigned I = 1; I != NumVals; ++I)
9150     Ops.push_back(Op.getValue(I));
9151 
9152   return DAG.getMergeValues(Ops, SL);
9153 }
9154 
9155 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9156 /// the call being lowered.
9157 ///
9158 /// This is a helper for lowering intrinsics that follow a target calling
9159 /// convention or require stack pointer adjustment. Only a subset of the
9160 /// intrinsic's operands need to participate in the calling convention.
9161 void SelectionDAGBuilder::populateCallLoweringInfo(
9162     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9163     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9164     bool IsPatchPoint) {
9165   TargetLowering::ArgListTy Args;
9166   Args.reserve(NumArgs);
9167 
9168   // Populate the argument list.
9169   // Attributes for args start at offset 1, after the return attribute.
9170   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9171        ArgI != ArgE; ++ArgI) {
9172     const Value *V = Call->getOperand(ArgI);
9173 
9174     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9175 
9176     TargetLowering::ArgListEntry Entry;
9177     Entry.Node = getValue(V);
9178     Entry.Ty = V->getType();
9179     Entry.setAttributes(Call, ArgI);
9180     Args.push_back(Entry);
9181   }
9182 
9183   CLI.setDebugLoc(getCurSDLoc())
9184       .setChain(getRoot())
9185       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9186       .setDiscardResult(Call->use_empty())
9187       .setIsPatchPoint(IsPatchPoint)
9188       .setIsPreallocated(
9189           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9190 }
9191 
9192 /// Add a stack map intrinsic call's live variable operands to a stackmap
9193 /// or patchpoint target node's operand list.
9194 ///
9195 /// Constants are converted to TargetConstants purely as an optimization to
9196 /// avoid constant materialization and register allocation.
9197 ///
9198 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9199 /// generate addess computation nodes, and so FinalizeISel can convert the
9200 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9201 /// address materialization and register allocation, but may also be required
9202 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9203 /// alloca in the entry block, then the runtime may assume that the alloca's
9204 /// StackMap location can be read immediately after compilation and that the
9205 /// location is valid at any point during execution (this is similar to the
9206 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9207 /// only available in a register, then the runtime would need to trap when
9208 /// execution reaches the StackMap in order to read the alloca's location.
9209 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9210                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9211                                 SelectionDAGBuilder &Builder) {
9212   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9213     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9214     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9215       Ops.push_back(
9216         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9217       Ops.push_back(
9218         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9219     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9220       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9221       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9222           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9223     } else
9224       Ops.push_back(OpVal);
9225   }
9226 }
9227 
9228 /// Lower llvm.experimental.stackmap directly to its target opcode.
9229 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9230   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9231   //                                  [live variables...])
9232 
9233   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9234 
9235   SDValue Chain, InFlag, Callee, NullPtr;
9236   SmallVector<SDValue, 32> Ops;
9237 
9238   SDLoc DL = getCurSDLoc();
9239   Callee = getValue(CI.getCalledOperand());
9240   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9241 
9242   // The stackmap intrinsic only records the live variables (the arguments
9243   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9244   // intrinsic, this won't be lowered to a function call. This means we don't
9245   // have to worry about calling conventions and target specific lowering code.
9246   // Instead we perform the call lowering right here.
9247   //
9248   // chain, flag = CALLSEQ_START(chain, 0, 0)
9249   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9250   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9251   //
9252   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9253   InFlag = Chain.getValue(1);
9254 
9255   // Add the <id> and <numBytes> constants.
9256   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9257   Ops.push_back(DAG.getTargetConstant(
9258                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9259   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9260   Ops.push_back(DAG.getTargetConstant(
9261                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9262                   MVT::i32));
9263 
9264   // Push live variables for the stack map.
9265   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9266 
9267   // We are not pushing any register mask info here on the operands list,
9268   // because the stackmap doesn't clobber anything.
9269 
9270   // Push the chain and the glue flag.
9271   Ops.push_back(Chain);
9272   Ops.push_back(InFlag);
9273 
9274   // Create the STACKMAP node.
9275   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9276   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9277   Chain = SDValue(SM, 0);
9278   InFlag = Chain.getValue(1);
9279 
9280   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9281 
9282   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9283 
9284   // Set the root to the target-lowered call chain.
9285   DAG.setRoot(Chain);
9286 
9287   // Inform the Frame Information that we have a stackmap in this function.
9288   FuncInfo.MF->getFrameInfo().setHasStackMap();
9289 }
9290 
9291 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9292 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9293                                           const BasicBlock *EHPadBB) {
9294   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9295   //                                                 i32 <numBytes>,
9296   //                                                 i8* <target>,
9297   //                                                 i32 <numArgs>,
9298   //                                                 [Args...],
9299   //                                                 [live variables...])
9300 
9301   CallingConv::ID CC = CB.getCallingConv();
9302   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9303   bool HasDef = !CB.getType()->isVoidTy();
9304   SDLoc dl = getCurSDLoc();
9305   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9306 
9307   // Handle immediate and symbolic callees.
9308   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9309     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9310                                    /*isTarget=*/true);
9311   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9312     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9313                                          SDLoc(SymbolicCallee),
9314                                          SymbolicCallee->getValueType(0));
9315 
9316   // Get the real number of arguments participating in the call <numArgs>
9317   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9318   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9319 
9320   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9321   // Intrinsics include all meta-operands up to but not including CC.
9322   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9323   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9324          "Not enough arguments provided to the patchpoint intrinsic");
9325 
9326   // For AnyRegCC the arguments are lowered later on manually.
9327   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9328   Type *ReturnTy =
9329       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9330 
9331   TargetLowering::CallLoweringInfo CLI(DAG);
9332   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9333                            ReturnTy, true);
9334   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9335 
9336   SDNode *CallEnd = Result.second.getNode();
9337   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9338     CallEnd = CallEnd->getOperand(0).getNode();
9339 
9340   /// Get a call instruction from the call sequence chain.
9341   /// Tail calls are not allowed.
9342   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9343          "Expected a callseq node.");
9344   SDNode *Call = CallEnd->getOperand(0).getNode();
9345   bool HasGlue = Call->getGluedNode();
9346 
9347   // Replace the target specific call node with the patchable intrinsic.
9348   SmallVector<SDValue, 8> Ops;
9349 
9350   // Add the <id> and <numBytes> constants.
9351   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9352   Ops.push_back(DAG.getTargetConstant(
9353                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9354   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9355   Ops.push_back(DAG.getTargetConstant(
9356                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9357                   MVT::i32));
9358 
9359   // Add the callee.
9360   Ops.push_back(Callee);
9361 
9362   // Adjust <numArgs> to account for any arguments that have been passed on the
9363   // stack instead.
9364   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9365   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9366   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9367   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9368 
9369   // Add the calling convention
9370   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9371 
9372   // Add the arguments we omitted previously. The register allocator should
9373   // place these in any free register.
9374   if (IsAnyRegCC)
9375     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9376       Ops.push_back(getValue(CB.getArgOperand(i)));
9377 
9378   // Push the arguments from the call instruction up to the register mask.
9379   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9380   Ops.append(Call->op_begin() + 2, e);
9381 
9382   // Push live variables for the stack map.
9383   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9384 
9385   // Push the register mask info.
9386   if (HasGlue)
9387     Ops.push_back(*(Call->op_end()-2));
9388   else
9389     Ops.push_back(*(Call->op_end()-1));
9390 
9391   // Push the chain (this is originally the first operand of the call, but
9392   // becomes now the last or second to last operand).
9393   Ops.push_back(*(Call->op_begin()));
9394 
9395   // Push the glue flag (last operand).
9396   if (HasGlue)
9397     Ops.push_back(*(Call->op_end()-1));
9398 
9399   SDVTList NodeTys;
9400   if (IsAnyRegCC && HasDef) {
9401     // Create the return types based on the intrinsic definition
9402     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9403     SmallVector<EVT, 3> ValueVTs;
9404     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9405     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9406 
9407     // There is always a chain and a glue type at the end
9408     ValueVTs.push_back(MVT::Other);
9409     ValueVTs.push_back(MVT::Glue);
9410     NodeTys = DAG.getVTList(ValueVTs);
9411   } else
9412     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9413 
9414   // Replace the target specific call node with a PATCHPOINT node.
9415   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9416                                          dl, NodeTys, Ops);
9417 
9418   // Update the NodeMap.
9419   if (HasDef) {
9420     if (IsAnyRegCC)
9421       setValue(&CB, SDValue(MN, 0));
9422     else
9423       setValue(&CB, Result.first);
9424   }
9425 
9426   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9427   // call sequence. Furthermore the location of the chain and glue can change
9428   // when the AnyReg calling convention is used and the intrinsic returns a
9429   // value.
9430   if (IsAnyRegCC && HasDef) {
9431     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9432     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9433     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9434   } else
9435     DAG.ReplaceAllUsesWith(Call, MN);
9436   DAG.DeleteNode(Call);
9437 
9438   // Inform the Frame Information that we have a patchpoint in this function.
9439   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9440 }
9441 
9442 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9443                                             unsigned Intrinsic) {
9444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9445   SDValue Op1 = getValue(I.getArgOperand(0));
9446   SDValue Op2;
9447   if (I.arg_size() > 1)
9448     Op2 = getValue(I.getArgOperand(1));
9449   SDLoc dl = getCurSDLoc();
9450   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9451   SDValue Res;
9452   SDNodeFlags SDFlags;
9453   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9454     SDFlags.copyFMF(*FPMO);
9455 
9456   switch (Intrinsic) {
9457   case Intrinsic::vector_reduce_fadd:
9458     if (SDFlags.hasAllowReassociation())
9459       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9460                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9461                         SDFlags);
9462     else
9463       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9464     break;
9465   case Intrinsic::vector_reduce_fmul:
9466     if (SDFlags.hasAllowReassociation())
9467       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9468                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9469                         SDFlags);
9470     else
9471       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9472     break;
9473   case Intrinsic::vector_reduce_add:
9474     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9475     break;
9476   case Intrinsic::vector_reduce_mul:
9477     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9478     break;
9479   case Intrinsic::vector_reduce_and:
9480     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9481     break;
9482   case Intrinsic::vector_reduce_or:
9483     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9484     break;
9485   case Intrinsic::vector_reduce_xor:
9486     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9487     break;
9488   case Intrinsic::vector_reduce_smax:
9489     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9490     break;
9491   case Intrinsic::vector_reduce_smin:
9492     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9493     break;
9494   case Intrinsic::vector_reduce_umax:
9495     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9496     break;
9497   case Intrinsic::vector_reduce_umin:
9498     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9499     break;
9500   case Intrinsic::vector_reduce_fmax:
9501     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9502     break;
9503   case Intrinsic::vector_reduce_fmin:
9504     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9505     break;
9506   default:
9507     llvm_unreachable("Unhandled vector reduce intrinsic");
9508   }
9509   setValue(&I, Res);
9510 }
9511 
9512 /// Returns an AttributeList representing the attributes applied to the return
9513 /// value of the given call.
9514 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9515   SmallVector<Attribute::AttrKind, 2> Attrs;
9516   if (CLI.RetSExt)
9517     Attrs.push_back(Attribute::SExt);
9518   if (CLI.RetZExt)
9519     Attrs.push_back(Attribute::ZExt);
9520   if (CLI.IsInReg)
9521     Attrs.push_back(Attribute::InReg);
9522 
9523   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9524                             Attrs);
9525 }
9526 
9527 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9528 /// implementation, which just calls LowerCall.
9529 /// FIXME: When all targets are
9530 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9531 std::pair<SDValue, SDValue>
9532 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9533   // Handle the incoming return values from the call.
9534   CLI.Ins.clear();
9535   Type *OrigRetTy = CLI.RetTy;
9536   SmallVector<EVT, 4> RetTys;
9537   SmallVector<uint64_t, 4> Offsets;
9538   auto &DL = CLI.DAG.getDataLayout();
9539   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9540 
9541   if (CLI.IsPostTypeLegalization) {
9542     // If we are lowering a libcall after legalization, split the return type.
9543     SmallVector<EVT, 4> OldRetTys;
9544     SmallVector<uint64_t, 4> OldOffsets;
9545     RetTys.swap(OldRetTys);
9546     Offsets.swap(OldOffsets);
9547 
9548     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9549       EVT RetVT = OldRetTys[i];
9550       uint64_t Offset = OldOffsets[i];
9551       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9552       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9553       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9554       RetTys.append(NumRegs, RegisterVT);
9555       for (unsigned j = 0; j != NumRegs; ++j)
9556         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9557     }
9558   }
9559 
9560   SmallVector<ISD::OutputArg, 4> Outs;
9561   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9562 
9563   bool CanLowerReturn =
9564       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9565                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9566 
9567   SDValue DemoteStackSlot;
9568   int DemoteStackIdx = -100;
9569   if (!CanLowerReturn) {
9570     // FIXME: equivalent assert?
9571     // assert(!CS.hasInAllocaArgument() &&
9572     //        "sret demotion is incompatible with inalloca");
9573     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9574     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9575     MachineFunction &MF = CLI.DAG.getMachineFunction();
9576     DemoteStackIdx =
9577         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9578     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9579                                               DL.getAllocaAddrSpace());
9580 
9581     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9582     ArgListEntry Entry;
9583     Entry.Node = DemoteStackSlot;
9584     Entry.Ty = StackSlotPtrType;
9585     Entry.IsSExt = false;
9586     Entry.IsZExt = false;
9587     Entry.IsInReg = false;
9588     Entry.IsSRet = true;
9589     Entry.IsNest = false;
9590     Entry.IsByVal = false;
9591     Entry.IsByRef = false;
9592     Entry.IsReturned = false;
9593     Entry.IsSwiftSelf = false;
9594     Entry.IsSwiftAsync = false;
9595     Entry.IsSwiftError = false;
9596     Entry.IsCFGuardTarget = false;
9597     Entry.Alignment = Alignment;
9598     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9599     CLI.NumFixedArgs += 1;
9600     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9601 
9602     // sret demotion isn't compatible with tail-calls, since the sret argument
9603     // points into the callers stack frame.
9604     CLI.IsTailCall = false;
9605   } else {
9606     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9607         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9608     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9609       ISD::ArgFlagsTy Flags;
9610       if (NeedsRegBlock) {
9611         Flags.setInConsecutiveRegs();
9612         if (I == RetTys.size() - 1)
9613           Flags.setInConsecutiveRegsLast();
9614       }
9615       EVT VT = RetTys[I];
9616       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9617                                                      CLI.CallConv, VT);
9618       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9619                                                        CLI.CallConv, VT);
9620       for (unsigned i = 0; i != NumRegs; ++i) {
9621         ISD::InputArg MyFlags;
9622         MyFlags.Flags = Flags;
9623         MyFlags.VT = RegisterVT;
9624         MyFlags.ArgVT = VT;
9625         MyFlags.Used = CLI.IsReturnValueUsed;
9626         if (CLI.RetTy->isPointerTy()) {
9627           MyFlags.Flags.setPointer();
9628           MyFlags.Flags.setPointerAddrSpace(
9629               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9630         }
9631         if (CLI.RetSExt)
9632           MyFlags.Flags.setSExt();
9633         if (CLI.RetZExt)
9634           MyFlags.Flags.setZExt();
9635         if (CLI.IsInReg)
9636           MyFlags.Flags.setInReg();
9637         CLI.Ins.push_back(MyFlags);
9638       }
9639     }
9640   }
9641 
9642   // We push in swifterror return as the last element of CLI.Ins.
9643   ArgListTy &Args = CLI.getArgs();
9644   if (supportSwiftError()) {
9645     for (const ArgListEntry &Arg : Args) {
9646       if (Arg.IsSwiftError) {
9647         ISD::InputArg MyFlags;
9648         MyFlags.VT = getPointerTy(DL);
9649         MyFlags.ArgVT = EVT(getPointerTy(DL));
9650         MyFlags.Flags.setSwiftError();
9651         CLI.Ins.push_back(MyFlags);
9652       }
9653     }
9654   }
9655 
9656   // Handle all of the outgoing arguments.
9657   CLI.Outs.clear();
9658   CLI.OutVals.clear();
9659   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9660     SmallVector<EVT, 4> ValueVTs;
9661     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9662     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9663     Type *FinalType = Args[i].Ty;
9664     if (Args[i].IsByVal)
9665       FinalType = Args[i].IndirectType;
9666     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9667         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9668     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9669          ++Value) {
9670       EVT VT = ValueVTs[Value];
9671       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9672       SDValue Op = SDValue(Args[i].Node.getNode(),
9673                            Args[i].Node.getResNo() + Value);
9674       ISD::ArgFlagsTy Flags;
9675 
9676       // Certain targets (such as MIPS), may have a different ABI alignment
9677       // for a type depending on the context. Give the target a chance to
9678       // specify the alignment it wants.
9679       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9680       Flags.setOrigAlign(OriginalAlignment);
9681 
9682       if (Args[i].Ty->isPointerTy()) {
9683         Flags.setPointer();
9684         Flags.setPointerAddrSpace(
9685             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9686       }
9687       if (Args[i].IsZExt)
9688         Flags.setZExt();
9689       if (Args[i].IsSExt)
9690         Flags.setSExt();
9691       if (Args[i].IsInReg) {
9692         // If we are using vectorcall calling convention, a structure that is
9693         // passed InReg - is surely an HVA
9694         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9695             isa<StructType>(FinalType)) {
9696           // The first value of a structure is marked
9697           if (0 == Value)
9698             Flags.setHvaStart();
9699           Flags.setHva();
9700         }
9701         // Set InReg Flag
9702         Flags.setInReg();
9703       }
9704       if (Args[i].IsSRet)
9705         Flags.setSRet();
9706       if (Args[i].IsSwiftSelf)
9707         Flags.setSwiftSelf();
9708       if (Args[i].IsSwiftAsync)
9709         Flags.setSwiftAsync();
9710       if (Args[i].IsSwiftError)
9711         Flags.setSwiftError();
9712       if (Args[i].IsCFGuardTarget)
9713         Flags.setCFGuardTarget();
9714       if (Args[i].IsByVal)
9715         Flags.setByVal();
9716       if (Args[i].IsByRef)
9717         Flags.setByRef();
9718       if (Args[i].IsPreallocated) {
9719         Flags.setPreallocated();
9720         // Set the byval flag for CCAssignFn callbacks that don't know about
9721         // preallocated.  This way we can know how many bytes we should've
9722         // allocated and how many bytes a callee cleanup function will pop.  If
9723         // we port preallocated to more targets, we'll have to add custom
9724         // preallocated handling in the various CC lowering callbacks.
9725         Flags.setByVal();
9726       }
9727       if (Args[i].IsInAlloca) {
9728         Flags.setInAlloca();
9729         // Set the byval flag for CCAssignFn callbacks that don't know about
9730         // inalloca.  This way we can know how many bytes we should've allocated
9731         // and how many bytes a callee cleanup function will pop.  If we port
9732         // inalloca to more targets, we'll have to add custom inalloca handling
9733         // in the various CC lowering callbacks.
9734         Flags.setByVal();
9735       }
9736       Align MemAlign;
9737       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9738         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9739         Flags.setByValSize(FrameSize);
9740 
9741         // info is not there but there are cases it cannot get right.
9742         if (auto MA = Args[i].Alignment)
9743           MemAlign = *MA;
9744         else
9745           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9746       } else if (auto MA = Args[i].Alignment) {
9747         MemAlign = *MA;
9748       } else {
9749         MemAlign = OriginalAlignment;
9750       }
9751       Flags.setMemAlign(MemAlign);
9752       if (Args[i].IsNest)
9753         Flags.setNest();
9754       if (NeedsRegBlock)
9755         Flags.setInConsecutiveRegs();
9756 
9757       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9758                                                  CLI.CallConv, VT);
9759       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9760                                                         CLI.CallConv, VT);
9761       SmallVector<SDValue, 4> Parts(NumParts);
9762       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9763 
9764       if (Args[i].IsSExt)
9765         ExtendKind = ISD::SIGN_EXTEND;
9766       else if (Args[i].IsZExt)
9767         ExtendKind = ISD::ZERO_EXTEND;
9768 
9769       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9770       // for now.
9771       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9772           CanLowerReturn) {
9773         assert((CLI.RetTy == Args[i].Ty ||
9774                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9775                  CLI.RetTy->getPointerAddressSpace() ==
9776                      Args[i].Ty->getPointerAddressSpace())) &&
9777                RetTys.size() == NumValues && "unexpected use of 'returned'");
9778         // Before passing 'returned' to the target lowering code, ensure that
9779         // either the register MVT and the actual EVT are the same size or that
9780         // the return value and argument are extended in the same way; in these
9781         // cases it's safe to pass the argument register value unchanged as the
9782         // return register value (although it's at the target's option whether
9783         // to do so)
9784         // TODO: allow code generation to take advantage of partially preserved
9785         // registers rather than clobbering the entire register when the
9786         // parameter extension method is not compatible with the return
9787         // extension method
9788         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9789             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9790              CLI.RetZExt == Args[i].IsZExt))
9791           Flags.setReturned();
9792       }
9793 
9794       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9795                      CLI.CallConv, ExtendKind);
9796 
9797       for (unsigned j = 0; j != NumParts; ++j) {
9798         // if it isn't first piece, alignment must be 1
9799         // For scalable vectors the scalable part is currently handled
9800         // by individual targets, so we just use the known minimum size here.
9801         ISD::OutputArg MyFlags(
9802             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9803             i < CLI.NumFixedArgs, i,
9804             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9805         if (NumParts > 1 && j == 0)
9806           MyFlags.Flags.setSplit();
9807         else if (j != 0) {
9808           MyFlags.Flags.setOrigAlign(Align(1));
9809           if (j == NumParts - 1)
9810             MyFlags.Flags.setSplitEnd();
9811         }
9812 
9813         CLI.Outs.push_back(MyFlags);
9814         CLI.OutVals.push_back(Parts[j]);
9815       }
9816 
9817       if (NeedsRegBlock && Value == NumValues - 1)
9818         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9819     }
9820   }
9821 
9822   SmallVector<SDValue, 4> InVals;
9823   CLI.Chain = LowerCall(CLI, InVals);
9824 
9825   // Update CLI.InVals to use outside of this function.
9826   CLI.InVals = InVals;
9827 
9828   // Verify that the target's LowerCall behaved as expected.
9829   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9830          "LowerCall didn't return a valid chain!");
9831   assert((!CLI.IsTailCall || InVals.empty()) &&
9832          "LowerCall emitted a return value for a tail call!");
9833   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9834          "LowerCall didn't emit the correct number of values!");
9835 
9836   // For a tail call, the return value is merely live-out and there aren't
9837   // any nodes in the DAG representing it. Return a special value to
9838   // indicate that a tail call has been emitted and no more Instructions
9839   // should be processed in the current block.
9840   if (CLI.IsTailCall) {
9841     CLI.DAG.setRoot(CLI.Chain);
9842     return std::make_pair(SDValue(), SDValue());
9843   }
9844 
9845 #ifndef NDEBUG
9846   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9847     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9848     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9849            "LowerCall emitted a value with the wrong type!");
9850   }
9851 #endif
9852 
9853   SmallVector<SDValue, 4> ReturnValues;
9854   if (!CanLowerReturn) {
9855     // The instruction result is the result of loading from the
9856     // hidden sret parameter.
9857     SmallVector<EVT, 1> PVTs;
9858     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9859 
9860     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9861     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9862     EVT PtrVT = PVTs[0];
9863 
9864     unsigned NumValues = RetTys.size();
9865     ReturnValues.resize(NumValues);
9866     SmallVector<SDValue, 4> Chains(NumValues);
9867 
9868     // An aggregate return value cannot wrap around the address space, so
9869     // offsets to its parts don't wrap either.
9870     SDNodeFlags Flags;
9871     Flags.setNoUnsignedWrap(true);
9872 
9873     MachineFunction &MF = CLI.DAG.getMachineFunction();
9874     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9875     for (unsigned i = 0; i < NumValues; ++i) {
9876       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9877                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9878                                                         PtrVT), Flags);
9879       SDValue L = CLI.DAG.getLoad(
9880           RetTys[i], CLI.DL, CLI.Chain, Add,
9881           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9882                                             DemoteStackIdx, Offsets[i]),
9883           HiddenSRetAlign);
9884       ReturnValues[i] = L;
9885       Chains[i] = L.getValue(1);
9886     }
9887 
9888     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9889   } else {
9890     // Collect the legal value parts into potentially illegal values
9891     // that correspond to the original function's return values.
9892     Optional<ISD::NodeType> AssertOp;
9893     if (CLI.RetSExt)
9894       AssertOp = ISD::AssertSext;
9895     else if (CLI.RetZExt)
9896       AssertOp = ISD::AssertZext;
9897     unsigned CurReg = 0;
9898     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9899       EVT VT = RetTys[I];
9900       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9901                                                      CLI.CallConv, VT);
9902       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9903                                                        CLI.CallConv, VT);
9904 
9905       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9906                                               NumRegs, RegisterVT, VT, nullptr,
9907                                               CLI.CallConv, AssertOp));
9908       CurReg += NumRegs;
9909     }
9910 
9911     // For a function returning void, there is no return value. We can't create
9912     // such a node, so we just return a null return value in that case. In
9913     // that case, nothing will actually look at the value.
9914     if (ReturnValues.empty())
9915       return std::make_pair(SDValue(), CLI.Chain);
9916   }
9917 
9918   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9919                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9920   return std::make_pair(Res, CLI.Chain);
9921 }
9922 
9923 /// Places new result values for the node in Results (their number
9924 /// and types must exactly match those of the original return values of
9925 /// the node), or leaves Results empty, which indicates that the node is not
9926 /// to be custom lowered after all.
9927 void TargetLowering::LowerOperationWrapper(SDNode *N,
9928                                            SmallVectorImpl<SDValue> &Results,
9929                                            SelectionDAG &DAG) const {
9930   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9931 
9932   if (!Res.getNode())
9933     return;
9934 
9935   // If the original node has one result, take the return value from
9936   // LowerOperation as is. It might not be result number 0.
9937   if (N->getNumValues() == 1) {
9938     Results.push_back(Res);
9939     return;
9940   }
9941 
9942   // If the original node has multiple results, then the return node should
9943   // have the same number of results.
9944   assert((N->getNumValues() == Res->getNumValues()) &&
9945       "Lowering returned the wrong number of results!");
9946 
9947   // Places new result values base on N result number.
9948   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9949     Results.push_back(Res.getValue(I));
9950 }
9951 
9952 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9953   llvm_unreachable("LowerOperation not implemented for this target!");
9954 }
9955 
9956 void
9957 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9958   SDValue Op = getNonRegisterValue(V);
9959   assert((Op.getOpcode() != ISD::CopyFromReg ||
9960           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9961          "Copy from a reg to the same reg!");
9962   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9963 
9964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9965   // If this is an InlineAsm we have to match the registers required, not the
9966   // notional registers required by the type.
9967 
9968   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9969                    None); // This is not an ABI copy.
9970   SDValue Chain = DAG.getEntryNode();
9971 
9972   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9973   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9974   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9975     ExtendType = PreferredExtendIt->second;
9976   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9977   PendingExports.push_back(Chain);
9978 }
9979 
9980 #include "llvm/CodeGen/SelectionDAGISel.h"
9981 
9982 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9983 /// entry block, return true.  This includes arguments used by switches, since
9984 /// the switch may expand into multiple basic blocks.
9985 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9986   // With FastISel active, we may be splitting blocks, so force creation
9987   // of virtual registers for all non-dead arguments.
9988   if (FastISel)
9989     return A->use_empty();
9990 
9991   const BasicBlock &Entry = A->getParent()->front();
9992   for (const User *U : A->users())
9993     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9994       return false;  // Use not in entry block.
9995 
9996   return true;
9997 }
9998 
9999 using ArgCopyElisionMapTy =
10000     DenseMap<const Argument *,
10001              std::pair<const AllocaInst *, const StoreInst *>>;
10002 
10003 /// Scan the entry block of the function in FuncInfo for arguments that look
10004 /// like copies into a local alloca. Record any copied arguments in
10005 /// ArgCopyElisionCandidates.
10006 static void
10007 findArgumentCopyElisionCandidates(const DataLayout &DL,
10008                                   FunctionLoweringInfo *FuncInfo,
10009                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10010   // Record the state of every static alloca used in the entry block. Argument
10011   // allocas are all used in the entry block, so we need approximately as many
10012   // entries as we have arguments.
10013   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10014   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10015   unsigned NumArgs = FuncInfo->Fn->arg_size();
10016   StaticAllocas.reserve(NumArgs * 2);
10017 
10018   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10019     if (!V)
10020       return nullptr;
10021     V = V->stripPointerCasts();
10022     const auto *AI = dyn_cast<AllocaInst>(V);
10023     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10024       return nullptr;
10025     auto Iter = StaticAllocas.insert({AI, Unknown});
10026     return &Iter.first->second;
10027   };
10028 
10029   // Look for stores of arguments to static allocas. Look through bitcasts and
10030   // GEPs to handle type coercions, as long as the alloca is fully initialized
10031   // by the store. Any non-store use of an alloca escapes it and any subsequent
10032   // unanalyzed store might write it.
10033   // FIXME: Handle structs initialized with multiple stores.
10034   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10035     // Look for stores, and handle non-store uses conservatively.
10036     const auto *SI = dyn_cast<StoreInst>(&I);
10037     if (!SI) {
10038       // We will look through cast uses, so ignore them completely.
10039       if (I.isCast())
10040         continue;
10041       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10042       // to allocas.
10043       if (I.isDebugOrPseudoInst())
10044         continue;
10045       // This is an unknown instruction. Assume it escapes or writes to all
10046       // static alloca operands.
10047       for (const Use &U : I.operands()) {
10048         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10049           *Info = StaticAllocaInfo::Clobbered;
10050       }
10051       continue;
10052     }
10053 
10054     // If the stored value is a static alloca, mark it as escaped.
10055     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10056       *Info = StaticAllocaInfo::Clobbered;
10057 
10058     // Check if the destination is a static alloca.
10059     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10060     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10061     if (!Info)
10062       continue;
10063     const AllocaInst *AI = cast<AllocaInst>(Dst);
10064 
10065     // Skip allocas that have been initialized or clobbered.
10066     if (*Info != StaticAllocaInfo::Unknown)
10067       continue;
10068 
10069     // Check if the stored value is an argument, and that this store fully
10070     // initializes the alloca.
10071     // If the argument type has padding bits we can't directly forward a pointer
10072     // as the upper bits may contain garbage.
10073     // Don't elide copies from the same argument twice.
10074     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10075     const auto *Arg = dyn_cast<Argument>(Val);
10076     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10077         Arg->getType()->isEmptyTy() ||
10078         DL.getTypeStoreSize(Arg->getType()) !=
10079             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10080         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10081         ArgCopyElisionCandidates.count(Arg)) {
10082       *Info = StaticAllocaInfo::Clobbered;
10083       continue;
10084     }
10085 
10086     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10087                       << '\n');
10088 
10089     // Mark this alloca and store for argument copy elision.
10090     *Info = StaticAllocaInfo::Elidable;
10091     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10092 
10093     // Stop scanning if we've seen all arguments. This will happen early in -O0
10094     // builds, which is useful, because -O0 builds have large entry blocks and
10095     // many allocas.
10096     if (ArgCopyElisionCandidates.size() == NumArgs)
10097       break;
10098   }
10099 }
10100 
10101 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10102 /// ArgVal is a load from a suitable fixed stack object.
10103 static void tryToElideArgumentCopy(
10104     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10105     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10106     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10107     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10108     SDValue ArgVal, bool &ArgHasUses) {
10109   // Check if this is a load from a fixed stack object.
10110   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10111   if (!LNode)
10112     return;
10113   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10114   if (!FINode)
10115     return;
10116 
10117   // Check that the fixed stack object is the right size and alignment.
10118   // Look at the alignment that the user wrote on the alloca instead of looking
10119   // at the stack object.
10120   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10121   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10122   const AllocaInst *AI = ArgCopyIter->second.first;
10123   int FixedIndex = FINode->getIndex();
10124   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10125   int OldIndex = AllocaIndex;
10126   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10127   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10128     LLVM_DEBUG(
10129         dbgs() << "  argument copy elision failed due to bad fixed stack "
10130                   "object size\n");
10131     return;
10132   }
10133   Align RequiredAlignment = AI->getAlign();
10134   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10135     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10136                          "greater than stack argument alignment ("
10137                       << DebugStr(RequiredAlignment) << " vs "
10138                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10139     return;
10140   }
10141 
10142   // Perform the elision. Delete the old stack object and replace its only use
10143   // in the variable info map. Mark the stack object as mutable.
10144   LLVM_DEBUG({
10145     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10146            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10147            << '\n';
10148   });
10149   MFI.RemoveStackObject(OldIndex);
10150   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10151   AllocaIndex = FixedIndex;
10152   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10153   Chains.push_back(ArgVal.getValue(1));
10154 
10155   // Avoid emitting code for the store implementing the copy.
10156   const StoreInst *SI = ArgCopyIter->second.second;
10157   ElidedArgCopyInstrs.insert(SI);
10158 
10159   // Check for uses of the argument again so that we can avoid exporting ArgVal
10160   // if it is't used by anything other than the store.
10161   for (const Value *U : Arg.users()) {
10162     if (U != SI) {
10163       ArgHasUses = true;
10164       break;
10165     }
10166   }
10167 }
10168 
10169 void SelectionDAGISel::LowerArguments(const Function &F) {
10170   SelectionDAG &DAG = SDB->DAG;
10171   SDLoc dl = SDB->getCurSDLoc();
10172   const DataLayout &DL = DAG.getDataLayout();
10173   SmallVector<ISD::InputArg, 16> Ins;
10174 
10175   // In Naked functions we aren't going to save any registers.
10176   if (F.hasFnAttribute(Attribute::Naked))
10177     return;
10178 
10179   if (!FuncInfo->CanLowerReturn) {
10180     // Put in an sret pointer parameter before all the other parameters.
10181     SmallVector<EVT, 1> ValueVTs;
10182     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10183                     F.getReturnType()->getPointerTo(
10184                         DAG.getDataLayout().getAllocaAddrSpace()),
10185                     ValueVTs);
10186 
10187     // NOTE: Assuming that a pointer will never break down to more than one VT
10188     // or one register.
10189     ISD::ArgFlagsTy Flags;
10190     Flags.setSRet();
10191     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10192     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10193                          ISD::InputArg::NoArgIndex, 0);
10194     Ins.push_back(RetArg);
10195   }
10196 
10197   // Look for stores of arguments to static allocas. Mark such arguments with a
10198   // flag to ask the target to give us the memory location of that argument if
10199   // available.
10200   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10201   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10202                                     ArgCopyElisionCandidates);
10203 
10204   // Set up the incoming argument description vector.
10205   for (const Argument &Arg : F.args()) {
10206     unsigned ArgNo = Arg.getArgNo();
10207     SmallVector<EVT, 4> ValueVTs;
10208     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10209     bool isArgValueUsed = !Arg.use_empty();
10210     unsigned PartBase = 0;
10211     Type *FinalType = Arg.getType();
10212     if (Arg.hasAttribute(Attribute::ByVal))
10213       FinalType = Arg.getParamByValType();
10214     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10215         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10216     for (unsigned Value = 0, NumValues = ValueVTs.size();
10217          Value != NumValues; ++Value) {
10218       EVT VT = ValueVTs[Value];
10219       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10220       ISD::ArgFlagsTy Flags;
10221 
10222 
10223       if (Arg.getType()->isPointerTy()) {
10224         Flags.setPointer();
10225         Flags.setPointerAddrSpace(
10226             cast<PointerType>(Arg.getType())->getAddressSpace());
10227       }
10228       if (Arg.hasAttribute(Attribute::ZExt))
10229         Flags.setZExt();
10230       if (Arg.hasAttribute(Attribute::SExt))
10231         Flags.setSExt();
10232       if (Arg.hasAttribute(Attribute::InReg)) {
10233         // If we are using vectorcall calling convention, a structure that is
10234         // passed InReg - is surely an HVA
10235         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10236             isa<StructType>(Arg.getType())) {
10237           // The first value of a structure is marked
10238           if (0 == Value)
10239             Flags.setHvaStart();
10240           Flags.setHva();
10241         }
10242         // Set InReg Flag
10243         Flags.setInReg();
10244       }
10245       if (Arg.hasAttribute(Attribute::StructRet))
10246         Flags.setSRet();
10247       if (Arg.hasAttribute(Attribute::SwiftSelf))
10248         Flags.setSwiftSelf();
10249       if (Arg.hasAttribute(Attribute::SwiftAsync))
10250         Flags.setSwiftAsync();
10251       if (Arg.hasAttribute(Attribute::SwiftError))
10252         Flags.setSwiftError();
10253       if (Arg.hasAttribute(Attribute::ByVal))
10254         Flags.setByVal();
10255       if (Arg.hasAttribute(Attribute::ByRef))
10256         Flags.setByRef();
10257       if (Arg.hasAttribute(Attribute::InAlloca)) {
10258         Flags.setInAlloca();
10259         // Set the byval flag for CCAssignFn callbacks that don't know about
10260         // inalloca.  This way we can know how many bytes we should've allocated
10261         // and how many bytes a callee cleanup function will pop.  If we port
10262         // inalloca to more targets, we'll have to add custom inalloca handling
10263         // in the various CC lowering callbacks.
10264         Flags.setByVal();
10265       }
10266       if (Arg.hasAttribute(Attribute::Preallocated)) {
10267         Flags.setPreallocated();
10268         // Set the byval flag for CCAssignFn callbacks that don't know about
10269         // preallocated.  This way we can know how many bytes we should've
10270         // allocated and how many bytes a callee cleanup function will pop.  If
10271         // we port preallocated to more targets, we'll have to add custom
10272         // preallocated handling in the various CC lowering callbacks.
10273         Flags.setByVal();
10274       }
10275 
10276       // Certain targets (such as MIPS), may have a different ABI alignment
10277       // for a type depending on the context. Give the target a chance to
10278       // specify the alignment it wants.
10279       const Align OriginalAlignment(
10280           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10281       Flags.setOrigAlign(OriginalAlignment);
10282 
10283       Align MemAlign;
10284       Type *ArgMemTy = nullptr;
10285       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10286           Flags.isByRef()) {
10287         if (!ArgMemTy)
10288           ArgMemTy = Arg.getPointeeInMemoryValueType();
10289 
10290         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10291 
10292         // For in-memory arguments, size and alignment should be passed from FE.
10293         // BE will guess if this info is not there but there are cases it cannot
10294         // get right.
10295         if (auto ParamAlign = Arg.getParamStackAlign())
10296           MemAlign = *ParamAlign;
10297         else if ((ParamAlign = Arg.getParamAlign()))
10298           MemAlign = *ParamAlign;
10299         else
10300           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10301         if (Flags.isByRef())
10302           Flags.setByRefSize(MemSize);
10303         else
10304           Flags.setByValSize(MemSize);
10305       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10306         MemAlign = *ParamAlign;
10307       } else {
10308         MemAlign = OriginalAlignment;
10309       }
10310       Flags.setMemAlign(MemAlign);
10311 
10312       if (Arg.hasAttribute(Attribute::Nest))
10313         Flags.setNest();
10314       if (NeedsRegBlock)
10315         Flags.setInConsecutiveRegs();
10316       if (ArgCopyElisionCandidates.count(&Arg))
10317         Flags.setCopyElisionCandidate();
10318       if (Arg.hasAttribute(Attribute::Returned))
10319         Flags.setReturned();
10320 
10321       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10322           *CurDAG->getContext(), F.getCallingConv(), VT);
10323       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10324           *CurDAG->getContext(), F.getCallingConv(), VT);
10325       for (unsigned i = 0; i != NumRegs; ++i) {
10326         // For scalable vectors, use the minimum size; individual targets
10327         // are responsible for handling scalable vector arguments and
10328         // return values.
10329         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10330                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10331         if (NumRegs > 1 && i == 0)
10332           MyFlags.Flags.setSplit();
10333         // if it isn't first piece, alignment must be 1
10334         else if (i > 0) {
10335           MyFlags.Flags.setOrigAlign(Align(1));
10336           if (i == NumRegs - 1)
10337             MyFlags.Flags.setSplitEnd();
10338         }
10339         Ins.push_back(MyFlags);
10340       }
10341       if (NeedsRegBlock && Value == NumValues - 1)
10342         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10343       PartBase += VT.getStoreSize().getKnownMinSize();
10344     }
10345   }
10346 
10347   // Call the target to set up the argument values.
10348   SmallVector<SDValue, 8> InVals;
10349   SDValue NewRoot = TLI->LowerFormalArguments(
10350       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10351 
10352   // Verify that the target's LowerFormalArguments behaved as expected.
10353   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10354          "LowerFormalArguments didn't return a valid chain!");
10355   assert(InVals.size() == Ins.size() &&
10356          "LowerFormalArguments didn't emit the correct number of values!");
10357   LLVM_DEBUG({
10358     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10359       assert(InVals[i].getNode() &&
10360              "LowerFormalArguments emitted a null value!");
10361       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10362              "LowerFormalArguments emitted a value with the wrong type!");
10363     }
10364   });
10365 
10366   // Update the DAG with the new chain value resulting from argument lowering.
10367   DAG.setRoot(NewRoot);
10368 
10369   // Set up the argument values.
10370   unsigned i = 0;
10371   if (!FuncInfo->CanLowerReturn) {
10372     // Create a virtual register for the sret pointer, and put in a copy
10373     // from the sret argument into it.
10374     SmallVector<EVT, 1> ValueVTs;
10375     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10376                     F.getReturnType()->getPointerTo(
10377                         DAG.getDataLayout().getAllocaAddrSpace()),
10378                     ValueVTs);
10379     MVT VT = ValueVTs[0].getSimpleVT();
10380     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10381     Optional<ISD::NodeType> AssertOp = None;
10382     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10383                                         nullptr, F.getCallingConv(), AssertOp);
10384 
10385     MachineFunction& MF = SDB->DAG.getMachineFunction();
10386     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10387     Register SRetReg =
10388         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10389     FuncInfo->DemoteRegister = SRetReg;
10390     NewRoot =
10391         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10392     DAG.setRoot(NewRoot);
10393 
10394     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10395     ++i;
10396   }
10397 
10398   SmallVector<SDValue, 4> Chains;
10399   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10400   for (const Argument &Arg : F.args()) {
10401     SmallVector<SDValue, 4> ArgValues;
10402     SmallVector<EVT, 4> ValueVTs;
10403     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10404     unsigned NumValues = ValueVTs.size();
10405     if (NumValues == 0)
10406       continue;
10407 
10408     bool ArgHasUses = !Arg.use_empty();
10409 
10410     // Elide the copying store if the target loaded this argument from a
10411     // suitable fixed stack object.
10412     if (Ins[i].Flags.isCopyElisionCandidate()) {
10413       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10414                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10415                              InVals[i], ArgHasUses);
10416     }
10417 
10418     // If this argument is unused then remember its value. It is used to generate
10419     // debugging information.
10420     bool isSwiftErrorArg =
10421         TLI->supportSwiftError() &&
10422         Arg.hasAttribute(Attribute::SwiftError);
10423     if (!ArgHasUses && !isSwiftErrorArg) {
10424       SDB->setUnusedArgValue(&Arg, InVals[i]);
10425 
10426       // Also remember any frame index for use in FastISel.
10427       if (FrameIndexSDNode *FI =
10428           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10429         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10430     }
10431 
10432     for (unsigned Val = 0; Val != NumValues; ++Val) {
10433       EVT VT = ValueVTs[Val];
10434       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10435                                                       F.getCallingConv(), VT);
10436       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10437           *CurDAG->getContext(), F.getCallingConv(), VT);
10438 
10439       // Even an apparent 'unused' swifterror argument needs to be returned. So
10440       // we do generate a copy for it that can be used on return from the
10441       // function.
10442       if (ArgHasUses || isSwiftErrorArg) {
10443         Optional<ISD::NodeType> AssertOp;
10444         if (Arg.hasAttribute(Attribute::SExt))
10445           AssertOp = ISD::AssertSext;
10446         else if (Arg.hasAttribute(Attribute::ZExt))
10447           AssertOp = ISD::AssertZext;
10448 
10449         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10450                                              PartVT, VT, nullptr,
10451                                              F.getCallingConv(), AssertOp));
10452       }
10453 
10454       i += NumParts;
10455     }
10456 
10457     // We don't need to do anything else for unused arguments.
10458     if (ArgValues.empty())
10459       continue;
10460 
10461     // Note down frame index.
10462     if (FrameIndexSDNode *FI =
10463         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10464       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10465 
10466     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10467                                      SDB->getCurSDLoc());
10468 
10469     SDB->setValue(&Arg, Res);
10470     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10471       // We want to associate the argument with the frame index, among
10472       // involved operands, that correspond to the lowest address. The
10473       // getCopyFromParts function, called earlier, is swapping the order of
10474       // the operands to BUILD_PAIR depending on endianness. The result of
10475       // that swapping is that the least significant bits of the argument will
10476       // be in the first operand of the BUILD_PAIR node, and the most
10477       // significant bits will be in the second operand.
10478       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10479       if (LoadSDNode *LNode =
10480           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10481         if (FrameIndexSDNode *FI =
10482             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10483           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10484     }
10485 
10486     // Analyses past this point are naive and don't expect an assertion.
10487     if (Res.getOpcode() == ISD::AssertZext)
10488       Res = Res.getOperand(0);
10489 
10490     // Update the SwiftErrorVRegDefMap.
10491     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10492       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10493       if (Register::isVirtualRegister(Reg))
10494         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10495                                    Reg);
10496     }
10497 
10498     // If this argument is live outside of the entry block, insert a copy from
10499     // wherever we got it to the vreg that other BB's will reference it as.
10500     if (Res.getOpcode() == ISD::CopyFromReg) {
10501       // If we can, though, try to skip creating an unnecessary vreg.
10502       // FIXME: This isn't very clean... it would be nice to make this more
10503       // general.
10504       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10505       if (Register::isVirtualRegister(Reg)) {
10506         FuncInfo->ValueMap[&Arg] = Reg;
10507         continue;
10508       }
10509     }
10510     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10511       FuncInfo->InitializeRegForValue(&Arg);
10512       SDB->CopyToExportRegsIfNeeded(&Arg);
10513     }
10514   }
10515 
10516   if (!Chains.empty()) {
10517     Chains.push_back(NewRoot);
10518     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10519   }
10520 
10521   DAG.setRoot(NewRoot);
10522 
10523   assert(i == InVals.size() && "Argument register count mismatch!");
10524 
10525   // If any argument copy elisions occurred and we have debug info, update the
10526   // stale frame indices used in the dbg.declare variable info table.
10527   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10528   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10529     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10530       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10531       if (I != ArgCopyElisionFrameIndexMap.end())
10532         VI.Slot = I->second;
10533     }
10534   }
10535 
10536   // Finally, if the target has anything special to do, allow it to do so.
10537   emitFunctionEntryCode();
10538 }
10539 
10540 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10541 /// ensure constants are generated when needed.  Remember the virtual registers
10542 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10543 /// directly add them, because expansion might result in multiple MBB's for one
10544 /// BB.  As such, the start of the BB might correspond to a different MBB than
10545 /// the end.
10546 void
10547 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10548   const Instruction *TI = LLVMBB->getTerminator();
10549 
10550   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10551 
10552   // Check PHI nodes in successors that expect a value to be available from this
10553   // block.
10554   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10555     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10556     if (!isa<PHINode>(SuccBB->begin())) continue;
10557     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10558 
10559     // If this terminator has multiple identical successors (common for
10560     // switches), only handle each succ once.
10561     if (!SuccsHandled.insert(SuccMBB).second)
10562       continue;
10563 
10564     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10565 
10566     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10567     // nodes and Machine PHI nodes, but the incoming operands have not been
10568     // emitted yet.
10569     for (const PHINode &PN : SuccBB->phis()) {
10570       // Ignore dead phi's.
10571       if (PN.use_empty())
10572         continue;
10573 
10574       // Skip empty types
10575       if (PN.getType()->isEmptyTy())
10576         continue;
10577 
10578       unsigned Reg;
10579       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10580 
10581       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10582         unsigned &RegOut = ConstantsOut[C];
10583         if (RegOut == 0) {
10584           RegOut = FuncInfo.CreateRegs(C);
10585           CopyValueToVirtualRegister(C, RegOut);
10586         }
10587         Reg = RegOut;
10588       } else {
10589         DenseMap<const Value *, Register>::iterator I =
10590           FuncInfo.ValueMap.find(PHIOp);
10591         if (I != FuncInfo.ValueMap.end())
10592           Reg = I->second;
10593         else {
10594           assert(isa<AllocaInst>(PHIOp) &&
10595                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10596                  "Didn't codegen value into a register!??");
10597           Reg = FuncInfo.CreateRegs(PHIOp);
10598           CopyValueToVirtualRegister(PHIOp, Reg);
10599         }
10600       }
10601 
10602       // Remember that this register needs to added to the machine PHI node as
10603       // the input for this MBB.
10604       SmallVector<EVT, 4> ValueVTs;
10605       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10606       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10607       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10608         EVT VT = ValueVTs[vti];
10609         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10610         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10611           FuncInfo.PHINodesToUpdate.push_back(
10612               std::make_pair(&*MBBI++, Reg + i));
10613         Reg += NumRegisters;
10614       }
10615     }
10616   }
10617 
10618   ConstantsOut.clear();
10619 }
10620 
10621 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10622   MachineFunction::iterator I(MBB);
10623   if (++I == FuncInfo.MF->end())
10624     return nullptr;
10625   return &*I;
10626 }
10627 
10628 /// During lowering new call nodes can be created (such as memset, etc.).
10629 /// Those will become new roots of the current DAG, but complications arise
10630 /// when they are tail calls. In such cases, the call lowering will update
10631 /// the root, but the builder still needs to know that a tail call has been
10632 /// lowered in order to avoid generating an additional return.
10633 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10634   // If the node is null, we do have a tail call.
10635   if (MaybeTC.getNode() != nullptr)
10636     DAG.setRoot(MaybeTC);
10637   else
10638     HasTailCall = true;
10639 }
10640 
10641 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10642                                         MachineBasicBlock *SwitchMBB,
10643                                         MachineBasicBlock *DefaultMBB) {
10644   MachineFunction *CurMF = FuncInfo.MF;
10645   MachineBasicBlock *NextMBB = nullptr;
10646   MachineFunction::iterator BBI(W.MBB);
10647   if (++BBI != FuncInfo.MF->end())
10648     NextMBB = &*BBI;
10649 
10650   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10651 
10652   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10653 
10654   if (Size == 2 && W.MBB == SwitchMBB) {
10655     // If any two of the cases has the same destination, and if one value
10656     // is the same as the other, but has one bit unset that the other has set,
10657     // use bit manipulation to do two compares at once.  For example:
10658     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10659     // TODO: This could be extended to merge any 2 cases in switches with 3
10660     // cases.
10661     // TODO: Handle cases where W.CaseBB != SwitchBB.
10662     CaseCluster &Small = *W.FirstCluster;
10663     CaseCluster &Big = *W.LastCluster;
10664 
10665     if (Small.Low == Small.High && Big.Low == Big.High &&
10666         Small.MBB == Big.MBB) {
10667       const APInt &SmallValue = Small.Low->getValue();
10668       const APInt &BigValue = Big.Low->getValue();
10669 
10670       // Check that there is only one bit different.
10671       APInt CommonBit = BigValue ^ SmallValue;
10672       if (CommonBit.isPowerOf2()) {
10673         SDValue CondLHS = getValue(Cond);
10674         EVT VT = CondLHS.getValueType();
10675         SDLoc DL = getCurSDLoc();
10676 
10677         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10678                                  DAG.getConstant(CommonBit, DL, VT));
10679         SDValue Cond = DAG.getSetCC(
10680             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10681             ISD::SETEQ);
10682 
10683         // Update successor info.
10684         // Both Small and Big will jump to Small.BB, so we sum up the
10685         // probabilities.
10686         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10687         if (BPI)
10688           addSuccessorWithProb(
10689               SwitchMBB, DefaultMBB,
10690               // The default destination is the first successor in IR.
10691               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10692         else
10693           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10694 
10695         // Insert the true branch.
10696         SDValue BrCond =
10697             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10698                         DAG.getBasicBlock(Small.MBB));
10699         // Insert the false branch.
10700         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10701                              DAG.getBasicBlock(DefaultMBB));
10702 
10703         DAG.setRoot(BrCond);
10704         return;
10705       }
10706     }
10707   }
10708 
10709   if (TM.getOptLevel() != CodeGenOpt::None) {
10710     // Here, we order cases by probability so the most likely case will be
10711     // checked first. However, two clusters can have the same probability in
10712     // which case their relative ordering is non-deterministic. So we use Low
10713     // as a tie-breaker as clusters are guaranteed to never overlap.
10714     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10715                [](const CaseCluster &a, const CaseCluster &b) {
10716       return a.Prob != b.Prob ?
10717              a.Prob > b.Prob :
10718              a.Low->getValue().slt(b.Low->getValue());
10719     });
10720 
10721     // Rearrange the case blocks so that the last one falls through if possible
10722     // without changing the order of probabilities.
10723     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10724       --I;
10725       if (I->Prob > W.LastCluster->Prob)
10726         break;
10727       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10728         std::swap(*I, *W.LastCluster);
10729         break;
10730       }
10731     }
10732   }
10733 
10734   // Compute total probability.
10735   BranchProbability DefaultProb = W.DefaultProb;
10736   BranchProbability UnhandledProbs = DefaultProb;
10737   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10738     UnhandledProbs += I->Prob;
10739 
10740   MachineBasicBlock *CurMBB = W.MBB;
10741   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10742     bool FallthroughUnreachable = false;
10743     MachineBasicBlock *Fallthrough;
10744     if (I == W.LastCluster) {
10745       // For the last cluster, fall through to the default destination.
10746       Fallthrough = DefaultMBB;
10747       FallthroughUnreachable = isa<UnreachableInst>(
10748           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10749     } else {
10750       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10751       CurMF->insert(BBI, Fallthrough);
10752       // Put Cond in a virtual register to make it available from the new blocks.
10753       ExportFromCurrentBlock(Cond);
10754     }
10755     UnhandledProbs -= I->Prob;
10756 
10757     switch (I->Kind) {
10758       case CC_JumpTable: {
10759         // FIXME: Optimize away range check based on pivot comparisons.
10760         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10761         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10762 
10763         // The jump block hasn't been inserted yet; insert it here.
10764         MachineBasicBlock *JumpMBB = JT->MBB;
10765         CurMF->insert(BBI, JumpMBB);
10766 
10767         auto JumpProb = I->Prob;
10768         auto FallthroughProb = UnhandledProbs;
10769 
10770         // If the default statement is a target of the jump table, we evenly
10771         // distribute the default probability to successors of CurMBB. Also
10772         // update the probability on the edge from JumpMBB to Fallthrough.
10773         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10774                                               SE = JumpMBB->succ_end();
10775              SI != SE; ++SI) {
10776           if (*SI == DefaultMBB) {
10777             JumpProb += DefaultProb / 2;
10778             FallthroughProb -= DefaultProb / 2;
10779             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10780             JumpMBB->normalizeSuccProbs();
10781             break;
10782           }
10783         }
10784 
10785         if (FallthroughUnreachable)
10786           JTH->FallthroughUnreachable = true;
10787 
10788         if (!JTH->FallthroughUnreachable)
10789           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10790         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10791         CurMBB->normalizeSuccProbs();
10792 
10793         // The jump table header will be inserted in our current block, do the
10794         // range check, and fall through to our fallthrough block.
10795         JTH->HeaderBB = CurMBB;
10796         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10797 
10798         // If we're in the right place, emit the jump table header right now.
10799         if (CurMBB == SwitchMBB) {
10800           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10801           JTH->Emitted = true;
10802         }
10803         break;
10804       }
10805       case CC_BitTests: {
10806         // FIXME: Optimize away range check based on pivot comparisons.
10807         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10808 
10809         // The bit test blocks haven't been inserted yet; insert them here.
10810         for (BitTestCase &BTC : BTB->Cases)
10811           CurMF->insert(BBI, BTC.ThisBB);
10812 
10813         // Fill in fields of the BitTestBlock.
10814         BTB->Parent = CurMBB;
10815         BTB->Default = Fallthrough;
10816 
10817         BTB->DefaultProb = UnhandledProbs;
10818         // If the cases in bit test don't form a contiguous range, we evenly
10819         // distribute the probability on the edge to Fallthrough to two
10820         // successors of CurMBB.
10821         if (!BTB->ContiguousRange) {
10822           BTB->Prob += DefaultProb / 2;
10823           BTB->DefaultProb -= DefaultProb / 2;
10824         }
10825 
10826         if (FallthroughUnreachable)
10827           BTB->FallthroughUnreachable = true;
10828 
10829         // If we're in the right place, emit the bit test header right now.
10830         if (CurMBB == SwitchMBB) {
10831           visitBitTestHeader(*BTB, SwitchMBB);
10832           BTB->Emitted = true;
10833         }
10834         break;
10835       }
10836       case CC_Range: {
10837         const Value *RHS, *LHS, *MHS;
10838         ISD::CondCode CC;
10839         if (I->Low == I->High) {
10840           // Check Cond == I->Low.
10841           CC = ISD::SETEQ;
10842           LHS = Cond;
10843           RHS=I->Low;
10844           MHS = nullptr;
10845         } else {
10846           // Check I->Low <= Cond <= I->High.
10847           CC = ISD::SETLE;
10848           LHS = I->Low;
10849           MHS = Cond;
10850           RHS = I->High;
10851         }
10852 
10853         // If Fallthrough is unreachable, fold away the comparison.
10854         if (FallthroughUnreachable)
10855           CC = ISD::SETTRUE;
10856 
10857         // The false probability is the sum of all unhandled cases.
10858         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10859                      getCurSDLoc(), I->Prob, UnhandledProbs);
10860 
10861         if (CurMBB == SwitchMBB)
10862           visitSwitchCase(CB, SwitchMBB);
10863         else
10864           SL->SwitchCases.push_back(CB);
10865 
10866         break;
10867       }
10868     }
10869     CurMBB = Fallthrough;
10870   }
10871 }
10872 
10873 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10874                                               CaseClusterIt First,
10875                                               CaseClusterIt Last) {
10876   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10877     if (X.Prob != CC.Prob)
10878       return X.Prob > CC.Prob;
10879 
10880     // Ties are broken by comparing the case value.
10881     return X.Low->getValue().slt(CC.Low->getValue());
10882   });
10883 }
10884 
10885 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10886                                         const SwitchWorkListItem &W,
10887                                         Value *Cond,
10888                                         MachineBasicBlock *SwitchMBB) {
10889   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10890          "Clusters not sorted?");
10891 
10892   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10893 
10894   // Balance the tree based on branch probabilities to create a near-optimal (in
10895   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10896   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10897   CaseClusterIt LastLeft = W.FirstCluster;
10898   CaseClusterIt FirstRight = W.LastCluster;
10899   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10900   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10901 
10902   // Move LastLeft and FirstRight towards each other from opposite directions to
10903   // find a partitioning of the clusters which balances the probability on both
10904   // sides. If LeftProb and RightProb are equal, alternate which side is
10905   // taken to ensure 0-probability nodes are distributed evenly.
10906   unsigned I = 0;
10907   while (LastLeft + 1 < FirstRight) {
10908     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10909       LeftProb += (++LastLeft)->Prob;
10910     else
10911       RightProb += (--FirstRight)->Prob;
10912     I++;
10913   }
10914 
10915   while (true) {
10916     // Our binary search tree differs from a typical BST in that ours can have up
10917     // to three values in each leaf. The pivot selection above doesn't take that
10918     // into account, which means the tree might require more nodes and be less
10919     // efficient. We compensate for this here.
10920 
10921     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10922     unsigned NumRight = W.LastCluster - FirstRight + 1;
10923 
10924     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10925       // If one side has less than 3 clusters, and the other has more than 3,
10926       // consider taking a cluster from the other side.
10927 
10928       if (NumLeft < NumRight) {
10929         // Consider moving the first cluster on the right to the left side.
10930         CaseCluster &CC = *FirstRight;
10931         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10932         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10933         if (LeftSideRank <= RightSideRank) {
10934           // Moving the cluster to the left does not demote it.
10935           ++LastLeft;
10936           ++FirstRight;
10937           continue;
10938         }
10939       } else {
10940         assert(NumRight < NumLeft);
10941         // Consider moving the last element on the left to the right side.
10942         CaseCluster &CC = *LastLeft;
10943         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10944         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10945         if (RightSideRank <= LeftSideRank) {
10946           // Moving the cluster to the right does not demot it.
10947           --LastLeft;
10948           --FirstRight;
10949           continue;
10950         }
10951       }
10952     }
10953     break;
10954   }
10955 
10956   assert(LastLeft + 1 == FirstRight);
10957   assert(LastLeft >= W.FirstCluster);
10958   assert(FirstRight <= W.LastCluster);
10959 
10960   // Use the first element on the right as pivot since we will make less-than
10961   // comparisons against it.
10962   CaseClusterIt PivotCluster = FirstRight;
10963   assert(PivotCluster > W.FirstCluster);
10964   assert(PivotCluster <= W.LastCluster);
10965 
10966   CaseClusterIt FirstLeft = W.FirstCluster;
10967   CaseClusterIt LastRight = W.LastCluster;
10968 
10969   const ConstantInt *Pivot = PivotCluster->Low;
10970 
10971   // New blocks will be inserted immediately after the current one.
10972   MachineFunction::iterator BBI(W.MBB);
10973   ++BBI;
10974 
10975   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10976   // we can branch to its destination directly if it's squeezed exactly in
10977   // between the known lower bound and Pivot - 1.
10978   MachineBasicBlock *LeftMBB;
10979   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10980       FirstLeft->Low == W.GE &&
10981       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10982     LeftMBB = FirstLeft->MBB;
10983   } else {
10984     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10985     FuncInfo.MF->insert(BBI, LeftMBB);
10986     WorkList.push_back(
10987         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10988     // Put Cond in a virtual register to make it available from the new blocks.
10989     ExportFromCurrentBlock(Cond);
10990   }
10991 
10992   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10993   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10994   // directly if RHS.High equals the current upper bound.
10995   MachineBasicBlock *RightMBB;
10996   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10997       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10998     RightMBB = FirstRight->MBB;
10999   } else {
11000     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11001     FuncInfo.MF->insert(BBI, RightMBB);
11002     WorkList.push_back(
11003         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11004     // Put Cond in a virtual register to make it available from the new blocks.
11005     ExportFromCurrentBlock(Cond);
11006   }
11007 
11008   // Create the CaseBlock record that will be used to lower the branch.
11009   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11010                getCurSDLoc(), LeftProb, RightProb);
11011 
11012   if (W.MBB == SwitchMBB)
11013     visitSwitchCase(CB, SwitchMBB);
11014   else
11015     SL->SwitchCases.push_back(CB);
11016 }
11017 
11018 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11019 // from the swith statement.
11020 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11021                                             BranchProbability PeeledCaseProb) {
11022   if (PeeledCaseProb == BranchProbability::getOne())
11023     return BranchProbability::getZero();
11024   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11025 
11026   uint32_t Numerator = CaseProb.getNumerator();
11027   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11028   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11029 }
11030 
11031 // Try to peel the top probability case if it exceeds the threshold.
11032 // Return current MachineBasicBlock for the switch statement if the peeling
11033 // does not occur.
11034 // If the peeling is performed, return the newly created MachineBasicBlock
11035 // for the peeled switch statement. Also update Clusters to remove the peeled
11036 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11037 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11038     const SwitchInst &SI, CaseClusterVector &Clusters,
11039     BranchProbability &PeeledCaseProb) {
11040   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11041   // Don't perform if there is only one cluster or optimizing for size.
11042   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11043       TM.getOptLevel() == CodeGenOpt::None ||
11044       SwitchMBB->getParent()->getFunction().hasMinSize())
11045     return SwitchMBB;
11046 
11047   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11048   unsigned PeeledCaseIndex = 0;
11049   bool SwitchPeeled = false;
11050   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11051     CaseCluster &CC = Clusters[Index];
11052     if (CC.Prob < TopCaseProb)
11053       continue;
11054     TopCaseProb = CC.Prob;
11055     PeeledCaseIndex = Index;
11056     SwitchPeeled = true;
11057   }
11058   if (!SwitchPeeled)
11059     return SwitchMBB;
11060 
11061   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11062                     << TopCaseProb << "\n");
11063 
11064   // Record the MBB for the peeled switch statement.
11065   MachineFunction::iterator BBI(SwitchMBB);
11066   ++BBI;
11067   MachineBasicBlock *PeeledSwitchMBB =
11068       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11069   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11070 
11071   ExportFromCurrentBlock(SI.getCondition());
11072   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11073   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11074                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11075   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11076 
11077   Clusters.erase(PeeledCaseIt);
11078   for (CaseCluster &CC : Clusters) {
11079     LLVM_DEBUG(
11080         dbgs() << "Scale the probablity for one cluster, before scaling: "
11081                << CC.Prob << "\n");
11082     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11083     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11084   }
11085   PeeledCaseProb = TopCaseProb;
11086   return PeeledSwitchMBB;
11087 }
11088 
11089 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11090   // Extract cases from the switch.
11091   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11092   CaseClusterVector Clusters;
11093   Clusters.reserve(SI.getNumCases());
11094   for (auto I : SI.cases()) {
11095     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11096     const ConstantInt *CaseVal = I.getCaseValue();
11097     BranchProbability Prob =
11098         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11099             : BranchProbability(1, SI.getNumCases() + 1);
11100     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11101   }
11102 
11103   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11104 
11105   // Cluster adjacent cases with the same destination. We do this at all
11106   // optimization levels because it's cheap to do and will make codegen faster
11107   // if there are many clusters.
11108   sortAndRangeify(Clusters);
11109 
11110   // The branch probablity of the peeled case.
11111   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11112   MachineBasicBlock *PeeledSwitchMBB =
11113       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11114 
11115   // If there is only the default destination, jump there directly.
11116   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11117   if (Clusters.empty()) {
11118     assert(PeeledSwitchMBB == SwitchMBB);
11119     SwitchMBB->addSuccessor(DefaultMBB);
11120     if (DefaultMBB != NextBlock(SwitchMBB)) {
11121       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11122                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11123     }
11124     return;
11125   }
11126 
11127   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11128   SL->findBitTestClusters(Clusters, &SI);
11129 
11130   LLVM_DEBUG({
11131     dbgs() << "Case clusters: ";
11132     for (const CaseCluster &C : Clusters) {
11133       if (C.Kind == CC_JumpTable)
11134         dbgs() << "JT:";
11135       if (C.Kind == CC_BitTests)
11136         dbgs() << "BT:";
11137 
11138       C.Low->getValue().print(dbgs(), true);
11139       if (C.Low != C.High) {
11140         dbgs() << '-';
11141         C.High->getValue().print(dbgs(), true);
11142       }
11143       dbgs() << ' ';
11144     }
11145     dbgs() << '\n';
11146   });
11147 
11148   assert(!Clusters.empty());
11149   SwitchWorkList WorkList;
11150   CaseClusterIt First = Clusters.begin();
11151   CaseClusterIt Last = Clusters.end() - 1;
11152   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11153   // Scale the branchprobability for DefaultMBB if the peel occurs and
11154   // DefaultMBB is not replaced.
11155   if (PeeledCaseProb != BranchProbability::getZero() &&
11156       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11157     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11158   WorkList.push_back(
11159       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11160 
11161   while (!WorkList.empty()) {
11162     SwitchWorkListItem W = WorkList.pop_back_val();
11163     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11164 
11165     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11166         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11167       // For optimized builds, lower large range as a balanced binary tree.
11168       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11169       continue;
11170     }
11171 
11172     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11173   }
11174 }
11175 
11176 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11178   auto DL = getCurSDLoc();
11179   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11180   setValue(&I, DAG.getStepVector(DL, ResultVT));
11181 }
11182 
11183 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11185   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11186 
11187   SDLoc DL = getCurSDLoc();
11188   SDValue V = getValue(I.getOperand(0));
11189   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11190 
11191   if (VT.isScalableVector()) {
11192     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11193     return;
11194   }
11195 
11196   // Use VECTOR_SHUFFLE for the fixed-length vector
11197   // to maintain existing behavior.
11198   SmallVector<int, 8> Mask;
11199   unsigned NumElts = VT.getVectorMinNumElements();
11200   for (unsigned i = 0; i != NumElts; ++i)
11201     Mask.push_back(NumElts - 1 - i);
11202 
11203   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11204 }
11205 
11206 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11207   SmallVector<EVT, 4> ValueVTs;
11208   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11209                   ValueVTs);
11210   unsigned NumValues = ValueVTs.size();
11211   if (NumValues == 0) return;
11212 
11213   SmallVector<SDValue, 4> Values(NumValues);
11214   SDValue Op = getValue(I.getOperand(0));
11215 
11216   for (unsigned i = 0; i != NumValues; ++i)
11217     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11218                             SDValue(Op.getNode(), Op.getResNo() + i));
11219 
11220   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11221                            DAG.getVTList(ValueVTs), Values));
11222 }
11223 
11224 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11226   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11227 
11228   SDLoc DL = getCurSDLoc();
11229   SDValue V1 = getValue(I.getOperand(0));
11230   SDValue V2 = getValue(I.getOperand(1));
11231   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11232 
11233   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11234   if (VT.isScalableVector()) {
11235     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11236     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11237                              DAG.getConstant(Imm, DL, IdxVT)));
11238     return;
11239   }
11240 
11241   unsigned NumElts = VT.getVectorNumElements();
11242 
11243   uint64_t Idx = (NumElts + Imm) % NumElts;
11244 
11245   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11246   SmallVector<int, 8> Mask;
11247   for (unsigned i = 0; i < NumElts; ++i)
11248     Mask.push_back(Idx + i);
11249   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11250 }
11251