xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 7255ce30e48feb07e4e82613f518683fbc247c1c)
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 {
677       if (ValueVT.getVectorElementCount().isScalar()) {
678         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
679                           DAG.getVectorIdxConstant(0, DL));
680       } else {
681         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
682         assert(PartVT.getFixedSizeInBits() > ValueSize &&
683                "lossy conversion of vector to scalar type");
684         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
685         Val = DAG.getBitcast(IntermediateType, Val);
686         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687       }
688     }
689 
690     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
691     Parts[0] = Val;
692     return;
693   }
694 
695   // Handle a multi-element vector.
696   EVT IntermediateVT;
697   MVT RegisterVT;
698   unsigned NumIntermediates;
699   unsigned NumRegs;
700   if (IsABIRegCopy) {
701     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
702         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
703         NumIntermediates, RegisterVT);
704   } else {
705     NumRegs =
706         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
707                                    NumIntermediates, RegisterVT);
708   }
709 
710   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
711   NumParts = NumRegs; // Silence a compiler warning.
712   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
713 
714   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
715          "Mixing scalable and fixed vectors when copying in parts");
716 
717   Optional<ElementCount> DestEltCnt;
718 
719   if (IntermediateVT.isVector())
720     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
721   else
722     DestEltCnt = ElementCount::getFixed(NumIntermediates);
723 
724   EVT BuiltVectorTy = EVT::getVectorVT(
725       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
726 
727   if (ValueVT == BuiltVectorTy) {
728     // Nothing to do.
729   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
730     // Bitconvert vector->vector case.
731     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
732   } else {
733     if (BuiltVectorTy.getVectorElementType().bitsGT(
734             ValueVT.getVectorElementType())) {
735       // Integer promotion.
736       ValueVT = EVT::getVectorVT(*DAG.getContext(),
737                                  BuiltVectorTy.getVectorElementType(),
738                                  ValueVT.getVectorElementCount());
739       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
740     }
741 
742     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
743       Val = Widened;
744     }
745   }
746 
747   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
748 
749   // Split the vector into intermediate operands.
750   SmallVector<SDValue, 8> Ops(NumIntermediates);
751   for (unsigned i = 0; i != NumIntermediates; ++i) {
752     if (IntermediateVT.isVector()) {
753       // This does something sensible for scalable vectors - see the
754       // definition of EXTRACT_SUBVECTOR for further details.
755       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
756       Ops[i] =
757           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
758                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
759     } else {
760       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
761                            DAG.getVectorIdxConstant(i, DL));
762     }
763   }
764 
765   // Split the intermediate operands into legal parts.
766   if (NumParts == NumIntermediates) {
767     // If the register was not expanded, promote or copy the value,
768     // as appropriate.
769     for (unsigned i = 0; i != NumParts; ++i)
770       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
771   } else if (NumParts > 0) {
772     // If the intermediate type was expanded, split each the value into
773     // legal parts.
774     assert(NumIntermediates != 0 && "division by zero");
775     assert(NumParts % NumIntermediates == 0 &&
776            "Must expand into a divisible number of parts!");
777     unsigned Factor = NumParts / NumIntermediates;
778     for (unsigned i = 0; i != NumIntermediates; ++i)
779       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
780                      CallConv);
781   }
782 }
783 
784 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
785                            EVT valuevt, Optional<CallingConv::ID> CC)
786     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
787       RegCount(1, regs.size()), CallConv(CC) {}
788 
789 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
790                            const DataLayout &DL, unsigned Reg, Type *Ty,
791                            Optional<CallingConv::ID> CC) {
792   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
793 
794   CallConv = CC;
795 
796   for (EVT ValueVT : ValueVTs) {
797     unsigned NumRegs =
798         isABIMangled()
799             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
800             : TLI.getNumRegisters(Context, ValueVT);
801     MVT RegisterVT =
802         isABIMangled()
803             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
804             : TLI.getRegisterType(Context, ValueVT);
805     for (unsigned i = 0; i != NumRegs; ++i)
806       Regs.push_back(Reg + i);
807     RegVTs.push_back(RegisterVT);
808     RegCount.push_back(NumRegs);
809     Reg += NumRegs;
810   }
811 }
812 
813 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
814                                       FunctionLoweringInfo &FuncInfo,
815                                       const SDLoc &dl, SDValue &Chain,
816                                       SDValue *Flag, const Value *V) const {
817   // A Value with type {} or [0 x %t] needs no registers.
818   if (ValueVTs.empty())
819     return SDValue();
820 
821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
822 
823   // Assemble the legal parts into the final values.
824   SmallVector<SDValue, 4> Values(ValueVTs.size());
825   SmallVector<SDValue, 8> Parts;
826   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
827     // Copy the legal parts from the registers.
828     EVT ValueVT = ValueVTs[Value];
829     unsigned NumRegs = RegCount[Value];
830     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
831                                           *DAG.getContext(),
832                                           CallConv.getValue(), RegVTs[Value])
833                                     : RegVTs[Value];
834 
835     Parts.resize(NumRegs);
836     for (unsigned i = 0; i != NumRegs; ++i) {
837       SDValue P;
838       if (!Flag) {
839         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
840       } else {
841         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
842         *Flag = P.getValue(2);
843       }
844 
845       Chain = P.getValue(1);
846       Parts[i] = P;
847 
848       // If the source register was virtual and if we know something about it,
849       // add an assert node.
850       if (!Register::isVirtualRegister(Regs[Part + i]) ||
851           !RegisterVT.isInteger())
852         continue;
853 
854       const FunctionLoweringInfo::LiveOutInfo *LOI =
855         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
856       if (!LOI)
857         continue;
858 
859       unsigned RegSize = RegisterVT.getScalarSizeInBits();
860       unsigned NumSignBits = LOI->NumSignBits;
861       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
862 
863       if (NumZeroBits == RegSize) {
864         // The current value is a zero.
865         // Explicitly express that as it would be easier for
866         // optimizations to kick in.
867         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
868         continue;
869       }
870 
871       // FIXME: We capture more information than the dag can represent.  For
872       // now, just use the tightest assertzext/assertsext possible.
873       bool isSExt;
874       EVT FromVT(MVT::Other);
875       if (NumZeroBits) {
876         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
877         isSExt = false;
878       } else if (NumSignBits > 1) {
879         FromVT =
880             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
881         isSExt = true;
882       } else {
883         continue;
884       }
885       // Add an assertion node.
886       assert(FromVT != MVT::Other);
887       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
888                              RegisterVT, P, DAG.getValueType(FromVT));
889     }
890 
891     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
892                                      RegisterVT, ValueVT, V, CallConv);
893     Part += NumRegs;
894     Parts.clear();
895   }
896 
897   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
898 }
899 
900 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
901                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
902                                  const Value *V,
903                                  ISD::NodeType PreferredExtendType) const {
904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
905   ISD::NodeType ExtendKind = PreferredExtendType;
906 
907   // Get the list of the values's legal parts.
908   unsigned NumRegs = Regs.size();
909   SmallVector<SDValue, 8> Parts(NumRegs);
910   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
911     unsigned NumParts = RegCount[Value];
912 
913     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
914                                           *DAG.getContext(),
915                                           CallConv.getValue(), RegVTs[Value])
916                                     : RegVTs[Value];
917 
918     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
919       ExtendKind = ISD::ZERO_EXTEND;
920 
921     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
922                    NumParts, RegisterVT, V, CallConv, ExtendKind);
923     Part += NumParts;
924   }
925 
926   // Copy the parts into the registers.
927   SmallVector<SDValue, 8> Chains(NumRegs);
928   for (unsigned i = 0; i != NumRegs; ++i) {
929     SDValue Part;
930     if (!Flag) {
931       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
932     } else {
933       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
934       *Flag = Part.getValue(1);
935     }
936 
937     Chains[i] = Part.getValue(0);
938   }
939 
940   if (NumRegs == 1 || Flag)
941     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
942     // flagged to it. That is the CopyToReg nodes and the user are considered
943     // a single scheduling unit. If we create a TokenFactor and return it as
944     // chain, then the TokenFactor is both a predecessor (operand) of the
945     // user as well as a successor (the TF operands are flagged to the user).
946     // c1, f1 = CopyToReg
947     // c2, f2 = CopyToReg
948     // c3     = TokenFactor c1, c2
949     // ...
950     //        = op c3, ..., f2
951     Chain = Chains[NumRegs-1];
952   else
953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
954 }
955 
956 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
957                                         unsigned MatchingIdx, const SDLoc &dl,
958                                         SelectionDAG &DAG,
959                                         std::vector<SDValue> &Ops) const {
960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
961 
962   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
963   if (HasMatching)
964     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
965   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
966     // Put the register class of the virtual registers in the flag word.  That
967     // way, later passes can recompute register class constraints for inline
968     // assembly as well as normal instructions.
969     // Don't do this for tied operands that can use the regclass information
970     // from the def.
971     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
972     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
973     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
974   }
975 
976   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
977   Ops.push_back(Res);
978 
979   if (Code == InlineAsm::Kind_Clobber) {
980     // Clobbers should always have a 1:1 mapping with registers, and may
981     // reference registers that have illegal (e.g. vector) types. Hence, we
982     // shouldn't try to apply any sort of splitting logic to them.
983     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
984            "No 1:1 mapping from clobbers to regs?");
985     Register SP = TLI.getStackPointerRegisterToSaveRestore();
986     (void)SP;
987     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
988       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
989       assert(
990           (Regs[I] != SP ||
991            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
992           "If we clobbered the stack pointer, MFI should know about it.");
993     }
994     return;
995   }
996 
997   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
998     MVT RegisterVT = RegVTs[Value];
999     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1000                                            RegisterVT);
1001     for (unsigned i = 0; i != NumRegs; ++i) {
1002       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1003       unsigned TheReg = Regs[Reg++];
1004       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1005     }
1006   }
1007 }
1008 
1009 SmallVector<std::pair<unsigned, TypeSize>, 4>
1010 RegsForValue::getRegsAndSizes() const {
1011   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1012   unsigned I = 0;
1013   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1014     unsigned RegCount = std::get<0>(CountAndVT);
1015     MVT RegisterVT = std::get<1>(CountAndVT);
1016     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1017     for (unsigned E = I + RegCount; I != E; ++I)
1018       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1019   }
1020   return OutVec;
1021 }
1022 
1023 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1024                                const TargetLibraryInfo *li) {
1025   AA = aa;
1026   GFI = gfi;
1027   LibInfo = li;
1028   DL = &DAG.getDataLayout();
1029   Context = DAG.getContext();
1030   LPadToCallSiteMap.clear();
1031   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1032 }
1033 
1034 void SelectionDAGBuilder::clear() {
1035   NodeMap.clear();
1036   UnusedArgNodeMap.clear();
1037   PendingLoads.clear();
1038   PendingExports.clear();
1039   PendingConstrainedFP.clear();
1040   PendingConstrainedFPStrict.clear();
1041   CurInst = nullptr;
1042   HasTailCall = false;
1043   SDNodeOrder = LowestSDNodeOrder;
1044   StatepointLowering.clear();
1045 }
1046 
1047 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1048   DanglingDebugInfoMap.clear();
1049 }
1050 
1051 // Update DAG root to include dependencies on Pending chains.
1052 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1053   SDValue Root = DAG.getRoot();
1054 
1055   if (Pending.empty())
1056     return Root;
1057 
1058   // Add current root to PendingChains, unless we already indirectly
1059   // depend on it.
1060   if (Root.getOpcode() != ISD::EntryToken) {
1061     unsigned i = 0, e = Pending.size();
1062     for (; i != e; ++i) {
1063       assert(Pending[i].getNode()->getNumOperands() > 1);
1064       if (Pending[i].getNode()->getOperand(0) == Root)
1065         break;  // Don't add the root if we already indirectly depend on it.
1066     }
1067 
1068     if (i == e)
1069       Pending.push_back(Root);
1070   }
1071 
1072   if (Pending.size() == 1)
1073     Root = Pending[0];
1074   else
1075     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1076 
1077   DAG.setRoot(Root);
1078   Pending.clear();
1079   return Root;
1080 }
1081 
1082 SDValue SelectionDAGBuilder::getMemoryRoot() {
1083   return updateRoot(PendingLoads);
1084 }
1085 
1086 SDValue SelectionDAGBuilder::getRoot() {
1087   // Chain up all pending constrained intrinsics together with all
1088   // pending loads, by simply appending them to PendingLoads and
1089   // then calling getMemoryRoot().
1090   PendingLoads.reserve(PendingLoads.size() +
1091                        PendingConstrainedFP.size() +
1092                        PendingConstrainedFPStrict.size());
1093   PendingLoads.append(PendingConstrainedFP.begin(),
1094                       PendingConstrainedFP.end());
1095   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1096                       PendingConstrainedFPStrict.end());
1097   PendingConstrainedFP.clear();
1098   PendingConstrainedFPStrict.clear();
1099   return getMemoryRoot();
1100 }
1101 
1102 SDValue SelectionDAGBuilder::getControlRoot() {
1103   // We need to emit pending fpexcept.strict constrained intrinsics,
1104   // so append them to the PendingExports list.
1105   PendingExports.append(PendingConstrainedFPStrict.begin(),
1106                         PendingConstrainedFPStrict.end());
1107   PendingConstrainedFPStrict.clear();
1108   return updateRoot(PendingExports);
1109 }
1110 
1111 void SelectionDAGBuilder::visit(const Instruction &I) {
1112   // Set up outgoing PHI node register values before emitting the terminator.
1113   if (I.isTerminator()) {
1114     HandlePHINodesInSuccessorBlocks(I.getParent());
1115   }
1116 
1117   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1118   if (!isa<DbgInfoIntrinsic>(I))
1119     ++SDNodeOrder;
1120 
1121   CurInst = &I;
1122 
1123   visit(I.getOpcode(), I);
1124 
1125   if (!I.isTerminator() && !HasTailCall &&
1126       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1127     CopyToExportRegsIfNeeded(&I);
1128 
1129   CurInst = nullptr;
1130 }
1131 
1132 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1133   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1134 }
1135 
1136 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1137   // Note: this doesn't use InstVisitor, because it has to work with
1138   // ConstantExpr's in addition to instructions.
1139   switch (Opcode) {
1140   default: llvm_unreachable("Unknown instruction type encountered!");
1141     // Build the switch statement using the Instruction.def file.
1142 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1143     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1144 #include "llvm/IR/Instruction.def"
1145   }
1146 }
1147 
1148 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1149                                                DebugLoc DL, unsigned Order) {
1150   // We treat variadic dbg_values differently at this stage.
1151   if (DI->hasArgList()) {
1152     // For variadic dbg_values we will now insert an undef.
1153     // FIXME: We can potentially recover these!
1154     SmallVector<SDDbgOperand, 2> Locs;
1155     for (const Value *V : DI->getValues()) {
1156       auto Undef = UndefValue::get(V->getType());
1157       Locs.push_back(SDDbgOperand::fromConst(Undef));
1158     }
1159     SDDbgValue *SDV = DAG.getDbgValueList(
1160         DI->getVariable(), DI->getExpression(), Locs, {},
1161         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1162     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1163   } else {
1164     // TODO: Dangling debug info will eventually either be resolved or produce
1165     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1166     // between the original dbg.value location and its resolved DBG_VALUE,
1167     // which we should ideally fill with an extra Undef DBG_VALUE.
1168     assert(DI->getNumVariableLocationOps() == 1 &&
1169            "DbgValueInst without an ArgList should have a single location "
1170            "operand.");
1171     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1172   }
1173 }
1174 
1175 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1176                                                 const DIExpression *Expr) {
1177   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1178     const DbgValueInst *DI = DDI.getDI();
1179     DIVariable *DanglingVariable = DI->getVariable();
1180     DIExpression *DanglingExpr = DI->getExpression();
1181     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1182       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1183       return true;
1184     }
1185     return false;
1186   };
1187 
1188   for (auto &DDIMI : DanglingDebugInfoMap) {
1189     DanglingDebugInfoVector &DDIV = DDIMI.second;
1190 
1191     // If debug info is to be dropped, run it through final checks to see
1192     // whether it can be salvaged.
1193     for (auto &DDI : DDIV)
1194       if (isMatchingDbgValue(DDI))
1195         salvageUnresolvedDbgValue(DDI);
1196 
1197     erase_if(DDIV, isMatchingDbgValue);
1198   }
1199 }
1200 
1201 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1202 // generate the debug data structures now that we've seen its definition.
1203 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1204                                                    SDValue Val) {
1205   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1206   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1207     return;
1208 
1209   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1210   for (auto &DDI : DDIV) {
1211     const DbgValueInst *DI = DDI.getDI();
1212     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1213     assert(DI && "Ill-formed DanglingDebugInfo");
1214     DebugLoc dl = DDI.getdl();
1215     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1216     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1217     DILocalVariable *Variable = DI->getVariable();
1218     DIExpression *Expr = DI->getExpression();
1219     assert(Variable->isValidLocationForIntrinsic(dl) &&
1220            "Expected inlined-at fields to agree");
1221     SDDbgValue *SDV;
1222     if (Val.getNode()) {
1223       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1224       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1225       // we couldn't resolve it directly when examining the DbgValue intrinsic
1226       // in the first place we should not be more successful here). Unless we
1227       // have some test case that prove this to be correct we should avoid
1228       // calling EmitFuncArgumentDbgValue here.
1229       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1230         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1231                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1232         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1233         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1234         // inserted after the definition of Val when emitting the instructions
1235         // after ISel. An alternative could be to teach
1236         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1237         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1238                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1239                    << ValSDNodeOrder << "\n");
1240         SDV = getDbgValue(Val, Variable, Expr, dl,
1241                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1242         DAG.AddDbgValue(SDV, false);
1243       } else
1244         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1245                           << "in EmitFuncArgumentDbgValue\n");
1246     } else {
1247       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1248       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1249       auto SDV =
1250           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1251       DAG.AddDbgValue(SDV, false);
1252     }
1253   }
1254   DDIV.clear();
1255 }
1256 
1257 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1258   // TODO: For the variadic implementation, instead of only checking the fail
1259   // state of `handleDebugValue`, we need know specifically which values were
1260   // invalid, so that we attempt to salvage only those values when processing
1261   // a DIArgList.
1262   assert(!DDI.getDI()->hasArgList() &&
1263          "Not implemented for variadic dbg_values");
1264   Value *V = DDI.getDI()->getValue(0);
1265   DILocalVariable *Var = DDI.getDI()->getVariable();
1266   DIExpression *Expr = DDI.getDI()->getExpression();
1267   DebugLoc DL = DDI.getdl();
1268   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1269   unsigned SDOrder = DDI.getSDNodeOrder();
1270   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1271   // that DW_OP_stack_value is desired.
1272   assert(isa<DbgValueInst>(DDI.getDI()));
1273   bool StackValue = true;
1274 
1275   // Can this Value can be encoded without any further work?
1276   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1277     return;
1278 
1279   // Attempt to salvage back through as many instructions as possible. Bail if
1280   // a non-instruction is seen, such as a constant expression or global
1281   // variable. FIXME: Further work could recover those too.
1282   while (isa<Instruction>(V)) {
1283     Instruction &VAsInst = *cast<Instruction>(V);
1284     // Temporary "0", awaiting real implementation.
1285     SmallVector<uint64_t, 16> Ops;
1286     SmallVector<Value *, 4> AdditionalValues;
1287     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1288                              AdditionalValues);
1289     // If we cannot salvage any further, and haven't yet found a suitable debug
1290     // expression, bail out.
1291     if (!V)
1292       break;
1293 
1294     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1295     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1296     // here for variadic dbg_values, remove that condition.
1297     if (!AdditionalValues.empty())
1298       break;
1299 
1300     // New value and expr now represent this debuginfo.
1301     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1302 
1303     // Some kind of simplification occurred: check whether the operand of the
1304     // salvaged debug expression can be encoded in this DAG.
1305     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1306                          /*IsVariadic=*/false)) {
1307       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1308                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1309       return;
1310     }
1311   }
1312 
1313   // This was the final opportunity to salvage this debug information, and it
1314   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1315   // any earlier variable location.
1316   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1317   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1318   DAG.AddDbgValue(SDV, false);
1319 
1320   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1321                     << "\n");
1322   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1323                     << "\n");
1324 }
1325 
1326 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1327                                            DILocalVariable *Var,
1328                                            DIExpression *Expr, DebugLoc dl,
1329                                            DebugLoc InstDL, unsigned Order,
1330                                            bool IsVariadic) {
1331   if (Values.empty())
1332     return true;
1333   SmallVector<SDDbgOperand> LocationOps;
1334   SmallVector<SDNode *> Dependencies;
1335   for (const Value *V : Values) {
1336     // Constant value.
1337     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1338         isa<ConstantPointerNull>(V)) {
1339       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1340       continue;
1341     }
1342 
1343     // If the Value is a frame index, we can create a FrameIndex debug value
1344     // without relying on the DAG at all.
1345     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1346       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1347       if (SI != FuncInfo.StaticAllocaMap.end()) {
1348         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1349         continue;
1350       }
1351     }
1352 
1353     // Do not use getValue() in here; we don't want to generate code at
1354     // this point if it hasn't been done yet.
1355     SDValue N = NodeMap[V];
1356     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1357       N = UnusedArgNodeMap[V];
1358     if (N.getNode()) {
1359       // Only emit func arg dbg value for non-variadic dbg.values for now.
1360       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1361         return true;
1362       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1363         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1364         // describe stack slot locations.
1365         //
1366         // Consider "int x = 0; int *px = &x;". There are two kinds of
1367         // interesting debug values here after optimization:
1368         //
1369         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1370         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1371         //
1372         // Both describe the direct values of their associated variables.
1373         Dependencies.push_back(N.getNode());
1374         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1375         continue;
1376       }
1377       LocationOps.emplace_back(
1378           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1379       continue;
1380     }
1381 
1382     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1383     // Special rules apply for the first dbg.values of parameter variables in a
1384     // function. Identify them by the fact they reference Argument Values, that
1385     // they're parameters, and they are parameters of the current function. We
1386     // need to let them dangle until they get an SDNode.
1387     bool IsParamOfFunc =
1388         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1389     if (IsParamOfFunc)
1390       return false;
1391 
1392     // The value is not used in this block yet (or it would have an SDNode).
1393     // We still want the value to appear for the user if possible -- if it has
1394     // an associated VReg, we can refer to that instead.
1395     auto VMI = FuncInfo.ValueMap.find(V);
1396     if (VMI != FuncInfo.ValueMap.end()) {
1397       unsigned Reg = VMI->second;
1398       // If this is a PHI node, it may be split up into several MI PHI nodes
1399       // (in FunctionLoweringInfo::set).
1400       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1401                        V->getType(), None);
1402       if (RFV.occupiesMultipleRegs()) {
1403         // FIXME: We could potentially support variadic dbg_values here.
1404         if (IsVariadic)
1405           return false;
1406         unsigned Offset = 0;
1407         unsigned BitsToDescribe = 0;
1408         if (auto VarSize = Var->getSizeInBits())
1409           BitsToDescribe = *VarSize;
1410         if (auto Fragment = Expr->getFragmentInfo())
1411           BitsToDescribe = Fragment->SizeInBits;
1412         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1413           // Bail out if all bits are described already.
1414           if (Offset >= BitsToDescribe)
1415             break;
1416           // TODO: handle scalable vectors.
1417           unsigned RegisterSize = RegAndSize.second;
1418           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1419                                       ? BitsToDescribe - Offset
1420                                       : RegisterSize;
1421           auto FragmentExpr = DIExpression::createFragmentExpression(
1422               Expr, Offset, FragmentSize);
1423           if (!FragmentExpr)
1424             continue;
1425           SDDbgValue *SDV = DAG.getVRegDbgValue(
1426               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1427           DAG.AddDbgValue(SDV, false);
1428           Offset += RegisterSize;
1429         }
1430         return true;
1431       }
1432       // We can use simple vreg locations for variadic dbg_values as well.
1433       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1434       continue;
1435     }
1436     // We failed to create a SDDbgOperand for V.
1437     return false;
1438   }
1439 
1440   // We have created a SDDbgOperand for each Value in Values.
1441   // Should use Order instead of SDNodeOrder?
1442   assert(!LocationOps.empty());
1443   SDDbgValue *SDV =
1444       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1445                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1446   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1447   return true;
1448 }
1449 
1450 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1451   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1452   for (auto &Pair : DanglingDebugInfoMap)
1453     for (auto &DDI : Pair.second)
1454       salvageUnresolvedDbgValue(DDI);
1455   clearDanglingDebugInfo();
1456 }
1457 
1458 /// getCopyFromRegs - If there was virtual register allocated for the value V
1459 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1460 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1461   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1462   SDValue Result;
1463 
1464   if (It != FuncInfo.ValueMap.end()) {
1465     Register InReg = It->second;
1466 
1467     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1468                      DAG.getDataLayout(), InReg, Ty,
1469                      None); // This is not an ABI copy.
1470     SDValue Chain = DAG.getEntryNode();
1471     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1472                                  V);
1473     resolveDanglingDebugInfo(V, Result);
1474   }
1475 
1476   return Result;
1477 }
1478 
1479 /// getValue - Return an SDValue for the given Value.
1480 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1481   // If we already have an SDValue for this value, use it. It's important
1482   // to do this first, so that we don't create a CopyFromReg if we already
1483   // have a regular SDValue.
1484   SDValue &N = NodeMap[V];
1485   if (N.getNode()) return N;
1486 
1487   // If there's a virtual register allocated and initialized for this
1488   // value, use it.
1489   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1490     return copyFromReg;
1491 
1492   // Otherwise create a new SDValue and remember it.
1493   SDValue Val = getValueImpl(V);
1494   NodeMap[V] = Val;
1495   resolveDanglingDebugInfo(V, Val);
1496   return Val;
1497 }
1498 
1499 /// getNonRegisterValue - Return an SDValue for the given Value, but
1500 /// don't look in FuncInfo.ValueMap for a virtual register.
1501 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1502   // If we already have an SDValue for this value, use it.
1503   SDValue &N = NodeMap[V];
1504   if (N.getNode()) {
1505     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1506       // Remove the debug location from the node as the node is about to be used
1507       // in a location which may differ from the original debug location.  This
1508       // is relevant to Constant and ConstantFP nodes because they can appear
1509       // as constant expressions inside PHI nodes.
1510       N->setDebugLoc(DebugLoc());
1511     }
1512     return N;
1513   }
1514 
1515   // Otherwise create a new SDValue and remember it.
1516   SDValue Val = getValueImpl(V);
1517   NodeMap[V] = Val;
1518   resolveDanglingDebugInfo(V, Val);
1519   return Val;
1520 }
1521 
1522 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1523 /// Create an SDValue for the given value.
1524 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1526 
1527   if (const Constant *C = dyn_cast<Constant>(V)) {
1528     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1529 
1530     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1531       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1532 
1533     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1534       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1535 
1536     if (isa<ConstantPointerNull>(C)) {
1537       unsigned AS = V->getType()->getPointerAddressSpace();
1538       return DAG.getConstant(0, getCurSDLoc(),
1539                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1540     }
1541 
1542     if (match(C, m_VScale(DAG.getDataLayout())))
1543       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1544 
1545     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1546       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1547 
1548     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1549       return DAG.getUNDEF(VT);
1550 
1551     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1552       visit(CE->getOpcode(), *CE);
1553       SDValue N1 = NodeMap[V];
1554       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1555       return N1;
1556     }
1557 
1558     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1559       SmallVector<SDValue, 4> Constants;
1560       for (const Use &U : C->operands()) {
1561         SDNode *Val = getValue(U).getNode();
1562         // If the operand is an empty aggregate, there are no values.
1563         if (!Val) continue;
1564         // Add each leaf value from the operand to the Constants list
1565         // to form a flattened list of all the values.
1566         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1567           Constants.push_back(SDValue(Val, i));
1568       }
1569 
1570       return DAG.getMergeValues(Constants, getCurSDLoc());
1571     }
1572 
1573     if (const ConstantDataSequential *CDS =
1574           dyn_cast<ConstantDataSequential>(C)) {
1575       SmallVector<SDValue, 4> Ops;
1576       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1577         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1578         // Add each leaf value from the operand to the Constants list
1579         // to form a flattened list of all the values.
1580         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1581           Ops.push_back(SDValue(Val, i));
1582       }
1583 
1584       if (isa<ArrayType>(CDS->getType()))
1585         return DAG.getMergeValues(Ops, getCurSDLoc());
1586       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1587     }
1588 
1589     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1590       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1591              "Unknown struct or array constant!");
1592 
1593       SmallVector<EVT, 4> ValueVTs;
1594       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1595       unsigned NumElts = ValueVTs.size();
1596       if (NumElts == 0)
1597         return SDValue(); // empty struct
1598       SmallVector<SDValue, 4> Constants(NumElts);
1599       for (unsigned i = 0; i != NumElts; ++i) {
1600         EVT EltVT = ValueVTs[i];
1601         if (isa<UndefValue>(C))
1602           Constants[i] = DAG.getUNDEF(EltVT);
1603         else if (EltVT.isFloatingPoint())
1604           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1605         else
1606           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1607       }
1608 
1609       return DAG.getMergeValues(Constants, getCurSDLoc());
1610     }
1611 
1612     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1613       return DAG.getBlockAddress(BA, VT);
1614 
1615     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1616       return getValue(Equiv->getGlobalValue());
1617 
1618     VectorType *VecTy = cast<VectorType>(V->getType());
1619 
1620     // Now that we know the number and type of the elements, get that number of
1621     // elements into the Ops array based on what kind of constant it is.
1622     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1623       SmallVector<SDValue, 16> Ops;
1624       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1625       for (unsigned i = 0; i != NumElements; ++i)
1626         Ops.push_back(getValue(CV->getOperand(i)));
1627 
1628       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1629     } else if (isa<ConstantAggregateZero>(C)) {
1630       EVT EltVT =
1631           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1632 
1633       SDValue Op;
1634       if (EltVT.isFloatingPoint())
1635         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1636       else
1637         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1638 
1639       if (isa<ScalableVectorType>(VecTy))
1640         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1641       else {
1642         SmallVector<SDValue, 16> Ops;
1643         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1644         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1645       }
1646     }
1647     llvm_unreachable("Unknown vector constant");
1648   }
1649 
1650   // If this is a static alloca, generate it as the frameindex instead of
1651   // computation.
1652   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1653     DenseMap<const AllocaInst*, int>::iterator SI =
1654       FuncInfo.StaticAllocaMap.find(AI);
1655     if (SI != FuncInfo.StaticAllocaMap.end())
1656       return DAG.getFrameIndex(SI->second,
1657                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1658   }
1659 
1660   // If this is an instruction which fast-isel has deferred, select it now.
1661   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1662     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1663 
1664     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1665                      Inst->getType(), None);
1666     SDValue Chain = DAG.getEntryNode();
1667     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1668   }
1669 
1670   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1671     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1672   }
1673   llvm_unreachable("Can't get register for value!");
1674 }
1675 
1676 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1677   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1678   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1679   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1680   bool IsSEH = isAsynchronousEHPersonality(Pers);
1681   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1682   if (!IsSEH)
1683     CatchPadMBB->setIsEHScopeEntry();
1684   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1685   if (IsMSVCCXX || IsCoreCLR)
1686     CatchPadMBB->setIsEHFuncletEntry();
1687 }
1688 
1689 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1690   // Update machine-CFG edge.
1691   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1692   FuncInfo.MBB->addSuccessor(TargetMBB);
1693   TargetMBB->setIsEHCatchretTarget(true);
1694   DAG.getMachineFunction().setHasEHCatchret(true);
1695 
1696   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1697   bool IsSEH = isAsynchronousEHPersonality(Pers);
1698   if (IsSEH) {
1699     // If this is not a fall-through branch or optimizations are switched off,
1700     // emit the branch.
1701     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1702         TM.getOptLevel() == CodeGenOpt::None)
1703       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1704                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1705     return;
1706   }
1707 
1708   // Figure out the funclet membership for the catchret's successor.
1709   // This will be used by the FuncletLayout pass to determine how to order the
1710   // BB's.
1711   // A 'catchret' returns to the outer scope's color.
1712   Value *ParentPad = I.getCatchSwitchParentPad();
1713   const BasicBlock *SuccessorColor;
1714   if (isa<ConstantTokenNone>(ParentPad))
1715     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1716   else
1717     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1718   assert(SuccessorColor && "No parent funclet for catchret!");
1719   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1720   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1721 
1722   // Create the terminator node.
1723   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1724                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1725                             DAG.getBasicBlock(SuccessorColorMBB));
1726   DAG.setRoot(Ret);
1727 }
1728 
1729 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1730   // Don't emit any special code for the cleanuppad instruction. It just marks
1731   // the start of an EH scope/funclet.
1732   FuncInfo.MBB->setIsEHScopeEntry();
1733   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1734   if (Pers != EHPersonality::Wasm_CXX) {
1735     FuncInfo.MBB->setIsEHFuncletEntry();
1736     FuncInfo.MBB->setIsCleanupFuncletEntry();
1737   }
1738 }
1739 
1740 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1741 // not match, it is OK to add only the first unwind destination catchpad to the
1742 // successors, because there will be at least one invoke instruction within the
1743 // catch scope that points to the next unwind destination, if one exists, so
1744 // CFGSort cannot mess up with BB sorting order.
1745 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1746 // call within them, and catchpads only consisting of 'catch (...)' have a
1747 // '__cxa_end_catch' call within them, both of which generate invokes in case
1748 // the next unwind destination exists, i.e., the next unwind destination is not
1749 // the caller.)
1750 //
1751 // Having at most one EH pad successor is also simpler and helps later
1752 // transformations.
1753 //
1754 // For example,
1755 // current:
1756 //   invoke void @foo to ... unwind label %catch.dispatch
1757 // catch.dispatch:
1758 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1759 // catch.start:
1760 //   ...
1761 //   ... in this BB or some other child BB dominated by this BB there will be an
1762 //   invoke that points to 'next' BB as an unwind destination
1763 //
1764 // next: ; We don't need to add this to 'current' BB's successor
1765 //   ...
1766 static void findWasmUnwindDestinations(
1767     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1768     BranchProbability Prob,
1769     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1770         &UnwindDests) {
1771   while (EHPadBB) {
1772     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1773     if (isa<CleanupPadInst>(Pad)) {
1774       // Stop on cleanup pads.
1775       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1776       UnwindDests.back().first->setIsEHScopeEntry();
1777       break;
1778     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1779       // Add the catchpad handlers to the possible destinations. We don't
1780       // continue to the unwind destination of the catchswitch for wasm.
1781       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1782         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1783         UnwindDests.back().first->setIsEHScopeEntry();
1784       }
1785       break;
1786     } else {
1787       continue;
1788     }
1789   }
1790 }
1791 
1792 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1793 /// many places it could ultimately go. In the IR, we have a single unwind
1794 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1795 /// This function skips over imaginary basic blocks that hold catchswitch
1796 /// instructions, and finds all the "real" machine
1797 /// basic block destinations. As those destinations may not be successors of
1798 /// EHPadBB, here we also calculate the edge probability to those destinations.
1799 /// The passed-in Prob is the edge probability to EHPadBB.
1800 static void findUnwindDestinations(
1801     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1802     BranchProbability Prob,
1803     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1804         &UnwindDests) {
1805   EHPersonality Personality =
1806     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1807   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1808   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1809   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1810   bool IsSEH = isAsynchronousEHPersonality(Personality);
1811 
1812   if (IsWasmCXX) {
1813     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1814     assert(UnwindDests.size() <= 1 &&
1815            "There should be at most one unwind destination for wasm");
1816     return;
1817   }
1818 
1819   while (EHPadBB) {
1820     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1821     BasicBlock *NewEHPadBB = nullptr;
1822     if (isa<LandingPadInst>(Pad)) {
1823       // Stop on landingpads. They are not funclets.
1824       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1825       break;
1826     } else if (isa<CleanupPadInst>(Pad)) {
1827       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1828       // personalities.
1829       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1830       UnwindDests.back().first->setIsEHScopeEntry();
1831       UnwindDests.back().first->setIsEHFuncletEntry();
1832       break;
1833     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1834       // Add the catchpad handlers to the possible destinations.
1835       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1836         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1837         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1838         if (IsMSVCCXX || IsCoreCLR)
1839           UnwindDests.back().first->setIsEHFuncletEntry();
1840         if (!IsSEH)
1841           UnwindDests.back().first->setIsEHScopeEntry();
1842       }
1843       NewEHPadBB = CatchSwitch->getUnwindDest();
1844     } else {
1845       continue;
1846     }
1847 
1848     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1849     if (BPI && NewEHPadBB)
1850       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1851     EHPadBB = NewEHPadBB;
1852   }
1853 }
1854 
1855 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1856   // Update successor info.
1857   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1858   auto UnwindDest = I.getUnwindDest();
1859   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1860   BranchProbability UnwindDestProb =
1861       (BPI && UnwindDest)
1862           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1863           : BranchProbability::getZero();
1864   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1865   for (auto &UnwindDest : UnwindDests) {
1866     UnwindDest.first->setIsEHPad();
1867     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1868   }
1869   FuncInfo.MBB->normalizeSuccProbs();
1870 
1871   // Create the terminator node.
1872   SDValue Ret =
1873       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1874   DAG.setRoot(Ret);
1875 }
1876 
1877 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1878   report_fatal_error("visitCatchSwitch not yet implemented!");
1879 }
1880 
1881 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1883   auto &DL = DAG.getDataLayout();
1884   SDValue Chain = getControlRoot();
1885   SmallVector<ISD::OutputArg, 8> Outs;
1886   SmallVector<SDValue, 8> OutVals;
1887 
1888   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1889   // lower
1890   //
1891   //   %val = call <ty> @llvm.experimental.deoptimize()
1892   //   ret <ty> %val
1893   //
1894   // differently.
1895   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1896     LowerDeoptimizingReturn();
1897     return;
1898   }
1899 
1900   if (!FuncInfo.CanLowerReturn) {
1901     unsigned DemoteReg = FuncInfo.DemoteRegister;
1902     const Function *F = I.getParent()->getParent();
1903 
1904     // Emit a store of the return value through the virtual register.
1905     // Leave Outs empty so that LowerReturn won't try to load return
1906     // registers the usual way.
1907     SmallVector<EVT, 1> PtrValueVTs;
1908     ComputeValueVTs(TLI, DL,
1909                     F->getReturnType()->getPointerTo(
1910                         DAG.getDataLayout().getAllocaAddrSpace()),
1911                     PtrValueVTs);
1912 
1913     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1914                                         DemoteReg, PtrValueVTs[0]);
1915     SDValue RetOp = getValue(I.getOperand(0));
1916 
1917     SmallVector<EVT, 4> ValueVTs, MemVTs;
1918     SmallVector<uint64_t, 4> Offsets;
1919     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1920                     &Offsets);
1921     unsigned NumValues = ValueVTs.size();
1922 
1923     SmallVector<SDValue, 4> Chains(NumValues);
1924     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1925     for (unsigned i = 0; i != NumValues; ++i) {
1926       // An aggregate return value cannot wrap around the address space, so
1927       // offsets to its parts don't wrap either.
1928       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1929                                            TypeSize::Fixed(Offsets[i]));
1930 
1931       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1932       if (MemVTs[i] != ValueVTs[i])
1933         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1934       Chains[i] = DAG.getStore(
1935           Chain, getCurSDLoc(), Val,
1936           // FIXME: better loc info would be nice.
1937           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1938           commonAlignment(BaseAlign, Offsets[i]));
1939     }
1940 
1941     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1942                         MVT::Other, Chains);
1943   } else if (I.getNumOperands() != 0) {
1944     SmallVector<EVT, 4> ValueVTs;
1945     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1946     unsigned NumValues = ValueVTs.size();
1947     if (NumValues) {
1948       SDValue RetOp = getValue(I.getOperand(0));
1949 
1950       const Function *F = I.getParent()->getParent();
1951 
1952       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1953           I.getOperand(0)->getType(), F->getCallingConv(),
1954           /*IsVarArg*/ false, DL);
1955 
1956       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1957       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1958         ExtendKind = ISD::SIGN_EXTEND;
1959       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1960         ExtendKind = ISD::ZERO_EXTEND;
1961 
1962       LLVMContext &Context = F->getContext();
1963       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1964 
1965       for (unsigned j = 0; j != NumValues; ++j) {
1966         EVT VT = ValueVTs[j];
1967 
1968         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1969           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1970 
1971         CallingConv::ID CC = F->getCallingConv();
1972 
1973         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1974         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1975         SmallVector<SDValue, 4> Parts(NumParts);
1976         getCopyToParts(DAG, getCurSDLoc(),
1977                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1978                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1979 
1980         // 'inreg' on function refers to return value
1981         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1982         if (RetInReg)
1983           Flags.setInReg();
1984 
1985         if (I.getOperand(0)->getType()->isPointerTy()) {
1986           Flags.setPointer();
1987           Flags.setPointerAddrSpace(
1988               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1989         }
1990 
1991         if (NeedsRegBlock) {
1992           Flags.setInConsecutiveRegs();
1993           if (j == NumValues - 1)
1994             Flags.setInConsecutiveRegsLast();
1995         }
1996 
1997         // Propagate extension type if any
1998         if (ExtendKind == ISD::SIGN_EXTEND)
1999           Flags.setSExt();
2000         else if (ExtendKind == ISD::ZERO_EXTEND)
2001           Flags.setZExt();
2002 
2003         for (unsigned i = 0; i < NumParts; ++i) {
2004           Outs.push_back(ISD::OutputArg(Flags,
2005                                         Parts[i].getValueType().getSimpleVT(),
2006                                         VT, /*isfixed=*/true, 0, 0));
2007           OutVals.push_back(Parts[i]);
2008         }
2009       }
2010     }
2011   }
2012 
2013   // Push in swifterror virtual register as the last element of Outs. This makes
2014   // sure swifterror virtual register will be returned in the swifterror
2015   // physical register.
2016   const Function *F = I.getParent()->getParent();
2017   if (TLI.supportSwiftError() &&
2018       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2019     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2020     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2021     Flags.setSwiftError();
2022     Outs.push_back(ISD::OutputArg(
2023         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2024         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2025     // Create SDNode for the swifterror virtual register.
2026     OutVals.push_back(
2027         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2028                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2029                         EVT(TLI.getPointerTy(DL))));
2030   }
2031 
2032   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2033   CallingConv::ID CallConv =
2034     DAG.getMachineFunction().getFunction().getCallingConv();
2035   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2036       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2037 
2038   // Verify that the target's LowerReturn behaved as expected.
2039   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2040          "LowerReturn didn't return a valid chain!");
2041 
2042   // Update the DAG with the new chain value resulting from return lowering.
2043   DAG.setRoot(Chain);
2044 }
2045 
2046 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2047 /// created for it, emit nodes to copy the value into the virtual
2048 /// registers.
2049 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2050   // Skip empty types
2051   if (V->getType()->isEmptyTy())
2052     return;
2053 
2054   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2055   if (VMI != FuncInfo.ValueMap.end()) {
2056     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2057     CopyValueToVirtualRegister(V, VMI->second);
2058   }
2059 }
2060 
2061 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2062 /// the current basic block, add it to ValueMap now so that we'll get a
2063 /// CopyTo/FromReg.
2064 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2065   // No need to export constants.
2066   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2067 
2068   // Already exported?
2069   if (FuncInfo.isExportedInst(V)) return;
2070 
2071   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2072   CopyValueToVirtualRegister(V, Reg);
2073 }
2074 
2075 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2076                                                      const BasicBlock *FromBB) {
2077   // The operands of the setcc have to be in this block.  We don't know
2078   // how to export them from some other block.
2079   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2080     // Can export from current BB.
2081     if (VI->getParent() == FromBB)
2082       return true;
2083 
2084     // Is already exported, noop.
2085     return FuncInfo.isExportedInst(V);
2086   }
2087 
2088   // If this is an argument, we can export it if the BB is the entry block or
2089   // if it is already exported.
2090   if (isa<Argument>(V)) {
2091     if (FromBB->isEntryBlock())
2092       return true;
2093 
2094     // Otherwise, can only export this if it is already exported.
2095     return FuncInfo.isExportedInst(V);
2096   }
2097 
2098   // Otherwise, constants can always be exported.
2099   return true;
2100 }
2101 
2102 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2103 BranchProbability
2104 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2105                                         const MachineBasicBlock *Dst) const {
2106   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2107   const BasicBlock *SrcBB = Src->getBasicBlock();
2108   const BasicBlock *DstBB = Dst->getBasicBlock();
2109   if (!BPI) {
2110     // If BPI is not available, set the default probability as 1 / N, where N is
2111     // the number of successors.
2112     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2113     return BranchProbability(1, SuccSize);
2114   }
2115   return BPI->getEdgeProbability(SrcBB, DstBB);
2116 }
2117 
2118 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2119                                                MachineBasicBlock *Dst,
2120                                                BranchProbability Prob) {
2121   if (!FuncInfo.BPI)
2122     Src->addSuccessorWithoutProb(Dst);
2123   else {
2124     if (Prob.isUnknown())
2125       Prob = getEdgeProbability(Src, Dst);
2126     Src->addSuccessor(Dst, Prob);
2127   }
2128 }
2129 
2130 static bool InBlock(const Value *V, const BasicBlock *BB) {
2131   if (const Instruction *I = dyn_cast<Instruction>(V))
2132     return I->getParent() == BB;
2133   return true;
2134 }
2135 
2136 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2137 /// This function emits a branch and is used at the leaves of an OR or an
2138 /// AND operator tree.
2139 void
2140 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2141                                                   MachineBasicBlock *TBB,
2142                                                   MachineBasicBlock *FBB,
2143                                                   MachineBasicBlock *CurBB,
2144                                                   MachineBasicBlock *SwitchBB,
2145                                                   BranchProbability TProb,
2146                                                   BranchProbability FProb,
2147                                                   bool InvertCond) {
2148   const BasicBlock *BB = CurBB->getBasicBlock();
2149 
2150   // If the leaf of the tree is a comparison, merge the condition into
2151   // the caseblock.
2152   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2153     // The operands of the cmp have to be in this block.  We don't know
2154     // how to export them from some other block.  If this is the first block
2155     // of the sequence, no exporting is needed.
2156     if (CurBB == SwitchBB ||
2157         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2158          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2159       ISD::CondCode Condition;
2160       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2161         ICmpInst::Predicate Pred =
2162             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2163         Condition = getICmpCondCode(Pred);
2164       } else {
2165         const FCmpInst *FC = cast<FCmpInst>(Cond);
2166         FCmpInst::Predicate Pred =
2167             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2168         Condition = getFCmpCondCode(Pred);
2169         if (TM.Options.NoNaNsFPMath)
2170           Condition = getFCmpCodeWithoutNaN(Condition);
2171       }
2172 
2173       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2174                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2175       SL->SwitchCases.push_back(CB);
2176       return;
2177     }
2178   }
2179 
2180   // Create a CaseBlock record representing this branch.
2181   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2182   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2183                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2184   SL->SwitchCases.push_back(CB);
2185 }
2186 
2187 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2188                                                MachineBasicBlock *TBB,
2189                                                MachineBasicBlock *FBB,
2190                                                MachineBasicBlock *CurBB,
2191                                                MachineBasicBlock *SwitchBB,
2192                                                Instruction::BinaryOps Opc,
2193                                                BranchProbability TProb,
2194                                                BranchProbability FProb,
2195                                                bool InvertCond) {
2196   // Skip over not part of the tree and remember to invert op and operands at
2197   // next level.
2198   Value *NotCond;
2199   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2200       InBlock(NotCond, CurBB->getBasicBlock())) {
2201     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2202                          !InvertCond);
2203     return;
2204   }
2205 
2206   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2207   const Value *BOpOp0, *BOpOp1;
2208   // Compute the effective opcode for Cond, taking into account whether it needs
2209   // to be inverted, e.g.
2210   //   and (not (or A, B)), C
2211   // gets lowered as
2212   //   and (and (not A, not B), C)
2213   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2214   if (BOp) {
2215     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2216                ? Instruction::And
2217                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2218                       ? Instruction::Or
2219                       : (Instruction::BinaryOps)0);
2220     if (InvertCond) {
2221       if (BOpc == Instruction::And)
2222         BOpc = Instruction::Or;
2223       else if (BOpc == Instruction::Or)
2224         BOpc = Instruction::And;
2225     }
2226   }
2227 
2228   // If this node is not part of the or/and tree, emit it as a branch.
2229   // Note that all nodes in the tree should have same opcode.
2230   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2231   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2232       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2233       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2234     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2235                                  TProb, FProb, InvertCond);
2236     return;
2237   }
2238 
2239   //  Create TmpBB after CurBB.
2240   MachineFunction::iterator BBI(CurBB);
2241   MachineFunction &MF = DAG.getMachineFunction();
2242   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2243   CurBB->getParent()->insert(++BBI, TmpBB);
2244 
2245   if (Opc == Instruction::Or) {
2246     // Codegen X | Y as:
2247     // BB1:
2248     //   jmp_if_X TBB
2249     //   jmp TmpBB
2250     // TmpBB:
2251     //   jmp_if_Y TBB
2252     //   jmp FBB
2253     //
2254 
2255     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2256     // The requirement is that
2257     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2258     //     = TrueProb for original BB.
2259     // Assuming the original probabilities are A and B, one choice is to set
2260     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2261     // A/(1+B) and 2B/(1+B). This choice assumes that
2262     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2263     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2264     // TmpBB, but the math is more complicated.
2265 
2266     auto NewTrueProb = TProb / 2;
2267     auto NewFalseProb = TProb / 2 + FProb;
2268     // Emit the LHS condition.
2269     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2270                          NewFalseProb, InvertCond);
2271 
2272     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2273     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2274     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2275     // Emit the RHS condition into TmpBB.
2276     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2277                          Probs[1], InvertCond);
2278   } else {
2279     assert(Opc == Instruction::And && "Unknown merge op!");
2280     // Codegen X & Y as:
2281     // BB1:
2282     //   jmp_if_X TmpBB
2283     //   jmp FBB
2284     // TmpBB:
2285     //   jmp_if_Y TBB
2286     //   jmp FBB
2287     //
2288     //  This requires creation of TmpBB after CurBB.
2289 
2290     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2291     // The requirement is that
2292     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2293     //     = FalseProb for original BB.
2294     // Assuming the original probabilities are A and B, one choice is to set
2295     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2296     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2297     // TrueProb for BB1 * FalseProb for TmpBB.
2298 
2299     auto NewTrueProb = TProb + FProb / 2;
2300     auto NewFalseProb = FProb / 2;
2301     // Emit the LHS condition.
2302     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2303                          NewFalseProb, InvertCond);
2304 
2305     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2306     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2307     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2308     // Emit the RHS condition into TmpBB.
2309     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2310                          Probs[1], InvertCond);
2311   }
2312 }
2313 
2314 /// If the set of cases should be emitted as a series of branches, return true.
2315 /// If we should emit this as a bunch of and/or'd together conditions, return
2316 /// false.
2317 bool
2318 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2319   if (Cases.size() != 2) return true;
2320 
2321   // If this is two comparisons of the same values or'd or and'd together, they
2322   // will get folded into a single comparison, so don't emit two blocks.
2323   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2324        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2325       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2326        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2327     return false;
2328   }
2329 
2330   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2331   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2332   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2333       Cases[0].CC == Cases[1].CC &&
2334       isa<Constant>(Cases[0].CmpRHS) &&
2335       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2336     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2337       return false;
2338     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2339       return false;
2340   }
2341 
2342   return true;
2343 }
2344 
2345 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2346   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2347 
2348   // Update machine-CFG edges.
2349   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2350 
2351   if (I.isUnconditional()) {
2352     // Update machine-CFG edges.
2353     BrMBB->addSuccessor(Succ0MBB);
2354 
2355     // If this is not a fall-through branch or optimizations are switched off,
2356     // emit the branch.
2357     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2358       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2359                               MVT::Other, getControlRoot(),
2360                               DAG.getBasicBlock(Succ0MBB)));
2361 
2362     return;
2363   }
2364 
2365   // If this condition is one of the special cases we handle, do special stuff
2366   // now.
2367   const Value *CondVal = I.getCondition();
2368   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2369 
2370   // If this is a series of conditions that are or'd or and'd together, emit
2371   // this as a sequence of branches instead of setcc's with and/or operations.
2372   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2373   // unpredictable branches, and vector extracts because those jumps are likely
2374   // expensive for any target), this should improve performance.
2375   // For example, instead of something like:
2376   //     cmp A, B
2377   //     C = seteq
2378   //     cmp D, E
2379   //     F = setle
2380   //     or C, F
2381   //     jnz foo
2382   // Emit:
2383   //     cmp A, B
2384   //     je foo
2385   //     cmp D, E
2386   //     jle foo
2387   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2388   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2389       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2390     Value *Vec;
2391     const Value *BOp0, *BOp1;
2392     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2393     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2394       Opcode = Instruction::And;
2395     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2396       Opcode = Instruction::Or;
2397 
2398     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2399                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2400       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2401                            getEdgeProbability(BrMBB, Succ0MBB),
2402                            getEdgeProbability(BrMBB, Succ1MBB),
2403                            /*InvertCond=*/false);
2404       // If the compares in later blocks need to use values not currently
2405       // exported from this block, export them now.  This block should always
2406       // be the first entry.
2407       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2408 
2409       // Allow some cases to be rejected.
2410       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2411         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2412           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2413           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2414         }
2415 
2416         // Emit the branch for this block.
2417         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2418         SL->SwitchCases.erase(SL->SwitchCases.begin());
2419         return;
2420       }
2421 
2422       // Okay, we decided not to do this, remove any inserted MBB's and clear
2423       // SwitchCases.
2424       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2425         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2426 
2427       SL->SwitchCases.clear();
2428     }
2429   }
2430 
2431   // Create a CaseBlock record representing this branch.
2432   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2433                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2434 
2435   // Use visitSwitchCase to actually insert the fast branch sequence for this
2436   // cond branch.
2437   visitSwitchCase(CB, BrMBB);
2438 }
2439 
2440 /// visitSwitchCase - Emits the necessary code to represent a single node in
2441 /// the binary search tree resulting from lowering a switch instruction.
2442 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2443                                           MachineBasicBlock *SwitchBB) {
2444   SDValue Cond;
2445   SDValue CondLHS = getValue(CB.CmpLHS);
2446   SDLoc dl = CB.DL;
2447 
2448   if (CB.CC == ISD::SETTRUE) {
2449     // Branch or fall through to TrueBB.
2450     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2451     SwitchBB->normalizeSuccProbs();
2452     if (CB.TrueBB != NextBlock(SwitchBB)) {
2453       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2454                               DAG.getBasicBlock(CB.TrueBB)));
2455     }
2456     return;
2457   }
2458 
2459   auto &TLI = DAG.getTargetLoweringInfo();
2460   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2461 
2462   // Build the setcc now.
2463   if (!CB.CmpMHS) {
2464     // Fold "(X == true)" to X and "(X == false)" to !X to
2465     // handle common cases produced by branch lowering.
2466     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2467         CB.CC == ISD::SETEQ)
2468       Cond = CondLHS;
2469     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2470              CB.CC == ISD::SETEQ) {
2471       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2472       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2473     } else {
2474       SDValue CondRHS = getValue(CB.CmpRHS);
2475 
2476       // If a pointer's DAG type is larger than its memory type then the DAG
2477       // values are zero-extended. This breaks signed comparisons so truncate
2478       // back to the underlying type before doing the compare.
2479       if (CondLHS.getValueType() != MemVT) {
2480         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2481         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2482       }
2483       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2484     }
2485   } else {
2486     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2487 
2488     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2489     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2490 
2491     SDValue CmpOp = getValue(CB.CmpMHS);
2492     EVT VT = CmpOp.getValueType();
2493 
2494     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2495       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2496                           ISD::SETLE);
2497     } else {
2498       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2499                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2500       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2501                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2502     }
2503   }
2504 
2505   // Update successor info
2506   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2507   // TrueBB and FalseBB are always different unless the incoming IR is
2508   // degenerate. This only happens when running llc on weird IR.
2509   if (CB.TrueBB != CB.FalseBB)
2510     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2511   SwitchBB->normalizeSuccProbs();
2512 
2513   // If the lhs block is the next block, invert the condition so that we can
2514   // fall through to the lhs instead of the rhs block.
2515   if (CB.TrueBB == NextBlock(SwitchBB)) {
2516     std::swap(CB.TrueBB, CB.FalseBB);
2517     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2518     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2519   }
2520 
2521   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2522                                MVT::Other, getControlRoot(), Cond,
2523                                DAG.getBasicBlock(CB.TrueBB));
2524 
2525   // Insert the false branch. Do this even if it's a fall through branch,
2526   // this makes it easier to do DAG optimizations which require inverting
2527   // the branch condition.
2528   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2529                        DAG.getBasicBlock(CB.FalseBB));
2530 
2531   DAG.setRoot(BrCond);
2532 }
2533 
2534 /// visitJumpTable - Emit JumpTable node in the current MBB
2535 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2536   // Emit the code for the jump table
2537   assert(JT.Reg != -1U && "Should lower JT Header first!");
2538   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2539   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2540                                      JT.Reg, PTy);
2541   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2542   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2543                                     MVT::Other, Index.getValue(1),
2544                                     Table, Index);
2545   DAG.setRoot(BrJumpTable);
2546 }
2547 
2548 /// visitJumpTableHeader - This function emits necessary code to produce index
2549 /// in the JumpTable from switch case.
2550 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2551                                                JumpTableHeader &JTH,
2552                                                MachineBasicBlock *SwitchBB) {
2553   SDLoc dl = getCurSDLoc();
2554 
2555   // Subtract the lowest switch case value from the value being switched on.
2556   SDValue SwitchOp = getValue(JTH.SValue);
2557   EVT VT = SwitchOp.getValueType();
2558   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2559                             DAG.getConstant(JTH.First, dl, VT));
2560 
2561   // The SDNode we just created, which holds the value being switched on minus
2562   // the smallest case value, needs to be copied to a virtual register so it
2563   // can be used as an index into the jump table in a subsequent basic block.
2564   // This value may be smaller or larger than the target's pointer type, and
2565   // therefore require extension or truncating.
2566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2567   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2568 
2569   unsigned JumpTableReg =
2570       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2571   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2572                                     JumpTableReg, SwitchOp);
2573   JT.Reg = JumpTableReg;
2574 
2575   if (!JTH.FallthroughUnreachable) {
2576     // Emit the range check for the jump table, and branch to the default block
2577     // for the switch statement if the value being switched on exceeds the
2578     // largest case in the switch.
2579     SDValue CMP = DAG.getSetCC(
2580         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2581                                    Sub.getValueType()),
2582         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2583 
2584     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2585                                  MVT::Other, CopyTo, CMP,
2586                                  DAG.getBasicBlock(JT.Default));
2587 
2588     // Avoid emitting unnecessary branches to the next block.
2589     if (JT.MBB != NextBlock(SwitchBB))
2590       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2591                            DAG.getBasicBlock(JT.MBB));
2592 
2593     DAG.setRoot(BrCond);
2594   } else {
2595     // Avoid emitting unnecessary branches to the next block.
2596     if (JT.MBB != NextBlock(SwitchBB))
2597       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2598                               DAG.getBasicBlock(JT.MBB)));
2599     else
2600       DAG.setRoot(CopyTo);
2601   }
2602 }
2603 
2604 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2605 /// variable if there exists one.
2606 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2607                                  SDValue &Chain) {
2608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2609   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2610   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2611   MachineFunction &MF = DAG.getMachineFunction();
2612   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2613   MachineSDNode *Node =
2614       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2615   if (Global) {
2616     MachinePointerInfo MPInfo(Global);
2617     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2618                  MachineMemOperand::MODereferenceable;
2619     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2620         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2621     DAG.setNodeMemRefs(Node, {MemRef});
2622   }
2623   if (PtrTy != PtrMemTy)
2624     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2625   return SDValue(Node, 0);
2626 }
2627 
2628 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2629 /// tail spliced into a stack protector check success bb.
2630 ///
2631 /// For a high level explanation of how this fits into the stack protector
2632 /// generation see the comment on the declaration of class
2633 /// StackProtectorDescriptor.
2634 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2635                                                   MachineBasicBlock *ParentBB) {
2636 
2637   // First create the loads to the guard/stack slot for the comparison.
2638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2639   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2640   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2641 
2642   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2643   int FI = MFI.getStackProtectorIndex();
2644 
2645   SDValue Guard;
2646   SDLoc dl = getCurSDLoc();
2647   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2648   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2649   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2650 
2651   // Generate code to load the content of the guard slot.
2652   SDValue GuardVal = DAG.getLoad(
2653       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2654       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2655       MachineMemOperand::MOVolatile);
2656 
2657   if (TLI.useStackGuardXorFP())
2658     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2659 
2660   // Retrieve guard check function, nullptr if instrumentation is inlined.
2661   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2662     // The target provides a guard check function to validate the guard value.
2663     // Generate a call to that function with the content of the guard slot as
2664     // argument.
2665     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2666     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2667 
2668     TargetLowering::ArgListTy Args;
2669     TargetLowering::ArgListEntry Entry;
2670     Entry.Node = GuardVal;
2671     Entry.Ty = FnTy->getParamType(0);
2672     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2673       Entry.IsInReg = true;
2674     Args.push_back(Entry);
2675 
2676     TargetLowering::CallLoweringInfo CLI(DAG);
2677     CLI.setDebugLoc(getCurSDLoc())
2678         .setChain(DAG.getEntryNode())
2679         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2680                    getValue(GuardCheckFn), std::move(Args));
2681 
2682     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2683     DAG.setRoot(Result.second);
2684     return;
2685   }
2686 
2687   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2688   // Otherwise, emit a volatile load to retrieve the stack guard value.
2689   SDValue Chain = DAG.getEntryNode();
2690   if (TLI.useLoadStackGuardNode()) {
2691     Guard = getLoadStackGuard(DAG, dl, Chain);
2692   } else {
2693     const Value *IRGuard = TLI.getSDagStackGuard(M);
2694     SDValue GuardPtr = getValue(IRGuard);
2695 
2696     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2697                         MachinePointerInfo(IRGuard, 0), Align,
2698                         MachineMemOperand::MOVolatile);
2699   }
2700 
2701   // Perform the comparison via a getsetcc.
2702   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2703                                                         *DAG.getContext(),
2704                                                         Guard.getValueType()),
2705                              Guard, GuardVal, ISD::SETNE);
2706 
2707   // If the guard/stackslot do not equal, branch to failure MBB.
2708   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2709                                MVT::Other, GuardVal.getOperand(0),
2710                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2711   // Otherwise branch to success MBB.
2712   SDValue Br = DAG.getNode(ISD::BR, dl,
2713                            MVT::Other, BrCond,
2714                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2715 
2716   DAG.setRoot(Br);
2717 }
2718 
2719 /// Codegen the failure basic block for a stack protector check.
2720 ///
2721 /// A failure stack protector machine basic block consists simply of a call to
2722 /// __stack_chk_fail().
2723 ///
2724 /// For a high level explanation of how this fits into the stack protector
2725 /// generation see the comment on the declaration of class
2726 /// StackProtectorDescriptor.
2727 void
2728 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2730   TargetLowering::MakeLibCallOptions CallOptions;
2731   CallOptions.setDiscardResult(true);
2732   SDValue Chain =
2733       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2734                       None, CallOptions, getCurSDLoc()).second;
2735   // On PS4, the "return address" must still be within the calling function,
2736   // even if it's at the very end, so emit an explicit TRAP here.
2737   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2738   if (TM.getTargetTriple().isPS4CPU())
2739     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2740   // WebAssembly needs an unreachable instruction after a non-returning call,
2741   // because the function return type can be different from __stack_chk_fail's
2742   // return type (void).
2743   if (TM.getTargetTriple().isWasm())
2744     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2745 
2746   DAG.setRoot(Chain);
2747 }
2748 
2749 /// visitBitTestHeader - This function emits necessary code to produce value
2750 /// suitable for "bit tests"
2751 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2752                                              MachineBasicBlock *SwitchBB) {
2753   SDLoc dl = getCurSDLoc();
2754 
2755   // Subtract the minimum value.
2756   SDValue SwitchOp = getValue(B.SValue);
2757   EVT VT = SwitchOp.getValueType();
2758   SDValue RangeSub =
2759       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2760 
2761   // Determine the type of the test operands.
2762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2763   bool UsePtrType = false;
2764   if (!TLI.isTypeLegal(VT)) {
2765     UsePtrType = true;
2766   } else {
2767     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2768       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2769         // Switch table case range are encoded into series of masks.
2770         // Just use pointer type, it's guaranteed to fit.
2771         UsePtrType = true;
2772         break;
2773       }
2774   }
2775   SDValue Sub = RangeSub;
2776   if (UsePtrType) {
2777     VT = TLI.getPointerTy(DAG.getDataLayout());
2778     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2779   }
2780 
2781   B.RegVT = VT.getSimpleVT();
2782   B.Reg = FuncInfo.CreateReg(B.RegVT);
2783   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2784 
2785   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2786 
2787   if (!B.FallthroughUnreachable)
2788     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2789   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2790   SwitchBB->normalizeSuccProbs();
2791 
2792   SDValue Root = CopyTo;
2793   if (!B.FallthroughUnreachable) {
2794     // Conditional branch to the default block.
2795     SDValue RangeCmp = DAG.getSetCC(dl,
2796         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2797                                RangeSub.getValueType()),
2798         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2799         ISD::SETUGT);
2800 
2801     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2802                        DAG.getBasicBlock(B.Default));
2803   }
2804 
2805   // Avoid emitting unnecessary branches to the next block.
2806   if (MBB != NextBlock(SwitchBB))
2807     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2808 
2809   DAG.setRoot(Root);
2810 }
2811 
2812 /// visitBitTestCase - this function produces one "bit test"
2813 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2814                                            MachineBasicBlock* NextMBB,
2815                                            BranchProbability BranchProbToNext,
2816                                            unsigned Reg,
2817                                            BitTestCase &B,
2818                                            MachineBasicBlock *SwitchBB) {
2819   SDLoc dl = getCurSDLoc();
2820   MVT VT = BB.RegVT;
2821   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2822   SDValue Cmp;
2823   unsigned PopCount = countPopulation(B.Mask);
2824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2825   if (PopCount == 1) {
2826     // Testing for a single bit; just compare the shift count with what it
2827     // would need to be to shift a 1 bit in that position.
2828     Cmp = DAG.getSetCC(
2829         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2830         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2831         ISD::SETEQ);
2832   } else if (PopCount == BB.Range) {
2833     // There is only one zero bit in the range, test for it directly.
2834     Cmp = DAG.getSetCC(
2835         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2836         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2837         ISD::SETNE);
2838   } else {
2839     // Make desired shift
2840     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2841                                     DAG.getConstant(1, dl, VT), ShiftOp);
2842 
2843     // Emit bit tests and jumps
2844     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2845                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2846     Cmp = DAG.getSetCC(
2847         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2848         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2849   }
2850 
2851   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2852   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2853   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2854   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2855   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2856   // one as they are relative probabilities (and thus work more like weights),
2857   // and hence we need to normalize them to let the sum of them become one.
2858   SwitchBB->normalizeSuccProbs();
2859 
2860   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2861                               MVT::Other, getControlRoot(),
2862                               Cmp, DAG.getBasicBlock(B.TargetBB));
2863 
2864   // Avoid emitting unnecessary branches to the next block.
2865   if (NextMBB != NextBlock(SwitchBB))
2866     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2867                         DAG.getBasicBlock(NextMBB));
2868 
2869   DAG.setRoot(BrAnd);
2870 }
2871 
2872 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2873   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2874 
2875   // Retrieve successors. Look through artificial IR level blocks like
2876   // catchswitch for successors.
2877   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2878   const BasicBlock *EHPadBB = I.getSuccessor(1);
2879 
2880   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2881   // have to do anything here to lower funclet bundles.
2882   assert(!I.hasOperandBundlesOtherThan(
2883              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2884               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2885               LLVMContext::OB_cfguardtarget,
2886               LLVMContext::OB_clang_arc_attachedcall}) &&
2887          "Cannot lower invokes with arbitrary operand bundles yet!");
2888 
2889   const Value *Callee(I.getCalledOperand());
2890   const Function *Fn = dyn_cast<Function>(Callee);
2891   if (isa<InlineAsm>(Callee))
2892     visitInlineAsm(I, EHPadBB);
2893   else if (Fn && Fn->isIntrinsic()) {
2894     switch (Fn->getIntrinsicID()) {
2895     default:
2896       llvm_unreachable("Cannot invoke this intrinsic");
2897     case Intrinsic::donothing:
2898       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2899     case Intrinsic::seh_try_begin:
2900     case Intrinsic::seh_scope_begin:
2901     case Intrinsic::seh_try_end:
2902     case Intrinsic::seh_scope_end:
2903       break;
2904     case Intrinsic::experimental_patchpoint_void:
2905     case Intrinsic::experimental_patchpoint_i64:
2906       visitPatchpoint(I, EHPadBB);
2907       break;
2908     case Intrinsic::experimental_gc_statepoint:
2909       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2910       break;
2911     case Intrinsic::wasm_rethrow: {
2912       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2913       // special because it can be invoked, so we manually lower it to a DAG
2914       // node here.
2915       SmallVector<SDValue, 8> Ops;
2916       Ops.push_back(getRoot()); // inchain
2917       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2918       Ops.push_back(
2919           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2920                                 TLI.getPointerTy(DAG.getDataLayout())));
2921       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2922       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2923       break;
2924     }
2925     }
2926   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2927     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2928     // Eventually we will support lowering the @llvm.experimental.deoptimize
2929     // intrinsic, and right now there are no plans to support other intrinsics
2930     // with deopt state.
2931     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2932   } else {
2933     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2934   }
2935 
2936   // If the value of the invoke is used outside of its defining block, make it
2937   // available as a virtual register.
2938   // We already took care of the exported value for the statepoint instruction
2939   // during call to the LowerStatepoint.
2940   if (!isa<GCStatepointInst>(I)) {
2941     CopyToExportRegsIfNeeded(&I);
2942   }
2943 
2944   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2945   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2946   BranchProbability EHPadBBProb =
2947       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2948           : BranchProbability::getZero();
2949   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2950 
2951   // Update successor info.
2952   addSuccessorWithProb(InvokeMBB, Return);
2953   for (auto &UnwindDest : UnwindDests) {
2954     UnwindDest.first->setIsEHPad();
2955     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2956   }
2957   InvokeMBB->normalizeSuccProbs();
2958 
2959   // Drop into normal successor.
2960   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2961                           DAG.getBasicBlock(Return)));
2962 }
2963 
2964 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2965   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2966 
2967   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2968   // have to do anything here to lower funclet bundles.
2969   assert(!I.hasOperandBundlesOtherThan(
2970              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2971          "Cannot lower callbrs with arbitrary operand bundles yet!");
2972 
2973   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2974   visitInlineAsm(I);
2975   CopyToExportRegsIfNeeded(&I);
2976 
2977   // Retrieve successors.
2978   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2979 
2980   // Update successor info.
2981   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2982   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2983     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2984     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2985     Target->setIsInlineAsmBrIndirectTarget();
2986   }
2987   CallBrMBB->normalizeSuccProbs();
2988 
2989   // Drop into default successor.
2990   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2991                           MVT::Other, getControlRoot(),
2992                           DAG.getBasicBlock(Return)));
2993 }
2994 
2995 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2996   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2997 }
2998 
2999 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3000   assert(FuncInfo.MBB->isEHPad() &&
3001          "Call to landingpad not in landing pad!");
3002 
3003   // If there aren't registers to copy the values into (e.g., during SjLj
3004   // exceptions), then don't bother to create these DAG nodes.
3005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3006   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3007   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3008       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3009     return;
3010 
3011   // If landingpad's return type is token type, we don't create DAG nodes
3012   // for its exception pointer and selector value. The extraction of exception
3013   // pointer or selector value from token type landingpads is not currently
3014   // supported.
3015   if (LP.getType()->isTokenTy())
3016     return;
3017 
3018   SmallVector<EVT, 2> ValueVTs;
3019   SDLoc dl = getCurSDLoc();
3020   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3021   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3022 
3023   // Get the two live-in registers as SDValues. The physregs have already been
3024   // copied into virtual registers.
3025   SDValue Ops[2];
3026   if (FuncInfo.ExceptionPointerVirtReg) {
3027     Ops[0] = DAG.getZExtOrTrunc(
3028         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3029                            FuncInfo.ExceptionPointerVirtReg,
3030                            TLI.getPointerTy(DAG.getDataLayout())),
3031         dl, ValueVTs[0]);
3032   } else {
3033     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3034   }
3035   Ops[1] = DAG.getZExtOrTrunc(
3036       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3037                          FuncInfo.ExceptionSelectorVirtReg,
3038                          TLI.getPointerTy(DAG.getDataLayout())),
3039       dl, ValueVTs[1]);
3040 
3041   // Merge into one.
3042   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3043                             DAG.getVTList(ValueVTs), Ops);
3044   setValue(&LP, Res);
3045 }
3046 
3047 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3048                                            MachineBasicBlock *Last) {
3049   // Update JTCases.
3050   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3051     if (SL->JTCases[i].first.HeaderBB == First)
3052       SL->JTCases[i].first.HeaderBB = Last;
3053 
3054   // Update BitTestCases.
3055   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3056     if (SL->BitTestCases[i].Parent == First)
3057       SL->BitTestCases[i].Parent = Last;
3058 }
3059 
3060 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3061   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3062 
3063   // Update machine-CFG edges with unique successors.
3064   SmallSet<BasicBlock*, 32> Done;
3065   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3066     BasicBlock *BB = I.getSuccessor(i);
3067     bool Inserted = Done.insert(BB).second;
3068     if (!Inserted)
3069         continue;
3070 
3071     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3072     addSuccessorWithProb(IndirectBrMBB, Succ);
3073   }
3074   IndirectBrMBB->normalizeSuccProbs();
3075 
3076   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3077                           MVT::Other, getControlRoot(),
3078                           getValue(I.getAddress())));
3079 }
3080 
3081 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3082   if (!DAG.getTarget().Options.TrapUnreachable)
3083     return;
3084 
3085   // We may be able to ignore unreachable behind a noreturn call.
3086   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3087     const BasicBlock &BB = *I.getParent();
3088     if (&I != &BB.front()) {
3089       BasicBlock::const_iterator PredI =
3090         std::prev(BasicBlock::const_iterator(&I));
3091       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3092         if (Call->doesNotReturn())
3093           return;
3094       }
3095     }
3096   }
3097 
3098   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3099 }
3100 
3101 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3102   SDNodeFlags Flags;
3103 
3104   SDValue Op = getValue(I.getOperand(0));
3105   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3106                                     Op, Flags);
3107   setValue(&I, UnNodeValue);
3108 }
3109 
3110 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3111   SDNodeFlags Flags;
3112   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3113     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3114     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3115   }
3116   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3117     Flags.setExact(ExactOp->isExact());
3118   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3119     Flags.copyFMF(*FPOp);
3120 
3121   SDValue Op1 = getValue(I.getOperand(0));
3122   SDValue Op2 = getValue(I.getOperand(1));
3123   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3124                                      Op1, Op2, Flags);
3125   setValue(&I, BinNodeValue);
3126 }
3127 
3128 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3129   SDValue Op1 = getValue(I.getOperand(0));
3130   SDValue Op2 = getValue(I.getOperand(1));
3131 
3132   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3133       Op1.getValueType(), DAG.getDataLayout());
3134 
3135   // Coerce the shift amount to the right type if we can.
3136   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3137     unsigned ShiftSize = ShiftTy.getSizeInBits();
3138     unsigned Op2Size = Op2.getValueSizeInBits();
3139     SDLoc DL = getCurSDLoc();
3140 
3141     // If the operand is smaller than the shift count type, promote it.
3142     if (ShiftSize > Op2Size)
3143       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3144 
3145     // If the operand is larger than the shift count type but the shift
3146     // count type has enough bits to represent any shift value, truncate
3147     // it now. This is a common case and it exposes the truncate to
3148     // optimization early.
3149     else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3150       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3151     // Otherwise we'll need to temporarily settle for some other convenient
3152     // type.  Type legalization will make adjustments once the shiftee is split.
3153     else
3154       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3155   }
3156 
3157   bool nuw = false;
3158   bool nsw = false;
3159   bool exact = false;
3160 
3161   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3162 
3163     if (const OverflowingBinaryOperator *OFBinOp =
3164             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3165       nuw = OFBinOp->hasNoUnsignedWrap();
3166       nsw = OFBinOp->hasNoSignedWrap();
3167     }
3168     if (const PossiblyExactOperator *ExactOp =
3169             dyn_cast<const PossiblyExactOperator>(&I))
3170       exact = ExactOp->isExact();
3171   }
3172   SDNodeFlags Flags;
3173   Flags.setExact(exact);
3174   Flags.setNoSignedWrap(nsw);
3175   Flags.setNoUnsignedWrap(nuw);
3176   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3177                             Flags);
3178   setValue(&I, Res);
3179 }
3180 
3181 void SelectionDAGBuilder::visitSDiv(const User &I) {
3182   SDValue Op1 = getValue(I.getOperand(0));
3183   SDValue Op2 = getValue(I.getOperand(1));
3184 
3185   SDNodeFlags Flags;
3186   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3187                  cast<PossiblyExactOperator>(&I)->isExact());
3188   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3189                            Op2, Flags));
3190 }
3191 
3192 void SelectionDAGBuilder::visitICmp(const User &I) {
3193   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3194   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3195     predicate = IC->getPredicate();
3196   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3197     predicate = ICmpInst::Predicate(IC->getPredicate());
3198   SDValue Op1 = getValue(I.getOperand(0));
3199   SDValue Op2 = getValue(I.getOperand(1));
3200   ISD::CondCode Opcode = getICmpCondCode(predicate);
3201 
3202   auto &TLI = DAG.getTargetLoweringInfo();
3203   EVT MemVT =
3204       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3205 
3206   // If a pointer's DAG type is larger than its memory type then the DAG values
3207   // are zero-extended. This breaks signed comparisons so truncate back to the
3208   // underlying type before doing the compare.
3209   if (Op1.getValueType() != MemVT) {
3210     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3211     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3212   }
3213 
3214   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3215                                                         I.getType());
3216   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3217 }
3218 
3219 void SelectionDAGBuilder::visitFCmp(const User &I) {
3220   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3221   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3222     predicate = FC->getPredicate();
3223   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3224     predicate = FCmpInst::Predicate(FC->getPredicate());
3225   SDValue Op1 = getValue(I.getOperand(0));
3226   SDValue Op2 = getValue(I.getOperand(1));
3227 
3228   ISD::CondCode Condition = getFCmpCondCode(predicate);
3229   auto *FPMO = cast<FPMathOperator>(&I);
3230   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3231     Condition = getFCmpCodeWithoutNaN(Condition);
3232 
3233   SDNodeFlags Flags;
3234   Flags.copyFMF(*FPMO);
3235   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3236 
3237   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3238                                                         I.getType());
3239   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3240 }
3241 
3242 // Check if the condition of the select has one use or two users that are both
3243 // selects with the same condition.
3244 static bool hasOnlySelectUsers(const Value *Cond) {
3245   return llvm::all_of(Cond->users(), [](const Value *V) {
3246     return isa<SelectInst>(V);
3247   });
3248 }
3249 
3250 void SelectionDAGBuilder::visitSelect(const User &I) {
3251   SmallVector<EVT, 4> ValueVTs;
3252   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3253                   ValueVTs);
3254   unsigned NumValues = ValueVTs.size();
3255   if (NumValues == 0) return;
3256 
3257   SmallVector<SDValue, 4> Values(NumValues);
3258   SDValue Cond     = getValue(I.getOperand(0));
3259   SDValue LHSVal   = getValue(I.getOperand(1));
3260   SDValue RHSVal   = getValue(I.getOperand(2));
3261   SmallVector<SDValue, 1> BaseOps(1, Cond);
3262   ISD::NodeType OpCode =
3263       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3264 
3265   bool IsUnaryAbs = false;
3266   bool Negate = false;
3267 
3268   SDNodeFlags Flags;
3269   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3270     Flags.copyFMF(*FPOp);
3271 
3272   // Min/max matching is only viable if all output VTs are the same.
3273   if (is_splat(ValueVTs)) {
3274     EVT VT = ValueVTs[0];
3275     LLVMContext &Ctx = *DAG.getContext();
3276     auto &TLI = DAG.getTargetLoweringInfo();
3277 
3278     // We care about the legality of the operation after it has been type
3279     // legalized.
3280     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3281       VT = TLI.getTypeToTransformTo(Ctx, VT);
3282 
3283     // If the vselect is legal, assume we want to leave this as a vector setcc +
3284     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3285     // min/max is legal on the scalar type.
3286     bool UseScalarMinMax = VT.isVector() &&
3287       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3288 
3289     Value *LHS, *RHS;
3290     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3291     ISD::NodeType Opc = ISD::DELETED_NODE;
3292     switch (SPR.Flavor) {
3293     case SPF_UMAX:    Opc = ISD::UMAX; break;
3294     case SPF_UMIN:    Opc = ISD::UMIN; break;
3295     case SPF_SMAX:    Opc = ISD::SMAX; break;
3296     case SPF_SMIN:    Opc = ISD::SMIN; break;
3297     case SPF_FMINNUM:
3298       switch (SPR.NaNBehavior) {
3299       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3300       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3301       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3302       case SPNB_RETURNS_ANY: {
3303         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3304           Opc = ISD::FMINNUM;
3305         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3306           Opc = ISD::FMINIMUM;
3307         else if (UseScalarMinMax)
3308           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3309             ISD::FMINNUM : ISD::FMINIMUM;
3310         break;
3311       }
3312       }
3313       break;
3314     case SPF_FMAXNUM:
3315       switch (SPR.NaNBehavior) {
3316       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3317       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3318       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3319       case SPNB_RETURNS_ANY:
3320 
3321         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3322           Opc = ISD::FMAXNUM;
3323         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3324           Opc = ISD::FMAXIMUM;
3325         else if (UseScalarMinMax)
3326           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3327             ISD::FMAXNUM : ISD::FMAXIMUM;
3328         break;
3329       }
3330       break;
3331     case SPF_NABS:
3332       Negate = true;
3333       LLVM_FALLTHROUGH;
3334     case SPF_ABS:
3335       IsUnaryAbs = true;
3336       Opc = ISD::ABS;
3337       break;
3338     default: break;
3339     }
3340 
3341     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3342         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3343          (UseScalarMinMax &&
3344           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3345         // If the underlying comparison instruction is used by any other
3346         // instruction, the consumed instructions won't be destroyed, so it is
3347         // not profitable to convert to a min/max.
3348         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3349       OpCode = Opc;
3350       LHSVal = getValue(LHS);
3351       RHSVal = getValue(RHS);
3352       BaseOps.clear();
3353     }
3354 
3355     if (IsUnaryAbs) {
3356       OpCode = Opc;
3357       LHSVal = getValue(LHS);
3358       BaseOps.clear();
3359     }
3360   }
3361 
3362   if (IsUnaryAbs) {
3363     for (unsigned i = 0; i != NumValues; ++i) {
3364       SDLoc dl = getCurSDLoc();
3365       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3366       Values[i] =
3367           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3368       if (Negate)
3369         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3370                                 Values[i]);
3371     }
3372   } else {
3373     for (unsigned i = 0; i != NumValues; ++i) {
3374       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3375       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3376       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3377       Values[i] = DAG.getNode(
3378           OpCode, getCurSDLoc(),
3379           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3380     }
3381   }
3382 
3383   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3384                            DAG.getVTList(ValueVTs), Values));
3385 }
3386 
3387 void SelectionDAGBuilder::visitTrunc(const User &I) {
3388   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3389   SDValue N = getValue(I.getOperand(0));
3390   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3391                                                         I.getType());
3392   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3393 }
3394 
3395 void SelectionDAGBuilder::visitZExt(const User &I) {
3396   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3397   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3398   SDValue N = getValue(I.getOperand(0));
3399   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3400                                                         I.getType());
3401   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3402 }
3403 
3404 void SelectionDAGBuilder::visitSExt(const User &I) {
3405   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3406   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3407   SDValue N = getValue(I.getOperand(0));
3408   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3409                                                         I.getType());
3410   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3411 }
3412 
3413 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3414   // FPTrunc is never a no-op cast, no need to check
3415   SDValue N = getValue(I.getOperand(0));
3416   SDLoc dl = getCurSDLoc();
3417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3418   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3419   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3420                            DAG.getTargetConstant(
3421                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3422 }
3423 
3424 void SelectionDAGBuilder::visitFPExt(const User &I) {
3425   // FPExt is never a no-op cast, no need to check
3426   SDValue N = getValue(I.getOperand(0));
3427   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3428                                                         I.getType());
3429   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3430 }
3431 
3432 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3433   // FPToUI is never a no-op cast, no need to check
3434   SDValue N = getValue(I.getOperand(0));
3435   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3436                                                         I.getType());
3437   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3441   // FPToSI is never a no-op cast, no need to check
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3449   // UIToFP is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3457   // SIToFP is never a no-op cast, no need to check
3458   SDValue N = getValue(I.getOperand(0));
3459   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3460                                                         I.getType());
3461   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3465   // What to do depends on the size of the integer and the size of the pointer.
3466   // We can either truncate, zero extend, or no-op, accordingly.
3467   SDValue N = getValue(I.getOperand(0));
3468   auto &TLI = DAG.getTargetLoweringInfo();
3469   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3470                                                         I.getType());
3471   EVT PtrMemVT =
3472       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3473   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3474   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3475   setValue(&I, N);
3476 }
3477 
3478 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3479   // What to do depends on the size of the integer and the size of the pointer.
3480   // We can either truncate, zero extend, or no-op, accordingly.
3481   SDValue N = getValue(I.getOperand(0));
3482   auto &TLI = DAG.getTargetLoweringInfo();
3483   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3484   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3485   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3486   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3487   setValue(&I, N);
3488 }
3489 
3490 void SelectionDAGBuilder::visitBitCast(const User &I) {
3491   SDValue N = getValue(I.getOperand(0));
3492   SDLoc dl = getCurSDLoc();
3493   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3494                                                         I.getType());
3495 
3496   // BitCast assures us that source and destination are the same size so this is
3497   // either a BITCAST or a no-op.
3498   if (DestVT != N.getValueType())
3499     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3500                              DestVT, N)); // convert types.
3501   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3502   // might fold any kind of constant expression to an integer constant and that
3503   // is not what we are looking for. Only recognize a bitcast of a genuine
3504   // constant integer as an opaque constant.
3505   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3506     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3507                                  /*isOpaque*/true));
3508   else
3509     setValue(&I, N);            // noop cast.
3510 }
3511 
3512 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3514   const Value *SV = I.getOperand(0);
3515   SDValue N = getValue(SV);
3516   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3517 
3518   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3519   unsigned DestAS = I.getType()->getPointerAddressSpace();
3520 
3521   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3522     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3523 
3524   setValue(&I, N);
3525 }
3526 
3527 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3529   SDValue InVec = getValue(I.getOperand(0));
3530   SDValue InVal = getValue(I.getOperand(1));
3531   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3532                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3533   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3534                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3535                            InVec, InVal, InIdx));
3536 }
3537 
3538 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3540   SDValue InVec = getValue(I.getOperand(0));
3541   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3542                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3543   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3544                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3545                            InVec, InIdx));
3546 }
3547 
3548 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3549   SDValue Src1 = getValue(I.getOperand(0));
3550   SDValue Src2 = getValue(I.getOperand(1));
3551   ArrayRef<int> Mask;
3552   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3553     Mask = SVI->getShuffleMask();
3554   else
3555     Mask = cast<ConstantExpr>(I).getShuffleMask();
3556   SDLoc DL = getCurSDLoc();
3557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3559   EVT SrcVT = Src1.getValueType();
3560 
3561   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3562       VT.isScalableVector()) {
3563     // Canonical splat form of first element of first input vector.
3564     SDValue FirstElt =
3565         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3566                     DAG.getVectorIdxConstant(0, DL));
3567     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3568     return;
3569   }
3570 
3571   // For now, we only handle splats for scalable vectors.
3572   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3573   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3574   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3575 
3576   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3577   unsigned MaskNumElts = Mask.size();
3578 
3579   if (SrcNumElts == MaskNumElts) {
3580     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3581     return;
3582   }
3583 
3584   // Normalize the shuffle vector since mask and vector length don't match.
3585   if (SrcNumElts < MaskNumElts) {
3586     // Mask is longer than the source vectors. We can use concatenate vector to
3587     // make the mask and vectors lengths match.
3588 
3589     if (MaskNumElts % SrcNumElts == 0) {
3590       // Mask length is a multiple of the source vector length.
3591       // Check if the shuffle is some kind of concatenation of the input
3592       // vectors.
3593       unsigned NumConcat = MaskNumElts / SrcNumElts;
3594       bool IsConcat = true;
3595       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3596       for (unsigned i = 0; i != MaskNumElts; ++i) {
3597         int Idx = Mask[i];
3598         if (Idx < 0)
3599           continue;
3600         // Ensure the indices in each SrcVT sized piece are sequential and that
3601         // the same source is used for the whole piece.
3602         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3603             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3604              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3605           IsConcat = false;
3606           break;
3607         }
3608         // Remember which source this index came from.
3609         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3610       }
3611 
3612       // The shuffle is concatenating multiple vectors together. Just emit
3613       // a CONCAT_VECTORS operation.
3614       if (IsConcat) {
3615         SmallVector<SDValue, 8> ConcatOps;
3616         for (auto Src : ConcatSrcs) {
3617           if (Src < 0)
3618             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3619           else if (Src == 0)
3620             ConcatOps.push_back(Src1);
3621           else
3622             ConcatOps.push_back(Src2);
3623         }
3624         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3625         return;
3626       }
3627     }
3628 
3629     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3630     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3631     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3632                                     PaddedMaskNumElts);
3633 
3634     // Pad both vectors with undefs to make them the same length as the mask.
3635     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3636 
3637     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3638     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3639     MOps1[0] = Src1;
3640     MOps2[0] = Src2;
3641 
3642     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3643     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3644 
3645     // Readjust mask for new input vector length.
3646     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3647     for (unsigned i = 0; i != MaskNumElts; ++i) {
3648       int Idx = Mask[i];
3649       if (Idx >= (int)SrcNumElts)
3650         Idx -= SrcNumElts - PaddedMaskNumElts;
3651       MappedOps[i] = Idx;
3652     }
3653 
3654     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3655 
3656     // If the concatenated vector was padded, extract a subvector with the
3657     // correct number of elements.
3658     if (MaskNumElts != PaddedMaskNumElts)
3659       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3660                            DAG.getVectorIdxConstant(0, DL));
3661 
3662     setValue(&I, Result);
3663     return;
3664   }
3665 
3666   if (SrcNumElts > MaskNumElts) {
3667     // Analyze the access pattern of the vector to see if we can extract
3668     // two subvectors and do the shuffle.
3669     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3670     bool CanExtract = true;
3671     for (int Idx : Mask) {
3672       unsigned Input = 0;
3673       if (Idx < 0)
3674         continue;
3675 
3676       if (Idx >= (int)SrcNumElts) {
3677         Input = 1;
3678         Idx -= SrcNumElts;
3679       }
3680 
3681       // If all the indices come from the same MaskNumElts sized portion of
3682       // the sources we can use extract. Also make sure the extract wouldn't
3683       // extract past the end of the source.
3684       int NewStartIdx = alignDown(Idx, MaskNumElts);
3685       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3686           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3687         CanExtract = false;
3688       // Make sure we always update StartIdx as we use it to track if all
3689       // elements are undef.
3690       StartIdx[Input] = NewStartIdx;
3691     }
3692 
3693     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3694       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3695       return;
3696     }
3697     if (CanExtract) {
3698       // Extract appropriate subvector and generate a vector shuffle
3699       for (unsigned Input = 0; Input < 2; ++Input) {
3700         SDValue &Src = Input == 0 ? Src1 : Src2;
3701         if (StartIdx[Input] < 0)
3702           Src = DAG.getUNDEF(VT);
3703         else {
3704           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3705                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3706         }
3707       }
3708 
3709       // Calculate new mask.
3710       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3711       for (int &Idx : MappedOps) {
3712         if (Idx >= (int)SrcNumElts)
3713           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3714         else if (Idx >= 0)
3715           Idx -= StartIdx[0];
3716       }
3717 
3718       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3719       return;
3720     }
3721   }
3722 
3723   // We can't use either concat vectors or extract subvectors so fall back to
3724   // replacing the shuffle with extract and build vector.
3725   // to insert and build vector.
3726   EVT EltVT = VT.getVectorElementType();
3727   SmallVector<SDValue,8> Ops;
3728   for (int Idx : Mask) {
3729     SDValue Res;
3730 
3731     if (Idx < 0) {
3732       Res = DAG.getUNDEF(EltVT);
3733     } else {
3734       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3735       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3736 
3737       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3738                         DAG.getVectorIdxConstant(Idx, DL));
3739     }
3740 
3741     Ops.push_back(Res);
3742   }
3743 
3744   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3745 }
3746 
3747 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3748   ArrayRef<unsigned> Indices;
3749   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3750     Indices = IV->getIndices();
3751   else
3752     Indices = cast<ConstantExpr>(&I)->getIndices();
3753 
3754   const Value *Op0 = I.getOperand(0);
3755   const Value *Op1 = I.getOperand(1);
3756   Type *AggTy = I.getType();
3757   Type *ValTy = Op1->getType();
3758   bool IntoUndef = isa<UndefValue>(Op0);
3759   bool FromUndef = isa<UndefValue>(Op1);
3760 
3761   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3762 
3763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3764   SmallVector<EVT, 4> AggValueVTs;
3765   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3766   SmallVector<EVT, 4> ValValueVTs;
3767   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3768 
3769   unsigned NumAggValues = AggValueVTs.size();
3770   unsigned NumValValues = ValValueVTs.size();
3771   SmallVector<SDValue, 4> Values(NumAggValues);
3772 
3773   // Ignore an insertvalue that produces an empty object
3774   if (!NumAggValues) {
3775     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3776     return;
3777   }
3778 
3779   SDValue Agg = getValue(Op0);
3780   unsigned i = 0;
3781   // Copy the beginning value(s) from the original aggregate.
3782   for (; i != LinearIndex; ++i)
3783     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3784                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3785   // Copy values from the inserted value(s).
3786   if (NumValValues) {
3787     SDValue Val = getValue(Op1);
3788     for (; i != LinearIndex + NumValValues; ++i)
3789       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3790                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3791   }
3792   // Copy remaining value(s) from the original aggregate.
3793   for (; i != NumAggValues; ++i)
3794     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3795                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3796 
3797   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3798                            DAG.getVTList(AggValueVTs), Values));
3799 }
3800 
3801 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3802   ArrayRef<unsigned> Indices;
3803   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3804     Indices = EV->getIndices();
3805   else
3806     Indices = cast<ConstantExpr>(&I)->getIndices();
3807 
3808   const Value *Op0 = I.getOperand(0);
3809   Type *AggTy = Op0->getType();
3810   Type *ValTy = I.getType();
3811   bool OutOfUndef = isa<UndefValue>(Op0);
3812 
3813   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3814 
3815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3816   SmallVector<EVT, 4> ValValueVTs;
3817   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3818 
3819   unsigned NumValValues = ValValueVTs.size();
3820 
3821   // Ignore a extractvalue that produces an empty object
3822   if (!NumValValues) {
3823     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3824     return;
3825   }
3826 
3827   SmallVector<SDValue, 4> Values(NumValValues);
3828 
3829   SDValue Agg = getValue(Op0);
3830   // Copy out the selected value(s).
3831   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3832     Values[i - LinearIndex] =
3833       OutOfUndef ?
3834         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3835         SDValue(Agg.getNode(), Agg.getResNo() + i);
3836 
3837   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3838                            DAG.getVTList(ValValueVTs), Values));
3839 }
3840 
3841 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3842   Value *Op0 = I.getOperand(0);
3843   // Note that the pointer operand may be a vector of pointers. Take the scalar
3844   // element which holds a pointer.
3845   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3846   SDValue N = getValue(Op0);
3847   SDLoc dl = getCurSDLoc();
3848   auto &TLI = DAG.getTargetLoweringInfo();
3849 
3850   // Normalize Vector GEP - all scalar operands should be converted to the
3851   // splat vector.
3852   bool IsVectorGEP = I.getType()->isVectorTy();
3853   ElementCount VectorElementCount =
3854       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3855                   : ElementCount::getFixed(0);
3856 
3857   if (IsVectorGEP && !N.getValueType().isVector()) {
3858     LLVMContext &Context = *DAG.getContext();
3859     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3860     if (VectorElementCount.isScalable())
3861       N = DAG.getSplatVector(VT, dl, N);
3862     else
3863       N = DAG.getSplatBuildVector(VT, dl, N);
3864   }
3865 
3866   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3867        GTI != E; ++GTI) {
3868     const Value *Idx = GTI.getOperand();
3869     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3870       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3871       if (Field) {
3872         // N = N + Offset
3873         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3874 
3875         // In an inbounds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3882                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3883       }
3884     } else {
3885       // IdxSize is the width of the arithmetic according to IR semantics.
3886       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3887       // (and fix up the result later).
3888       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3889       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3890       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3891       // We intentionally mask away the high bits here; ElementSize may not
3892       // fit in IdxTy.
3893       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3894       bool ElementScalable = ElementSize.isScalable();
3895 
3896       // If this is a scalar constant or a splat vector of constants,
3897       // handle it quickly.
3898       const auto *C = dyn_cast<Constant>(Idx);
3899       if (C && isa<VectorType>(C->getType()))
3900         C = C->getSplatValue();
3901 
3902       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3903       if (CI && CI->isZero())
3904         continue;
3905       if (CI && !ElementScalable) {
3906         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3907         LLVMContext &Context = *DAG.getContext();
3908         SDValue OffsVal;
3909         if (IsVectorGEP)
3910           OffsVal = DAG.getConstant(
3911               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3912         else
3913           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3914 
3915         // In an inbounds GEP with an offset that is nonnegative even when
3916         // interpreted as signed, assume there is no unsigned overflow.
3917         SDNodeFlags Flags;
3918         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3919           Flags.setNoUnsignedWrap(true);
3920 
3921         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3922 
3923         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3924         continue;
3925       }
3926 
3927       // N = N + Idx * ElementMul;
3928       SDValue IdxN = getValue(Idx);
3929 
3930       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3931         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3932                                   VectorElementCount);
3933         if (VectorElementCount.isScalable())
3934           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3935         else
3936           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3937       }
3938 
3939       // If the index is smaller or larger than intptr_t, truncate or extend
3940       // it.
3941       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3942 
3943       if (ElementScalable) {
3944         EVT VScaleTy = N.getValueType().getScalarType();
3945         SDValue VScale = DAG.getNode(
3946             ISD::VSCALE, dl, VScaleTy,
3947             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3948         if (IsVectorGEP)
3949           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3950         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3951       } else {
3952         // If this is a multiply by a power of two, turn it into a shl
3953         // immediately.  This is a very common case.
3954         if (ElementMul != 1) {
3955           if (ElementMul.isPowerOf2()) {
3956             unsigned Amt = ElementMul.logBase2();
3957             IdxN = DAG.getNode(ISD::SHL, dl,
3958                                N.getValueType(), IdxN,
3959                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3960           } else {
3961             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3962                                             IdxN.getValueType());
3963             IdxN = DAG.getNode(ISD::MUL, dl,
3964                                N.getValueType(), IdxN, Scale);
3965           }
3966         }
3967       }
3968 
3969       N = DAG.getNode(ISD::ADD, dl,
3970                       N.getValueType(), N, IdxN);
3971     }
3972   }
3973 
3974   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3975   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3976   if (IsVectorGEP) {
3977     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3978     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3979   }
3980 
3981   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3982     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3983 
3984   setValue(&I, N);
3985 }
3986 
3987 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3988   // If this is a fixed sized alloca in the entry block of the function,
3989   // allocate it statically on the stack.
3990   if (FuncInfo.StaticAllocaMap.count(&I))
3991     return;   // getValue will auto-populate this.
3992 
3993   SDLoc dl = getCurSDLoc();
3994   Type *Ty = I.getAllocatedType();
3995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3996   auto &DL = DAG.getDataLayout();
3997   uint64_t TySize = DL.getTypeAllocSize(Ty);
3998   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3999 
4000   SDValue AllocSize = getValue(I.getArraySize());
4001 
4002   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4003   if (AllocSize.getValueType() != IntPtr)
4004     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4005 
4006   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4007                           AllocSize,
4008                           DAG.getConstant(TySize, dl, IntPtr));
4009 
4010   // Handle alignment.  If the requested alignment is less than or equal to
4011   // the stack alignment, ignore it.  If the size is greater than or equal to
4012   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4013   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4014   if (*Alignment <= StackAlign)
4015     Alignment = None;
4016 
4017   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4018   // Round the size of the allocation up to the stack alignment size
4019   // by add SA-1 to the size. This doesn't overflow because we're computing
4020   // an address inside an alloca.
4021   SDNodeFlags Flags;
4022   Flags.setNoUnsignedWrap(true);
4023   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4024                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4025 
4026   // Mask out the low bits for alignment purposes.
4027   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4028                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4029 
4030   SDValue Ops[] = {
4031       getRoot(), AllocSize,
4032       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4033   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4034   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4035   setValue(&I, DSA);
4036   DAG.setRoot(DSA.getValue(1));
4037 
4038   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4039 }
4040 
4041 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4042   if (I.isAtomic())
4043     return visitAtomicLoad(I);
4044 
4045   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4046   const Value *SV = I.getOperand(0);
4047   if (TLI.supportSwiftError()) {
4048     // Swifterror values can come from either a function parameter with
4049     // swifterror attribute or an alloca with swifterror attribute.
4050     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4051       if (Arg->hasSwiftErrorAttr())
4052         return visitLoadFromSwiftError(I);
4053     }
4054 
4055     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4056       if (Alloca->isSwiftError())
4057         return visitLoadFromSwiftError(I);
4058     }
4059   }
4060 
4061   SDValue Ptr = getValue(SV);
4062 
4063   Type *Ty = I.getType();
4064   Align Alignment = I.getAlign();
4065 
4066   AAMDNodes AAInfo = I.getAAMetadata();
4067   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4068 
4069   SmallVector<EVT, 4> ValueVTs, MemVTs;
4070   SmallVector<uint64_t, 4> Offsets;
4071   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4072   unsigned NumValues = ValueVTs.size();
4073   if (NumValues == 0)
4074     return;
4075 
4076   bool isVolatile = I.isVolatile();
4077 
4078   SDValue Root;
4079   bool ConstantMemory = false;
4080   if (isVolatile)
4081     // Serialize volatile loads with other side effects.
4082     Root = getRoot();
4083   else if (NumValues > MaxParallelChains)
4084     Root = getMemoryRoot();
4085   else if (AA &&
4086            AA->pointsToConstantMemory(MemoryLocation(
4087                SV,
4088                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4089                AAInfo))) {
4090     // Do not serialize (non-volatile) loads of constant memory with anything.
4091     Root = DAG.getEntryNode();
4092     ConstantMemory = true;
4093   } else {
4094     // Do not serialize non-volatile loads against each other.
4095     Root = DAG.getRoot();
4096   }
4097 
4098   SDLoc dl = getCurSDLoc();
4099 
4100   if (isVolatile)
4101     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4102 
4103   // An aggregate load cannot wrap around the address space, so offsets to its
4104   // parts don't wrap either.
4105   SDNodeFlags Flags;
4106   Flags.setNoUnsignedWrap(true);
4107 
4108   SmallVector<SDValue, 4> Values(NumValues);
4109   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4110   EVT PtrVT = Ptr.getValueType();
4111 
4112   MachineMemOperand::Flags MMOFlags
4113     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4114 
4115   unsigned ChainI = 0;
4116   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4117     // Serializing loads here may result in excessive register pressure, and
4118     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4119     // could recover a bit by hoisting nodes upward in the chain by recognizing
4120     // they are side-effect free or do not alias. The optimizer should really
4121     // avoid this case by converting large object/array copies to llvm.memcpy
4122     // (MaxParallelChains should always remain as failsafe).
4123     if (ChainI == MaxParallelChains) {
4124       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4125       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4126                                   makeArrayRef(Chains.data(), ChainI));
4127       Root = Chain;
4128       ChainI = 0;
4129     }
4130     SDValue A = DAG.getNode(ISD::ADD, dl,
4131                             PtrVT, Ptr,
4132                             DAG.getConstant(Offsets[i], dl, PtrVT),
4133                             Flags);
4134 
4135     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4136                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4137                             MMOFlags, AAInfo, Ranges);
4138     Chains[ChainI] = L.getValue(1);
4139 
4140     if (MemVTs[i] != ValueVTs[i])
4141       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4142 
4143     Values[i] = L;
4144   }
4145 
4146   if (!ConstantMemory) {
4147     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4148                                 makeArrayRef(Chains.data(), ChainI));
4149     if (isVolatile)
4150       DAG.setRoot(Chain);
4151     else
4152       PendingLoads.push_back(Chain);
4153   }
4154 
4155   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4156                            DAG.getVTList(ValueVTs), Values));
4157 }
4158 
4159 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4160   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4161          "call visitStoreToSwiftError when backend supports swifterror");
4162 
4163   SmallVector<EVT, 4> ValueVTs;
4164   SmallVector<uint64_t, 4> Offsets;
4165   const Value *SrcV = I.getOperand(0);
4166   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4167                   SrcV->getType(), ValueVTs, &Offsets);
4168   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4169          "expect a single EVT for swifterror");
4170 
4171   SDValue Src = getValue(SrcV);
4172   // Create a virtual register, then update the virtual register.
4173   Register VReg =
4174       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4175   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4176   // Chain can be getRoot or getControlRoot.
4177   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4178                                       SDValue(Src.getNode(), Src.getResNo()));
4179   DAG.setRoot(CopyNode);
4180 }
4181 
4182 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4183   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4184          "call visitLoadFromSwiftError when backend supports swifterror");
4185 
4186   assert(!I.isVolatile() &&
4187          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4188          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4189          "Support volatile, non temporal, invariant for load_from_swift_error");
4190 
4191   const Value *SV = I.getOperand(0);
4192   Type *Ty = I.getType();
4193   assert(
4194       (!AA ||
4195        !AA->pointsToConstantMemory(MemoryLocation(
4196            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4197            I.getAAMetadata()))) &&
4198       "load_from_swift_error should not be constant memory");
4199 
4200   SmallVector<EVT, 4> ValueVTs;
4201   SmallVector<uint64_t, 4> Offsets;
4202   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4203                   ValueVTs, &Offsets);
4204   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4205          "expect a single EVT for swifterror");
4206 
4207   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4208   SDValue L = DAG.getCopyFromReg(
4209       getRoot(), getCurSDLoc(),
4210       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4211 
4212   setValue(&I, L);
4213 }
4214 
4215 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4216   if (I.isAtomic())
4217     return visitAtomicStore(I);
4218 
4219   const Value *SrcV = I.getOperand(0);
4220   const Value *PtrV = I.getOperand(1);
4221 
4222   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4223   if (TLI.supportSwiftError()) {
4224     // Swifterror values can come from either a function parameter with
4225     // swifterror attribute or an alloca with swifterror attribute.
4226     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4227       if (Arg->hasSwiftErrorAttr())
4228         return visitStoreToSwiftError(I);
4229     }
4230 
4231     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4232       if (Alloca->isSwiftError())
4233         return visitStoreToSwiftError(I);
4234     }
4235   }
4236 
4237   SmallVector<EVT, 4> ValueVTs, MemVTs;
4238   SmallVector<uint64_t, 4> Offsets;
4239   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4240                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4241   unsigned NumValues = ValueVTs.size();
4242   if (NumValues == 0)
4243     return;
4244 
4245   // Get the lowered operands. Note that we do this after
4246   // checking if NumResults is zero, because with zero results
4247   // the operands won't have values in the map.
4248   SDValue Src = getValue(SrcV);
4249   SDValue Ptr = getValue(PtrV);
4250 
4251   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4252   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4253   SDLoc dl = getCurSDLoc();
4254   Align Alignment = I.getAlign();
4255   AAMDNodes AAInfo = I.getAAMetadata();
4256 
4257   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4258 
4259   // An aggregate load cannot wrap around the address space, so offsets to its
4260   // parts don't wrap either.
4261   SDNodeFlags Flags;
4262   Flags.setNoUnsignedWrap(true);
4263 
4264   unsigned ChainI = 0;
4265   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4266     // See visitLoad comments.
4267     if (ChainI == MaxParallelChains) {
4268       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4269                                   makeArrayRef(Chains.data(), ChainI));
4270       Root = Chain;
4271       ChainI = 0;
4272     }
4273     SDValue Add =
4274         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4275     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4276     if (MemVTs[i] != ValueVTs[i])
4277       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4278     SDValue St =
4279         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4280                      Alignment, MMOFlags, AAInfo);
4281     Chains[ChainI] = St;
4282   }
4283 
4284   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4285                                   makeArrayRef(Chains.data(), ChainI));
4286   DAG.setRoot(StoreNode);
4287 }
4288 
4289 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4290                                            bool IsCompressing) {
4291   SDLoc sdl = getCurSDLoc();
4292 
4293   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4294                                MaybeAlign &Alignment) {
4295     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4296     Src0 = I.getArgOperand(0);
4297     Ptr = I.getArgOperand(1);
4298     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4299     Mask = I.getArgOperand(3);
4300   };
4301   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4302                                     MaybeAlign &Alignment) {
4303     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4304     Src0 = I.getArgOperand(0);
4305     Ptr = I.getArgOperand(1);
4306     Mask = I.getArgOperand(2);
4307     Alignment = None;
4308   };
4309 
4310   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4311   MaybeAlign Alignment;
4312   if (IsCompressing)
4313     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4314   else
4315     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4316 
4317   SDValue Ptr = getValue(PtrOperand);
4318   SDValue Src0 = getValue(Src0Operand);
4319   SDValue Mask = getValue(MaskOperand);
4320   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4321 
4322   EVT VT = Src0.getValueType();
4323   if (!Alignment)
4324     Alignment = DAG.getEVTAlign(VT);
4325 
4326   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4327       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4328       // TODO: Make MachineMemOperands aware of scalable
4329       // vectors.
4330       VT.getStoreSize().getKnownMinSize(), *Alignment, I.getAAMetadata());
4331   SDValue StoreNode =
4332       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4333                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4334   DAG.setRoot(StoreNode);
4335   setValue(&I, StoreNode);
4336 }
4337 
4338 // Get a uniform base for the Gather/Scatter intrinsic.
4339 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4340 // We try to represent it as a base pointer + vector of indices.
4341 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4342 // The first operand of the GEP may be a single pointer or a vector of pointers
4343 // Example:
4344 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4345 //  or
4346 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4347 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4348 //
4349 // When the first GEP operand is a single pointer - it is the uniform base we
4350 // are looking for. If first operand of the GEP is a splat vector - we
4351 // extract the splat value and use it as a uniform base.
4352 // In all other cases the function returns 'false'.
4353 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4354                            ISD::MemIndexType &IndexType, SDValue &Scale,
4355                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4356   SelectionDAG& DAG = SDB->DAG;
4357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4358   const DataLayout &DL = DAG.getDataLayout();
4359 
4360   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4361 
4362   // Handle splat constant pointer.
4363   if (auto *C = dyn_cast<Constant>(Ptr)) {
4364     C = C->getSplatValue();
4365     if (!C)
4366       return false;
4367 
4368     Base = SDB->getValue(C);
4369 
4370     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4371     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4372     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4373     IndexType = ISD::SIGNED_SCALED;
4374     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4375     return true;
4376   }
4377 
4378   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4379   if (!GEP || GEP->getParent() != CurBB)
4380     return false;
4381 
4382   if (GEP->getNumOperands() != 2)
4383     return false;
4384 
4385   const Value *BasePtr = GEP->getPointerOperand();
4386   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4387 
4388   // Make sure the base is scalar and the index is a vector.
4389   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4390     return false;
4391 
4392   Base = SDB->getValue(BasePtr);
4393   Index = SDB->getValue(IndexVal);
4394   IndexType = ISD::SIGNED_SCALED;
4395   Scale = DAG.getTargetConstant(
4396               DL.getTypeAllocSize(GEP->getResultElementType()),
4397               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4398   return true;
4399 }
4400 
4401 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4402   SDLoc sdl = getCurSDLoc();
4403 
4404   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4405   const Value *Ptr = I.getArgOperand(1);
4406   SDValue Src0 = getValue(I.getArgOperand(0));
4407   SDValue Mask = getValue(I.getArgOperand(3));
4408   EVT VT = Src0.getValueType();
4409   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4410                         ->getMaybeAlignValue()
4411                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4413 
4414   SDValue Base;
4415   SDValue Index;
4416   ISD::MemIndexType IndexType;
4417   SDValue Scale;
4418   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4419                                     I.getParent());
4420 
4421   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4422   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4423       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4424       // TODO: Make MachineMemOperands aware of scalable
4425       // vectors.
4426       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4427   if (!UniformBase) {
4428     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4429     Index = getValue(Ptr);
4430     IndexType = ISD::SIGNED_UNSCALED;
4431     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4432   }
4433 
4434   EVT IdxVT = Index.getValueType();
4435   EVT EltTy = IdxVT.getVectorElementType();
4436   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4437     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4438     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4439   }
4440 
4441   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4442   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4443                                          Ops, MMO, IndexType, false);
4444   DAG.setRoot(Scatter);
4445   setValue(&I, Scatter);
4446 }
4447 
4448 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4449   SDLoc sdl = getCurSDLoc();
4450 
4451   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4452                               MaybeAlign &Alignment) {
4453     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4454     Ptr = I.getArgOperand(0);
4455     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4456     Mask = I.getArgOperand(2);
4457     Src0 = I.getArgOperand(3);
4458   };
4459   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4460                                  MaybeAlign &Alignment) {
4461     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4462     Ptr = I.getArgOperand(0);
4463     Alignment = None;
4464     Mask = I.getArgOperand(1);
4465     Src0 = I.getArgOperand(2);
4466   };
4467 
4468   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4469   MaybeAlign Alignment;
4470   if (IsExpanding)
4471     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4472   else
4473     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4474 
4475   SDValue Ptr = getValue(PtrOperand);
4476   SDValue Src0 = getValue(Src0Operand);
4477   SDValue Mask = getValue(MaskOperand);
4478   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4479 
4480   EVT VT = Src0.getValueType();
4481   if (!Alignment)
4482     Alignment = DAG.getEVTAlign(VT);
4483 
4484   AAMDNodes AAInfo = I.getAAMetadata();
4485   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4486 
4487   // Do not serialize masked loads of constant memory with anything.
4488   MemoryLocation ML;
4489   if (VT.isScalableVector())
4490     ML = MemoryLocation::getAfter(PtrOperand);
4491   else
4492     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4493                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4494                            AAInfo);
4495   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4496 
4497   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4498 
4499   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4500       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4501       // TODO: Make MachineMemOperands aware of scalable
4502       // vectors.
4503       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4504 
4505   SDValue Load =
4506       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4507                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4508   if (AddToChain)
4509     PendingLoads.push_back(Load.getValue(1));
4510   setValue(&I, Load);
4511 }
4512 
4513 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4514   SDLoc sdl = getCurSDLoc();
4515 
4516   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4517   const Value *Ptr = I.getArgOperand(0);
4518   SDValue Src0 = getValue(I.getArgOperand(3));
4519   SDValue Mask = getValue(I.getArgOperand(2));
4520 
4521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4522   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4523   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4524                         ->getMaybeAlignValue()
4525                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4526 
4527   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4528 
4529   SDValue Root = DAG.getRoot();
4530   SDValue Base;
4531   SDValue Index;
4532   ISD::MemIndexType IndexType;
4533   SDValue Scale;
4534   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4535                                     I.getParent());
4536   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4537   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4538       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4539       // TODO: Make MachineMemOperands aware of scalable
4540       // vectors.
4541       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4542 
4543   if (!UniformBase) {
4544     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4545     Index = getValue(Ptr);
4546     IndexType = ISD::SIGNED_UNSCALED;
4547     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4548   }
4549 
4550   EVT IdxVT = Index.getValueType();
4551   EVT EltTy = IdxVT.getVectorElementType();
4552   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4553     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4554     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4555   }
4556 
4557   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4558   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4559                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4560 
4561   PendingLoads.push_back(Gather.getValue(1));
4562   setValue(&I, Gather);
4563 }
4564 
4565 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4566   SDLoc dl = getCurSDLoc();
4567   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4568   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4569   SyncScope::ID SSID = I.getSyncScopeID();
4570 
4571   SDValue InChain = getRoot();
4572 
4573   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4574   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4575 
4576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4577   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4578 
4579   MachineFunction &MF = DAG.getMachineFunction();
4580   MachineMemOperand *MMO = MF.getMachineMemOperand(
4581       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4582       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4583       FailureOrdering);
4584 
4585   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4586                                    dl, MemVT, VTs, InChain,
4587                                    getValue(I.getPointerOperand()),
4588                                    getValue(I.getCompareOperand()),
4589                                    getValue(I.getNewValOperand()), MMO);
4590 
4591   SDValue OutChain = L.getValue(2);
4592 
4593   setValue(&I, L);
4594   DAG.setRoot(OutChain);
4595 }
4596 
4597 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4598   SDLoc dl = getCurSDLoc();
4599   ISD::NodeType NT;
4600   switch (I.getOperation()) {
4601   default: llvm_unreachable("Unknown atomicrmw operation");
4602   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4603   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4604   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4605   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4606   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4607   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4608   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4609   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4610   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4611   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4612   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4613   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4614   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4615   }
4616   AtomicOrdering Ordering = I.getOrdering();
4617   SyncScope::ID SSID = I.getSyncScopeID();
4618 
4619   SDValue InChain = getRoot();
4620 
4621   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4623   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4624 
4625   MachineFunction &MF = DAG.getMachineFunction();
4626   MachineMemOperand *MMO = MF.getMachineMemOperand(
4627       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4628       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4629 
4630   SDValue L =
4631     DAG.getAtomic(NT, dl, MemVT, InChain,
4632                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4633                   MMO);
4634 
4635   SDValue OutChain = L.getValue(1);
4636 
4637   setValue(&I, L);
4638   DAG.setRoot(OutChain);
4639 }
4640 
4641 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4642   SDLoc dl = getCurSDLoc();
4643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4644   SDValue Ops[3];
4645   Ops[0] = getRoot();
4646   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4647                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4648   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4649                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4650   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4651 }
4652 
4653 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4654   SDLoc dl = getCurSDLoc();
4655   AtomicOrdering Order = I.getOrdering();
4656   SyncScope::ID SSID = I.getSyncScopeID();
4657 
4658   SDValue InChain = getRoot();
4659 
4660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4661   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4662   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4663 
4664   if (!TLI.supportsUnalignedAtomics() &&
4665       I.getAlignment() < MemVT.getSizeInBits() / 8)
4666     report_fatal_error("Cannot generate unaligned atomic load");
4667 
4668   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4669 
4670   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4671       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4672       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4673 
4674   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4675 
4676   SDValue Ptr = getValue(I.getPointerOperand());
4677 
4678   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4679     // TODO: Once this is better exercised by tests, it should be merged with
4680     // the normal path for loads to prevent future divergence.
4681     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4682     if (MemVT != VT)
4683       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4684 
4685     setValue(&I, L);
4686     SDValue OutChain = L.getValue(1);
4687     if (!I.isUnordered())
4688       DAG.setRoot(OutChain);
4689     else
4690       PendingLoads.push_back(OutChain);
4691     return;
4692   }
4693 
4694   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4695                             Ptr, MMO);
4696 
4697   SDValue OutChain = L.getValue(1);
4698   if (MemVT != VT)
4699     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4700 
4701   setValue(&I, L);
4702   DAG.setRoot(OutChain);
4703 }
4704 
4705 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4706   SDLoc dl = getCurSDLoc();
4707 
4708   AtomicOrdering Ordering = I.getOrdering();
4709   SyncScope::ID SSID = I.getSyncScopeID();
4710 
4711   SDValue InChain = getRoot();
4712 
4713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4714   EVT MemVT =
4715       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4716 
4717   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4718     report_fatal_error("Cannot generate unaligned atomic store");
4719 
4720   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4721 
4722   MachineFunction &MF = DAG.getMachineFunction();
4723   MachineMemOperand *MMO = MF.getMachineMemOperand(
4724       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4725       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4726 
4727   SDValue Val = getValue(I.getValueOperand());
4728   if (Val.getValueType() != MemVT)
4729     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4730   SDValue Ptr = getValue(I.getPointerOperand());
4731 
4732   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4733     // TODO: Once this is better exercised by tests, it should be merged with
4734     // the normal path for stores to prevent future divergence.
4735     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4736     DAG.setRoot(S);
4737     return;
4738   }
4739   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4740                                    Ptr, Val, MMO);
4741 
4742 
4743   DAG.setRoot(OutChain);
4744 }
4745 
4746 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4747 /// node.
4748 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4749                                                unsigned Intrinsic) {
4750   // Ignore the callsite's attributes. A specific call site may be marked with
4751   // readnone, but the lowering code will expect the chain based on the
4752   // definition.
4753   const Function *F = I.getCalledFunction();
4754   bool HasChain = !F->doesNotAccessMemory();
4755   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4756 
4757   // Build the operand list.
4758   SmallVector<SDValue, 8> Ops;
4759   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4760     if (OnlyLoad) {
4761       // We don't need to serialize loads against other loads.
4762       Ops.push_back(DAG.getRoot());
4763     } else {
4764       Ops.push_back(getRoot());
4765     }
4766   }
4767 
4768   // Info is set by getTgtMemInstrinsic
4769   TargetLowering::IntrinsicInfo Info;
4770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4771   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4772                                                DAG.getMachineFunction(),
4773                                                Intrinsic);
4774 
4775   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4776   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4777       Info.opc == ISD::INTRINSIC_W_CHAIN)
4778     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4779                                         TLI.getPointerTy(DAG.getDataLayout())));
4780 
4781   // Add all operands of the call to the operand list.
4782   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4783     const Value *Arg = I.getArgOperand(i);
4784     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4785       Ops.push_back(getValue(Arg));
4786       continue;
4787     }
4788 
4789     // Use TargetConstant instead of a regular constant for immarg.
4790     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4791     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4792       assert(CI->getBitWidth() <= 64 &&
4793              "large intrinsic immediates not handled");
4794       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4795     } else {
4796       Ops.push_back(
4797           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4798     }
4799   }
4800 
4801   SmallVector<EVT, 4> ValueVTs;
4802   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4803 
4804   if (HasChain)
4805     ValueVTs.push_back(MVT::Other);
4806 
4807   SDVTList VTs = DAG.getVTList(ValueVTs);
4808 
4809   // Propagate fast-math-flags from IR to node(s).
4810   SDNodeFlags Flags;
4811   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4812     Flags.copyFMF(*FPMO);
4813   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4814 
4815   // Create the node.
4816   SDValue Result;
4817   if (IsTgtIntrinsic) {
4818     // This is target intrinsic that touches memory
4819     Result =
4820         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4821                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4822                                 Info.align, Info.flags, Info.size,
4823                                 I.getAAMetadata());
4824   } else if (!HasChain) {
4825     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4826   } else if (!I.getType()->isVoidTy()) {
4827     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4828   } else {
4829     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4830   }
4831 
4832   if (HasChain) {
4833     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4834     if (OnlyLoad)
4835       PendingLoads.push_back(Chain);
4836     else
4837       DAG.setRoot(Chain);
4838   }
4839 
4840   if (!I.getType()->isVoidTy()) {
4841     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4842       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4843       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4844     } else
4845       Result = lowerRangeToAssertZExt(DAG, I, Result);
4846 
4847     MaybeAlign Alignment = I.getRetAlign();
4848     if (!Alignment)
4849       Alignment = F->getAttributes().getRetAlignment();
4850     // Insert `assertalign` node if there's an alignment.
4851     if (InsertAssertAlign && Alignment) {
4852       Result =
4853           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4854     }
4855 
4856     setValue(&I, Result);
4857   }
4858 }
4859 
4860 /// GetSignificand - Get the significand and build it into a floating-point
4861 /// number with exponent of 1:
4862 ///
4863 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4864 ///
4865 /// where Op is the hexadecimal representation of floating point value.
4866 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4867   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4868                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4869   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4870                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4871   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4872 }
4873 
4874 /// GetExponent - Get the exponent:
4875 ///
4876 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4877 ///
4878 /// where Op is the hexadecimal representation of floating point value.
4879 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4880                            const TargetLowering &TLI, const SDLoc &dl) {
4881   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4882                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4883   SDValue t1 = DAG.getNode(
4884       ISD::SRL, dl, MVT::i32, t0,
4885       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4886   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4887                            DAG.getConstant(127, dl, MVT::i32));
4888   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4889 }
4890 
4891 /// getF32Constant - Get 32-bit floating point constant.
4892 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4893                               const SDLoc &dl) {
4894   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4895                            MVT::f32);
4896 }
4897 
4898 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4899                                        SelectionDAG &DAG) {
4900   // TODO: What fast-math-flags should be set on the floating-point nodes?
4901 
4902   //   IntegerPartOfX = ((int32_t)(t0);
4903   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4904 
4905   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4906   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4907   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4908 
4909   //   IntegerPartOfX <<= 23;
4910   IntegerPartOfX = DAG.getNode(
4911       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4912       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4913                                   DAG.getDataLayout())));
4914 
4915   SDValue TwoToFractionalPartOfX;
4916   if (LimitFloatPrecision <= 6) {
4917     // For floating-point precision of 6:
4918     //
4919     //   TwoToFractionalPartOfX =
4920     //     0.997535578f +
4921     //       (0.735607626f + 0.252464424f * x) * x;
4922     //
4923     // error 0.0144103317, which is 6 bits
4924     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4925                              getF32Constant(DAG, 0x3e814304, dl));
4926     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4927                              getF32Constant(DAG, 0x3f3c50c8, dl));
4928     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4929     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4930                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4931   } else if (LimitFloatPrecision <= 12) {
4932     // For floating-point precision of 12:
4933     //
4934     //   TwoToFractionalPartOfX =
4935     //     0.999892986f +
4936     //       (0.696457318f +
4937     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4938     //
4939     // error 0.000107046256, which is 13 to 14 bits
4940     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4941                              getF32Constant(DAG, 0x3da235e3, dl));
4942     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4943                              getF32Constant(DAG, 0x3e65b8f3, dl));
4944     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4945     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4946                              getF32Constant(DAG, 0x3f324b07, dl));
4947     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4948     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4949                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4950   } else { // LimitFloatPrecision <= 18
4951     // For floating-point precision of 18:
4952     //
4953     //   TwoToFractionalPartOfX =
4954     //     0.999999982f +
4955     //       (0.693148872f +
4956     //         (0.240227044f +
4957     //           (0.554906021e-1f +
4958     //             (0.961591928e-2f +
4959     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4960     // error 2.47208000*10^(-7), which is better than 18 bits
4961     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4962                              getF32Constant(DAG, 0x3924b03e, dl));
4963     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4964                              getF32Constant(DAG, 0x3ab24b87, dl));
4965     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4966     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4967                              getF32Constant(DAG, 0x3c1d8c17, dl));
4968     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4969     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4970                              getF32Constant(DAG, 0x3d634a1d, dl));
4971     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4972     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4973                              getF32Constant(DAG, 0x3e75fe14, dl));
4974     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4975     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4976                               getF32Constant(DAG, 0x3f317234, dl));
4977     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4978     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4979                                          getF32Constant(DAG, 0x3f800000, dl));
4980   }
4981 
4982   // Add the exponent into the result in integer domain.
4983   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4984   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4985                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4986 }
4987 
4988 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4989 /// limited-precision mode.
4990 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4991                          const TargetLowering &TLI, SDNodeFlags Flags) {
4992   if (Op.getValueType() == MVT::f32 &&
4993       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4994 
4995     // Put the exponent in the right bit position for later addition to the
4996     // final result:
4997     //
4998     // t0 = Op * log2(e)
4999 
5000     // TODO: What fast-math-flags should be set here?
5001     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5002                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5003     return getLimitedPrecisionExp2(t0, dl, DAG);
5004   }
5005 
5006   // No special expansion.
5007   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5008 }
5009 
5010 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5011 /// limited-precision mode.
5012 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5013                          const TargetLowering &TLI, SDNodeFlags Flags) {
5014   // TODO: What fast-math-flags should be set on the floating-point nodes?
5015 
5016   if (Op.getValueType() == MVT::f32 &&
5017       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5018     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5019 
5020     // Scale the exponent by log(2).
5021     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5022     SDValue LogOfExponent =
5023         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5024                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5025 
5026     // Get the significand and build it into a floating-point number with
5027     // exponent of 1.
5028     SDValue X = GetSignificand(DAG, Op1, dl);
5029 
5030     SDValue LogOfMantissa;
5031     if (LimitFloatPrecision <= 6) {
5032       // For floating-point precision of 6:
5033       //
5034       //   LogofMantissa =
5035       //     -1.1609546f +
5036       //       (1.4034025f - 0.23903021f * x) * x;
5037       //
5038       // error 0.0034276066, which is better than 8 bits
5039       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5040                                getF32Constant(DAG, 0xbe74c456, dl));
5041       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5042                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5043       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5044       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5045                                   getF32Constant(DAG, 0x3f949a29, dl));
5046     } else if (LimitFloatPrecision <= 12) {
5047       // For floating-point precision of 12:
5048       //
5049       //   LogOfMantissa =
5050       //     -1.7417939f +
5051       //       (2.8212026f +
5052       //         (-1.4699568f +
5053       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5054       //
5055       // error 0.000061011436, which is 14 bits
5056       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5057                                getF32Constant(DAG, 0xbd67b6d6, dl));
5058       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5059                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5060       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5061       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5062                                getF32Constant(DAG, 0x3fbc278b, dl));
5063       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5064       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5065                                getF32Constant(DAG, 0x40348e95, dl));
5066       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5067       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5068                                   getF32Constant(DAG, 0x3fdef31a, dl));
5069     } else { // LimitFloatPrecision <= 18
5070       // For floating-point precision of 18:
5071       //
5072       //   LogOfMantissa =
5073       //     -2.1072184f +
5074       //       (4.2372794f +
5075       //         (-3.7029485f +
5076       //           (2.2781945f +
5077       //             (-0.87823314f +
5078       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5079       //
5080       // error 0.0000023660568, which is better than 18 bits
5081       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5082                                getF32Constant(DAG, 0xbc91e5ac, dl));
5083       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5084                                getF32Constant(DAG, 0x3e4350aa, dl));
5085       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5086       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5087                                getF32Constant(DAG, 0x3f60d3e3, dl));
5088       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5089       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5090                                getF32Constant(DAG, 0x4011cdf0, dl));
5091       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5092       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5093                                getF32Constant(DAG, 0x406cfd1c, dl));
5094       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5095       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5096                                getF32Constant(DAG, 0x408797cb, dl));
5097       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5098       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5099                                   getF32Constant(DAG, 0x4006dcab, dl));
5100     }
5101 
5102     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5103   }
5104 
5105   // No special expansion.
5106   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5107 }
5108 
5109 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5110 /// limited-precision mode.
5111 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5112                           const TargetLowering &TLI, SDNodeFlags Flags) {
5113   // TODO: What fast-math-flags should be set on the floating-point nodes?
5114 
5115   if (Op.getValueType() == MVT::f32 &&
5116       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5117     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5118 
5119     // Get the exponent.
5120     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5121 
5122     // Get the significand and build it into a floating-point number with
5123     // exponent of 1.
5124     SDValue X = GetSignificand(DAG, Op1, dl);
5125 
5126     // Different possible minimax approximations of significand in
5127     // floating-point for various degrees of accuracy over [1,2].
5128     SDValue Log2ofMantissa;
5129     if (LimitFloatPrecision <= 6) {
5130       // For floating-point precision of 6:
5131       //
5132       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5133       //
5134       // error 0.0049451742, which is more than 7 bits
5135       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5136                                getF32Constant(DAG, 0xbeb08fe0, dl));
5137       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5138                                getF32Constant(DAG, 0x40019463, dl));
5139       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5140       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5141                                    getF32Constant(DAG, 0x3fd6633d, dl));
5142     } else if (LimitFloatPrecision <= 12) {
5143       // For floating-point precision of 12:
5144       //
5145       //   Log2ofMantissa =
5146       //     -2.51285454f +
5147       //       (4.07009056f +
5148       //         (-2.12067489f +
5149       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5150       //
5151       // error 0.0000876136000, which is better than 13 bits
5152       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5153                                getF32Constant(DAG, 0xbda7262e, dl));
5154       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5155                                getF32Constant(DAG, 0x3f25280b, dl));
5156       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5157       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5158                                getF32Constant(DAG, 0x4007b923, dl));
5159       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5160       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5161                                getF32Constant(DAG, 0x40823e2f, dl));
5162       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5163       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5164                                    getF32Constant(DAG, 0x4020d29c, dl));
5165     } else { // LimitFloatPrecision <= 18
5166       // For floating-point precision of 18:
5167       //
5168       //   Log2ofMantissa =
5169       //     -3.0400495f +
5170       //       (6.1129976f +
5171       //         (-5.3420409f +
5172       //           (3.2865683f +
5173       //             (-1.2669343f +
5174       //               (0.27515199f -
5175       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5176       //
5177       // error 0.0000018516, which is better than 18 bits
5178       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5179                                getF32Constant(DAG, 0xbcd2769e, dl));
5180       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5181                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5182       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5183       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5184                                getF32Constant(DAG, 0x3fa22ae7, dl));
5185       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5186       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5187                                getF32Constant(DAG, 0x40525723, dl));
5188       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5189       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5190                                getF32Constant(DAG, 0x40aaf200, dl));
5191       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5192       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5193                                getF32Constant(DAG, 0x40c39dad, dl));
5194       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5195       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5196                                    getF32Constant(DAG, 0x4042902c, dl));
5197     }
5198 
5199     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5200   }
5201 
5202   // No special expansion.
5203   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5204 }
5205 
5206 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5207 /// limited-precision mode.
5208 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5209                            const TargetLowering &TLI, SDNodeFlags Flags) {
5210   // TODO: What fast-math-flags should be set on the floating-point nodes?
5211 
5212   if (Op.getValueType() == MVT::f32 &&
5213       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5214     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5215 
5216     // Scale the exponent by log10(2) [0.30102999f].
5217     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5218     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5219                                         getF32Constant(DAG, 0x3e9a209a, dl));
5220 
5221     // Get the significand and build it into a floating-point number with
5222     // exponent of 1.
5223     SDValue X = GetSignificand(DAG, Op1, dl);
5224 
5225     SDValue Log10ofMantissa;
5226     if (LimitFloatPrecision <= 6) {
5227       // For floating-point precision of 6:
5228       //
5229       //   Log10ofMantissa =
5230       //     -0.50419619f +
5231       //       (0.60948995f - 0.10380950f * x) * x;
5232       //
5233       // error 0.0014886165, which is 6 bits
5234       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5235                                getF32Constant(DAG, 0xbdd49a13, dl));
5236       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5237                                getF32Constant(DAG, 0x3f1c0789, dl));
5238       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5239       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5240                                     getF32Constant(DAG, 0x3f011300, dl));
5241     } else if (LimitFloatPrecision <= 12) {
5242       // For floating-point precision of 12:
5243       //
5244       //   Log10ofMantissa =
5245       //     -0.64831180f +
5246       //       (0.91751397f +
5247       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5248       //
5249       // error 0.00019228036, which is better than 12 bits
5250       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5251                                getF32Constant(DAG, 0x3d431f31, dl));
5252       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5253                                getF32Constant(DAG, 0x3ea21fb2, dl));
5254       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5255       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5256                                getF32Constant(DAG, 0x3f6ae232, dl));
5257       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5258       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5259                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5260     } else { // LimitFloatPrecision <= 18
5261       // For floating-point precision of 18:
5262       //
5263       //   Log10ofMantissa =
5264       //     -0.84299375f +
5265       //       (1.5327582f +
5266       //         (-1.0688956f +
5267       //           (0.49102474f +
5268       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5269       //
5270       // error 0.0000037995730, which is better than 18 bits
5271       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5272                                getF32Constant(DAG, 0x3c5d51ce, dl));
5273       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5274                                getF32Constant(DAG, 0x3e00685a, dl));
5275       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5276       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5277                                getF32Constant(DAG, 0x3efb6798, dl));
5278       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5279       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5280                                getF32Constant(DAG, 0x3f88d192, dl));
5281       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5282       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5283                                getF32Constant(DAG, 0x3fc4316c, dl));
5284       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5285       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5286                                     getF32Constant(DAG, 0x3f57ce70, dl));
5287     }
5288 
5289     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5290   }
5291 
5292   // No special expansion.
5293   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5294 }
5295 
5296 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5297 /// limited-precision mode.
5298 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5299                           const TargetLowering &TLI, SDNodeFlags Flags) {
5300   if (Op.getValueType() == MVT::f32 &&
5301       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5302     return getLimitedPrecisionExp2(Op, dl, DAG);
5303 
5304   // No special expansion.
5305   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5306 }
5307 
5308 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5309 /// limited-precision mode with x == 10.0f.
5310 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5311                          SelectionDAG &DAG, const TargetLowering &TLI,
5312                          SDNodeFlags Flags) {
5313   bool IsExp10 = false;
5314   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5315       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5316     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5317       APFloat Ten(10.0f);
5318       IsExp10 = LHSC->isExactlyValue(Ten);
5319     }
5320   }
5321 
5322   // TODO: What fast-math-flags should be set on the FMUL node?
5323   if (IsExp10) {
5324     // Put the exponent in the right bit position for later addition to the
5325     // final result:
5326     //
5327     //   #define LOG2OF10 3.3219281f
5328     //   t0 = Op * LOG2OF10;
5329     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5330                              getF32Constant(DAG, 0x40549a78, dl));
5331     return getLimitedPrecisionExp2(t0, dl, DAG);
5332   }
5333 
5334   // No special expansion.
5335   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5336 }
5337 
5338 /// ExpandPowI - Expand a llvm.powi intrinsic.
5339 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5340                           SelectionDAG &DAG) {
5341   // If RHS is a constant, we can expand this out to a multiplication tree,
5342   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5343   // optimizing for size, we only want to do this if the expansion would produce
5344   // a small number of multiplies, otherwise we do the full expansion.
5345   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5346     // Get the exponent as a positive value.
5347     unsigned Val = RHSC->getSExtValue();
5348     if ((int)Val < 0) Val = -Val;
5349 
5350     // powi(x, 0) -> 1.0
5351     if (Val == 0)
5352       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5353 
5354     bool OptForSize = DAG.shouldOptForSize();
5355     if (!OptForSize ||
5356         // If optimizing for size, don't insert too many multiplies.
5357         // This inserts up to 5 multiplies.
5358         countPopulation(Val) + Log2_32(Val) < 7) {
5359       // We use the simple binary decomposition method to generate the multiply
5360       // sequence.  There are more optimal ways to do this (for example,
5361       // powi(x,15) generates one more multiply than it should), but this has
5362       // the benefit of being both really simple and much better than a libcall.
5363       SDValue Res;  // Logically starts equal to 1.0
5364       SDValue CurSquare = LHS;
5365       // TODO: Intrinsics should have fast-math-flags that propagate to these
5366       // nodes.
5367       while (Val) {
5368         if (Val & 1) {
5369           if (Res.getNode())
5370             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5371           else
5372             Res = CurSquare;  // 1.0*CurSquare.
5373         }
5374 
5375         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5376                                 CurSquare, CurSquare);
5377         Val >>= 1;
5378       }
5379 
5380       // If the original was negative, invert the result, producing 1/(x*x*x).
5381       if (RHSC->getSExtValue() < 0)
5382         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5383                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5384       return Res;
5385     }
5386   }
5387 
5388   // Otherwise, expand to a libcall.
5389   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5390 }
5391 
5392 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5393                             SDValue LHS, SDValue RHS, SDValue Scale,
5394                             SelectionDAG &DAG, const TargetLowering &TLI) {
5395   EVT VT = LHS.getValueType();
5396   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5397   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5398   LLVMContext &Ctx = *DAG.getContext();
5399 
5400   // If the type is legal but the operation isn't, this node might survive all
5401   // the way to operation legalization. If we end up there and we do not have
5402   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5403   // node.
5404 
5405   // Coax the legalizer into expanding the node during type legalization instead
5406   // by bumping the size by one bit. This will force it to Promote, enabling the
5407   // early expansion and avoiding the need to expand later.
5408 
5409   // We don't have to do this if Scale is 0; that can always be expanded, unless
5410   // it's a saturating signed operation. Those can experience true integer
5411   // division overflow, a case which we must avoid.
5412 
5413   // FIXME: We wouldn't have to do this (or any of the early
5414   // expansion/promotion) if it was possible to expand a libcall of an
5415   // illegal type during operation legalization. But it's not, so things
5416   // get a bit hacky.
5417   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5418   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5419       (TLI.isTypeLegal(VT) ||
5420        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5421     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5422         Opcode, VT, ScaleInt);
5423     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5424       EVT PromVT;
5425       if (VT.isScalarInteger())
5426         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5427       else if (VT.isVector()) {
5428         PromVT = VT.getVectorElementType();
5429         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5430         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5431       } else
5432         llvm_unreachable("Wrong VT for DIVFIX?");
5433       if (Signed) {
5434         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5435         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5436       } else {
5437         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5438         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5439       }
5440       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5441       // For saturating operations, we need to shift up the LHS to get the
5442       // proper saturation width, and then shift down again afterwards.
5443       if (Saturating)
5444         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5445                           DAG.getConstant(1, DL, ShiftTy));
5446       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5447       if (Saturating)
5448         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5449                           DAG.getConstant(1, DL, ShiftTy));
5450       return DAG.getZExtOrTrunc(Res, DL, VT);
5451     }
5452   }
5453 
5454   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5455 }
5456 
5457 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5458 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5459 static void
5460 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5461                      const SDValue &N) {
5462   switch (N.getOpcode()) {
5463   case ISD::CopyFromReg: {
5464     SDValue Op = N.getOperand(1);
5465     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5466                       Op.getValueType().getSizeInBits());
5467     return;
5468   }
5469   case ISD::BITCAST:
5470   case ISD::AssertZext:
5471   case ISD::AssertSext:
5472   case ISD::TRUNCATE:
5473     getUnderlyingArgRegs(Regs, N.getOperand(0));
5474     return;
5475   case ISD::BUILD_PAIR:
5476   case ISD::BUILD_VECTOR:
5477   case ISD::CONCAT_VECTORS:
5478     for (SDValue Op : N->op_values())
5479       getUnderlyingArgRegs(Regs, Op);
5480     return;
5481   default:
5482     return;
5483   }
5484 }
5485 
5486 /// If the DbgValueInst is a dbg_value of a function argument, create the
5487 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5488 /// instruction selection, they will be inserted to the entry BB.
5489 /// We don't currently support this for variadic dbg_values, as they shouldn't
5490 /// appear for function arguments or in the prologue.
5491 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5492     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5493     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5494   const Argument *Arg = dyn_cast<Argument>(V);
5495   if (!Arg)
5496     return false;
5497 
5498   MachineFunction &MF = DAG.getMachineFunction();
5499   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5500 
5501   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5502   // we've been asked to pursue.
5503   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5504                               bool Indirect) {
5505     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5506       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5507       // pointing at the VReg, which will be patched up later.
5508       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5509       auto MIB = BuildMI(MF, DL, Inst);
5510       MIB.addReg(Reg, RegState::Debug);
5511       MIB.addImm(0);
5512       MIB.addMetadata(Variable);
5513       auto *NewDIExpr = FragExpr;
5514       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5515       // the DIExpression.
5516       if (Indirect)
5517         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5518       MIB.addMetadata(NewDIExpr);
5519       return MIB;
5520     } else {
5521       // Create a completely standard DBG_VALUE.
5522       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5523       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5524     }
5525   };
5526 
5527   if (!IsDbgDeclare) {
5528     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5529     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5530     // the entry block.
5531     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5532     if (!IsInEntryBlock)
5533       return false;
5534 
5535     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5536     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5537     // variable that also is a param.
5538     //
5539     // Although, if we are at the top of the entry block already, we can still
5540     // emit using ArgDbgValue. This might catch some situations when the
5541     // dbg.value refers to an argument that isn't used in the entry block, so
5542     // any CopyToReg node would be optimized out and the only way to express
5543     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5544     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5545     // we should only emit as ArgDbgValue if the Variable is an argument to the
5546     // current function, and the dbg.value intrinsic is found in the entry
5547     // block.
5548     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5549         !DL->getInlinedAt();
5550     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5551     if (!IsInPrologue && !VariableIsFunctionInputArg)
5552       return false;
5553 
5554     // Here we assume that a function argument on IR level only can be used to
5555     // describe one input parameter on source level. If we for example have
5556     // source code like this
5557     //
5558     //    struct A { long x, y; };
5559     //    void foo(struct A a, long b) {
5560     //      ...
5561     //      b = a.x;
5562     //      ...
5563     //    }
5564     //
5565     // and IR like this
5566     //
5567     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5568     //  entry:
5569     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5570     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5571     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5572     //    ...
5573     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5574     //    ...
5575     //
5576     // then the last dbg.value is describing a parameter "b" using a value that
5577     // is an argument. But since we already has used %a1 to describe a parameter
5578     // we should not handle that last dbg.value here (that would result in an
5579     // incorrect hoisting of the DBG_VALUE to the function entry).
5580     // Notice that we allow one dbg.value per IR level argument, to accommodate
5581     // for the situation with fragments above.
5582     if (VariableIsFunctionInputArg) {
5583       unsigned ArgNo = Arg->getArgNo();
5584       if (ArgNo >= FuncInfo.DescribedArgs.size())
5585         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5586       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5587         return false;
5588       FuncInfo.DescribedArgs.set(ArgNo);
5589     }
5590   }
5591 
5592   bool IsIndirect = false;
5593   Optional<MachineOperand> Op;
5594   // Some arguments' frame index is recorded during argument lowering.
5595   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5596   if (FI != std::numeric_limits<int>::max())
5597     Op = MachineOperand::CreateFI(FI);
5598 
5599   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5600   if (!Op && N.getNode()) {
5601     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5602     Register Reg;
5603     if (ArgRegsAndSizes.size() == 1)
5604       Reg = ArgRegsAndSizes.front().first;
5605 
5606     if (Reg && Reg.isVirtual()) {
5607       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5608       Register PR = RegInfo.getLiveInPhysReg(Reg);
5609       if (PR)
5610         Reg = PR;
5611     }
5612     if (Reg) {
5613       Op = MachineOperand::CreateReg(Reg, false);
5614       IsIndirect = IsDbgDeclare;
5615     }
5616   }
5617 
5618   if (!Op && N.getNode()) {
5619     // Check if frame index is available.
5620     SDValue LCandidate = peekThroughBitcasts(N);
5621     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5622       if (FrameIndexSDNode *FINode =
5623           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5624         Op = MachineOperand::CreateFI(FINode->getIndex());
5625   }
5626 
5627   if (!Op) {
5628     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5629     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5630                                          SplitRegs) {
5631       unsigned Offset = 0;
5632       for (const auto &RegAndSize : SplitRegs) {
5633         // If the expression is already a fragment, the current register
5634         // offset+size might extend beyond the fragment. In this case, only
5635         // the register bits that are inside the fragment are relevant.
5636         int RegFragmentSizeInBits = RegAndSize.second;
5637         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5638           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5639           // The register is entirely outside the expression fragment,
5640           // so is irrelevant for debug info.
5641           if (Offset >= ExprFragmentSizeInBits)
5642             break;
5643           // The register is partially outside the expression fragment, only
5644           // the low bits within the fragment are relevant for debug info.
5645           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5646             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5647           }
5648         }
5649 
5650         auto FragmentExpr = DIExpression::createFragmentExpression(
5651             Expr, Offset, RegFragmentSizeInBits);
5652         Offset += RegAndSize.second;
5653         // If a valid fragment expression cannot be created, the variable's
5654         // correct value cannot be determined and so it is set as Undef.
5655         if (!FragmentExpr) {
5656           SDDbgValue *SDV = DAG.getConstantDbgValue(
5657               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5658           DAG.AddDbgValue(SDV, false);
5659           continue;
5660         }
5661         MachineInstr *NewMI =
5662             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5663         FuncInfo.ArgDbgValues.push_back(NewMI);
5664       }
5665     };
5666 
5667     // Check if ValueMap has reg number.
5668     DenseMap<const Value *, Register>::const_iterator
5669       VMI = FuncInfo.ValueMap.find(V);
5670     if (VMI != FuncInfo.ValueMap.end()) {
5671       const auto &TLI = DAG.getTargetLoweringInfo();
5672       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5673                        V->getType(), None);
5674       if (RFV.occupiesMultipleRegs()) {
5675         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5676         return true;
5677       }
5678 
5679       Op = MachineOperand::CreateReg(VMI->second, false);
5680       IsIndirect = IsDbgDeclare;
5681     } else if (ArgRegsAndSizes.size() > 1) {
5682       // This was split due to the calling convention, and no virtual register
5683       // mapping exists for the value.
5684       splitMultiRegDbgValue(ArgRegsAndSizes);
5685       return true;
5686     }
5687   }
5688 
5689   if (!Op)
5690     return false;
5691 
5692   assert(Variable->isValidLocationForIntrinsic(DL) &&
5693          "Expected inlined-at fields to agree");
5694   MachineInstr *NewMI = nullptr;
5695 
5696   if (Op->isReg())
5697     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5698   else
5699     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5700                     Variable, Expr);
5701 
5702   FuncInfo.ArgDbgValues.push_back(NewMI);
5703   return true;
5704 }
5705 
5706 /// Return the appropriate SDDbgValue based on N.
5707 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5708                                              DILocalVariable *Variable,
5709                                              DIExpression *Expr,
5710                                              const DebugLoc &dl,
5711                                              unsigned DbgSDNodeOrder) {
5712   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5713     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5714     // stack slot locations.
5715     //
5716     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5717     // debug values here after optimization:
5718     //
5719     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5720     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5721     //
5722     // Both describe the direct values of their associated variables.
5723     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5724                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5725   }
5726   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5727                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5728 }
5729 
5730 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5731   switch (Intrinsic) {
5732   case Intrinsic::smul_fix:
5733     return ISD::SMULFIX;
5734   case Intrinsic::umul_fix:
5735     return ISD::UMULFIX;
5736   case Intrinsic::smul_fix_sat:
5737     return ISD::SMULFIXSAT;
5738   case Intrinsic::umul_fix_sat:
5739     return ISD::UMULFIXSAT;
5740   case Intrinsic::sdiv_fix:
5741     return ISD::SDIVFIX;
5742   case Intrinsic::udiv_fix:
5743     return ISD::UDIVFIX;
5744   case Intrinsic::sdiv_fix_sat:
5745     return ISD::SDIVFIXSAT;
5746   case Intrinsic::udiv_fix_sat:
5747     return ISD::UDIVFIXSAT;
5748   default:
5749     llvm_unreachable("Unhandled fixed point intrinsic");
5750   }
5751 }
5752 
5753 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5754                                            const char *FunctionName) {
5755   assert(FunctionName && "FunctionName must not be nullptr");
5756   SDValue Callee = DAG.getExternalSymbol(
5757       FunctionName,
5758       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5759   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5760 }
5761 
5762 /// Given a @llvm.call.preallocated.setup, return the corresponding
5763 /// preallocated call.
5764 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5765   assert(cast<CallBase>(PreallocatedSetup)
5766                  ->getCalledFunction()
5767                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5768          "expected call_preallocated_setup Value");
5769   for (auto *U : PreallocatedSetup->users()) {
5770     auto *UseCall = cast<CallBase>(U);
5771     const Function *Fn = UseCall->getCalledFunction();
5772     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5773       return UseCall;
5774     }
5775   }
5776   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5777 }
5778 
5779 /// Lower the call to the specified intrinsic function.
5780 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5781                                              unsigned Intrinsic) {
5782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5783   SDLoc sdl = getCurSDLoc();
5784   DebugLoc dl = getCurDebugLoc();
5785   SDValue Res;
5786 
5787   SDNodeFlags Flags;
5788   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5789     Flags.copyFMF(*FPOp);
5790 
5791   switch (Intrinsic) {
5792   default:
5793     // By default, turn this into a target intrinsic node.
5794     visitTargetIntrinsic(I, Intrinsic);
5795     return;
5796   case Intrinsic::vscale: {
5797     match(&I, m_VScale(DAG.getDataLayout()));
5798     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5799     setValue(&I,
5800              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5801     return;
5802   }
5803   case Intrinsic::vastart:  visitVAStart(I); return;
5804   case Intrinsic::vaend:    visitVAEnd(I); return;
5805   case Intrinsic::vacopy:   visitVACopy(I); return;
5806   case Intrinsic::returnaddress:
5807     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5808                              TLI.getPointerTy(DAG.getDataLayout()),
5809                              getValue(I.getArgOperand(0))));
5810     return;
5811   case Intrinsic::addressofreturnaddress:
5812     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5813                              TLI.getPointerTy(DAG.getDataLayout())));
5814     return;
5815   case Intrinsic::sponentry:
5816     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5817                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5818     return;
5819   case Intrinsic::frameaddress:
5820     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5821                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5822                              getValue(I.getArgOperand(0))));
5823     return;
5824   case Intrinsic::read_volatile_register:
5825   case Intrinsic::read_register: {
5826     Value *Reg = I.getArgOperand(0);
5827     SDValue Chain = getRoot();
5828     SDValue RegName =
5829         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5830     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5831     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5832       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5833     setValue(&I, Res);
5834     DAG.setRoot(Res.getValue(1));
5835     return;
5836   }
5837   case Intrinsic::write_register: {
5838     Value *Reg = I.getArgOperand(0);
5839     Value *RegValue = I.getArgOperand(1);
5840     SDValue Chain = getRoot();
5841     SDValue RegName =
5842         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5843     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5844                             RegName, getValue(RegValue)));
5845     return;
5846   }
5847   case Intrinsic::memcpy: {
5848     const auto &MCI = cast<MemCpyInst>(I);
5849     SDValue Op1 = getValue(I.getArgOperand(0));
5850     SDValue Op2 = getValue(I.getArgOperand(1));
5851     SDValue Op3 = getValue(I.getArgOperand(2));
5852     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5853     Align DstAlign = MCI.getDestAlign().valueOrOne();
5854     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5855     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5856     bool isVol = MCI.isVolatile();
5857     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5858     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5859     // node.
5860     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5861     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5862                                /* AlwaysInline */ false, isTC,
5863                                MachinePointerInfo(I.getArgOperand(0)),
5864                                MachinePointerInfo(I.getArgOperand(1)),
5865                                I.getAAMetadata());
5866     updateDAGForMaybeTailCall(MC);
5867     return;
5868   }
5869   case Intrinsic::memcpy_inline: {
5870     const auto &MCI = cast<MemCpyInlineInst>(I);
5871     SDValue Dst = getValue(I.getArgOperand(0));
5872     SDValue Src = getValue(I.getArgOperand(1));
5873     SDValue Size = getValue(I.getArgOperand(2));
5874     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5875     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5876     Align DstAlign = MCI.getDestAlign().valueOrOne();
5877     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5878     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5879     bool isVol = MCI.isVolatile();
5880     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5881     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5882     // node.
5883     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5884                                /* AlwaysInline */ true, isTC,
5885                                MachinePointerInfo(I.getArgOperand(0)),
5886                                MachinePointerInfo(I.getArgOperand(1)),
5887                                I.getAAMetadata());
5888     updateDAGForMaybeTailCall(MC);
5889     return;
5890   }
5891   case Intrinsic::memset: {
5892     const auto &MSI = cast<MemSetInst>(I);
5893     SDValue Op1 = getValue(I.getArgOperand(0));
5894     SDValue Op2 = getValue(I.getArgOperand(1));
5895     SDValue Op3 = getValue(I.getArgOperand(2));
5896     // @llvm.memset defines 0 and 1 to both mean no alignment.
5897     Align Alignment = MSI.getDestAlign().valueOrOne();
5898     bool isVol = MSI.isVolatile();
5899     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5900     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5901     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5902                                MachinePointerInfo(I.getArgOperand(0)),
5903                                I.getAAMetadata());
5904     updateDAGForMaybeTailCall(MS);
5905     return;
5906   }
5907   case Intrinsic::memmove: {
5908     const auto &MMI = cast<MemMoveInst>(I);
5909     SDValue Op1 = getValue(I.getArgOperand(0));
5910     SDValue Op2 = getValue(I.getArgOperand(1));
5911     SDValue Op3 = getValue(I.getArgOperand(2));
5912     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5913     Align DstAlign = MMI.getDestAlign().valueOrOne();
5914     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5915     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5916     bool isVol = MMI.isVolatile();
5917     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5918     // FIXME: Support passing different dest/src alignments to the memmove DAG
5919     // node.
5920     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5921     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5922                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5923                                 MachinePointerInfo(I.getArgOperand(1)),
5924                                 I.getAAMetadata());
5925     updateDAGForMaybeTailCall(MM);
5926     return;
5927   }
5928   case Intrinsic::memcpy_element_unordered_atomic: {
5929     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5930     SDValue Dst = getValue(MI.getRawDest());
5931     SDValue Src = getValue(MI.getRawSource());
5932     SDValue Length = getValue(MI.getLength());
5933 
5934     unsigned DstAlign = MI.getDestAlignment();
5935     unsigned SrcAlign = MI.getSourceAlignment();
5936     Type *LengthTy = MI.getLength()->getType();
5937     unsigned ElemSz = MI.getElementSizeInBytes();
5938     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5939     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5940                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5941                                      MachinePointerInfo(MI.getRawDest()),
5942                                      MachinePointerInfo(MI.getRawSource()));
5943     updateDAGForMaybeTailCall(MC);
5944     return;
5945   }
5946   case Intrinsic::memmove_element_unordered_atomic: {
5947     auto &MI = cast<AtomicMemMoveInst>(I);
5948     SDValue Dst = getValue(MI.getRawDest());
5949     SDValue Src = getValue(MI.getRawSource());
5950     SDValue Length = getValue(MI.getLength());
5951 
5952     unsigned DstAlign = MI.getDestAlignment();
5953     unsigned SrcAlign = MI.getSourceAlignment();
5954     Type *LengthTy = MI.getLength()->getType();
5955     unsigned ElemSz = MI.getElementSizeInBytes();
5956     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5957     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5958                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5959                                       MachinePointerInfo(MI.getRawDest()),
5960                                       MachinePointerInfo(MI.getRawSource()));
5961     updateDAGForMaybeTailCall(MC);
5962     return;
5963   }
5964   case Intrinsic::memset_element_unordered_atomic: {
5965     auto &MI = cast<AtomicMemSetInst>(I);
5966     SDValue Dst = getValue(MI.getRawDest());
5967     SDValue Val = getValue(MI.getValue());
5968     SDValue Length = getValue(MI.getLength());
5969 
5970     unsigned DstAlign = MI.getDestAlignment();
5971     Type *LengthTy = MI.getLength()->getType();
5972     unsigned ElemSz = MI.getElementSizeInBytes();
5973     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5974     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5975                                      LengthTy, ElemSz, isTC,
5976                                      MachinePointerInfo(MI.getRawDest()));
5977     updateDAGForMaybeTailCall(MC);
5978     return;
5979   }
5980   case Intrinsic::call_preallocated_setup: {
5981     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5982     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5983     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5984                               getRoot(), SrcValue);
5985     setValue(&I, Res);
5986     DAG.setRoot(Res);
5987     return;
5988   }
5989   case Intrinsic::call_preallocated_arg: {
5990     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5991     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5992     SDValue Ops[3];
5993     Ops[0] = getRoot();
5994     Ops[1] = SrcValue;
5995     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5996                                    MVT::i32); // arg index
5997     SDValue Res = DAG.getNode(
5998         ISD::PREALLOCATED_ARG, sdl,
5999         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6000     setValue(&I, Res);
6001     DAG.setRoot(Res.getValue(1));
6002     return;
6003   }
6004   case Intrinsic::dbg_addr:
6005   case Intrinsic::dbg_declare: {
6006     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6007     // they are non-variadic.
6008     const auto &DI = cast<DbgVariableIntrinsic>(I);
6009     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6010     DILocalVariable *Variable = DI.getVariable();
6011     DIExpression *Expression = DI.getExpression();
6012     dropDanglingDebugInfo(Variable, Expression);
6013     assert(Variable && "Missing variable");
6014     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6015                       << "\n");
6016     // Check if address has undef value.
6017     const Value *Address = DI.getVariableLocationOp(0);
6018     if (!Address || isa<UndefValue>(Address) ||
6019         (Address->use_empty() && !isa<Argument>(Address))) {
6020       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6021                         << " (bad/undef/unused-arg address)\n");
6022       return;
6023     }
6024 
6025     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6026 
6027     // Check if this variable can be described by a frame index, typically
6028     // either as a static alloca or a byval parameter.
6029     int FI = std::numeric_limits<int>::max();
6030     if (const auto *AI =
6031             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6032       if (AI->isStaticAlloca()) {
6033         auto I = FuncInfo.StaticAllocaMap.find(AI);
6034         if (I != FuncInfo.StaticAllocaMap.end())
6035           FI = I->second;
6036       }
6037     } else if (const auto *Arg = dyn_cast<Argument>(
6038                    Address->stripInBoundsConstantOffsets())) {
6039       FI = FuncInfo.getArgumentFrameIndex(Arg);
6040     }
6041 
6042     // llvm.dbg.addr is control dependent and always generates indirect
6043     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6044     // the MachineFunction variable table.
6045     if (FI != std::numeric_limits<int>::max()) {
6046       if (Intrinsic == Intrinsic::dbg_addr) {
6047         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6048             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6049             dl, SDNodeOrder);
6050         DAG.AddDbgValue(SDV, isParameter);
6051       } else {
6052         LLVM_DEBUG(dbgs() << "Skipping " << DI
6053                           << " (variable info stashed in MF side table)\n");
6054       }
6055       return;
6056     }
6057 
6058     SDValue &N = NodeMap[Address];
6059     if (!N.getNode() && isa<Argument>(Address))
6060       // Check unused arguments map.
6061       N = UnusedArgNodeMap[Address];
6062     SDDbgValue *SDV;
6063     if (N.getNode()) {
6064       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6065         Address = BCI->getOperand(0);
6066       // Parameters are handled specially.
6067       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6068       if (isParameter && FINode) {
6069         // Byval parameter. We have a frame index at this point.
6070         SDV =
6071             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6072                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6073       } else if (isa<Argument>(Address)) {
6074         // Address is an argument, so try to emit its dbg value using
6075         // virtual register info from the FuncInfo.ValueMap.
6076         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6077         return;
6078       } else {
6079         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6080                               true, dl, SDNodeOrder);
6081       }
6082       DAG.AddDbgValue(SDV, isParameter);
6083     } else {
6084       // If Address is an argument then try to emit its dbg value using
6085       // virtual register info from the FuncInfo.ValueMap.
6086       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6087                                     N)) {
6088         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6089                           << " (could not emit func-arg dbg_value)\n");
6090       }
6091     }
6092     return;
6093   }
6094   case Intrinsic::dbg_label: {
6095     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6096     DILabel *Label = DI.getLabel();
6097     assert(Label && "Missing label");
6098 
6099     SDDbgLabel *SDV;
6100     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6101     DAG.AddDbgLabel(SDV);
6102     return;
6103   }
6104   case Intrinsic::dbg_value: {
6105     const DbgValueInst &DI = cast<DbgValueInst>(I);
6106     assert(DI.getVariable() && "Missing variable");
6107 
6108     DILocalVariable *Variable = DI.getVariable();
6109     DIExpression *Expression = DI.getExpression();
6110     dropDanglingDebugInfo(Variable, Expression);
6111     SmallVector<Value *, 4> Values(DI.getValues());
6112     if (Values.empty())
6113       return;
6114 
6115     if (std::count(Values.begin(), Values.end(), nullptr))
6116       return;
6117 
6118     bool IsVariadic = DI.hasArgList();
6119     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6120                           SDNodeOrder, IsVariadic))
6121       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6122     return;
6123   }
6124 
6125   case Intrinsic::eh_typeid_for: {
6126     // Find the type id for the given typeinfo.
6127     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6128     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6129     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6130     setValue(&I, Res);
6131     return;
6132   }
6133 
6134   case Intrinsic::eh_return_i32:
6135   case Intrinsic::eh_return_i64:
6136     DAG.getMachineFunction().setCallsEHReturn(true);
6137     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6138                             MVT::Other,
6139                             getControlRoot(),
6140                             getValue(I.getArgOperand(0)),
6141                             getValue(I.getArgOperand(1))));
6142     return;
6143   case Intrinsic::eh_unwind_init:
6144     DAG.getMachineFunction().setCallsUnwindInit(true);
6145     return;
6146   case Intrinsic::eh_dwarf_cfa:
6147     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6148                              TLI.getPointerTy(DAG.getDataLayout()),
6149                              getValue(I.getArgOperand(0))));
6150     return;
6151   case Intrinsic::eh_sjlj_callsite: {
6152     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6153     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6154     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6155     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6156 
6157     MMI.setCurrentCallSite(CI->getZExtValue());
6158     return;
6159   }
6160   case Intrinsic::eh_sjlj_functioncontext: {
6161     // Get and store the index of the function context.
6162     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6163     AllocaInst *FnCtx =
6164       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6165     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6166     MFI.setFunctionContextIndex(FI);
6167     return;
6168   }
6169   case Intrinsic::eh_sjlj_setjmp: {
6170     SDValue Ops[2];
6171     Ops[0] = getRoot();
6172     Ops[1] = getValue(I.getArgOperand(0));
6173     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6174                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6175     setValue(&I, Op.getValue(0));
6176     DAG.setRoot(Op.getValue(1));
6177     return;
6178   }
6179   case Intrinsic::eh_sjlj_longjmp:
6180     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6181                             getRoot(), getValue(I.getArgOperand(0))));
6182     return;
6183   case Intrinsic::eh_sjlj_setup_dispatch:
6184     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6185                             getRoot()));
6186     return;
6187   case Intrinsic::masked_gather:
6188     visitMaskedGather(I);
6189     return;
6190   case Intrinsic::masked_load:
6191     visitMaskedLoad(I);
6192     return;
6193   case Intrinsic::masked_scatter:
6194     visitMaskedScatter(I);
6195     return;
6196   case Intrinsic::masked_store:
6197     visitMaskedStore(I);
6198     return;
6199   case Intrinsic::masked_expandload:
6200     visitMaskedLoad(I, true /* IsExpanding */);
6201     return;
6202   case Intrinsic::masked_compressstore:
6203     visitMaskedStore(I, true /* IsCompressing */);
6204     return;
6205   case Intrinsic::powi:
6206     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6207                             getValue(I.getArgOperand(1)), DAG));
6208     return;
6209   case Intrinsic::log:
6210     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6211     return;
6212   case Intrinsic::log2:
6213     setValue(&I,
6214              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6215     return;
6216   case Intrinsic::log10:
6217     setValue(&I,
6218              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6219     return;
6220   case Intrinsic::exp:
6221     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6222     return;
6223   case Intrinsic::exp2:
6224     setValue(&I,
6225              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6226     return;
6227   case Intrinsic::pow:
6228     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6229                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6230     return;
6231   case Intrinsic::sqrt:
6232   case Intrinsic::fabs:
6233   case Intrinsic::sin:
6234   case Intrinsic::cos:
6235   case Intrinsic::floor:
6236   case Intrinsic::ceil:
6237   case Intrinsic::trunc:
6238   case Intrinsic::rint:
6239   case Intrinsic::nearbyint:
6240   case Intrinsic::round:
6241   case Intrinsic::roundeven:
6242   case Intrinsic::canonicalize: {
6243     unsigned Opcode;
6244     switch (Intrinsic) {
6245     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6246     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6247     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6248     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6249     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6250     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6251     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6252     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6253     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6254     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6255     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6256     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6257     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6258     }
6259 
6260     setValue(&I, DAG.getNode(Opcode, sdl,
6261                              getValue(I.getArgOperand(0)).getValueType(),
6262                              getValue(I.getArgOperand(0)), Flags));
6263     return;
6264   }
6265   case Intrinsic::lround:
6266   case Intrinsic::llround:
6267   case Intrinsic::lrint:
6268   case Intrinsic::llrint: {
6269     unsigned Opcode;
6270     switch (Intrinsic) {
6271     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6272     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6273     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6274     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6275     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6276     }
6277 
6278     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6279     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6280                              getValue(I.getArgOperand(0))));
6281     return;
6282   }
6283   case Intrinsic::minnum:
6284     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6285                              getValue(I.getArgOperand(0)).getValueType(),
6286                              getValue(I.getArgOperand(0)),
6287                              getValue(I.getArgOperand(1)), Flags));
6288     return;
6289   case Intrinsic::maxnum:
6290     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6291                              getValue(I.getArgOperand(0)).getValueType(),
6292                              getValue(I.getArgOperand(0)),
6293                              getValue(I.getArgOperand(1)), Flags));
6294     return;
6295   case Intrinsic::minimum:
6296     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6297                              getValue(I.getArgOperand(0)).getValueType(),
6298                              getValue(I.getArgOperand(0)),
6299                              getValue(I.getArgOperand(1)), Flags));
6300     return;
6301   case Intrinsic::maximum:
6302     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6303                              getValue(I.getArgOperand(0)).getValueType(),
6304                              getValue(I.getArgOperand(0)),
6305                              getValue(I.getArgOperand(1)), Flags));
6306     return;
6307   case Intrinsic::copysign:
6308     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6309                              getValue(I.getArgOperand(0)).getValueType(),
6310                              getValue(I.getArgOperand(0)),
6311                              getValue(I.getArgOperand(1)), Flags));
6312     return;
6313   case Intrinsic::arithmetic_fence: {
6314     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6315                              getValue(I.getArgOperand(0)).getValueType(),
6316                              getValue(I.getArgOperand(0)), Flags));
6317     return;
6318   }
6319   case Intrinsic::fma:
6320     setValue(&I, DAG.getNode(
6321                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6322                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6323                      getValue(I.getArgOperand(2)), Flags));
6324     return;
6325 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6326   case Intrinsic::INTRINSIC:
6327 #include "llvm/IR/ConstrainedOps.def"
6328     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6329     return;
6330 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6331 #include "llvm/IR/VPIntrinsics.def"
6332     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6333     return;
6334   case Intrinsic::fmuladd: {
6335     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6336     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6337         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6338       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6339                                getValue(I.getArgOperand(0)).getValueType(),
6340                                getValue(I.getArgOperand(0)),
6341                                getValue(I.getArgOperand(1)),
6342                                getValue(I.getArgOperand(2)), Flags));
6343     } else {
6344       // TODO: Intrinsic calls should have fast-math-flags.
6345       SDValue Mul = DAG.getNode(
6346           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6347           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6348       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6349                                 getValue(I.getArgOperand(0)).getValueType(),
6350                                 Mul, getValue(I.getArgOperand(2)), Flags);
6351       setValue(&I, Add);
6352     }
6353     return;
6354   }
6355   case Intrinsic::convert_to_fp16:
6356     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6357                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6358                                          getValue(I.getArgOperand(0)),
6359                                          DAG.getTargetConstant(0, sdl,
6360                                                                MVT::i32))));
6361     return;
6362   case Intrinsic::convert_from_fp16:
6363     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6364                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6365                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6366                                          getValue(I.getArgOperand(0)))));
6367     return;
6368   case Intrinsic::fptosi_sat: {
6369     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6370     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6371                              getValue(I.getArgOperand(0)),
6372                              DAG.getValueType(VT.getScalarType())));
6373     return;
6374   }
6375   case Intrinsic::fptoui_sat: {
6376     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6377     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6378                              getValue(I.getArgOperand(0)),
6379                              DAG.getValueType(VT.getScalarType())));
6380     return;
6381   }
6382   case Intrinsic::set_rounding:
6383     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6384                       {getRoot(), getValue(I.getArgOperand(0))});
6385     setValue(&I, Res);
6386     DAG.setRoot(Res.getValue(0));
6387     return;
6388   case Intrinsic::pcmarker: {
6389     SDValue Tmp = getValue(I.getArgOperand(0));
6390     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6391     return;
6392   }
6393   case Intrinsic::readcyclecounter: {
6394     SDValue Op = getRoot();
6395     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6396                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6397     setValue(&I, Res);
6398     DAG.setRoot(Res.getValue(1));
6399     return;
6400   }
6401   case Intrinsic::bitreverse:
6402     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6403                              getValue(I.getArgOperand(0)).getValueType(),
6404                              getValue(I.getArgOperand(0))));
6405     return;
6406   case Intrinsic::bswap:
6407     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6408                              getValue(I.getArgOperand(0)).getValueType(),
6409                              getValue(I.getArgOperand(0))));
6410     return;
6411   case Intrinsic::cttz: {
6412     SDValue Arg = getValue(I.getArgOperand(0));
6413     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6414     EVT Ty = Arg.getValueType();
6415     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6416                              sdl, Ty, Arg));
6417     return;
6418   }
6419   case Intrinsic::ctlz: {
6420     SDValue Arg = getValue(I.getArgOperand(0));
6421     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6422     EVT Ty = Arg.getValueType();
6423     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6424                              sdl, Ty, Arg));
6425     return;
6426   }
6427   case Intrinsic::ctpop: {
6428     SDValue Arg = getValue(I.getArgOperand(0));
6429     EVT Ty = Arg.getValueType();
6430     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6431     return;
6432   }
6433   case Intrinsic::fshl:
6434   case Intrinsic::fshr: {
6435     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6436     SDValue X = getValue(I.getArgOperand(0));
6437     SDValue Y = getValue(I.getArgOperand(1));
6438     SDValue Z = getValue(I.getArgOperand(2));
6439     EVT VT = X.getValueType();
6440 
6441     if (X == Y) {
6442       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6443       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6444     } else {
6445       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6446       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6447     }
6448     return;
6449   }
6450   case Intrinsic::sadd_sat: {
6451     SDValue Op1 = getValue(I.getArgOperand(0));
6452     SDValue Op2 = getValue(I.getArgOperand(1));
6453     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6454     return;
6455   }
6456   case Intrinsic::uadd_sat: {
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6460     return;
6461   }
6462   case Intrinsic::ssub_sat: {
6463     SDValue Op1 = getValue(I.getArgOperand(0));
6464     SDValue Op2 = getValue(I.getArgOperand(1));
6465     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6466     return;
6467   }
6468   case Intrinsic::usub_sat: {
6469     SDValue Op1 = getValue(I.getArgOperand(0));
6470     SDValue Op2 = getValue(I.getArgOperand(1));
6471     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6472     return;
6473   }
6474   case Intrinsic::sshl_sat: {
6475     SDValue Op1 = getValue(I.getArgOperand(0));
6476     SDValue Op2 = getValue(I.getArgOperand(1));
6477     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6478     return;
6479   }
6480   case Intrinsic::ushl_sat: {
6481     SDValue Op1 = getValue(I.getArgOperand(0));
6482     SDValue Op2 = getValue(I.getArgOperand(1));
6483     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6484     return;
6485   }
6486   case Intrinsic::smul_fix:
6487   case Intrinsic::umul_fix:
6488   case Intrinsic::smul_fix_sat:
6489   case Intrinsic::umul_fix_sat: {
6490     SDValue Op1 = getValue(I.getArgOperand(0));
6491     SDValue Op2 = getValue(I.getArgOperand(1));
6492     SDValue Op3 = getValue(I.getArgOperand(2));
6493     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6494                              Op1.getValueType(), Op1, Op2, Op3));
6495     return;
6496   }
6497   case Intrinsic::sdiv_fix:
6498   case Intrinsic::udiv_fix:
6499   case Intrinsic::sdiv_fix_sat:
6500   case Intrinsic::udiv_fix_sat: {
6501     SDValue Op1 = getValue(I.getArgOperand(0));
6502     SDValue Op2 = getValue(I.getArgOperand(1));
6503     SDValue Op3 = getValue(I.getArgOperand(2));
6504     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6505                               Op1, Op2, Op3, DAG, TLI));
6506     return;
6507   }
6508   case Intrinsic::smax: {
6509     SDValue Op1 = getValue(I.getArgOperand(0));
6510     SDValue Op2 = getValue(I.getArgOperand(1));
6511     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6512     return;
6513   }
6514   case Intrinsic::smin: {
6515     SDValue Op1 = getValue(I.getArgOperand(0));
6516     SDValue Op2 = getValue(I.getArgOperand(1));
6517     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6518     return;
6519   }
6520   case Intrinsic::umax: {
6521     SDValue Op1 = getValue(I.getArgOperand(0));
6522     SDValue Op2 = getValue(I.getArgOperand(1));
6523     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6524     return;
6525   }
6526   case Intrinsic::umin: {
6527     SDValue Op1 = getValue(I.getArgOperand(0));
6528     SDValue Op2 = getValue(I.getArgOperand(1));
6529     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6530     return;
6531   }
6532   case Intrinsic::abs: {
6533     // TODO: Preserve "int min is poison" arg in SDAG?
6534     SDValue Op1 = getValue(I.getArgOperand(0));
6535     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6536     return;
6537   }
6538   case Intrinsic::stacksave: {
6539     SDValue Op = getRoot();
6540     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6541     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6542     setValue(&I, Res);
6543     DAG.setRoot(Res.getValue(1));
6544     return;
6545   }
6546   case Intrinsic::stackrestore:
6547     Res = getValue(I.getArgOperand(0));
6548     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6549     return;
6550   case Intrinsic::get_dynamic_area_offset: {
6551     SDValue Op = getRoot();
6552     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6553     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6554     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6555     // target.
6556     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6557       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6558                          " intrinsic!");
6559     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6560                       Op);
6561     DAG.setRoot(Op);
6562     setValue(&I, Res);
6563     return;
6564   }
6565   case Intrinsic::stackguard: {
6566     MachineFunction &MF = DAG.getMachineFunction();
6567     const Module &M = *MF.getFunction().getParent();
6568     SDValue Chain = getRoot();
6569     if (TLI.useLoadStackGuardNode()) {
6570       Res = getLoadStackGuard(DAG, sdl, Chain);
6571     } else {
6572       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6573       const Value *Global = TLI.getSDagStackGuard(M);
6574       Align Align = DL->getPrefTypeAlign(Global->getType());
6575       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6576                         MachinePointerInfo(Global, 0), Align,
6577                         MachineMemOperand::MOVolatile);
6578     }
6579     if (TLI.useStackGuardXorFP())
6580       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6581     DAG.setRoot(Chain);
6582     setValue(&I, Res);
6583     return;
6584   }
6585   case Intrinsic::stackprotector: {
6586     // Emit code into the DAG to store the stack guard onto the stack.
6587     MachineFunction &MF = DAG.getMachineFunction();
6588     MachineFrameInfo &MFI = MF.getFrameInfo();
6589     SDValue Src, Chain = getRoot();
6590 
6591     if (TLI.useLoadStackGuardNode())
6592       Src = getLoadStackGuard(DAG, sdl, Chain);
6593     else
6594       Src = getValue(I.getArgOperand(0));   // The guard's value.
6595 
6596     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6597 
6598     int FI = FuncInfo.StaticAllocaMap[Slot];
6599     MFI.setStackProtectorIndex(FI);
6600     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6601 
6602     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6603 
6604     // Store the stack protector onto the stack.
6605     Res = DAG.getStore(
6606         Chain, sdl, Src, FIN,
6607         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6608         MaybeAlign(), MachineMemOperand::MOVolatile);
6609     setValue(&I, Res);
6610     DAG.setRoot(Res);
6611     return;
6612   }
6613   case Intrinsic::objectsize:
6614     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6615 
6616   case Intrinsic::is_constant:
6617     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6618 
6619   case Intrinsic::annotation:
6620   case Intrinsic::ptr_annotation:
6621   case Intrinsic::launder_invariant_group:
6622   case Intrinsic::strip_invariant_group:
6623     // Drop the intrinsic, but forward the value
6624     setValue(&I, getValue(I.getOperand(0)));
6625     return;
6626 
6627   case Intrinsic::assume:
6628   case Intrinsic::experimental_noalias_scope_decl:
6629   case Intrinsic::var_annotation:
6630   case Intrinsic::sideeffect:
6631     // Discard annotate attributes, noalias scope declarations, assumptions, and
6632     // artificial side-effects.
6633     return;
6634 
6635   case Intrinsic::codeview_annotation: {
6636     // Emit a label associated with this metadata.
6637     MachineFunction &MF = DAG.getMachineFunction();
6638     MCSymbol *Label =
6639         MF.getMMI().getContext().createTempSymbol("annotation", true);
6640     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6641     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6642     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6643     DAG.setRoot(Res);
6644     return;
6645   }
6646 
6647   case Intrinsic::init_trampoline: {
6648     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6649 
6650     SDValue Ops[6];
6651     Ops[0] = getRoot();
6652     Ops[1] = getValue(I.getArgOperand(0));
6653     Ops[2] = getValue(I.getArgOperand(1));
6654     Ops[3] = getValue(I.getArgOperand(2));
6655     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6656     Ops[5] = DAG.getSrcValue(F);
6657 
6658     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6659 
6660     DAG.setRoot(Res);
6661     return;
6662   }
6663   case Intrinsic::adjust_trampoline:
6664     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6665                              TLI.getPointerTy(DAG.getDataLayout()),
6666                              getValue(I.getArgOperand(0))));
6667     return;
6668   case Intrinsic::gcroot: {
6669     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6670            "only valid in functions with gc specified, enforced by Verifier");
6671     assert(GFI && "implied by previous");
6672     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6673     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6674 
6675     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6676     GFI->addStackRoot(FI->getIndex(), TypeMap);
6677     return;
6678   }
6679   case Intrinsic::gcread:
6680   case Intrinsic::gcwrite:
6681     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6682   case Intrinsic::flt_rounds:
6683     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6684     setValue(&I, Res);
6685     DAG.setRoot(Res.getValue(1));
6686     return;
6687 
6688   case Intrinsic::expect:
6689     // Just replace __builtin_expect(exp, c) with EXP.
6690     setValue(&I, getValue(I.getArgOperand(0)));
6691     return;
6692 
6693   case Intrinsic::ubsantrap:
6694   case Intrinsic::debugtrap:
6695   case Intrinsic::trap: {
6696     StringRef TrapFuncName =
6697         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6698     if (TrapFuncName.empty()) {
6699       switch (Intrinsic) {
6700       case Intrinsic::trap:
6701         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6702         break;
6703       case Intrinsic::debugtrap:
6704         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6705         break;
6706       case Intrinsic::ubsantrap:
6707         DAG.setRoot(DAG.getNode(
6708             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6709             DAG.getTargetConstant(
6710                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6711                 MVT::i32)));
6712         break;
6713       default: llvm_unreachable("unknown trap intrinsic");
6714       }
6715       return;
6716     }
6717     TargetLowering::ArgListTy Args;
6718     if (Intrinsic == Intrinsic::ubsantrap) {
6719       Args.push_back(TargetLoweringBase::ArgListEntry());
6720       Args[0].Val = I.getArgOperand(0);
6721       Args[0].Node = getValue(Args[0].Val);
6722       Args[0].Ty = Args[0].Val->getType();
6723     }
6724 
6725     TargetLowering::CallLoweringInfo CLI(DAG);
6726     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6727         CallingConv::C, I.getType(),
6728         DAG.getExternalSymbol(TrapFuncName.data(),
6729                               TLI.getPointerTy(DAG.getDataLayout())),
6730         std::move(Args));
6731 
6732     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6733     DAG.setRoot(Result.second);
6734     return;
6735   }
6736 
6737   case Intrinsic::uadd_with_overflow:
6738   case Intrinsic::sadd_with_overflow:
6739   case Intrinsic::usub_with_overflow:
6740   case Intrinsic::ssub_with_overflow:
6741   case Intrinsic::umul_with_overflow:
6742   case Intrinsic::smul_with_overflow: {
6743     ISD::NodeType Op;
6744     switch (Intrinsic) {
6745     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6746     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6747     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6748     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6749     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6750     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6751     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6752     }
6753     SDValue Op1 = getValue(I.getArgOperand(0));
6754     SDValue Op2 = getValue(I.getArgOperand(1));
6755 
6756     EVT ResultVT = Op1.getValueType();
6757     EVT OverflowVT = MVT::i1;
6758     if (ResultVT.isVector())
6759       OverflowVT = EVT::getVectorVT(
6760           *Context, OverflowVT, ResultVT.getVectorElementCount());
6761 
6762     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6763     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6764     return;
6765   }
6766   case Intrinsic::prefetch: {
6767     SDValue Ops[5];
6768     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6769     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6770     Ops[0] = DAG.getRoot();
6771     Ops[1] = getValue(I.getArgOperand(0));
6772     Ops[2] = getValue(I.getArgOperand(1));
6773     Ops[3] = getValue(I.getArgOperand(2));
6774     Ops[4] = getValue(I.getArgOperand(3));
6775     SDValue Result = DAG.getMemIntrinsicNode(
6776         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6777         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6778         /* align */ None, Flags);
6779 
6780     // Chain the prefetch in parallell with any pending loads, to stay out of
6781     // the way of later optimizations.
6782     PendingLoads.push_back(Result);
6783     Result = getRoot();
6784     DAG.setRoot(Result);
6785     return;
6786   }
6787   case Intrinsic::lifetime_start:
6788   case Intrinsic::lifetime_end: {
6789     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6790     // Stack coloring is not enabled in O0, discard region information.
6791     if (TM.getOptLevel() == CodeGenOpt::None)
6792       return;
6793 
6794     const int64_t ObjectSize =
6795         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6796     Value *const ObjectPtr = I.getArgOperand(1);
6797     SmallVector<const Value *, 4> Allocas;
6798     getUnderlyingObjects(ObjectPtr, Allocas);
6799 
6800     for (const Value *Alloca : Allocas) {
6801       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6802 
6803       // Could not find an Alloca.
6804       if (!LifetimeObject)
6805         continue;
6806 
6807       // First check that the Alloca is static, otherwise it won't have a
6808       // valid frame index.
6809       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6810       if (SI == FuncInfo.StaticAllocaMap.end())
6811         return;
6812 
6813       const int FrameIndex = SI->second;
6814       int64_t Offset;
6815       if (GetPointerBaseWithConstantOffset(
6816               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6817         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6818       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6819                                 Offset);
6820       DAG.setRoot(Res);
6821     }
6822     return;
6823   }
6824   case Intrinsic::pseudoprobe: {
6825     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6826     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6827     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6828     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6829     DAG.setRoot(Res);
6830     return;
6831   }
6832   case Intrinsic::invariant_start:
6833     // Discard region information.
6834     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6835     return;
6836   case Intrinsic::invariant_end:
6837     // Discard region information.
6838     return;
6839   case Intrinsic::clear_cache:
6840     /// FunctionName may be null.
6841     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6842       lowerCallToExternalSymbol(I, FunctionName);
6843     return;
6844   case Intrinsic::donothing:
6845   case Intrinsic::seh_try_begin:
6846   case Intrinsic::seh_scope_begin:
6847   case Intrinsic::seh_try_end:
6848   case Intrinsic::seh_scope_end:
6849     // ignore
6850     return;
6851   case Intrinsic::experimental_stackmap:
6852     visitStackmap(I);
6853     return;
6854   case Intrinsic::experimental_patchpoint_void:
6855   case Intrinsic::experimental_patchpoint_i64:
6856     visitPatchpoint(I);
6857     return;
6858   case Intrinsic::experimental_gc_statepoint:
6859     LowerStatepoint(cast<GCStatepointInst>(I));
6860     return;
6861   case Intrinsic::experimental_gc_result:
6862     visitGCResult(cast<GCResultInst>(I));
6863     return;
6864   case Intrinsic::experimental_gc_relocate:
6865     visitGCRelocate(cast<GCRelocateInst>(I));
6866     return;
6867   case Intrinsic::instrprof_increment:
6868     llvm_unreachable("instrprof failed to lower an increment");
6869   case Intrinsic::instrprof_value_profile:
6870     llvm_unreachable("instrprof failed to lower a value profiling call");
6871   case Intrinsic::localescape: {
6872     MachineFunction &MF = DAG.getMachineFunction();
6873     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6874 
6875     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6876     // is the same on all targets.
6877     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6878       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6879       if (isa<ConstantPointerNull>(Arg))
6880         continue; // Skip null pointers. They represent a hole in index space.
6881       AllocaInst *Slot = cast<AllocaInst>(Arg);
6882       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6883              "can only escape static allocas");
6884       int FI = FuncInfo.StaticAllocaMap[Slot];
6885       MCSymbol *FrameAllocSym =
6886           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6887               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6888       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6889               TII->get(TargetOpcode::LOCAL_ESCAPE))
6890           .addSym(FrameAllocSym)
6891           .addFrameIndex(FI);
6892     }
6893 
6894     return;
6895   }
6896 
6897   case Intrinsic::localrecover: {
6898     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6899     MachineFunction &MF = DAG.getMachineFunction();
6900 
6901     // Get the symbol that defines the frame offset.
6902     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6903     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6904     unsigned IdxVal =
6905         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6906     MCSymbol *FrameAllocSym =
6907         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6908             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6909 
6910     Value *FP = I.getArgOperand(1);
6911     SDValue FPVal = getValue(FP);
6912     EVT PtrVT = FPVal.getValueType();
6913 
6914     // Create a MCSymbol for the label to avoid any target lowering
6915     // that would make this PC relative.
6916     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6917     SDValue OffsetVal =
6918         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6919 
6920     // Add the offset to the FP.
6921     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6922     setValue(&I, Add);
6923 
6924     return;
6925   }
6926 
6927   case Intrinsic::eh_exceptionpointer:
6928   case Intrinsic::eh_exceptioncode: {
6929     // Get the exception pointer vreg, copy from it, and resize it to fit.
6930     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6931     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6932     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6933     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6934     SDValue N =
6935         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6936     if (Intrinsic == Intrinsic::eh_exceptioncode)
6937       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6938     setValue(&I, N);
6939     return;
6940   }
6941   case Intrinsic::xray_customevent: {
6942     // Here we want to make sure that the intrinsic behaves as if it has a
6943     // specific calling convention, and only for x86_64.
6944     // FIXME: Support other platforms later.
6945     const auto &Triple = DAG.getTarget().getTargetTriple();
6946     if (Triple.getArch() != Triple::x86_64)
6947       return;
6948 
6949     SDLoc DL = getCurSDLoc();
6950     SmallVector<SDValue, 8> Ops;
6951 
6952     // We want to say that we always want the arguments in registers.
6953     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6954     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6955     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6956     SDValue Chain = getRoot();
6957     Ops.push_back(LogEntryVal);
6958     Ops.push_back(StrSizeVal);
6959     Ops.push_back(Chain);
6960 
6961     // We need to enforce the calling convention for the callsite, so that
6962     // argument ordering is enforced correctly, and that register allocation can
6963     // see that some registers may be assumed clobbered and have to preserve
6964     // them across calls to the intrinsic.
6965     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6966                                            DL, NodeTys, Ops);
6967     SDValue patchableNode = SDValue(MN, 0);
6968     DAG.setRoot(patchableNode);
6969     setValue(&I, patchableNode);
6970     return;
6971   }
6972   case Intrinsic::xray_typedevent: {
6973     // Here we want to make sure that the intrinsic behaves as if it has a
6974     // specific calling convention, and only for x86_64.
6975     // FIXME: Support other platforms later.
6976     const auto &Triple = DAG.getTarget().getTargetTriple();
6977     if (Triple.getArch() != Triple::x86_64)
6978       return;
6979 
6980     SDLoc DL = getCurSDLoc();
6981     SmallVector<SDValue, 8> Ops;
6982 
6983     // We want to say that we always want the arguments in registers.
6984     // It's unclear to me how manipulating the selection DAG here forces callers
6985     // to provide arguments in registers instead of on the stack.
6986     SDValue LogTypeId = getValue(I.getArgOperand(0));
6987     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6988     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6989     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6990     SDValue Chain = getRoot();
6991     Ops.push_back(LogTypeId);
6992     Ops.push_back(LogEntryVal);
6993     Ops.push_back(StrSizeVal);
6994     Ops.push_back(Chain);
6995 
6996     // We need to enforce the calling convention for the callsite, so that
6997     // argument ordering is enforced correctly, and that register allocation can
6998     // see that some registers may be assumed clobbered and have to preserve
6999     // them across calls to the intrinsic.
7000     MachineSDNode *MN = DAG.getMachineNode(
7001         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
7002     SDValue patchableNode = SDValue(MN, 0);
7003     DAG.setRoot(patchableNode);
7004     setValue(&I, patchableNode);
7005     return;
7006   }
7007   case Intrinsic::experimental_deoptimize:
7008     LowerDeoptimizeCall(&I);
7009     return;
7010   case Intrinsic::experimental_stepvector:
7011     visitStepVector(I);
7012     return;
7013   case Intrinsic::vector_reduce_fadd:
7014   case Intrinsic::vector_reduce_fmul:
7015   case Intrinsic::vector_reduce_add:
7016   case Intrinsic::vector_reduce_mul:
7017   case Intrinsic::vector_reduce_and:
7018   case Intrinsic::vector_reduce_or:
7019   case Intrinsic::vector_reduce_xor:
7020   case Intrinsic::vector_reduce_smax:
7021   case Intrinsic::vector_reduce_smin:
7022   case Intrinsic::vector_reduce_umax:
7023   case Intrinsic::vector_reduce_umin:
7024   case Intrinsic::vector_reduce_fmax:
7025   case Intrinsic::vector_reduce_fmin:
7026     visitVectorReduce(I, Intrinsic);
7027     return;
7028 
7029   case Intrinsic::icall_branch_funnel: {
7030     SmallVector<SDValue, 16> Ops;
7031     Ops.push_back(getValue(I.getArgOperand(0)));
7032 
7033     int64_t Offset;
7034     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7035         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7036     if (!Base)
7037       report_fatal_error(
7038           "llvm.icall.branch.funnel operand must be a GlobalValue");
7039     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
7040 
7041     struct BranchFunnelTarget {
7042       int64_t Offset;
7043       SDValue Target;
7044     };
7045     SmallVector<BranchFunnelTarget, 8> Targets;
7046 
7047     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
7048       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7049           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7050       if (ElemBase != Base)
7051         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7052                            "to the same GlobalValue");
7053 
7054       SDValue Val = getValue(I.getArgOperand(Op + 1));
7055       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7056       if (!GA)
7057         report_fatal_error(
7058             "llvm.icall.branch.funnel operand must be a GlobalValue");
7059       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7060                                      GA->getGlobal(), getCurSDLoc(),
7061                                      Val.getValueType(), GA->getOffset())});
7062     }
7063     llvm::sort(Targets,
7064                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7065                  return T1.Offset < T2.Offset;
7066                });
7067 
7068     for (auto &T : Targets) {
7069       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7070       Ops.push_back(T.Target);
7071     }
7072 
7073     Ops.push_back(DAG.getRoot()); // Chain
7074     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7075                                  getCurSDLoc(), MVT::Other, Ops),
7076               0);
7077     DAG.setRoot(N);
7078     setValue(&I, N);
7079     HasTailCall = true;
7080     return;
7081   }
7082 
7083   case Intrinsic::wasm_landingpad_index:
7084     // Information this intrinsic contained has been transferred to
7085     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7086     // delete it now.
7087     return;
7088 
7089   case Intrinsic::aarch64_settag:
7090   case Intrinsic::aarch64_settag_zero: {
7091     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7092     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7093     SDValue Val = TSI.EmitTargetCodeForSetTag(
7094         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7095         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7096         ZeroMemory);
7097     DAG.setRoot(Val);
7098     setValue(&I, Val);
7099     return;
7100   }
7101   case Intrinsic::ptrmask: {
7102     SDValue Ptr = getValue(I.getOperand(0));
7103     SDValue Const = getValue(I.getOperand(1));
7104 
7105     EVT PtrVT = Ptr.getValueType();
7106     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7107                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7108     return;
7109   }
7110   case Intrinsic::get_active_lane_mask: {
7111     auto DL = getCurSDLoc();
7112     SDValue Index = getValue(I.getOperand(0));
7113     SDValue TripCount = getValue(I.getOperand(1));
7114     Type *ElementTy = I.getOperand(0)->getType();
7115     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7116     unsigned VecWidth = VT.getVectorNumElements();
7117 
7118     SmallVector<SDValue, 16> OpsTripCount;
7119     SmallVector<SDValue, 16> OpsIndex;
7120     SmallVector<SDValue, 16> OpsStepConstants;
7121     for (unsigned i = 0; i < VecWidth; i++) {
7122       OpsTripCount.push_back(TripCount);
7123       OpsIndex.push_back(Index);
7124       OpsStepConstants.push_back(
7125           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7126     }
7127 
7128     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7129 
7130     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7131     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7132     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7133     SDValue VectorInduction = DAG.getNode(
7134        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7135     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7136     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7137                                  VectorTripCount, ISD::CondCode::SETULT);
7138     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7139                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7140                              SetCC));
7141     return;
7142   }
7143   case Intrinsic::experimental_vector_insert: {
7144     auto DL = getCurSDLoc();
7145 
7146     SDValue Vec = getValue(I.getOperand(0));
7147     SDValue SubVec = getValue(I.getOperand(1));
7148     SDValue Index = getValue(I.getOperand(2));
7149 
7150     // The intrinsic's index type is i64, but the SDNode requires an index type
7151     // suitable for the target. Convert the index as required.
7152     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7153     if (Index.getValueType() != VectorIdxTy)
7154       Index = DAG.getVectorIdxConstant(
7155           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7156 
7157     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7158     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7159                              Index));
7160     return;
7161   }
7162   case Intrinsic::experimental_vector_extract: {
7163     auto DL = getCurSDLoc();
7164 
7165     SDValue Vec = getValue(I.getOperand(0));
7166     SDValue Index = getValue(I.getOperand(1));
7167     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7168 
7169     // The intrinsic's index type is i64, but the SDNode requires an index type
7170     // suitable for the target. Convert the index as required.
7171     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7172     if (Index.getValueType() != VectorIdxTy)
7173       Index = DAG.getVectorIdxConstant(
7174           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7175 
7176     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7177     return;
7178   }
7179   case Intrinsic::experimental_vector_reverse:
7180     visitVectorReverse(I);
7181     return;
7182   case Intrinsic::experimental_vector_splice:
7183     visitVectorSplice(I);
7184     return;
7185   }
7186 }
7187 
7188 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7189     const ConstrainedFPIntrinsic &FPI) {
7190   SDLoc sdl = getCurSDLoc();
7191 
7192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7193   SmallVector<EVT, 4> ValueVTs;
7194   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7195   ValueVTs.push_back(MVT::Other); // Out chain
7196 
7197   // We do not need to serialize constrained FP intrinsics against
7198   // each other or against (nonvolatile) loads, so they can be
7199   // chained like loads.
7200   SDValue Chain = DAG.getRoot();
7201   SmallVector<SDValue, 4> Opers;
7202   Opers.push_back(Chain);
7203   if (FPI.isUnaryOp()) {
7204     Opers.push_back(getValue(FPI.getArgOperand(0)));
7205   } else if (FPI.isTernaryOp()) {
7206     Opers.push_back(getValue(FPI.getArgOperand(0)));
7207     Opers.push_back(getValue(FPI.getArgOperand(1)));
7208     Opers.push_back(getValue(FPI.getArgOperand(2)));
7209   } else {
7210     Opers.push_back(getValue(FPI.getArgOperand(0)));
7211     Opers.push_back(getValue(FPI.getArgOperand(1)));
7212   }
7213 
7214   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7215     assert(Result.getNode()->getNumValues() == 2);
7216 
7217     // Push node to the appropriate list so that future instructions can be
7218     // chained up correctly.
7219     SDValue OutChain = Result.getValue(1);
7220     switch (EB) {
7221     case fp::ExceptionBehavior::ebIgnore:
7222       // The only reason why ebIgnore nodes still need to be chained is that
7223       // they might depend on the current rounding mode, and therefore must
7224       // not be moved across instruction that may change that mode.
7225       LLVM_FALLTHROUGH;
7226     case fp::ExceptionBehavior::ebMayTrap:
7227       // These must not be moved across calls or instructions that may change
7228       // floating-point exception masks.
7229       PendingConstrainedFP.push_back(OutChain);
7230       break;
7231     case fp::ExceptionBehavior::ebStrict:
7232       // These must not be moved across calls or instructions that may change
7233       // floating-point exception masks or read floating-point exception flags.
7234       // In addition, they cannot be optimized out even if unused.
7235       PendingConstrainedFPStrict.push_back(OutChain);
7236       break;
7237     }
7238   };
7239 
7240   SDVTList VTs = DAG.getVTList(ValueVTs);
7241   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7242 
7243   SDNodeFlags Flags;
7244   if (EB == fp::ExceptionBehavior::ebIgnore)
7245     Flags.setNoFPExcept(true);
7246 
7247   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7248     Flags.copyFMF(*FPOp);
7249 
7250   unsigned Opcode;
7251   switch (FPI.getIntrinsicID()) {
7252   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7253 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7254   case Intrinsic::INTRINSIC:                                                   \
7255     Opcode = ISD::STRICT_##DAGN;                                               \
7256     break;
7257 #include "llvm/IR/ConstrainedOps.def"
7258   case Intrinsic::experimental_constrained_fmuladd: {
7259     Opcode = ISD::STRICT_FMA;
7260     // Break fmuladd into fmul and fadd.
7261     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7262         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7263                                         ValueVTs[0])) {
7264       Opers.pop_back();
7265       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7266       pushOutChain(Mul, EB);
7267       Opcode = ISD::STRICT_FADD;
7268       Opers.clear();
7269       Opers.push_back(Mul.getValue(1));
7270       Opers.push_back(Mul.getValue(0));
7271       Opers.push_back(getValue(FPI.getArgOperand(2)));
7272     }
7273     break;
7274   }
7275   }
7276 
7277   // A few strict DAG nodes carry additional operands that are not
7278   // set up by the default code above.
7279   switch (Opcode) {
7280   default: break;
7281   case ISD::STRICT_FP_ROUND:
7282     Opers.push_back(
7283         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7284     break;
7285   case ISD::STRICT_FSETCC:
7286   case ISD::STRICT_FSETCCS: {
7287     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7288     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7289     if (TM.Options.NoNaNsFPMath)
7290       Condition = getFCmpCodeWithoutNaN(Condition);
7291     Opers.push_back(DAG.getCondCode(Condition));
7292     break;
7293   }
7294   }
7295 
7296   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7297   pushOutChain(Result, EB);
7298 
7299   SDValue FPResult = Result.getValue(0);
7300   setValue(&FPI, FPResult);
7301 }
7302 
7303 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7304   Optional<unsigned> ResOPC;
7305   switch (VPIntrin.getIntrinsicID()) {
7306 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7307 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7308 #define END_REGISTER_VP_INTRINSIC(...) break;
7309 #include "llvm/IR/VPIntrinsics.def"
7310   }
7311 
7312   if (!ResOPC.hasValue())
7313     llvm_unreachable(
7314         "Inconsistency: no SDNode available for this VPIntrinsic!");
7315 
7316   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7317       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7318     if (VPIntrin.getFastMathFlags().allowReassoc())
7319       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7320                                                 : ISD::VP_REDUCE_FMUL;
7321   }
7322 
7323   return ResOPC.getValue();
7324 }
7325 
7326 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7327                                             SmallVector<SDValue, 7> &OpValues,
7328                                             bool isGather) {
7329   SDLoc DL = getCurSDLoc();
7330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7331   Value *PtrOperand = VPIntrin.getArgOperand(0);
7332   MaybeAlign Alignment = DAG.getEVTAlign(VT);
7333   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7334   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7335   SDValue LD;
7336   bool AddToChain = true;
7337   if (!isGather) {
7338     // Do not serialize variable-length loads of constant memory with
7339     // anything.
7340     MemoryLocation ML;
7341     if (VT.isScalableVector())
7342       ML = MemoryLocation::getAfter(PtrOperand);
7343     else
7344       ML = MemoryLocation(
7345           PtrOperand,
7346           LocationSize::precise(
7347               DAG.getDataLayout().getTypeStoreSize(VPIntrin.getType())),
7348           AAInfo);
7349     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7350     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7351     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7352         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7353         VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
7354     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7355                        MMO, false /*IsExpanding */);
7356   } else {
7357     unsigned AS =
7358         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7359     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7360         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7361         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7362     SDValue Base, Index, Scale;
7363     ISD::MemIndexType IndexType;
7364     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7365                                       this, VPIntrin.getParent());
7366     if (!UniformBase) {
7367       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7368       Index = getValue(PtrOperand);
7369       IndexType = ISD::SIGNED_UNSCALED;
7370       Scale =
7371           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7372     }
7373     EVT IdxVT = Index.getValueType();
7374     EVT EltTy = IdxVT.getVectorElementType();
7375     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7376       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7377       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7378     }
7379     LD = DAG.getGatherVP(
7380         DAG.getVTList(VT, MVT::Other), VT, DL,
7381         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7382         IndexType);
7383   }
7384   if (AddToChain)
7385     PendingLoads.push_back(LD.getValue(1));
7386   setValue(&VPIntrin, LD);
7387 }
7388 
7389 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7390                                               SmallVector<SDValue, 7> &OpValues,
7391                                               bool isScatter) {
7392   SDLoc DL = getCurSDLoc();
7393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7394   Value *PtrOperand = VPIntrin.getArgOperand(1);
7395   EVT VT = OpValues[0].getValueType();
7396   MaybeAlign Alignment = DAG.getEVTAlign(VT);
7397   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7398   SDValue ST;
7399   if (!isScatter) {
7400     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7401         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7402         VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
7403     ST =
7404         DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], OpValues[1],
7405                        OpValues[2], OpValues[3], MMO, false /* IsTruncating */);
7406   } else {
7407     unsigned AS =
7408         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7409     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7410         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7411         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7412     SDValue Base, Index, Scale;
7413     ISD::MemIndexType IndexType;
7414     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7415                                       this, VPIntrin.getParent());
7416     if (!UniformBase) {
7417       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7418       Index = getValue(PtrOperand);
7419       IndexType = ISD::SIGNED_UNSCALED;
7420       Scale =
7421           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7422     }
7423     EVT IdxVT = Index.getValueType();
7424     EVT EltTy = IdxVT.getVectorElementType();
7425     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7426       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7427       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7428     }
7429     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7430                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7431                            OpValues[2], OpValues[3]},
7432                           MMO, IndexType);
7433   }
7434   DAG.setRoot(ST);
7435   setValue(&VPIntrin, ST);
7436 }
7437 
7438 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7439     const VPIntrinsic &VPIntrin) {
7440   SDLoc DL = getCurSDLoc();
7441   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7442 
7443   SmallVector<EVT, 4> ValueVTs;
7444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7445   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7446   SDVTList VTs = DAG.getVTList(ValueVTs);
7447 
7448   auto EVLParamPos =
7449       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7450 
7451   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7452   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7453          "Unexpected target EVL type");
7454 
7455   // Request operands.
7456   SmallVector<SDValue, 7> OpValues;
7457   for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) {
7458     auto Op = getValue(VPIntrin.getArgOperand(I));
7459     if (I == EVLParamPos)
7460       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7461     OpValues.push_back(Op);
7462   }
7463 
7464   switch (Opcode) {
7465   default: {
7466     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7467     setValue(&VPIntrin, Result);
7468     break;
7469   }
7470   case ISD::VP_LOAD:
7471   case ISD::VP_GATHER:
7472     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7473                       Opcode == ISD::VP_GATHER);
7474     break;
7475   case ISD::VP_STORE:
7476   case ISD::VP_SCATTER:
7477     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7478     break;
7479   }
7480 }
7481 
7482 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7483                                           const BasicBlock *EHPadBB,
7484                                           MCSymbol *&BeginLabel) {
7485   MachineFunction &MF = DAG.getMachineFunction();
7486   MachineModuleInfo &MMI = MF.getMMI();
7487 
7488   // Insert a label before the invoke call to mark the try range.  This can be
7489   // used to detect deletion of the invoke via the MachineModuleInfo.
7490   BeginLabel = MMI.getContext().createTempSymbol();
7491 
7492   // For SjLj, keep track of which landing pads go with which invokes
7493   // so as to maintain the ordering of pads in the LSDA.
7494   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7495   if (CallSiteIndex) {
7496     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7497     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7498 
7499     // Now that the call site is handled, stop tracking it.
7500     MMI.setCurrentCallSite(0);
7501   }
7502 
7503   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7504 }
7505 
7506 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7507                                         const BasicBlock *EHPadBB,
7508                                         MCSymbol *BeginLabel) {
7509   assert(BeginLabel && "BeginLabel should've been set");
7510 
7511   MachineFunction &MF = DAG.getMachineFunction();
7512   MachineModuleInfo &MMI = MF.getMMI();
7513 
7514   // Insert a label at the end of the invoke call to mark the try range.  This
7515   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7516   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7517   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7518 
7519   // Inform MachineModuleInfo of range.
7520   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7521   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7522   // actually use outlined funclets and their LSDA info style.
7523   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7524     assert(II && "II should've been set");
7525     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7526     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7527   } else if (!isScopedEHPersonality(Pers)) {
7528     assert(EHPadBB);
7529     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7530   }
7531 
7532   return Chain;
7533 }
7534 
7535 std::pair<SDValue, SDValue>
7536 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7537                                     const BasicBlock *EHPadBB) {
7538   MCSymbol *BeginLabel = nullptr;
7539 
7540   if (EHPadBB) {
7541     // Both PendingLoads and PendingExports must be flushed here;
7542     // this call might not return.
7543     (void)getRoot();
7544     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7545     CLI.setChain(getRoot());
7546   }
7547 
7548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7549   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7550 
7551   assert((CLI.IsTailCall || Result.second.getNode()) &&
7552          "Non-null chain expected with non-tail call!");
7553   assert((Result.second.getNode() || !Result.first.getNode()) &&
7554          "Null value expected with tail call!");
7555 
7556   if (!Result.second.getNode()) {
7557     // As a special case, a null chain means that a tail call has been emitted
7558     // and the DAG root is already updated.
7559     HasTailCall = true;
7560 
7561     // Since there's no actual continuation from this block, nothing can be
7562     // relying on us setting vregs for them.
7563     PendingExports.clear();
7564   } else {
7565     DAG.setRoot(Result.second);
7566   }
7567 
7568   if (EHPadBB) {
7569     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7570                            BeginLabel));
7571   }
7572 
7573   return Result;
7574 }
7575 
7576 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7577                                       bool isTailCall,
7578                                       bool isMustTailCall,
7579                                       const BasicBlock *EHPadBB) {
7580   auto &DL = DAG.getDataLayout();
7581   FunctionType *FTy = CB.getFunctionType();
7582   Type *RetTy = CB.getType();
7583 
7584   TargetLowering::ArgListTy Args;
7585   Args.reserve(CB.arg_size());
7586 
7587   const Value *SwiftErrorVal = nullptr;
7588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7589 
7590   if (isTailCall) {
7591     // Avoid emitting tail calls in functions with the disable-tail-calls
7592     // attribute.
7593     auto *Caller = CB.getParent()->getParent();
7594     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7595         "true" && !isMustTailCall)
7596       isTailCall = false;
7597 
7598     // We can't tail call inside a function with a swifterror argument. Lowering
7599     // does not support this yet. It would have to move into the swifterror
7600     // register before the call.
7601     if (TLI.supportSwiftError() &&
7602         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7603       isTailCall = false;
7604   }
7605 
7606   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7607     TargetLowering::ArgListEntry Entry;
7608     const Value *V = *I;
7609 
7610     // Skip empty types
7611     if (V->getType()->isEmptyTy())
7612       continue;
7613 
7614     SDValue ArgNode = getValue(V);
7615     Entry.Node = ArgNode; Entry.Ty = V->getType();
7616 
7617     Entry.setAttributes(&CB, I - CB.arg_begin());
7618 
7619     // Use swifterror virtual register as input to the call.
7620     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7621       SwiftErrorVal = V;
7622       // We find the virtual register for the actual swifterror argument.
7623       // Instead of using the Value, we use the virtual register instead.
7624       Entry.Node =
7625           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7626                           EVT(TLI.getPointerTy(DL)));
7627     }
7628 
7629     Args.push_back(Entry);
7630 
7631     // If we have an explicit sret argument that is an Instruction, (i.e., it
7632     // might point to function-local memory), we can't meaningfully tail-call.
7633     if (Entry.IsSRet && isa<Instruction>(V))
7634       isTailCall = false;
7635   }
7636 
7637   // If call site has a cfguardtarget operand bundle, create and add an
7638   // additional ArgListEntry.
7639   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7640     TargetLowering::ArgListEntry Entry;
7641     Value *V = Bundle->Inputs[0];
7642     SDValue ArgNode = getValue(V);
7643     Entry.Node = ArgNode;
7644     Entry.Ty = V->getType();
7645     Entry.IsCFGuardTarget = true;
7646     Args.push_back(Entry);
7647   }
7648 
7649   // Check if target-independent constraints permit a tail call here.
7650   // Target-dependent constraints are checked within TLI->LowerCallTo.
7651   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7652     isTailCall = false;
7653 
7654   // Disable tail calls if there is an swifterror argument. Targets have not
7655   // been updated to support tail calls.
7656   if (TLI.supportSwiftError() && SwiftErrorVal)
7657     isTailCall = false;
7658 
7659   TargetLowering::CallLoweringInfo CLI(DAG);
7660   CLI.setDebugLoc(getCurSDLoc())
7661       .setChain(getRoot())
7662       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7663       .setTailCall(isTailCall)
7664       .setConvergent(CB.isConvergent())
7665       .setIsPreallocated(
7666           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7667   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7668 
7669   if (Result.first.getNode()) {
7670     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7671     setValue(&CB, Result.first);
7672   }
7673 
7674   // The last element of CLI.InVals has the SDValue for swifterror return.
7675   // Here we copy it to a virtual register and update SwiftErrorMap for
7676   // book-keeping.
7677   if (SwiftErrorVal && TLI.supportSwiftError()) {
7678     // Get the last element of InVals.
7679     SDValue Src = CLI.InVals.back();
7680     Register VReg =
7681         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7682     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7683     DAG.setRoot(CopyNode);
7684   }
7685 }
7686 
7687 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7688                              SelectionDAGBuilder &Builder) {
7689   // Check to see if this load can be trivially constant folded, e.g. if the
7690   // input is from a string literal.
7691   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7692     // Cast pointer to the type we really want to load.
7693     Type *LoadTy =
7694         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7695     if (LoadVT.isVector())
7696       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7697 
7698     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7699                                          PointerType::getUnqual(LoadTy));
7700 
7701     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7702             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7703       return Builder.getValue(LoadCst);
7704   }
7705 
7706   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7707   // still constant memory, the input chain can be the entry node.
7708   SDValue Root;
7709   bool ConstantMemory = false;
7710 
7711   // Do not serialize (non-volatile) loads of constant memory with anything.
7712   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7713     Root = Builder.DAG.getEntryNode();
7714     ConstantMemory = true;
7715   } else {
7716     // Do not serialize non-volatile loads against each other.
7717     Root = Builder.DAG.getRoot();
7718   }
7719 
7720   SDValue Ptr = Builder.getValue(PtrVal);
7721   SDValue LoadVal =
7722       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7723                           MachinePointerInfo(PtrVal), Align(1));
7724 
7725   if (!ConstantMemory)
7726     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7727   return LoadVal;
7728 }
7729 
7730 /// Record the value for an instruction that produces an integer result,
7731 /// converting the type where necessary.
7732 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7733                                                   SDValue Value,
7734                                                   bool IsSigned) {
7735   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7736                                                     I.getType(), true);
7737   if (IsSigned)
7738     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7739   else
7740     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7741   setValue(&I, Value);
7742 }
7743 
7744 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7745 /// true and lower it. Otherwise return false, and it will be lowered like a
7746 /// normal call.
7747 /// The caller already checked that \p I calls the appropriate LibFunc with a
7748 /// correct prototype.
7749 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7750   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7751   const Value *Size = I.getArgOperand(2);
7752   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7753   if (CSize && CSize->getZExtValue() == 0) {
7754     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7755                                                           I.getType(), true);
7756     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7757     return true;
7758   }
7759 
7760   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7761   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7762       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7763       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7764   if (Res.first.getNode()) {
7765     processIntegerCallValue(I, Res.first, true);
7766     PendingLoads.push_back(Res.second);
7767     return true;
7768   }
7769 
7770   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7771   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7772   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7773     return false;
7774 
7775   // If the target has a fast compare for the given size, it will return a
7776   // preferred load type for that size. Require that the load VT is legal and
7777   // that the target supports unaligned loads of that type. Otherwise, return
7778   // INVALID.
7779   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7780     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7781     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7782     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7783       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7784       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7785       // TODO: Check alignment of src and dest ptrs.
7786       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7787       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7788       if (!TLI.isTypeLegal(LVT) ||
7789           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7790           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7791         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7792     }
7793 
7794     return LVT;
7795   };
7796 
7797   // This turns into unaligned loads. We only do this if the target natively
7798   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7799   // we'll only produce a small number of byte loads.
7800   MVT LoadVT;
7801   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7802   switch (NumBitsToCompare) {
7803   default:
7804     return false;
7805   case 16:
7806     LoadVT = MVT::i16;
7807     break;
7808   case 32:
7809     LoadVT = MVT::i32;
7810     break;
7811   case 64:
7812   case 128:
7813   case 256:
7814     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7815     break;
7816   }
7817 
7818   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7819     return false;
7820 
7821   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7822   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7823 
7824   // Bitcast to a wide integer type if the loads are vectors.
7825   if (LoadVT.isVector()) {
7826     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7827     LoadL = DAG.getBitcast(CmpVT, LoadL);
7828     LoadR = DAG.getBitcast(CmpVT, LoadR);
7829   }
7830 
7831   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7832   processIntegerCallValue(I, Cmp, false);
7833   return true;
7834 }
7835 
7836 /// See if we can lower a memchr call into an optimized form. If so, return
7837 /// true and lower it. Otherwise return false, and it will be lowered like a
7838 /// normal call.
7839 /// The caller already checked that \p I calls the appropriate LibFunc with a
7840 /// correct prototype.
7841 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7842   const Value *Src = I.getArgOperand(0);
7843   const Value *Char = I.getArgOperand(1);
7844   const Value *Length = I.getArgOperand(2);
7845 
7846   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7847   std::pair<SDValue, SDValue> Res =
7848     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7849                                 getValue(Src), getValue(Char), getValue(Length),
7850                                 MachinePointerInfo(Src));
7851   if (Res.first.getNode()) {
7852     setValue(&I, Res.first);
7853     PendingLoads.push_back(Res.second);
7854     return true;
7855   }
7856 
7857   return false;
7858 }
7859 
7860 /// See if we can lower a mempcpy call into an optimized form. If so, return
7861 /// true and lower it. Otherwise return false, and it will be lowered like a
7862 /// normal call.
7863 /// The caller already checked that \p I calls the appropriate LibFunc with a
7864 /// correct prototype.
7865 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7866   SDValue Dst = getValue(I.getArgOperand(0));
7867   SDValue Src = getValue(I.getArgOperand(1));
7868   SDValue Size = getValue(I.getArgOperand(2));
7869 
7870   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7871   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7872   // DAG::getMemcpy needs Alignment to be defined.
7873   Align Alignment = std::min(DstAlign, SrcAlign);
7874 
7875   bool isVol = false;
7876   SDLoc sdl = getCurSDLoc();
7877 
7878   // In the mempcpy context we need to pass in a false value for isTailCall
7879   // because the return pointer needs to be adjusted by the size of
7880   // the copied memory.
7881   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7882   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7883                              /*isTailCall=*/false,
7884                              MachinePointerInfo(I.getArgOperand(0)),
7885                              MachinePointerInfo(I.getArgOperand(1)),
7886                              I.getAAMetadata());
7887   assert(MC.getNode() != nullptr &&
7888          "** memcpy should not be lowered as TailCall in mempcpy context **");
7889   DAG.setRoot(MC);
7890 
7891   // Check if Size needs to be truncated or extended.
7892   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7893 
7894   // Adjust return pointer to point just past the last dst byte.
7895   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7896                                     Dst, Size);
7897   setValue(&I, DstPlusSize);
7898   return true;
7899 }
7900 
7901 /// See if we can lower a strcpy call into an optimized form.  If so, return
7902 /// true and lower it, otherwise return false and it will be lowered like a
7903 /// normal call.
7904 /// The caller already checked that \p I calls the appropriate LibFunc with a
7905 /// correct prototype.
7906 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7907   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7908 
7909   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7910   std::pair<SDValue, SDValue> Res =
7911     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7912                                 getValue(Arg0), getValue(Arg1),
7913                                 MachinePointerInfo(Arg0),
7914                                 MachinePointerInfo(Arg1), isStpcpy);
7915   if (Res.first.getNode()) {
7916     setValue(&I, Res.first);
7917     DAG.setRoot(Res.second);
7918     return true;
7919   }
7920 
7921   return false;
7922 }
7923 
7924 /// See if we can lower a strcmp call into an optimized form.  If so, return
7925 /// true and lower it, otherwise return false and it will be lowered like a
7926 /// normal call.
7927 /// The caller already checked that \p I calls the appropriate LibFunc with a
7928 /// correct prototype.
7929 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7930   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7931 
7932   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7933   std::pair<SDValue, SDValue> Res =
7934     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7935                                 getValue(Arg0), getValue(Arg1),
7936                                 MachinePointerInfo(Arg0),
7937                                 MachinePointerInfo(Arg1));
7938   if (Res.first.getNode()) {
7939     processIntegerCallValue(I, Res.first, true);
7940     PendingLoads.push_back(Res.second);
7941     return true;
7942   }
7943 
7944   return false;
7945 }
7946 
7947 /// See if we can lower a strlen call into an optimized form.  If so, return
7948 /// true and lower it, otherwise return false and it will be lowered like a
7949 /// normal call.
7950 /// The caller already checked that \p I calls the appropriate LibFunc with a
7951 /// correct prototype.
7952 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7953   const Value *Arg0 = I.getArgOperand(0);
7954 
7955   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7956   std::pair<SDValue, SDValue> Res =
7957     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7958                                 getValue(Arg0), MachinePointerInfo(Arg0));
7959   if (Res.first.getNode()) {
7960     processIntegerCallValue(I, Res.first, false);
7961     PendingLoads.push_back(Res.second);
7962     return true;
7963   }
7964 
7965   return false;
7966 }
7967 
7968 /// See if we can lower a strnlen call into an optimized form.  If so, return
7969 /// true and lower it, otherwise return false and it will be lowered like a
7970 /// normal call.
7971 /// The caller already checked that \p I calls the appropriate LibFunc with a
7972 /// correct prototype.
7973 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7974   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7975 
7976   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7977   std::pair<SDValue, SDValue> Res =
7978     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7979                                  getValue(Arg0), getValue(Arg1),
7980                                  MachinePointerInfo(Arg0));
7981   if (Res.first.getNode()) {
7982     processIntegerCallValue(I, Res.first, false);
7983     PendingLoads.push_back(Res.second);
7984     return true;
7985   }
7986 
7987   return false;
7988 }
7989 
7990 /// See if we can lower a unary floating-point operation into an SDNode with
7991 /// the specified Opcode.  If so, return true and lower it, otherwise return
7992 /// false and it will be lowered like a normal call.
7993 /// The caller already checked that \p I calls the appropriate LibFunc with a
7994 /// correct prototype.
7995 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7996                                               unsigned Opcode) {
7997   // We already checked this call's prototype; verify it doesn't modify errno.
7998   if (!I.onlyReadsMemory())
7999     return false;
8000 
8001   SDNodeFlags Flags;
8002   Flags.copyFMF(cast<FPMathOperator>(I));
8003 
8004   SDValue Tmp = getValue(I.getArgOperand(0));
8005   setValue(&I,
8006            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8007   return true;
8008 }
8009 
8010 /// See if we can lower a binary floating-point operation into an SDNode with
8011 /// the specified Opcode. If so, return true and lower it. Otherwise return
8012 /// false, and it will be lowered like a normal call.
8013 /// The caller already checked that \p I calls the appropriate LibFunc with a
8014 /// correct prototype.
8015 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8016                                                unsigned Opcode) {
8017   // We already checked this call's prototype; verify it doesn't modify errno.
8018   if (!I.onlyReadsMemory())
8019     return false;
8020 
8021   SDNodeFlags Flags;
8022   Flags.copyFMF(cast<FPMathOperator>(I));
8023 
8024   SDValue Tmp0 = getValue(I.getArgOperand(0));
8025   SDValue Tmp1 = getValue(I.getArgOperand(1));
8026   EVT VT = Tmp0.getValueType();
8027   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8028   return true;
8029 }
8030 
8031 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8032   // Handle inline assembly differently.
8033   if (I.isInlineAsm()) {
8034     visitInlineAsm(I);
8035     return;
8036   }
8037 
8038   if (Function *F = I.getCalledFunction()) {
8039     diagnoseDontCall(I);
8040 
8041     if (F->isDeclaration()) {
8042       // Is this an LLVM intrinsic or a target-specific intrinsic?
8043       unsigned IID = F->getIntrinsicID();
8044       if (!IID)
8045         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8046           IID = II->getIntrinsicID(F);
8047 
8048       if (IID) {
8049         visitIntrinsicCall(I, IID);
8050         return;
8051       }
8052     }
8053 
8054     // Check for well-known libc/libm calls.  If the function is internal, it
8055     // can't be a library call.  Don't do the check if marked as nobuiltin for
8056     // some reason or the call site requires strict floating point semantics.
8057     LibFunc Func;
8058     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8059         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8060         LibInfo->hasOptimizedCodeGen(Func)) {
8061       switch (Func) {
8062       default: break;
8063       case LibFunc_bcmp:
8064         if (visitMemCmpBCmpCall(I))
8065           return;
8066         break;
8067       case LibFunc_copysign:
8068       case LibFunc_copysignf:
8069       case LibFunc_copysignl:
8070         // We already checked this call's prototype; verify it doesn't modify
8071         // errno.
8072         if (I.onlyReadsMemory()) {
8073           SDValue LHS = getValue(I.getArgOperand(0));
8074           SDValue RHS = getValue(I.getArgOperand(1));
8075           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8076                                    LHS.getValueType(), LHS, RHS));
8077           return;
8078         }
8079         break;
8080       case LibFunc_fabs:
8081       case LibFunc_fabsf:
8082       case LibFunc_fabsl:
8083         if (visitUnaryFloatCall(I, ISD::FABS))
8084           return;
8085         break;
8086       case LibFunc_fmin:
8087       case LibFunc_fminf:
8088       case LibFunc_fminl:
8089         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8090           return;
8091         break;
8092       case LibFunc_fmax:
8093       case LibFunc_fmaxf:
8094       case LibFunc_fmaxl:
8095         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8096           return;
8097         break;
8098       case LibFunc_sin:
8099       case LibFunc_sinf:
8100       case LibFunc_sinl:
8101         if (visitUnaryFloatCall(I, ISD::FSIN))
8102           return;
8103         break;
8104       case LibFunc_cos:
8105       case LibFunc_cosf:
8106       case LibFunc_cosl:
8107         if (visitUnaryFloatCall(I, ISD::FCOS))
8108           return;
8109         break;
8110       case LibFunc_sqrt:
8111       case LibFunc_sqrtf:
8112       case LibFunc_sqrtl:
8113       case LibFunc_sqrt_finite:
8114       case LibFunc_sqrtf_finite:
8115       case LibFunc_sqrtl_finite:
8116         if (visitUnaryFloatCall(I, ISD::FSQRT))
8117           return;
8118         break;
8119       case LibFunc_floor:
8120       case LibFunc_floorf:
8121       case LibFunc_floorl:
8122         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8123           return;
8124         break;
8125       case LibFunc_nearbyint:
8126       case LibFunc_nearbyintf:
8127       case LibFunc_nearbyintl:
8128         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8129           return;
8130         break;
8131       case LibFunc_ceil:
8132       case LibFunc_ceilf:
8133       case LibFunc_ceill:
8134         if (visitUnaryFloatCall(I, ISD::FCEIL))
8135           return;
8136         break;
8137       case LibFunc_rint:
8138       case LibFunc_rintf:
8139       case LibFunc_rintl:
8140         if (visitUnaryFloatCall(I, ISD::FRINT))
8141           return;
8142         break;
8143       case LibFunc_round:
8144       case LibFunc_roundf:
8145       case LibFunc_roundl:
8146         if (visitUnaryFloatCall(I, ISD::FROUND))
8147           return;
8148         break;
8149       case LibFunc_trunc:
8150       case LibFunc_truncf:
8151       case LibFunc_truncl:
8152         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8153           return;
8154         break;
8155       case LibFunc_log2:
8156       case LibFunc_log2f:
8157       case LibFunc_log2l:
8158         if (visitUnaryFloatCall(I, ISD::FLOG2))
8159           return;
8160         break;
8161       case LibFunc_exp2:
8162       case LibFunc_exp2f:
8163       case LibFunc_exp2l:
8164         if (visitUnaryFloatCall(I, ISD::FEXP2))
8165           return;
8166         break;
8167       case LibFunc_memcmp:
8168         if (visitMemCmpBCmpCall(I))
8169           return;
8170         break;
8171       case LibFunc_mempcpy:
8172         if (visitMemPCpyCall(I))
8173           return;
8174         break;
8175       case LibFunc_memchr:
8176         if (visitMemChrCall(I))
8177           return;
8178         break;
8179       case LibFunc_strcpy:
8180         if (visitStrCpyCall(I, false))
8181           return;
8182         break;
8183       case LibFunc_stpcpy:
8184         if (visitStrCpyCall(I, true))
8185           return;
8186         break;
8187       case LibFunc_strcmp:
8188         if (visitStrCmpCall(I))
8189           return;
8190         break;
8191       case LibFunc_strlen:
8192         if (visitStrLenCall(I))
8193           return;
8194         break;
8195       case LibFunc_strnlen:
8196         if (visitStrNLenCall(I))
8197           return;
8198         break;
8199       }
8200     }
8201   }
8202 
8203   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8204   // have to do anything here to lower funclet bundles.
8205   // CFGuardTarget bundles are lowered in LowerCallTo.
8206   assert(!I.hasOperandBundlesOtherThan(
8207              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8208               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8209               LLVMContext::OB_clang_arc_attachedcall}) &&
8210          "Cannot lower calls with arbitrary operand bundles!");
8211 
8212   SDValue Callee = getValue(I.getCalledOperand());
8213 
8214   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8215     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8216   else
8217     // Check if we can potentially perform a tail call. More detailed checking
8218     // is be done within LowerCallTo, after more information about the call is
8219     // known.
8220     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8221 }
8222 
8223 namespace {
8224 
8225 /// AsmOperandInfo - This contains information for each constraint that we are
8226 /// lowering.
8227 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8228 public:
8229   /// CallOperand - If this is the result output operand or a clobber
8230   /// this is null, otherwise it is the incoming operand to the CallInst.
8231   /// This gets modified as the asm is processed.
8232   SDValue CallOperand;
8233 
8234   /// AssignedRegs - If this is a register or register class operand, this
8235   /// contains the set of register corresponding to the operand.
8236   RegsForValue AssignedRegs;
8237 
8238   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8239     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8240   }
8241 
8242   /// Whether or not this operand accesses memory
8243   bool hasMemory(const TargetLowering &TLI) const {
8244     // Indirect operand accesses access memory.
8245     if (isIndirect)
8246       return true;
8247 
8248     for (const auto &Code : Codes)
8249       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8250         return true;
8251 
8252     return false;
8253   }
8254 
8255   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8256   /// corresponds to.  If there is no Value* for this operand, it returns
8257   /// MVT::Other.
8258   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8259                            const DataLayout &DL) const {
8260     if (!CallOperandVal) return MVT::Other;
8261 
8262     if (isa<BasicBlock>(CallOperandVal))
8263       return TLI.getProgramPointerTy(DL);
8264 
8265     llvm::Type *OpTy = CallOperandVal->getType();
8266 
8267     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8268     // If this is an indirect operand, the operand is a pointer to the
8269     // accessed type.
8270     if (isIndirect) {
8271       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8272       if (!PtrTy)
8273         report_fatal_error("Indirect operand for inline asm not a pointer!");
8274       OpTy = PtrTy->getElementType();
8275     }
8276 
8277     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8278     if (StructType *STy = dyn_cast<StructType>(OpTy))
8279       if (STy->getNumElements() == 1)
8280         OpTy = STy->getElementType(0);
8281 
8282     // If OpTy is not a single value, it may be a struct/union that we
8283     // can tile with integers.
8284     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8285       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8286       switch (BitSize) {
8287       default: break;
8288       case 1:
8289       case 8:
8290       case 16:
8291       case 32:
8292       case 64:
8293       case 128:
8294         OpTy = IntegerType::get(Context, BitSize);
8295         break;
8296       }
8297     }
8298 
8299     return TLI.getAsmOperandValueType(DL, OpTy, true);
8300   }
8301 };
8302 
8303 
8304 } // end anonymous namespace
8305 
8306 /// Make sure that the output operand \p OpInfo and its corresponding input
8307 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8308 /// out).
8309 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8310                                SDISelAsmOperandInfo &MatchingOpInfo,
8311                                SelectionDAG &DAG) {
8312   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8313     return;
8314 
8315   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8316   const auto &TLI = DAG.getTargetLoweringInfo();
8317 
8318   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8319       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8320                                        OpInfo.ConstraintVT);
8321   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8322       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8323                                        MatchingOpInfo.ConstraintVT);
8324   if ((OpInfo.ConstraintVT.isInteger() !=
8325        MatchingOpInfo.ConstraintVT.isInteger()) ||
8326       (MatchRC.second != InputRC.second)) {
8327     // FIXME: error out in a more elegant fashion
8328     report_fatal_error("Unsupported asm: input constraint"
8329                        " with a matching output constraint of"
8330                        " incompatible type!");
8331   }
8332   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8333 }
8334 
8335 /// Get a direct memory input to behave well as an indirect operand.
8336 /// This may introduce stores, hence the need for a \p Chain.
8337 /// \return The (possibly updated) chain.
8338 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8339                                         SDISelAsmOperandInfo &OpInfo,
8340                                         SelectionDAG &DAG) {
8341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8342 
8343   // If we don't have an indirect input, put it in the constpool if we can,
8344   // otherwise spill it to a stack slot.
8345   // TODO: This isn't quite right. We need to handle these according to
8346   // the addressing mode that the constraint wants. Also, this may take
8347   // an additional register for the computation and we don't want that
8348   // either.
8349 
8350   // If the operand is a float, integer, or vector constant, spill to a
8351   // constant pool entry to get its address.
8352   const Value *OpVal = OpInfo.CallOperandVal;
8353   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8354       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8355     OpInfo.CallOperand = DAG.getConstantPool(
8356         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8357     return Chain;
8358   }
8359 
8360   // Otherwise, create a stack slot and emit a store to it before the asm.
8361   Type *Ty = OpVal->getType();
8362   auto &DL = DAG.getDataLayout();
8363   uint64_t TySize = DL.getTypeAllocSize(Ty);
8364   MachineFunction &MF = DAG.getMachineFunction();
8365   int SSFI = MF.getFrameInfo().CreateStackObject(
8366       TySize, DL.getPrefTypeAlign(Ty), false);
8367   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8368   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8369                             MachinePointerInfo::getFixedStack(MF, SSFI),
8370                             TLI.getMemValueType(DL, Ty));
8371   OpInfo.CallOperand = StackSlot;
8372 
8373   return Chain;
8374 }
8375 
8376 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8377 /// specified operand.  We prefer to assign virtual registers, to allow the
8378 /// register allocator to handle the assignment process.  However, if the asm
8379 /// uses features that we can't model on machineinstrs, we have SDISel do the
8380 /// allocation.  This produces generally horrible, but correct, code.
8381 ///
8382 ///   OpInfo describes the operand
8383 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8384 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8385                                  SDISelAsmOperandInfo &OpInfo,
8386                                  SDISelAsmOperandInfo &RefOpInfo) {
8387   LLVMContext &Context = *DAG.getContext();
8388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8389 
8390   MachineFunction &MF = DAG.getMachineFunction();
8391   SmallVector<unsigned, 4> Regs;
8392   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8393 
8394   // No work to do for memory operations.
8395   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8396     return;
8397 
8398   // If this is a constraint for a single physreg, or a constraint for a
8399   // register class, find it.
8400   unsigned AssignedReg;
8401   const TargetRegisterClass *RC;
8402   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8403       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8404   // RC is unset only on failure. Return immediately.
8405   if (!RC)
8406     return;
8407 
8408   // Get the actual register value type.  This is important, because the user
8409   // may have asked for (e.g.) the AX register in i32 type.  We need to
8410   // remember that AX is actually i16 to get the right extension.
8411   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8412 
8413   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8414     // If this is an FP operand in an integer register (or visa versa), or more
8415     // generally if the operand value disagrees with the register class we plan
8416     // to stick it in, fix the operand type.
8417     //
8418     // If this is an input value, the bitcast to the new type is done now.
8419     // Bitcast for output value is done at the end of visitInlineAsm().
8420     if ((OpInfo.Type == InlineAsm::isOutput ||
8421          OpInfo.Type == InlineAsm::isInput) &&
8422         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8423       // Try to convert to the first EVT that the reg class contains.  If the
8424       // types are identical size, use a bitcast to convert (e.g. two differing
8425       // vector types).  Note: output bitcast is done at the end of
8426       // visitInlineAsm().
8427       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8428         // Exclude indirect inputs while they are unsupported because the code
8429         // to perform the load is missing and thus OpInfo.CallOperand still
8430         // refers to the input address rather than the pointed-to value.
8431         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8432           OpInfo.CallOperand =
8433               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8434         OpInfo.ConstraintVT = RegVT;
8435         // If the operand is an FP value and we want it in integer registers,
8436         // use the corresponding integer type. This turns an f64 value into
8437         // i64, which can be passed with two i32 values on a 32-bit machine.
8438       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8439         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8440         if (OpInfo.Type == InlineAsm::isInput)
8441           OpInfo.CallOperand =
8442               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8443         OpInfo.ConstraintVT = VT;
8444       }
8445     }
8446   }
8447 
8448   // No need to allocate a matching input constraint since the constraint it's
8449   // matching to has already been allocated.
8450   if (OpInfo.isMatchingInputConstraint())
8451     return;
8452 
8453   EVT ValueVT = OpInfo.ConstraintVT;
8454   if (OpInfo.ConstraintVT == MVT::Other)
8455     ValueVT = RegVT;
8456 
8457   // Initialize NumRegs.
8458   unsigned NumRegs = 1;
8459   if (OpInfo.ConstraintVT != MVT::Other)
8460     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8461 
8462   // If this is a constraint for a specific physical register, like {r17},
8463   // assign it now.
8464 
8465   // If this associated to a specific register, initialize iterator to correct
8466   // place. If virtual, make sure we have enough registers
8467 
8468   // Initialize iterator if necessary
8469   TargetRegisterClass::iterator I = RC->begin();
8470   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8471 
8472   // Do not check for single registers.
8473   if (AssignedReg) {
8474       for (; *I != AssignedReg; ++I)
8475         assert(I != RC->end() && "AssignedReg should be member of RC");
8476   }
8477 
8478   for (; NumRegs; --NumRegs, ++I) {
8479     assert(I != RC->end() && "Ran out of registers to allocate!");
8480     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8481     Regs.push_back(R);
8482   }
8483 
8484   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8485 }
8486 
8487 static unsigned
8488 findMatchingInlineAsmOperand(unsigned OperandNo,
8489                              const std::vector<SDValue> &AsmNodeOperands) {
8490   // Scan until we find the definition we already emitted of this operand.
8491   unsigned CurOp = InlineAsm::Op_FirstOperand;
8492   for (; OperandNo; --OperandNo) {
8493     // Advance to the next operand.
8494     unsigned OpFlag =
8495         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8496     assert((InlineAsm::isRegDefKind(OpFlag) ||
8497             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8498             InlineAsm::isMemKind(OpFlag)) &&
8499            "Skipped past definitions?");
8500     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8501   }
8502   return CurOp;
8503 }
8504 
8505 namespace {
8506 
8507 class ExtraFlags {
8508   unsigned Flags = 0;
8509 
8510 public:
8511   explicit ExtraFlags(const CallBase &Call) {
8512     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8513     if (IA->hasSideEffects())
8514       Flags |= InlineAsm::Extra_HasSideEffects;
8515     if (IA->isAlignStack())
8516       Flags |= InlineAsm::Extra_IsAlignStack;
8517     if (Call.isConvergent())
8518       Flags |= InlineAsm::Extra_IsConvergent;
8519     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8520   }
8521 
8522   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8523     // Ideally, we would only check against memory constraints.  However, the
8524     // meaning of an Other constraint can be target-specific and we can't easily
8525     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8526     // for Other constraints as well.
8527     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8528         OpInfo.ConstraintType == TargetLowering::C_Other) {
8529       if (OpInfo.Type == InlineAsm::isInput)
8530         Flags |= InlineAsm::Extra_MayLoad;
8531       else if (OpInfo.Type == InlineAsm::isOutput)
8532         Flags |= InlineAsm::Extra_MayStore;
8533       else if (OpInfo.Type == InlineAsm::isClobber)
8534         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8535     }
8536   }
8537 
8538   unsigned get() const { return Flags; }
8539 };
8540 
8541 } // end anonymous namespace
8542 
8543 /// visitInlineAsm - Handle a call to an InlineAsm object.
8544 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8545                                          const BasicBlock *EHPadBB) {
8546   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8547 
8548   /// ConstraintOperands - Information about all of the constraints.
8549   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8550 
8551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8552   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8553       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8554 
8555   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8556   // AsmDialect, MayLoad, MayStore).
8557   bool HasSideEffect = IA->hasSideEffects();
8558   ExtraFlags ExtraInfo(Call);
8559 
8560   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8561   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8562   unsigned NumMatchingOps = 0;
8563   for (auto &T : TargetConstraints) {
8564     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8565     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8566 
8567     // Compute the value type for each operand.
8568     if (OpInfo.Type == InlineAsm::isInput ||
8569         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8570       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8571 
8572       // Process the call argument. BasicBlocks are labels, currently appearing
8573       // only in asm's.
8574       if (isa<CallBrInst>(Call) &&
8575           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8576                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8577                         NumMatchingOps) &&
8578           (NumMatchingOps == 0 ||
8579            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8580                         NumMatchingOps))) {
8581         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8582         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8583         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8584       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8585         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8586       } else {
8587         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8588       }
8589 
8590       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8591                                            DAG.getDataLayout());
8592       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8593     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8594       // The return value of the call is this value.  As such, there is no
8595       // corresponding argument.
8596       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8597       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8598         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8599             DAG.getDataLayout(), STy->getElementType(ResNo));
8600       } else {
8601         assert(ResNo == 0 && "Asm only has one result!");
8602         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8603             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8604       }
8605       ++ResNo;
8606     } else {
8607       OpInfo.ConstraintVT = MVT::Other;
8608     }
8609 
8610     if (OpInfo.hasMatchingInput())
8611       ++NumMatchingOps;
8612 
8613     if (!HasSideEffect)
8614       HasSideEffect = OpInfo.hasMemory(TLI);
8615 
8616     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8617     // FIXME: Could we compute this on OpInfo rather than T?
8618 
8619     // Compute the constraint code and ConstraintType to use.
8620     TLI.ComputeConstraintToUse(T, SDValue());
8621 
8622     if (T.ConstraintType == TargetLowering::C_Immediate &&
8623         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8624       // We've delayed emitting a diagnostic like the "n" constraint because
8625       // inlining could cause an integer showing up.
8626       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8627                                           "' expects an integer constant "
8628                                           "expression");
8629 
8630     ExtraInfo.update(T);
8631   }
8632 
8633   // We won't need to flush pending loads if this asm doesn't touch
8634   // memory and is nonvolatile.
8635   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8636 
8637   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8638   if (EmitEHLabels) {
8639     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8640   }
8641   bool IsCallBr = isa<CallBrInst>(Call);
8642 
8643   if (IsCallBr || EmitEHLabels) {
8644     // If this is a callbr or invoke we need to flush pending exports since
8645     // inlineasm_br and invoke are terminators.
8646     // We need to do this before nodes are glued to the inlineasm_br node.
8647     Chain = getControlRoot();
8648   }
8649 
8650   MCSymbol *BeginLabel = nullptr;
8651   if (EmitEHLabels) {
8652     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8653   }
8654 
8655   // Second pass over the constraints: compute which constraint option to use.
8656   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8657     // If this is an output operand with a matching input operand, look up the
8658     // matching input. If their types mismatch, e.g. one is an integer, the
8659     // other is floating point, or their sizes are different, flag it as an
8660     // error.
8661     if (OpInfo.hasMatchingInput()) {
8662       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8663       patchMatchingInput(OpInfo, Input, DAG);
8664     }
8665 
8666     // Compute the constraint code and ConstraintType to use.
8667     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8668 
8669     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8670         OpInfo.Type == InlineAsm::isClobber)
8671       continue;
8672 
8673     // If this is a memory input, and if the operand is not indirect, do what we
8674     // need to provide an address for the memory input.
8675     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8676         !OpInfo.isIndirect) {
8677       assert((OpInfo.isMultipleAlternative ||
8678               (OpInfo.Type == InlineAsm::isInput)) &&
8679              "Can only indirectify direct input operands!");
8680 
8681       // Memory operands really want the address of the value.
8682       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8683 
8684       // There is no longer a Value* corresponding to this operand.
8685       OpInfo.CallOperandVal = nullptr;
8686 
8687       // It is now an indirect operand.
8688       OpInfo.isIndirect = true;
8689     }
8690 
8691   }
8692 
8693   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8694   std::vector<SDValue> AsmNodeOperands;
8695   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8696   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8697       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8698 
8699   // If we have a !srcloc metadata node associated with it, we want to attach
8700   // this to the ultimately generated inline asm machineinstr.  To do this, we
8701   // pass in the third operand as this (potentially null) inline asm MDNode.
8702   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8703   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8704 
8705   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8706   // bits as operand 3.
8707   AsmNodeOperands.push_back(DAG.getTargetConstant(
8708       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8709 
8710   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8711   // this, assign virtual and physical registers for inputs and otput.
8712   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8713     // Assign Registers.
8714     SDISelAsmOperandInfo &RefOpInfo =
8715         OpInfo.isMatchingInputConstraint()
8716             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8717             : OpInfo;
8718     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8719 
8720     auto DetectWriteToReservedRegister = [&]() {
8721       const MachineFunction &MF = DAG.getMachineFunction();
8722       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8723       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8724         if (Register::isPhysicalRegister(Reg) &&
8725             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8726           const char *RegName = TRI.getName(Reg);
8727           emitInlineAsmError(Call, "write to reserved register '" +
8728                                        Twine(RegName) + "'");
8729           return true;
8730         }
8731       }
8732       return false;
8733     };
8734 
8735     switch (OpInfo.Type) {
8736     case InlineAsm::isOutput:
8737       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8738         unsigned ConstraintID =
8739             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8740         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8741                "Failed to convert memory constraint code to constraint id.");
8742 
8743         // Add information to the INLINEASM node to know about this output.
8744         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8745         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8746         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8747                                                         MVT::i32));
8748         AsmNodeOperands.push_back(OpInfo.CallOperand);
8749       } else {
8750         // Otherwise, this outputs to a register (directly for C_Register /
8751         // C_RegisterClass, and a target-defined fashion for
8752         // C_Immediate/C_Other). Find a register that we can use.
8753         if (OpInfo.AssignedRegs.Regs.empty()) {
8754           emitInlineAsmError(
8755               Call, "couldn't allocate output register for constraint '" +
8756                         Twine(OpInfo.ConstraintCode) + "'");
8757           return;
8758         }
8759 
8760         if (DetectWriteToReservedRegister())
8761           return;
8762 
8763         // Add information to the INLINEASM node to know that this register is
8764         // set.
8765         OpInfo.AssignedRegs.AddInlineAsmOperands(
8766             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8767                                   : InlineAsm::Kind_RegDef,
8768             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8769       }
8770       break;
8771 
8772     case InlineAsm::isInput: {
8773       SDValue InOperandVal = OpInfo.CallOperand;
8774 
8775       if (OpInfo.isMatchingInputConstraint()) {
8776         // If this is required to match an output register we have already set,
8777         // just use its register.
8778         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8779                                                   AsmNodeOperands);
8780         unsigned OpFlag =
8781           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8782         if (InlineAsm::isRegDefKind(OpFlag) ||
8783             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8784           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8785           if (OpInfo.isIndirect) {
8786             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8787             emitInlineAsmError(Call, "inline asm not supported yet: "
8788                                      "don't know how to handle tied "
8789                                      "indirect register inputs");
8790             return;
8791           }
8792 
8793           SmallVector<unsigned, 4> Regs;
8794           MachineFunction &MF = DAG.getMachineFunction();
8795           MachineRegisterInfo &MRI = MF.getRegInfo();
8796           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8797           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8798           Register TiedReg = R->getReg();
8799           MVT RegVT = R->getSimpleValueType(0);
8800           const TargetRegisterClass *RC =
8801               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8802               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8803                                       : TRI.getMinimalPhysRegClass(TiedReg);
8804           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8805           for (unsigned i = 0; i != NumRegs; ++i)
8806             Regs.push_back(MRI.createVirtualRegister(RC));
8807 
8808           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8809 
8810           SDLoc dl = getCurSDLoc();
8811           // Use the produced MatchedRegs object to
8812           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8813           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8814                                            true, OpInfo.getMatchedOperand(), dl,
8815                                            DAG, AsmNodeOperands);
8816           break;
8817         }
8818 
8819         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8820         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8821                "Unexpected number of operands");
8822         // Add information to the INLINEASM node to know about this input.
8823         // See InlineAsm.h isUseOperandTiedToDef.
8824         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8825         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8826                                                     OpInfo.getMatchedOperand());
8827         AsmNodeOperands.push_back(DAG.getTargetConstant(
8828             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8829         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8830         break;
8831       }
8832 
8833       // Treat indirect 'X' constraint as memory.
8834       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8835           OpInfo.isIndirect)
8836         OpInfo.ConstraintType = TargetLowering::C_Memory;
8837 
8838       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8839           OpInfo.ConstraintType == TargetLowering::C_Other) {
8840         std::vector<SDValue> Ops;
8841         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8842                                           Ops, DAG);
8843         if (Ops.empty()) {
8844           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8845             if (isa<ConstantSDNode>(InOperandVal)) {
8846               emitInlineAsmError(Call, "value out of range for constraint '" +
8847                                            Twine(OpInfo.ConstraintCode) + "'");
8848               return;
8849             }
8850 
8851           emitInlineAsmError(Call,
8852                              "invalid operand for inline asm constraint '" +
8853                                  Twine(OpInfo.ConstraintCode) + "'");
8854           return;
8855         }
8856 
8857         // Add information to the INLINEASM node to know about this input.
8858         unsigned ResOpType =
8859           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8860         AsmNodeOperands.push_back(DAG.getTargetConstant(
8861             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8862         llvm::append_range(AsmNodeOperands, Ops);
8863         break;
8864       }
8865 
8866       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8867         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8868         assert(InOperandVal.getValueType() ==
8869                    TLI.getPointerTy(DAG.getDataLayout()) &&
8870                "Memory operands expect pointer values");
8871 
8872         unsigned ConstraintID =
8873             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8874         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8875                "Failed to convert memory constraint code to constraint id.");
8876 
8877         // Add information to the INLINEASM node to know about this input.
8878         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8879         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8880         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8881                                                         getCurSDLoc(),
8882                                                         MVT::i32));
8883         AsmNodeOperands.push_back(InOperandVal);
8884         break;
8885       }
8886 
8887       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8888               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8889              "Unknown constraint type!");
8890 
8891       // TODO: Support this.
8892       if (OpInfo.isIndirect) {
8893         emitInlineAsmError(
8894             Call, "Don't know how to handle indirect register inputs yet "
8895                   "for constraint '" +
8896                       Twine(OpInfo.ConstraintCode) + "'");
8897         return;
8898       }
8899 
8900       // Copy the input into the appropriate registers.
8901       if (OpInfo.AssignedRegs.Regs.empty()) {
8902         emitInlineAsmError(Call,
8903                            "couldn't allocate input reg for constraint '" +
8904                                Twine(OpInfo.ConstraintCode) + "'");
8905         return;
8906       }
8907 
8908       if (DetectWriteToReservedRegister())
8909         return;
8910 
8911       SDLoc dl = getCurSDLoc();
8912 
8913       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8914                                         &Call);
8915 
8916       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8917                                                dl, DAG, AsmNodeOperands);
8918       break;
8919     }
8920     case InlineAsm::isClobber:
8921       // Add the clobbered value to the operand list, so that the register
8922       // allocator is aware that the physreg got clobbered.
8923       if (!OpInfo.AssignedRegs.Regs.empty())
8924         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8925                                                  false, 0, getCurSDLoc(), DAG,
8926                                                  AsmNodeOperands);
8927       break;
8928     }
8929   }
8930 
8931   // Finish up input operands.  Set the input chain and add the flag last.
8932   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8933   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8934 
8935   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8936   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8937                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8938   Flag = Chain.getValue(1);
8939 
8940   // Do additional work to generate outputs.
8941 
8942   SmallVector<EVT, 1> ResultVTs;
8943   SmallVector<SDValue, 1> ResultValues;
8944   SmallVector<SDValue, 8> OutChains;
8945 
8946   llvm::Type *CallResultType = Call.getType();
8947   ArrayRef<Type *> ResultTypes;
8948   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8949     ResultTypes = StructResult->elements();
8950   else if (!CallResultType->isVoidTy())
8951     ResultTypes = makeArrayRef(CallResultType);
8952 
8953   auto CurResultType = ResultTypes.begin();
8954   auto handleRegAssign = [&](SDValue V) {
8955     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8956     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8957     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8958     ++CurResultType;
8959     // If the type of the inline asm call site return value is different but has
8960     // same size as the type of the asm output bitcast it.  One example of this
8961     // is for vectors with different width / number of elements.  This can
8962     // happen for register classes that can contain multiple different value
8963     // types.  The preg or vreg allocated may not have the same VT as was
8964     // expected.
8965     //
8966     // This can also happen for a return value that disagrees with the register
8967     // class it is put in, eg. a double in a general-purpose register on a
8968     // 32-bit machine.
8969     if (ResultVT != V.getValueType() &&
8970         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8971       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8972     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8973              V.getValueType().isInteger()) {
8974       // If a result value was tied to an input value, the computed result
8975       // may have a wider width than the expected result.  Extract the
8976       // relevant portion.
8977       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8978     }
8979     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8980     ResultVTs.push_back(ResultVT);
8981     ResultValues.push_back(V);
8982   };
8983 
8984   // Deal with output operands.
8985   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8986     if (OpInfo.Type == InlineAsm::isOutput) {
8987       SDValue Val;
8988       // Skip trivial output operands.
8989       if (OpInfo.AssignedRegs.Regs.empty())
8990         continue;
8991 
8992       switch (OpInfo.ConstraintType) {
8993       case TargetLowering::C_Register:
8994       case TargetLowering::C_RegisterClass:
8995         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8996                                                   Chain, &Flag, &Call);
8997         break;
8998       case TargetLowering::C_Immediate:
8999       case TargetLowering::C_Other:
9000         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9001                                               OpInfo, DAG);
9002         break;
9003       case TargetLowering::C_Memory:
9004         break; // Already handled.
9005       case TargetLowering::C_Unknown:
9006         assert(false && "Unexpected unknown constraint");
9007       }
9008 
9009       // Indirect output manifest as stores. Record output chains.
9010       if (OpInfo.isIndirect) {
9011         const Value *Ptr = OpInfo.CallOperandVal;
9012         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9013         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9014                                      MachinePointerInfo(Ptr));
9015         OutChains.push_back(Store);
9016       } else {
9017         // generate CopyFromRegs to associated registers.
9018         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9019         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9020           for (const SDValue &V : Val->op_values())
9021             handleRegAssign(V);
9022         } else
9023           handleRegAssign(Val);
9024       }
9025     }
9026   }
9027 
9028   // Set results.
9029   if (!ResultValues.empty()) {
9030     assert(CurResultType == ResultTypes.end() &&
9031            "Mismatch in number of ResultTypes");
9032     assert(ResultValues.size() == ResultTypes.size() &&
9033            "Mismatch in number of output operands in asm result");
9034 
9035     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9036                             DAG.getVTList(ResultVTs), ResultValues);
9037     setValue(&Call, V);
9038   }
9039 
9040   // Collect store chains.
9041   if (!OutChains.empty())
9042     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9043 
9044   if (EmitEHLabels) {
9045     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9046   }
9047 
9048   // Only Update Root if inline assembly has a memory effect.
9049   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9050       EmitEHLabels)
9051     DAG.setRoot(Chain);
9052 }
9053 
9054 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9055                                              const Twine &Message) {
9056   LLVMContext &Ctx = *DAG.getContext();
9057   Ctx.emitError(&Call, Message);
9058 
9059   // Make sure we leave the DAG in a valid state
9060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9061   SmallVector<EVT, 1> ValueVTs;
9062   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9063 
9064   if (ValueVTs.empty())
9065     return;
9066 
9067   SmallVector<SDValue, 1> Ops;
9068   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9069     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9070 
9071   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9072 }
9073 
9074 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9075   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9076                           MVT::Other, getRoot(),
9077                           getValue(I.getArgOperand(0)),
9078                           DAG.getSrcValue(I.getArgOperand(0))));
9079 }
9080 
9081 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9083   const DataLayout &DL = DAG.getDataLayout();
9084   SDValue V = DAG.getVAArg(
9085       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9086       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9087       DL.getABITypeAlign(I.getType()).value());
9088   DAG.setRoot(V.getValue(1));
9089 
9090   if (I.getType()->isPointerTy())
9091     V = DAG.getPtrExtOrTrunc(
9092         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9093   setValue(&I, V);
9094 }
9095 
9096 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9097   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9098                           MVT::Other, getRoot(),
9099                           getValue(I.getArgOperand(0)),
9100                           DAG.getSrcValue(I.getArgOperand(0))));
9101 }
9102 
9103 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9104   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9105                           MVT::Other, getRoot(),
9106                           getValue(I.getArgOperand(0)),
9107                           getValue(I.getArgOperand(1)),
9108                           DAG.getSrcValue(I.getArgOperand(0)),
9109                           DAG.getSrcValue(I.getArgOperand(1))));
9110 }
9111 
9112 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9113                                                     const Instruction &I,
9114                                                     SDValue Op) {
9115   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9116   if (!Range)
9117     return Op;
9118 
9119   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9120   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9121     return Op;
9122 
9123   APInt Lo = CR.getUnsignedMin();
9124   if (!Lo.isMinValue())
9125     return Op;
9126 
9127   APInt Hi = CR.getUnsignedMax();
9128   unsigned Bits = std::max(Hi.getActiveBits(),
9129                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9130 
9131   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9132 
9133   SDLoc SL = getCurSDLoc();
9134 
9135   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9136                              DAG.getValueType(SmallVT));
9137   unsigned NumVals = Op.getNode()->getNumValues();
9138   if (NumVals == 1)
9139     return ZExt;
9140 
9141   SmallVector<SDValue, 4> Ops;
9142 
9143   Ops.push_back(ZExt);
9144   for (unsigned I = 1; I != NumVals; ++I)
9145     Ops.push_back(Op.getValue(I));
9146 
9147   return DAG.getMergeValues(Ops, SL);
9148 }
9149 
9150 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9151 /// the call being lowered.
9152 ///
9153 /// This is a helper for lowering intrinsics that follow a target calling
9154 /// convention or require stack pointer adjustment. Only a subset of the
9155 /// intrinsic's operands need to participate in the calling convention.
9156 void SelectionDAGBuilder::populateCallLoweringInfo(
9157     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9158     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9159     bool IsPatchPoint) {
9160   TargetLowering::ArgListTy Args;
9161   Args.reserve(NumArgs);
9162 
9163   // Populate the argument list.
9164   // Attributes for args start at offset 1, after the return attribute.
9165   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9166        ArgI != ArgE; ++ArgI) {
9167     const Value *V = Call->getOperand(ArgI);
9168 
9169     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9170 
9171     TargetLowering::ArgListEntry Entry;
9172     Entry.Node = getValue(V);
9173     Entry.Ty = V->getType();
9174     Entry.setAttributes(Call, ArgI);
9175     Args.push_back(Entry);
9176   }
9177 
9178   CLI.setDebugLoc(getCurSDLoc())
9179       .setChain(getRoot())
9180       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9181       .setDiscardResult(Call->use_empty())
9182       .setIsPatchPoint(IsPatchPoint)
9183       .setIsPreallocated(
9184           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9185 }
9186 
9187 /// Add a stack map intrinsic call's live variable operands to a stackmap
9188 /// or patchpoint target node's operand list.
9189 ///
9190 /// Constants are converted to TargetConstants purely as an optimization to
9191 /// avoid constant materialization and register allocation.
9192 ///
9193 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9194 /// generate addess computation nodes, and so FinalizeISel can convert the
9195 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9196 /// address materialization and register allocation, but may also be required
9197 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9198 /// alloca in the entry block, then the runtime may assume that the alloca's
9199 /// StackMap location can be read immediately after compilation and that the
9200 /// location is valid at any point during execution (this is similar to the
9201 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9202 /// only available in a register, then the runtime would need to trap when
9203 /// execution reaches the StackMap in order to read the alloca's location.
9204 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9205                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9206                                 SelectionDAGBuilder &Builder) {
9207   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9208     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9209     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9210       Ops.push_back(
9211         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9212       Ops.push_back(
9213         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9214     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9215       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9216       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9217           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9218     } else
9219       Ops.push_back(OpVal);
9220   }
9221 }
9222 
9223 /// Lower llvm.experimental.stackmap directly to its target opcode.
9224 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9225   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9226   //                                  [live variables...])
9227 
9228   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9229 
9230   SDValue Chain, InFlag, Callee, NullPtr;
9231   SmallVector<SDValue, 32> Ops;
9232 
9233   SDLoc DL = getCurSDLoc();
9234   Callee = getValue(CI.getCalledOperand());
9235   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9236 
9237   // The stackmap intrinsic only records the live variables (the arguments
9238   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9239   // intrinsic, this won't be lowered to a function call. This means we don't
9240   // have to worry about calling conventions and target specific lowering code.
9241   // Instead we perform the call lowering right here.
9242   //
9243   // chain, flag = CALLSEQ_START(chain, 0, 0)
9244   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9245   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9246   //
9247   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9248   InFlag = Chain.getValue(1);
9249 
9250   // Add the <id> and <numBytes> constants.
9251   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9252   Ops.push_back(DAG.getTargetConstant(
9253                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9254   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9255   Ops.push_back(DAG.getTargetConstant(
9256                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9257                   MVT::i32));
9258 
9259   // Push live variables for the stack map.
9260   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9261 
9262   // We are not pushing any register mask info here on the operands list,
9263   // because the stackmap doesn't clobber anything.
9264 
9265   // Push the chain and the glue flag.
9266   Ops.push_back(Chain);
9267   Ops.push_back(InFlag);
9268 
9269   // Create the STACKMAP node.
9270   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9271   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9272   Chain = SDValue(SM, 0);
9273   InFlag = Chain.getValue(1);
9274 
9275   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9276 
9277   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9278 
9279   // Set the root to the target-lowered call chain.
9280   DAG.setRoot(Chain);
9281 
9282   // Inform the Frame Information that we have a stackmap in this function.
9283   FuncInfo.MF->getFrameInfo().setHasStackMap();
9284 }
9285 
9286 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9287 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9288                                           const BasicBlock *EHPadBB) {
9289   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9290   //                                                 i32 <numBytes>,
9291   //                                                 i8* <target>,
9292   //                                                 i32 <numArgs>,
9293   //                                                 [Args...],
9294   //                                                 [live variables...])
9295 
9296   CallingConv::ID CC = CB.getCallingConv();
9297   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9298   bool HasDef = !CB.getType()->isVoidTy();
9299   SDLoc dl = getCurSDLoc();
9300   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9301 
9302   // Handle immediate and symbolic callees.
9303   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9304     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9305                                    /*isTarget=*/true);
9306   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9307     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9308                                          SDLoc(SymbolicCallee),
9309                                          SymbolicCallee->getValueType(0));
9310 
9311   // Get the real number of arguments participating in the call <numArgs>
9312   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9313   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9314 
9315   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9316   // Intrinsics include all meta-operands up to but not including CC.
9317   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9318   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9319          "Not enough arguments provided to the patchpoint intrinsic");
9320 
9321   // For AnyRegCC the arguments are lowered later on manually.
9322   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9323   Type *ReturnTy =
9324       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9325 
9326   TargetLowering::CallLoweringInfo CLI(DAG);
9327   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9328                            ReturnTy, true);
9329   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9330 
9331   SDNode *CallEnd = Result.second.getNode();
9332   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9333     CallEnd = CallEnd->getOperand(0).getNode();
9334 
9335   /// Get a call instruction from the call sequence chain.
9336   /// Tail calls are not allowed.
9337   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9338          "Expected a callseq node.");
9339   SDNode *Call = CallEnd->getOperand(0).getNode();
9340   bool HasGlue = Call->getGluedNode();
9341 
9342   // Replace the target specific call node with the patchable intrinsic.
9343   SmallVector<SDValue, 8> Ops;
9344 
9345   // Add the <id> and <numBytes> constants.
9346   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9347   Ops.push_back(DAG.getTargetConstant(
9348                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9349   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9350   Ops.push_back(DAG.getTargetConstant(
9351                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9352                   MVT::i32));
9353 
9354   // Add the callee.
9355   Ops.push_back(Callee);
9356 
9357   // Adjust <numArgs> to account for any arguments that have been passed on the
9358   // stack instead.
9359   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9360   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9361   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9362   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9363 
9364   // Add the calling convention
9365   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9366 
9367   // Add the arguments we omitted previously. The register allocator should
9368   // place these in any free register.
9369   if (IsAnyRegCC)
9370     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9371       Ops.push_back(getValue(CB.getArgOperand(i)));
9372 
9373   // Push the arguments from the call instruction up to the register mask.
9374   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9375   Ops.append(Call->op_begin() + 2, e);
9376 
9377   // Push live variables for the stack map.
9378   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9379 
9380   // Push the register mask info.
9381   if (HasGlue)
9382     Ops.push_back(*(Call->op_end()-2));
9383   else
9384     Ops.push_back(*(Call->op_end()-1));
9385 
9386   // Push the chain (this is originally the first operand of the call, but
9387   // becomes now the last or second to last operand).
9388   Ops.push_back(*(Call->op_begin()));
9389 
9390   // Push the glue flag (last operand).
9391   if (HasGlue)
9392     Ops.push_back(*(Call->op_end()-1));
9393 
9394   SDVTList NodeTys;
9395   if (IsAnyRegCC && HasDef) {
9396     // Create the return types based on the intrinsic definition
9397     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398     SmallVector<EVT, 3> ValueVTs;
9399     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9400     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9401 
9402     // There is always a chain and a glue type at the end
9403     ValueVTs.push_back(MVT::Other);
9404     ValueVTs.push_back(MVT::Glue);
9405     NodeTys = DAG.getVTList(ValueVTs);
9406   } else
9407     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9408 
9409   // Replace the target specific call node with a PATCHPOINT node.
9410   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9411                                          dl, NodeTys, Ops);
9412 
9413   // Update the NodeMap.
9414   if (HasDef) {
9415     if (IsAnyRegCC)
9416       setValue(&CB, SDValue(MN, 0));
9417     else
9418       setValue(&CB, Result.first);
9419   }
9420 
9421   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9422   // call sequence. Furthermore the location of the chain and glue can change
9423   // when the AnyReg calling convention is used and the intrinsic returns a
9424   // value.
9425   if (IsAnyRegCC && HasDef) {
9426     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9427     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9428     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9429   } else
9430     DAG.ReplaceAllUsesWith(Call, MN);
9431   DAG.DeleteNode(Call);
9432 
9433   // Inform the Frame Information that we have a patchpoint in this function.
9434   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9435 }
9436 
9437 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9438                                             unsigned Intrinsic) {
9439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9440   SDValue Op1 = getValue(I.getArgOperand(0));
9441   SDValue Op2;
9442   if (I.getNumArgOperands() > 1)
9443     Op2 = getValue(I.getArgOperand(1));
9444   SDLoc dl = getCurSDLoc();
9445   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9446   SDValue Res;
9447   SDNodeFlags SDFlags;
9448   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9449     SDFlags.copyFMF(*FPMO);
9450 
9451   switch (Intrinsic) {
9452   case Intrinsic::vector_reduce_fadd:
9453     if (SDFlags.hasAllowReassociation())
9454       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9455                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9456                         SDFlags);
9457     else
9458       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9459     break;
9460   case Intrinsic::vector_reduce_fmul:
9461     if (SDFlags.hasAllowReassociation())
9462       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9463                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9464                         SDFlags);
9465     else
9466       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9467     break;
9468   case Intrinsic::vector_reduce_add:
9469     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9470     break;
9471   case Intrinsic::vector_reduce_mul:
9472     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9473     break;
9474   case Intrinsic::vector_reduce_and:
9475     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9476     break;
9477   case Intrinsic::vector_reduce_or:
9478     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9479     break;
9480   case Intrinsic::vector_reduce_xor:
9481     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9482     break;
9483   case Intrinsic::vector_reduce_smax:
9484     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9485     break;
9486   case Intrinsic::vector_reduce_smin:
9487     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9488     break;
9489   case Intrinsic::vector_reduce_umax:
9490     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9491     break;
9492   case Intrinsic::vector_reduce_umin:
9493     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9494     break;
9495   case Intrinsic::vector_reduce_fmax:
9496     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9497     break;
9498   case Intrinsic::vector_reduce_fmin:
9499     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9500     break;
9501   default:
9502     llvm_unreachable("Unhandled vector reduce intrinsic");
9503   }
9504   setValue(&I, Res);
9505 }
9506 
9507 /// Returns an AttributeList representing the attributes applied to the return
9508 /// value of the given call.
9509 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9510   SmallVector<Attribute::AttrKind, 2> Attrs;
9511   if (CLI.RetSExt)
9512     Attrs.push_back(Attribute::SExt);
9513   if (CLI.RetZExt)
9514     Attrs.push_back(Attribute::ZExt);
9515   if (CLI.IsInReg)
9516     Attrs.push_back(Attribute::InReg);
9517 
9518   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9519                             Attrs);
9520 }
9521 
9522 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9523 /// implementation, which just calls LowerCall.
9524 /// FIXME: When all targets are
9525 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9526 std::pair<SDValue, SDValue>
9527 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9528   // Handle the incoming return values from the call.
9529   CLI.Ins.clear();
9530   Type *OrigRetTy = CLI.RetTy;
9531   SmallVector<EVT, 4> RetTys;
9532   SmallVector<uint64_t, 4> Offsets;
9533   auto &DL = CLI.DAG.getDataLayout();
9534   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9535 
9536   if (CLI.IsPostTypeLegalization) {
9537     // If we are lowering a libcall after legalization, split the return type.
9538     SmallVector<EVT, 4> OldRetTys;
9539     SmallVector<uint64_t, 4> OldOffsets;
9540     RetTys.swap(OldRetTys);
9541     Offsets.swap(OldOffsets);
9542 
9543     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9544       EVT RetVT = OldRetTys[i];
9545       uint64_t Offset = OldOffsets[i];
9546       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9547       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9548       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9549       RetTys.append(NumRegs, RegisterVT);
9550       for (unsigned j = 0; j != NumRegs; ++j)
9551         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9552     }
9553   }
9554 
9555   SmallVector<ISD::OutputArg, 4> Outs;
9556   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9557 
9558   bool CanLowerReturn =
9559       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9560                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9561 
9562   SDValue DemoteStackSlot;
9563   int DemoteStackIdx = -100;
9564   if (!CanLowerReturn) {
9565     // FIXME: equivalent assert?
9566     // assert(!CS.hasInAllocaArgument() &&
9567     //        "sret demotion is incompatible with inalloca");
9568     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9569     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9570     MachineFunction &MF = CLI.DAG.getMachineFunction();
9571     DemoteStackIdx =
9572         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9573     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9574                                               DL.getAllocaAddrSpace());
9575 
9576     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9577     ArgListEntry Entry;
9578     Entry.Node = DemoteStackSlot;
9579     Entry.Ty = StackSlotPtrType;
9580     Entry.IsSExt = false;
9581     Entry.IsZExt = false;
9582     Entry.IsInReg = false;
9583     Entry.IsSRet = true;
9584     Entry.IsNest = false;
9585     Entry.IsByVal = false;
9586     Entry.IsByRef = false;
9587     Entry.IsReturned = false;
9588     Entry.IsSwiftSelf = false;
9589     Entry.IsSwiftAsync = false;
9590     Entry.IsSwiftError = false;
9591     Entry.IsCFGuardTarget = false;
9592     Entry.Alignment = Alignment;
9593     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9594     CLI.NumFixedArgs += 1;
9595     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9596 
9597     // sret demotion isn't compatible with tail-calls, since the sret argument
9598     // points into the callers stack frame.
9599     CLI.IsTailCall = false;
9600   } else {
9601     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9602         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9603     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9604       ISD::ArgFlagsTy Flags;
9605       if (NeedsRegBlock) {
9606         Flags.setInConsecutiveRegs();
9607         if (I == RetTys.size() - 1)
9608           Flags.setInConsecutiveRegsLast();
9609       }
9610       EVT VT = RetTys[I];
9611       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9612                                                      CLI.CallConv, VT);
9613       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9614                                                        CLI.CallConv, VT);
9615       for (unsigned i = 0; i != NumRegs; ++i) {
9616         ISD::InputArg MyFlags;
9617         MyFlags.Flags = Flags;
9618         MyFlags.VT = RegisterVT;
9619         MyFlags.ArgVT = VT;
9620         MyFlags.Used = CLI.IsReturnValueUsed;
9621         if (CLI.RetTy->isPointerTy()) {
9622           MyFlags.Flags.setPointer();
9623           MyFlags.Flags.setPointerAddrSpace(
9624               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9625         }
9626         if (CLI.RetSExt)
9627           MyFlags.Flags.setSExt();
9628         if (CLI.RetZExt)
9629           MyFlags.Flags.setZExt();
9630         if (CLI.IsInReg)
9631           MyFlags.Flags.setInReg();
9632         CLI.Ins.push_back(MyFlags);
9633       }
9634     }
9635   }
9636 
9637   // We push in swifterror return as the last element of CLI.Ins.
9638   ArgListTy &Args = CLI.getArgs();
9639   if (supportSwiftError()) {
9640     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9641       if (Args[i].IsSwiftError) {
9642         ISD::InputArg MyFlags;
9643         MyFlags.VT = getPointerTy(DL);
9644         MyFlags.ArgVT = EVT(getPointerTy(DL));
9645         MyFlags.Flags.setSwiftError();
9646         CLI.Ins.push_back(MyFlags);
9647       }
9648     }
9649   }
9650 
9651   // Handle all of the outgoing arguments.
9652   CLI.Outs.clear();
9653   CLI.OutVals.clear();
9654   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9655     SmallVector<EVT, 4> ValueVTs;
9656     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9657     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9658     Type *FinalType = Args[i].Ty;
9659     if (Args[i].IsByVal)
9660       FinalType = Args[i].IndirectType;
9661     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9662         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9663     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9664          ++Value) {
9665       EVT VT = ValueVTs[Value];
9666       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9667       SDValue Op = SDValue(Args[i].Node.getNode(),
9668                            Args[i].Node.getResNo() + Value);
9669       ISD::ArgFlagsTy Flags;
9670 
9671       // Certain targets (such as MIPS), may have a different ABI alignment
9672       // for a type depending on the context. Give the target a chance to
9673       // specify the alignment it wants.
9674       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9675       Flags.setOrigAlign(OriginalAlignment);
9676 
9677       if (Args[i].Ty->isPointerTy()) {
9678         Flags.setPointer();
9679         Flags.setPointerAddrSpace(
9680             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9681       }
9682       if (Args[i].IsZExt)
9683         Flags.setZExt();
9684       if (Args[i].IsSExt)
9685         Flags.setSExt();
9686       if (Args[i].IsInReg) {
9687         // If we are using vectorcall calling convention, a structure that is
9688         // passed InReg - is surely an HVA
9689         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9690             isa<StructType>(FinalType)) {
9691           // The first value of a structure is marked
9692           if (0 == Value)
9693             Flags.setHvaStart();
9694           Flags.setHva();
9695         }
9696         // Set InReg Flag
9697         Flags.setInReg();
9698       }
9699       if (Args[i].IsSRet)
9700         Flags.setSRet();
9701       if (Args[i].IsSwiftSelf)
9702         Flags.setSwiftSelf();
9703       if (Args[i].IsSwiftAsync)
9704         Flags.setSwiftAsync();
9705       if (Args[i].IsSwiftError)
9706         Flags.setSwiftError();
9707       if (Args[i].IsCFGuardTarget)
9708         Flags.setCFGuardTarget();
9709       if (Args[i].IsByVal)
9710         Flags.setByVal();
9711       if (Args[i].IsByRef)
9712         Flags.setByRef();
9713       if (Args[i].IsPreallocated) {
9714         Flags.setPreallocated();
9715         // Set the byval flag for CCAssignFn callbacks that don't know about
9716         // preallocated.  This way we can know how many bytes we should've
9717         // allocated and how many bytes a callee cleanup function will pop.  If
9718         // we port preallocated to more targets, we'll have to add custom
9719         // preallocated handling in the various CC lowering callbacks.
9720         Flags.setByVal();
9721       }
9722       if (Args[i].IsInAlloca) {
9723         Flags.setInAlloca();
9724         // Set the byval flag for CCAssignFn callbacks that don't know about
9725         // inalloca.  This way we can know how many bytes we should've allocated
9726         // and how many bytes a callee cleanup function will pop.  If we port
9727         // inalloca to more targets, we'll have to add custom inalloca handling
9728         // in the various CC lowering callbacks.
9729         Flags.setByVal();
9730       }
9731       Align MemAlign;
9732       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9733         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9734         Flags.setByValSize(FrameSize);
9735 
9736         // info is not there but there are cases it cannot get right.
9737         if (auto MA = Args[i].Alignment)
9738           MemAlign = *MA;
9739         else
9740           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9741       } else if (auto MA = Args[i].Alignment) {
9742         MemAlign = *MA;
9743       } else {
9744         MemAlign = OriginalAlignment;
9745       }
9746       Flags.setMemAlign(MemAlign);
9747       if (Args[i].IsNest)
9748         Flags.setNest();
9749       if (NeedsRegBlock)
9750         Flags.setInConsecutiveRegs();
9751 
9752       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9753                                                  CLI.CallConv, VT);
9754       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9755                                                         CLI.CallConv, VT);
9756       SmallVector<SDValue, 4> Parts(NumParts);
9757       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9758 
9759       if (Args[i].IsSExt)
9760         ExtendKind = ISD::SIGN_EXTEND;
9761       else if (Args[i].IsZExt)
9762         ExtendKind = ISD::ZERO_EXTEND;
9763 
9764       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9765       // for now.
9766       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9767           CanLowerReturn) {
9768         assert((CLI.RetTy == Args[i].Ty ||
9769                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9770                  CLI.RetTy->getPointerAddressSpace() ==
9771                      Args[i].Ty->getPointerAddressSpace())) &&
9772                RetTys.size() == NumValues && "unexpected use of 'returned'");
9773         // Before passing 'returned' to the target lowering code, ensure that
9774         // either the register MVT and the actual EVT are the same size or that
9775         // the return value and argument are extended in the same way; in these
9776         // cases it's safe to pass the argument register value unchanged as the
9777         // return register value (although it's at the target's option whether
9778         // to do so)
9779         // TODO: allow code generation to take advantage of partially preserved
9780         // registers rather than clobbering the entire register when the
9781         // parameter extension method is not compatible with the return
9782         // extension method
9783         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9784             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9785              CLI.RetZExt == Args[i].IsZExt))
9786           Flags.setReturned();
9787       }
9788 
9789       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9790                      CLI.CallConv, ExtendKind);
9791 
9792       for (unsigned j = 0; j != NumParts; ++j) {
9793         // if it isn't first piece, alignment must be 1
9794         // For scalable vectors the scalable part is currently handled
9795         // by individual targets, so we just use the known minimum size here.
9796         ISD::OutputArg MyFlags(
9797             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9798             i < CLI.NumFixedArgs, i,
9799             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9800         if (NumParts > 1 && j == 0)
9801           MyFlags.Flags.setSplit();
9802         else if (j != 0) {
9803           MyFlags.Flags.setOrigAlign(Align(1));
9804           if (j == NumParts - 1)
9805             MyFlags.Flags.setSplitEnd();
9806         }
9807 
9808         CLI.Outs.push_back(MyFlags);
9809         CLI.OutVals.push_back(Parts[j]);
9810       }
9811 
9812       if (NeedsRegBlock && Value == NumValues - 1)
9813         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9814     }
9815   }
9816 
9817   SmallVector<SDValue, 4> InVals;
9818   CLI.Chain = LowerCall(CLI, InVals);
9819 
9820   // Update CLI.InVals to use outside of this function.
9821   CLI.InVals = InVals;
9822 
9823   // Verify that the target's LowerCall behaved as expected.
9824   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9825          "LowerCall didn't return a valid chain!");
9826   assert((!CLI.IsTailCall || InVals.empty()) &&
9827          "LowerCall emitted a return value for a tail call!");
9828   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9829          "LowerCall didn't emit the correct number of values!");
9830 
9831   // For a tail call, the return value is merely live-out and there aren't
9832   // any nodes in the DAG representing it. Return a special value to
9833   // indicate that a tail call has been emitted and no more Instructions
9834   // should be processed in the current block.
9835   if (CLI.IsTailCall) {
9836     CLI.DAG.setRoot(CLI.Chain);
9837     return std::make_pair(SDValue(), SDValue());
9838   }
9839 
9840 #ifndef NDEBUG
9841   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9842     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9843     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9844            "LowerCall emitted a value with the wrong type!");
9845   }
9846 #endif
9847 
9848   SmallVector<SDValue, 4> ReturnValues;
9849   if (!CanLowerReturn) {
9850     // The instruction result is the result of loading from the
9851     // hidden sret parameter.
9852     SmallVector<EVT, 1> PVTs;
9853     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9854 
9855     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9856     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9857     EVT PtrVT = PVTs[0];
9858 
9859     unsigned NumValues = RetTys.size();
9860     ReturnValues.resize(NumValues);
9861     SmallVector<SDValue, 4> Chains(NumValues);
9862 
9863     // An aggregate return value cannot wrap around the address space, so
9864     // offsets to its parts don't wrap either.
9865     SDNodeFlags Flags;
9866     Flags.setNoUnsignedWrap(true);
9867 
9868     MachineFunction &MF = CLI.DAG.getMachineFunction();
9869     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9870     for (unsigned i = 0; i < NumValues; ++i) {
9871       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9872                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9873                                                         PtrVT), Flags);
9874       SDValue L = CLI.DAG.getLoad(
9875           RetTys[i], CLI.DL, CLI.Chain, Add,
9876           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9877                                             DemoteStackIdx, Offsets[i]),
9878           HiddenSRetAlign);
9879       ReturnValues[i] = L;
9880       Chains[i] = L.getValue(1);
9881     }
9882 
9883     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9884   } else {
9885     // Collect the legal value parts into potentially illegal values
9886     // that correspond to the original function's return values.
9887     Optional<ISD::NodeType> AssertOp;
9888     if (CLI.RetSExt)
9889       AssertOp = ISD::AssertSext;
9890     else if (CLI.RetZExt)
9891       AssertOp = ISD::AssertZext;
9892     unsigned CurReg = 0;
9893     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9894       EVT VT = RetTys[I];
9895       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9896                                                      CLI.CallConv, VT);
9897       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9898                                                        CLI.CallConv, VT);
9899 
9900       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9901                                               NumRegs, RegisterVT, VT, nullptr,
9902                                               CLI.CallConv, AssertOp));
9903       CurReg += NumRegs;
9904     }
9905 
9906     // For a function returning void, there is no return value. We can't create
9907     // such a node, so we just return a null return value in that case. In
9908     // that case, nothing will actually look at the value.
9909     if (ReturnValues.empty())
9910       return std::make_pair(SDValue(), CLI.Chain);
9911   }
9912 
9913   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9914                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9915   return std::make_pair(Res, CLI.Chain);
9916 }
9917 
9918 /// Places new result values for the node in Results (their number
9919 /// and types must exactly match those of the original return values of
9920 /// the node), or leaves Results empty, which indicates that the node is not
9921 /// to be custom lowered after all.
9922 void TargetLowering::LowerOperationWrapper(SDNode *N,
9923                                            SmallVectorImpl<SDValue> &Results,
9924                                            SelectionDAG &DAG) const {
9925   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9926 
9927   if (!Res.getNode())
9928     return;
9929 
9930   // If the original node has one result, take the return value from
9931   // LowerOperation as is. It might not be result number 0.
9932   if (N->getNumValues() == 1) {
9933     Results.push_back(Res);
9934     return;
9935   }
9936 
9937   // If the original node has multiple results, then the return node should
9938   // have the same number of results.
9939   assert((N->getNumValues() == Res->getNumValues()) &&
9940       "Lowering returned the wrong number of results!");
9941 
9942   // Places new result values base on N result number.
9943   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9944     Results.push_back(Res.getValue(I));
9945 }
9946 
9947 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9948   llvm_unreachable("LowerOperation not implemented for this target!");
9949 }
9950 
9951 void
9952 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9953   SDValue Op = getNonRegisterValue(V);
9954   assert((Op.getOpcode() != ISD::CopyFromReg ||
9955           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9956          "Copy from a reg to the same reg!");
9957   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9958 
9959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9960   // If this is an InlineAsm we have to match the registers required, not the
9961   // notional registers required by the type.
9962 
9963   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9964                    None); // This is not an ABI copy.
9965   SDValue Chain = DAG.getEntryNode();
9966 
9967   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9968   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9969   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9970     ExtendType = PreferredExtendIt->second;
9971   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9972   PendingExports.push_back(Chain);
9973 }
9974 
9975 #include "llvm/CodeGen/SelectionDAGISel.h"
9976 
9977 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9978 /// entry block, return true.  This includes arguments used by switches, since
9979 /// the switch may expand into multiple basic blocks.
9980 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9981   // With FastISel active, we may be splitting blocks, so force creation
9982   // of virtual registers for all non-dead arguments.
9983   if (FastISel)
9984     return A->use_empty();
9985 
9986   const BasicBlock &Entry = A->getParent()->front();
9987   for (const User *U : A->users())
9988     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9989       return false;  // Use not in entry block.
9990 
9991   return true;
9992 }
9993 
9994 using ArgCopyElisionMapTy =
9995     DenseMap<const Argument *,
9996              std::pair<const AllocaInst *, const StoreInst *>>;
9997 
9998 /// Scan the entry block of the function in FuncInfo for arguments that look
9999 /// like copies into a local alloca. Record any copied arguments in
10000 /// ArgCopyElisionCandidates.
10001 static void
10002 findArgumentCopyElisionCandidates(const DataLayout &DL,
10003                                   FunctionLoweringInfo *FuncInfo,
10004                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10005   // Record the state of every static alloca used in the entry block. Argument
10006   // allocas are all used in the entry block, so we need approximately as many
10007   // entries as we have arguments.
10008   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10009   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10010   unsigned NumArgs = FuncInfo->Fn->arg_size();
10011   StaticAllocas.reserve(NumArgs * 2);
10012 
10013   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10014     if (!V)
10015       return nullptr;
10016     V = V->stripPointerCasts();
10017     const auto *AI = dyn_cast<AllocaInst>(V);
10018     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10019       return nullptr;
10020     auto Iter = StaticAllocas.insert({AI, Unknown});
10021     return &Iter.first->second;
10022   };
10023 
10024   // Look for stores of arguments to static allocas. Look through bitcasts and
10025   // GEPs to handle type coercions, as long as the alloca is fully initialized
10026   // by the store. Any non-store use of an alloca escapes it and any subsequent
10027   // unanalyzed store might write it.
10028   // FIXME: Handle structs initialized with multiple stores.
10029   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10030     // Look for stores, and handle non-store uses conservatively.
10031     const auto *SI = dyn_cast<StoreInst>(&I);
10032     if (!SI) {
10033       // We will look through cast uses, so ignore them completely.
10034       if (I.isCast())
10035         continue;
10036       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10037       // to allocas.
10038       if (I.isDebugOrPseudoInst())
10039         continue;
10040       // This is an unknown instruction. Assume it escapes or writes to all
10041       // static alloca operands.
10042       for (const Use &U : I.operands()) {
10043         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10044           *Info = StaticAllocaInfo::Clobbered;
10045       }
10046       continue;
10047     }
10048 
10049     // If the stored value is a static alloca, mark it as escaped.
10050     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10051       *Info = StaticAllocaInfo::Clobbered;
10052 
10053     // Check if the destination is a static alloca.
10054     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10055     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10056     if (!Info)
10057       continue;
10058     const AllocaInst *AI = cast<AllocaInst>(Dst);
10059 
10060     // Skip allocas that have been initialized or clobbered.
10061     if (*Info != StaticAllocaInfo::Unknown)
10062       continue;
10063 
10064     // Check if the stored value is an argument, and that this store fully
10065     // initializes the alloca.
10066     // If the argument type has padding bits we can't directly forward a pointer
10067     // as the upper bits may contain garbage.
10068     // Don't elide copies from the same argument twice.
10069     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10070     const auto *Arg = dyn_cast<Argument>(Val);
10071     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10072         Arg->getType()->isEmptyTy() ||
10073         DL.getTypeStoreSize(Arg->getType()) !=
10074             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10075         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10076         ArgCopyElisionCandidates.count(Arg)) {
10077       *Info = StaticAllocaInfo::Clobbered;
10078       continue;
10079     }
10080 
10081     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10082                       << '\n');
10083 
10084     // Mark this alloca and store for argument copy elision.
10085     *Info = StaticAllocaInfo::Elidable;
10086     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10087 
10088     // Stop scanning if we've seen all arguments. This will happen early in -O0
10089     // builds, which is useful, because -O0 builds have large entry blocks and
10090     // many allocas.
10091     if (ArgCopyElisionCandidates.size() == NumArgs)
10092       break;
10093   }
10094 }
10095 
10096 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10097 /// ArgVal is a load from a suitable fixed stack object.
10098 static void tryToElideArgumentCopy(
10099     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10100     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10101     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10102     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10103     SDValue ArgVal, bool &ArgHasUses) {
10104   // Check if this is a load from a fixed stack object.
10105   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10106   if (!LNode)
10107     return;
10108   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10109   if (!FINode)
10110     return;
10111 
10112   // Check that the fixed stack object is the right size and alignment.
10113   // Look at the alignment that the user wrote on the alloca instead of looking
10114   // at the stack object.
10115   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10116   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10117   const AllocaInst *AI = ArgCopyIter->second.first;
10118   int FixedIndex = FINode->getIndex();
10119   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10120   int OldIndex = AllocaIndex;
10121   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10122   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10123     LLVM_DEBUG(
10124         dbgs() << "  argument copy elision failed due to bad fixed stack "
10125                   "object size\n");
10126     return;
10127   }
10128   Align RequiredAlignment = AI->getAlign();
10129   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10130     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10131                          "greater than stack argument alignment ("
10132                       << DebugStr(RequiredAlignment) << " vs "
10133                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10134     return;
10135   }
10136 
10137   // Perform the elision. Delete the old stack object and replace its only use
10138   // in the variable info map. Mark the stack object as mutable.
10139   LLVM_DEBUG({
10140     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10141            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10142            << '\n';
10143   });
10144   MFI.RemoveStackObject(OldIndex);
10145   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10146   AllocaIndex = FixedIndex;
10147   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10148   Chains.push_back(ArgVal.getValue(1));
10149 
10150   // Avoid emitting code for the store implementing the copy.
10151   const StoreInst *SI = ArgCopyIter->second.second;
10152   ElidedArgCopyInstrs.insert(SI);
10153 
10154   // Check for uses of the argument again so that we can avoid exporting ArgVal
10155   // if it is't used by anything other than the store.
10156   for (const Value *U : Arg.users()) {
10157     if (U != SI) {
10158       ArgHasUses = true;
10159       break;
10160     }
10161   }
10162 }
10163 
10164 void SelectionDAGISel::LowerArguments(const Function &F) {
10165   SelectionDAG &DAG = SDB->DAG;
10166   SDLoc dl = SDB->getCurSDLoc();
10167   const DataLayout &DL = DAG.getDataLayout();
10168   SmallVector<ISD::InputArg, 16> Ins;
10169 
10170   // In Naked functions we aren't going to save any registers.
10171   if (F.hasFnAttribute(Attribute::Naked))
10172     return;
10173 
10174   if (!FuncInfo->CanLowerReturn) {
10175     // Put in an sret pointer parameter before all the other parameters.
10176     SmallVector<EVT, 1> ValueVTs;
10177     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10178                     F.getReturnType()->getPointerTo(
10179                         DAG.getDataLayout().getAllocaAddrSpace()),
10180                     ValueVTs);
10181 
10182     // NOTE: Assuming that a pointer will never break down to more than one VT
10183     // or one register.
10184     ISD::ArgFlagsTy Flags;
10185     Flags.setSRet();
10186     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10187     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10188                          ISD::InputArg::NoArgIndex, 0);
10189     Ins.push_back(RetArg);
10190   }
10191 
10192   // Look for stores of arguments to static allocas. Mark such arguments with a
10193   // flag to ask the target to give us the memory location of that argument if
10194   // available.
10195   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10196   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10197                                     ArgCopyElisionCandidates);
10198 
10199   // Set up the incoming argument description vector.
10200   for (const Argument &Arg : F.args()) {
10201     unsigned ArgNo = Arg.getArgNo();
10202     SmallVector<EVT, 4> ValueVTs;
10203     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10204     bool isArgValueUsed = !Arg.use_empty();
10205     unsigned PartBase = 0;
10206     Type *FinalType = Arg.getType();
10207     if (Arg.hasAttribute(Attribute::ByVal))
10208       FinalType = Arg.getParamByValType();
10209     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10210         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10211     for (unsigned Value = 0, NumValues = ValueVTs.size();
10212          Value != NumValues; ++Value) {
10213       EVT VT = ValueVTs[Value];
10214       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10215       ISD::ArgFlagsTy Flags;
10216 
10217 
10218       if (Arg.getType()->isPointerTy()) {
10219         Flags.setPointer();
10220         Flags.setPointerAddrSpace(
10221             cast<PointerType>(Arg.getType())->getAddressSpace());
10222       }
10223       if (Arg.hasAttribute(Attribute::ZExt))
10224         Flags.setZExt();
10225       if (Arg.hasAttribute(Attribute::SExt))
10226         Flags.setSExt();
10227       if (Arg.hasAttribute(Attribute::InReg)) {
10228         // If we are using vectorcall calling convention, a structure that is
10229         // passed InReg - is surely an HVA
10230         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10231             isa<StructType>(Arg.getType())) {
10232           // The first value of a structure is marked
10233           if (0 == Value)
10234             Flags.setHvaStart();
10235           Flags.setHva();
10236         }
10237         // Set InReg Flag
10238         Flags.setInReg();
10239       }
10240       if (Arg.hasAttribute(Attribute::StructRet))
10241         Flags.setSRet();
10242       if (Arg.hasAttribute(Attribute::SwiftSelf))
10243         Flags.setSwiftSelf();
10244       if (Arg.hasAttribute(Attribute::SwiftAsync))
10245         Flags.setSwiftAsync();
10246       if (Arg.hasAttribute(Attribute::SwiftError))
10247         Flags.setSwiftError();
10248       if (Arg.hasAttribute(Attribute::ByVal))
10249         Flags.setByVal();
10250       if (Arg.hasAttribute(Attribute::ByRef))
10251         Flags.setByRef();
10252       if (Arg.hasAttribute(Attribute::InAlloca)) {
10253         Flags.setInAlloca();
10254         // Set the byval flag for CCAssignFn callbacks that don't know about
10255         // inalloca.  This way we can know how many bytes we should've allocated
10256         // and how many bytes a callee cleanup function will pop.  If we port
10257         // inalloca to more targets, we'll have to add custom inalloca handling
10258         // in the various CC lowering callbacks.
10259         Flags.setByVal();
10260       }
10261       if (Arg.hasAttribute(Attribute::Preallocated)) {
10262         Flags.setPreallocated();
10263         // Set the byval flag for CCAssignFn callbacks that don't know about
10264         // preallocated.  This way we can know how many bytes we should've
10265         // allocated and how many bytes a callee cleanup function will pop.  If
10266         // we port preallocated to more targets, we'll have to add custom
10267         // preallocated handling in the various CC lowering callbacks.
10268         Flags.setByVal();
10269       }
10270 
10271       // Certain targets (such as MIPS), may have a different ABI alignment
10272       // for a type depending on the context. Give the target a chance to
10273       // specify the alignment it wants.
10274       const Align OriginalAlignment(
10275           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10276       Flags.setOrigAlign(OriginalAlignment);
10277 
10278       Align MemAlign;
10279       Type *ArgMemTy = nullptr;
10280       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10281           Flags.isByRef()) {
10282         if (!ArgMemTy)
10283           ArgMemTy = Arg.getPointeeInMemoryValueType();
10284 
10285         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10286 
10287         // For in-memory arguments, size and alignment should be passed from FE.
10288         // BE will guess if this info is not there but there are cases it cannot
10289         // get right.
10290         if (auto ParamAlign = Arg.getParamStackAlign())
10291           MemAlign = *ParamAlign;
10292         else if ((ParamAlign = Arg.getParamAlign()))
10293           MemAlign = *ParamAlign;
10294         else
10295           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10296         if (Flags.isByRef())
10297           Flags.setByRefSize(MemSize);
10298         else
10299           Flags.setByValSize(MemSize);
10300       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10301         MemAlign = *ParamAlign;
10302       } else {
10303         MemAlign = OriginalAlignment;
10304       }
10305       Flags.setMemAlign(MemAlign);
10306 
10307       if (Arg.hasAttribute(Attribute::Nest))
10308         Flags.setNest();
10309       if (NeedsRegBlock)
10310         Flags.setInConsecutiveRegs();
10311       if (ArgCopyElisionCandidates.count(&Arg))
10312         Flags.setCopyElisionCandidate();
10313       if (Arg.hasAttribute(Attribute::Returned))
10314         Flags.setReturned();
10315 
10316       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10317           *CurDAG->getContext(), F.getCallingConv(), VT);
10318       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10319           *CurDAG->getContext(), F.getCallingConv(), VT);
10320       for (unsigned i = 0; i != NumRegs; ++i) {
10321         // For scalable vectors, use the minimum size; individual targets
10322         // are responsible for handling scalable vector arguments and
10323         // return values.
10324         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10325                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10326         if (NumRegs > 1 && i == 0)
10327           MyFlags.Flags.setSplit();
10328         // if it isn't first piece, alignment must be 1
10329         else if (i > 0) {
10330           MyFlags.Flags.setOrigAlign(Align(1));
10331           if (i == NumRegs - 1)
10332             MyFlags.Flags.setSplitEnd();
10333         }
10334         Ins.push_back(MyFlags);
10335       }
10336       if (NeedsRegBlock && Value == NumValues - 1)
10337         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10338       PartBase += VT.getStoreSize().getKnownMinSize();
10339     }
10340   }
10341 
10342   // Call the target to set up the argument values.
10343   SmallVector<SDValue, 8> InVals;
10344   SDValue NewRoot = TLI->LowerFormalArguments(
10345       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10346 
10347   // Verify that the target's LowerFormalArguments behaved as expected.
10348   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10349          "LowerFormalArguments didn't return a valid chain!");
10350   assert(InVals.size() == Ins.size() &&
10351          "LowerFormalArguments didn't emit the correct number of values!");
10352   LLVM_DEBUG({
10353     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10354       assert(InVals[i].getNode() &&
10355              "LowerFormalArguments emitted a null value!");
10356       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10357              "LowerFormalArguments emitted a value with the wrong type!");
10358     }
10359   });
10360 
10361   // Update the DAG with the new chain value resulting from argument lowering.
10362   DAG.setRoot(NewRoot);
10363 
10364   // Set up the argument values.
10365   unsigned i = 0;
10366   if (!FuncInfo->CanLowerReturn) {
10367     // Create a virtual register for the sret pointer, and put in a copy
10368     // from the sret argument into it.
10369     SmallVector<EVT, 1> ValueVTs;
10370     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10371                     F.getReturnType()->getPointerTo(
10372                         DAG.getDataLayout().getAllocaAddrSpace()),
10373                     ValueVTs);
10374     MVT VT = ValueVTs[0].getSimpleVT();
10375     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10376     Optional<ISD::NodeType> AssertOp = None;
10377     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10378                                         nullptr, F.getCallingConv(), AssertOp);
10379 
10380     MachineFunction& MF = SDB->DAG.getMachineFunction();
10381     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10382     Register SRetReg =
10383         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10384     FuncInfo->DemoteRegister = SRetReg;
10385     NewRoot =
10386         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10387     DAG.setRoot(NewRoot);
10388 
10389     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10390     ++i;
10391   }
10392 
10393   SmallVector<SDValue, 4> Chains;
10394   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10395   for (const Argument &Arg : F.args()) {
10396     SmallVector<SDValue, 4> ArgValues;
10397     SmallVector<EVT, 4> ValueVTs;
10398     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10399     unsigned NumValues = ValueVTs.size();
10400     if (NumValues == 0)
10401       continue;
10402 
10403     bool ArgHasUses = !Arg.use_empty();
10404 
10405     // Elide the copying store if the target loaded this argument from a
10406     // suitable fixed stack object.
10407     if (Ins[i].Flags.isCopyElisionCandidate()) {
10408       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10409                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10410                              InVals[i], ArgHasUses);
10411     }
10412 
10413     // If this argument is unused then remember its value. It is used to generate
10414     // debugging information.
10415     bool isSwiftErrorArg =
10416         TLI->supportSwiftError() &&
10417         Arg.hasAttribute(Attribute::SwiftError);
10418     if (!ArgHasUses && !isSwiftErrorArg) {
10419       SDB->setUnusedArgValue(&Arg, InVals[i]);
10420 
10421       // Also remember any frame index for use in FastISel.
10422       if (FrameIndexSDNode *FI =
10423           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10424         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10425     }
10426 
10427     for (unsigned Val = 0; Val != NumValues; ++Val) {
10428       EVT VT = ValueVTs[Val];
10429       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10430                                                       F.getCallingConv(), VT);
10431       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10432           *CurDAG->getContext(), F.getCallingConv(), VT);
10433 
10434       // Even an apparent 'unused' swifterror argument needs to be returned. So
10435       // we do generate a copy for it that can be used on return from the
10436       // function.
10437       if (ArgHasUses || isSwiftErrorArg) {
10438         Optional<ISD::NodeType> AssertOp;
10439         if (Arg.hasAttribute(Attribute::SExt))
10440           AssertOp = ISD::AssertSext;
10441         else if (Arg.hasAttribute(Attribute::ZExt))
10442           AssertOp = ISD::AssertZext;
10443 
10444         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10445                                              PartVT, VT, nullptr,
10446                                              F.getCallingConv(), AssertOp));
10447       }
10448 
10449       i += NumParts;
10450     }
10451 
10452     // We don't need to do anything else for unused arguments.
10453     if (ArgValues.empty())
10454       continue;
10455 
10456     // Note down frame index.
10457     if (FrameIndexSDNode *FI =
10458         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10459       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10460 
10461     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10462                                      SDB->getCurSDLoc());
10463 
10464     SDB->setValue(&Arg, Res);
10465     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10466       // We want to associate the argument with the frame index, among
10467       // involved operands, that correspond to the lowest address. The
10468       // getCopyFromParts function, called earlier, is swapping the order of
10469       // the operands to BUILD_PAIR depending on endianness. The result of
10470       // that swapping is that the least significant bits of the argument will
10471       // be in the first operand of the BUILD_PAIR node, and the most
10472       // significant bits will be in the second operand.
10473       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10474       if (LoadSDNode *LNode =
10475           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10476         if (FrameIndexSDNode *FI =
10477             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10478           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10479     }
10480 
10481     // Analyses past this point are naive and don't expect an assertion.
10482     if (Res.getOpcode() == ISD::AssertZext)
10483       Res = Res.getOperand(0);
10484 
10485     // Update the SwiftErrorVRegDefMap.
10486     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10487       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10488       if (Register::isVirtualRegister(Reg))
10489         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10490                                    Reg);
10491     }
10492 
10493     // If this argument is live outside of the entry block, insert a copy from
10494     // wherever we got it to the vreg that other BB's will reference it as.
10495     if (Res.getOpcode() == ISD::CopyFromReg) {
10496       // If we can, though, try to skip creating an unnecessary vreg.
10497       // FIXME: This isn't very clean... it would be nice to make this more
10498       // general.
10499       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10500       if (Register::isVirtualRegister(Reg)) {
10501         FuncInfo->ValueMap[&Arg] = Reg;
10502         continue;
10503       }
10504     }
10505     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10506       FuncInfo->InitializeRegForValue(&Arg);
10507       SDB->CopyToExportRegsIfNeeded(&Arg);
10508     }
10509   }
10510 
10511   if (!Chains.empty()) {
10512     Chains.push_back(NewRoot);
10513     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10514   }
10515 
10516   DAG.setRoot(NewRoot);
10517 
10518   assert(i == InVals.size() && "Argument register count mismatch!");
10519 
10520   // If any argument copy elisions occurred and we have debug info, update the
10521   // stale frame indices used in the dbg.declare variable info table.
10522   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10523   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10524     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10525       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10526       if (I != ArgCopyElisionFrameIndexMap.end())
10527         VI.Slot = I->second;
10528     }
10529   }
10530 
10531   // Finally, if the target has anything special to do, allow it to do so.
10532   emitFunctionEntryCode();
10533 }
10534 
10535 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10536 /// ensure constants are generated when needed.  Remember the virtual registers
10537 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10538 /// directly add them, because expansion might result in multiple MBB's for one
10539 /// BB.  As such, the start of the BB might correspond to a different MBB than
10540 /// the end.
10541 void
10542 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10543   const Instruction *TI = LLVMBB->getTerminator();
10544 
10545   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10546 
10547   // Check PHI nodes in successors that expect a value to be available from this
10548   // block.
10549   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10550     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10551     if (!isa<PHINode>(SuccBB->begin())) continue;
10552     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10553 
10554     // If this terminator has multiple identical successors (common for
10555     // switches), only handle each succ once.
10556     if (!SuccsHandled.insert(SuccMBB).second)
10557       continue;
10558 
10559     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10560 
10561     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10562     // nodes and Machine PHI nodes, but the incoming operands have not been
10563     // emitted yet.
10564     for (const PHINode &PN : SuccBB->phis()) {
10565       // Ignore dead phi's.
10566       if (PN.use_empty())
10567         continue;
10568 
10569       // Skip empty types
10570       if (PN.getType()->isEmptyTy())
10571         continue;
10572 
10573       unsigned Reg;
10574       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10575 
10576       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10577         unsigned &RegOut = ConstantsOut[C];
10578         if (RegOut == 0) {
10579           RegOut = FuncInfo.CreateRegs(C);
10580           CopyValueToVirtualRegister(C, RegOut);
10581         }
10582         Reg = RegOut;
10583       } else {
10584         DenseMap<const Value *, Register>::iterator I =
10585           FuncInfo.ValueMap.find(PHIOp);
10586         if (I != FuncInfo.ValueMap.end())
10587           Reg = I->second;
10588         else {
10589           assert(isa<AllocaInst>(PHIOp) &&
10590                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10591                  "Didn't codegen value into a register!??");
10592           Reg = FuncInfo.CreateRegs(PHIOp);
10593           CopyValueToVirtualRegister(PHIOp, Reg);
10594         }
10595       }
10596 
10597       // Remember that this register needs to added to the machine PHI node as
10598       // the input for this MBB.
10599       SmallVector<EVT, 4> ValueVTs;
10600       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10601       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10602       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10603         EVT VT = ValueVTs[vti];
10604         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10605         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10606           FuncInfo.PHINodesToUpdate.push_back(
10607               std::make_pair(&*MBBI++, Reg + i));
10608         Reg += NumRegisters;
10609       }
10610     }
10611   }
10612 
10613   ConstantsOut.clear();
10614 }
10615 
10616 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10617 /// is 0.
10618 MachineBasicBlock *
10619 SelectionDAGBuilder::StackProtectorDescriptor::
10620 AddSuccessorMBB(const BasicBlock *BB,
10621                 MachineBasicBlock *ParentMBB,
10622                 bool IsLikely,
10623                 MachineBasicBlock *SuccMBB) {
10624   // If SuccBB has not been created yet, create it.
10625   if (!SuccMBB) {
10626     MachineFunction *MF = ParentMBB->getParent();
10627     MachineFunction::iterator BBI(ParentMBB);
10628     SuccMBB = MF->CreateMachineBasicBlock(BB);
10629     MF->insert(++BBI, SuccMBB);
10630   }
10631   // Add it as a successor of ParentMBB.
10632   ParentMBB->addSuccessor(
10633       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10634   return SuccMBB;
10635 }
10636 
10637 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10638   MachineFunction::iterator I(MBB);
10639   if (++I == FuncInfo.MF->end())
10640     return nullptr;
10641   return &*I;
10642 }
10643 
10644 /// During lowering new call nodes can be created (such as memset, etc.).
10645 /// Those will become new roots of the current DAG, but complications arise
10646 /// when they are tail calls. In such cases, the call lowering will update
10647 /// the root, but the builder still needs to know that a tail call has been
10648 /// lowered in order to avoid generating an additional return.
10649 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10650   // If the node is null, we do have a tail call.
10651   if (MaybeTC.getNode() != nullptr)
10652     DAG.setRoot(MaybeTC);
10653   else
10654     HasTailCall = true;
10655 }
10656 
10657 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10658                                         MachineBasicBlock *SwitchMBB,
10659                                         MachineBasicBlock *DefaultMBB) {
10660   MachineFunction *CurMF = FuncInfo.MF;
10661   MachineBasicBlock *NextMBB = nullptr;
10662   MachineFunction::iterator BBI(W.MBB);
10663   if (++BBI != FuncInfo.MF->end())
10664     NextMBB = &*BBI;
10665 
10666   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10667 
10668   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10669 
10670   if (Size == 2 && W.MBB == SwitchMBB) {
10671     // If any two of the cases has the same destination, and if one value
10672     // is the same as the other, but has one bit unset that the other has set,
10673     // use bit manipulation to do two compares at once.  For example:
10674     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10675     // TODO: This could be extended to merge any 2 cases in switches with 3
10676     // cases.
10677     // TODO: Handle cases where W.CaseBB != SwitchBB.
10678     CaseCluster &Small = *W.FirstCluster;
10679     CaseCluster &Big = *W.LastCluster;
10680 
10681     if (Small.Low == Small.High && Big.Low == Big.High &&
10682         Small.MBB == Big.MBB) {
10683       const APInt &SmallValue = Small.Low->getValue();
10684       const APInt &BigValue = Big.Low->getValue();
10685 
10686       // Check that there is only one bit different.
10687       APInt CommonBit = BigValue ^ SmallValue;
10688       if (CommonBit.isPowerOf2()) {
10689         SDValue CondLHS = getValue(Cond);
10690         EVT VT = CondLHS.getValueType();
10691         SDLoc DL = getCurSDLoc();
10692 
10693         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10694                                  DAG.getConstant(CommonBit, DL, VT));
10695         SDValue Cond = DAG.getSetCC(
10696             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10697             ISD::SETEQ);
10698 
10699         // Update successor info.
10700         // Both Small and Big will jump to Small.BB, so we sum up the
10701         // probabilities.
10702         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10703         if (BPI)
10704           addSuccessorWithProb(
10705               SwitchMBB, DefaultMBB,
10706               // The default destination is the first successor in IR.
10707               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10708         else
10709           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10710 
10711         // Insert the true branch.
10712         SDValue BrCond =
10713             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10714                         DAG.getBasicBlock(Small.MBB));
10715         // Insert the false branch.
10716         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10717                              DAG.getBasicBlock(DefaultMBB));
10718 
10719         DAG.setRoot(BrCond);
10720         return;
10721       }
10722     }
10723   }
10724 
10725   if (TM.getOptLevel() != CodeGenOpt::None) {
10726     // Here, we order cases by probability so the most likely case will be
10727     // checked first. However, two clusters can have the same probability in
10728     // which case their relative ordering is non-deterministic. So we use Low
10729     // as a tie-breaker as clusters are guaranteed to never overlap.
10730     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10731                [](const CaseCluster &a, const CaseCluster &b) {
10732       return a.Prob != b.Prob ?
10733              a.Prob > b.Prob :
10734              a.Low->getValue().slt(b.Low->getValue());
10735     });
10736 
10737     // Rearrange the case blocks so that the last one falls through if possible
10738     // without changing the order of probabilities.
10739     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10740       --I;
10741       if (I->Prob > W.LastCluster->Prob)
10742         break;
10743       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10744         std::swap(*I, *W.LastCluster);
10745         break;
10746       }
10747     }
10748   }
10749 
10750   // Compute total probability.
10751   BranchProbability DefaultProb = W.DefaultProb;
10752   BranchProbability UnhandledProbs = DefaultProb;
10753   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10754     UnhandledProbs += I->Prob;
10755 
10756   MachineBasicBlock *CurMBB = W.MBB;
10757   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10758     bool FallthroughUnreachable = false;
10759     MachineBasicBlock *Fallthrough;
10760     if (I == W.LastCluster) {
10761       // For the last cluster, fall through to the default destination.
10762       Fallthrough = DefaultMBB;
10763       FallthroughUnreachable = isa<UnreachableInst>(
10764           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10765     } else {
10766       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10767       CurMF->insert(BBI, Fallthrough);
10768       // Put Cond in a virtual register to make it available from the new blocks.
10769       ExportFromCurrentBlock(Cond);
10770     }
10771     UnhandledProbs -= I->Prob;
10772 
10773     switch (I->Kind) {
10774       case CC_JumpTable: {
10775         // FIXME: Optimize away range check based on pivot comparisons.
10776         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10777         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10778 
10779         // The jump block hasn't been inserted yet; insert it here.
10780         MachineBasicBlock *JumpMBB = JT->MBB;
10781         CurMF->insert(BBI, JumpMBB);
10782 
10783         auto JumpProb = I->Prob;
10784         auto FallthroughProb = UnhandledProbs;
10785 
10786         // If the default statement is a target of the jump table, we evenly
10787         // distribute the default probability to successors of CurMBB. Also
10788         // update the probability on the edge from JumpMBB to Fallthrough.
10789         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10790                                               SE = JumpMBB->succ_end();
10791              SI != SE; ++SI) {
10792           if (*SI == DefaultMBB) {
10793             JumpProb += DefaultProb / 2;
10794             FallthroughProb -= DefaultProb / 2;
10795             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10796             JumpMBB->normalizeSuccProbs();
10797             break;
10798           }
10799         }
10800 
10801         if (FallthroughUnreachable)
10802           JTH->FallthroughUnreachable = true;
10803 
10804         if (!JTH->FallthroughUnreachable)
10805           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10806         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10807         CurMBB->normalizeSuccProbs();
10808 
10809         // The jump table header will be inserted in our current block, do the
10810         // range check, and fall through to our fallthrough block.
10811         JTH->HeaderBB = CurMBB;
10812         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10813 
10814         // If we're in the right place, emit the jump table header right now.
10815         if (CurMBB == SwitchMBB) {
10816           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10817           JTH->Emitted = true;
10818         }
10819         break;
10820       }
10821       case CC_BitTests: {
10822         // FIXME: Optimize away range check based on pivot comparisons.
10823         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10824 
10825         // The bit test blocks haven't been inserted yet; insert them here.
10826         for (BitTestCase &BTC : BTB->Cases)
10827           CurMF->insert(BBI, BTC.ThisBB);
10828 
10829         // Fill in fields of the BitTestBlock.
10830         BTB->Parent = CurMBB;
10831         BTB->Default = Fallthrough;
10832 
10833         BTB->DefaultProb = UnhandledProbs;
10834         // If the cases in bit test don't form a contiguous range, we evenly
10835         // distribute the probability on the edge to Fallthrough to two
10836         // successors of CurMBB.
10837         if (!BTB->ContiguousRange) {
10838           BTB->Prob += DefaultProb / 2;
10839           BTB->DefaultProb -= DefaultProb / 2;
10840         }
10841 
10842         if (FallthroughUnreachable)
10843           BTB->FallthroughUnreachable = true;
10844 
10845         // If we're in the right place, emit the bit test header right now.
10846         if (CurMBB == SwitchMBB) {
10847           visitBitTestHeader(*BTB, SwitchMBB);
10848           BTB->Emitted = true;
10849         }
10850         break;
10851       }
10852       case CC_Range: {
10853         const Value *RHS, *LHS, *MHS;
10854         ISD::CondCode CC;
10855         if (I->Low == I->High) {
10856           // Check Cond == I->Low.
10857           CC = ISD::SETEQ;
10858           LHS = Cond;
10859           RHS=I->Low;
10860           MHS = nullptr;
10861         } else {
10862           // Check I->Low <= Cond <= I->High.
10863           CC = ISD::SETLE;
10864           LHS = I->Low;
10865           MHS = Cond;
10866           RHS = I->High;
10867         }
10868 
10869         // If Fallthrough is unreachable, fold away the comparison.
10870         if (FallthroughUnreachable)
10871           CC = ISD::SETTRUE;
10872 
10873         // The false probability is the sum of all unhandled cases.
10874         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10875                      getCurSDLoc(), I->Prob, UnhandledProbs);
10876 
10877         if (CurMBB == SwitchMBB)
10878           visitSwitchCase(CB, SwitchMBB);
10879         else
10880           SL->SwitchCases.push_back(CB);
10881 
10882         break;
10883       }
10884     }
10885     CurMBB = Fallthrough;
10886   }
10887 }
10888 
10889 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10890                                               CaseClusterIt First,
10891                                               CaseClusterIt Last) {
10892   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10893     if (X.Prob != CC.Prob)
10894       return X.Prob > CC.Prob;
10895 
10896     // Ties are broken by comparing the case value.
10897     return X.Low->getValue().slt(CC.Low->getValue());
10898   });
10899 }
10900 
10901 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10902                                         const SwitchWorkListItem &W,
10903                                         Value *Cond,
10904                                         MachineBasicBlock *SwitchMBB) {
10905   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10906          "Clusters not sorted?");
10907 
10908   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10909 
10910   // Balance the tree based on branch probabilities to create a near-optimal (in
10911   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10912   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10913   CaseClusterIt LastLeft = W.FirstCluster;
10914   CaseClusterIt FirstRight = W.LastCluster;
10915   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10916   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10917 
10918   // Move LastLeft and FirstRight towards each other from opposite directions to
10919   // find a partitioning of the clusters which balances the probability on both
10920   // sides. If LeftProb and RightProb are equal, alternate which side is
10921   // taken to ensure 0-probability nodes are distributed evenly.
10922   unsigned I = 0;
10923   while (LastLeft + 1 < FirstRight) {
10924     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10925       LeftProb += (++LastLeft)->Prob;
10926     else
10927       RightProb += (--FirstRight)->Prob;
10928     I++;
10929   }
10930 
10931   while (true) {
10932     // Our binary search tree differs from a typical BST in that ours can have up
10933     // to three values in each leaf. The pivot selection above doesn't take that
10934     // into account, which means the tree might require more nodes and be less
10935     // efficient. We compensate for this here.
10936 
10937     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10938     unsigned NumRight = W.LastCluster - FirstRight + 1;
10939 
10940     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10941       // If one side has less than 3 clusters, and the other has more than 3,
10942       // consider taking a cluster from the other side.
10943 
10944       if (NumLeft < NumRight) {
10945         // Consider moving the first cluster on the right to the left side.
10946         CaseCluster &CC = *FirstRight;
10947         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10948         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10949         if (LeftSideRank <= RightSideRank) {
10950           // Moving the cluster to the left does not demote it.
10951           ++LastLeft;
10952           ++FirstRight;
10953           continue;
10954         }
10955       } else {
10956         assert(NumRight < NumLeft);
10957         // Consider moving the last element on the left to the right side.
10958         CaseCluster &CC = *LastLeft;
10959         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10960         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10961         if (RightSideRank <= LeftSideRank) {
10962           // Moving the cluster to the right does not demot it.
10963           --LastLeft;
10964           --FirstRight;
10965           continue;
10966         }
10967       }
10968     }
10969     break;
10970   }
10971 
10972   assert(LastLeft + 1 == FirstRight);
10973   assert(LastLeft >= W.FirstCluster);
10974   assert(FirstRight <= W.LastCluster);
10975 
10976   // Use the first element on the right as pivot since we will make less-than
10977   // comparisons against it.
10978   CaseClusterIt PivotCluster = FirstRight;
10979   assert(PivotCluster > W.FirstCluster);
10980   assert(PivotCluster <= W.LastCluster);
10981 
10982   CaseClusterIt FirstLeft = W.FirstCluster;
10983   CaseClusterIt LastRight = W.LastCluster;
10984 
10985   const ConstantInt *Pivot = PivotCluster->Low;
10986 
10987   // New blocks will be inserted immediately after the current one.
10988   MachineFunction::iterator BBI(W.MBB);
10989   ++BBI;
10990 
10991   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10992   // we can branch to its destination directly if it's squeezed exactly in
10993   // between the known lower bound and Pivot - 1.
10994   MachineBasicBlock *LeftMBB;
10995   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10996       FirstLeft->Low == W.GE &&
10997       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10998     LeftMBB = FirstLeft->MBB;
10999   } else {
11000     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11001     FuncInfo.MF->insert(BBI, LeftMBB);
11002     WorkList.push_back(
11003         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11004     // Put Cond in a virtual register to make it available from the new blocks.
11005     ExportFromCurrentBlock(Cond);
11006   }
11007 
11008   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11009   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11010   // directly if RHS.High equals the current upper bound.
11011   MachineBasicBlock *RightMBB;
11012   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11013       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11014     RightMBB = FirstRight->MBB;
11015   } else {
11016     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11017     FuncInfo.MF->insert(BBI, RightMBB);
11018     WorkList.push_back(
11019         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11020     // Put Cond in a virtual register to make it available from the new blocks.
11021     ExportFromCurrentBlock(Cond);
11022   }
11023 
11024   // Create the CaseBlock record that will be used to lower the branch.
11025   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11026                getCurSDLoc(), LeftProb, RightProb);
11027 
11028   if (W.MBB == SwitchMBB)
11029     visitSwitchCase(CB, SwitchMBB);
11030   else
11031     SL->SwitchCases.push_back(CB);
11032 }
11033 
11034 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11035 // from the swith statement.
11036 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11037                                             BranchProbability PeeledCaseProb) {
11038   if (PeeledCaseProb == BranchProbability::getOne())
11039     return BranchProbability::getZero();
11040   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11041 
11042   uint32_t Numerator = CaseProb.getNumerator();
11043   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11044   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11045 }
11046 
11047 // Try to peel the top probability case if it exceeds the threshold.
11048 // Return current MachineBasicBlock for the switch statement if the peeling
11049 // does not occur.
11050 // If the peeling is performed, return the newly created MachineBasicBlock
11051 // for the peeled switch statement. Also update Clusters to remove the peeled
11052 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11053 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11054     const SwitchInst &SI, CaseClusterVector &Clusters,
11055     BranchProbability &PeeledCaseProb) {
11056   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11057   // Don't perform if there is only one cluster or optimizing for size.
11058   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11059       TM.getOptLevel() == CodeGenOpt::None ||
11060       SwitchMBB->getParent()->getFunction().hasMinSize())
11061     return SwitchMBB;
11062 
11063   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11064   unsigned PeeledCaseIndex = 0;
11065   bool SwitchPeeled = false;
11066   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11067     CaseCluster &CC = Clusters[Index];
11068     if (CC.Prob < TopCaseProb)
11069       continue;
11070     TopCaseProb = CC.Prob;
11071     PeeledCaseIndex = Index;
11072     SwitchPeeled = true;
11073   }
11074   if (!SwitchPeeled)
11075     return SwitchMBB;
11076 
11077   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11078                     << TopCaseProb << "\n");
11079 
11080   // Record the MBB for the peeled switch statement.
11081   MachineFunction::iterator BBI(SwitchMBB);
11082   ++BBI;
11083   MachineBasicBlock *PeeledSwitchMBB =
11084       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11085   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11086 
11087   ExportFromCurrentBlock(SI.getCondition());
11088   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11089   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11090                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11091   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11092 
11093   Clusters.erase(PeeledCaseIt);
11094   for (CaseCluster &CC : Clusters) {
11095     LLVM_DEBUG(
11096         dbgs() << "Scale the probablity for one cluster, before scaling: "
11097                << CC.Prob << "\n");
11098     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11099     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11100   }
11101   PeeledCaseProb = TopCaseProb;
11102   return PeeledSwitchMBB;
11103 }
11104 
11105 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11106   // Extract cases from the switch.
11107   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11108   CaseClusterVector Clusters;
11109   Clusters.reserve(SI.getNumCases());
11110   for (auto I : SI.cases()) {
11111     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11112     const ConstantInt *CaseVal = I.getCaseValue();
11113     BranchProbability Prob =
11114         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11115             : BranchProbability(1, SI.getNumCases() + 1);
11116     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11117   }
11118 
11119   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11120 
11121   // Cluster adjacent cases with the same destination. We do this at all
11122   // optimization levels because it's cheap to do and will make codegen faster
11123   // if there are many clusters.
11124   sortAndRangeify(Clusters);
11125 
11126   // The branch probablity of the peeled case.
11127   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11128   MachineBasicBlock *PeeledSwitchMBB =
11129       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11130 
11131   // If there is only the default destination, jump there directly.
11132   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11133   if (Clusters.empty()) {
11134     assert(PeeledSwitchMBB == SwitchMBB);
11135     SwitchMBB->addSuccessor(DefaultMBB);
11136     if (DefaultMBB != NextBlock(SwitchMBB)) {
11137       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11138                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11139     }
11140     return;
11141   }
11142 
11143   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11144   SL->findBitTestClusters(Clusters, &SI);
11145 
11146   LLVM_DEBUG({
11147     dbgs() << "Case clusters: ";
11148     for (const CaseCluster &C : Clusters) {
11149       if (C.Kind == CC_JumpTable)
11150         dbgs() << "JT:";
11151       if (C.Kind == CC_BitTests)
11152         dbgs() << "BT:";
11153 
11154       C.Low->getValue().print(dbgs(), true);
11155       if (C.Low != C.High) {
11156         dbgs() << '-';
11157         C.High->getValue().print(dbgs(), true);
11158       }
11159       dbgs() << ' ';
11160     }
11161     dbgs() << '\n';
11162   });
11163 
11164   assert(!Clusters.empty());
11165   SwitchWorkList WorkList;
11166   CaseClusterIt First = Clusters.begin();
11167   CaseClusterIt Last = Clusters.end() - 1;
11168   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11169   // Scale the branchprobability for DefaultMBB if the peel occurs and
11170   // DefaultMBB is not replaced.
11171   if (PeeledCaseProb != BranchProbability::getZero() &&
11172       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11173     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11174   WorkList.push_back(
11175       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11176 
11177   while (!WorkList.empty()) {
11178     SwitchWorkListItem W = WorkList.pop_back_val();
11179     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11180 
11181     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11182         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11183       // For optimized builds, lower large range as a balanced binary tree.
11184       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11185       continue;
11186     }
11187 
11188     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11189   }
11190 }
11191 
11192 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11194   auto DL = getCurSDLoc();
11195   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11196   setValue(&I, DAG.getStepVector(DL, ResultVT));
11197 }
11198 
11199 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11201   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11202 
11203   SDLoc DL = getCurSDLoc();
11204   SDValue V = getValue(I.getOperand(0));
11205   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11206 
11207   if (VT.isScalableVector()) {
11208     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11209     return;
11210   }
11211 
11212   // Use VECTOR_SHUFFLE for the fixed-length vector
11213   // to maintain existing behavior.
11214   SmallVector<int, 8> Mask;
11215   unsigned NumElts = VT.getVectorMinNumElements();
11216   for (unsigned i = 0; i != NumElts; ++i)
11217     Mask.push_back(NumElts - 1 - i);
11218 
11219   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11220 }
11221 
11222 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11223   SmallVector<EVT, 4> ValueVTs;
11224   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11225                   ValueVTs);
11226   unsigned NumValues = ValueVTs.size();
11227   if (NumValues == 0) return;
11228 
11229   SmallVector<SDValue, 4> Values(NumValues);
11230   SDValue Op = getValue(I.getOperand(0));
11231 
11232   for (unsigned i = 0; i != NumValues; ++i)
11233     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11234                             SDValue(Op.getNode(), Op.getResNo() + i));
11235 
11236   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11237                            DAG.getVTList(ValueVTs), Values));
11238 }
11239 
11240 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11242   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11243 
11244   SDLoc DL = getCurSDLoc();
11245   SDValue V1 = getValue(I.getOperand(0));
11246   SDValue V2 = getValue(I.getOperand(1));
11247   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11248 
11249   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11250   if (VT.isScalableVector()) {
11251     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11252     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11253                              DAG.getConstant(Imm, DL, IdxVT)));
11254     return;
11255   }
11256 
11257   unsigned NumElts = VT.getVectorNumElements();
11258 
11259   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11260     // Result is undefined if immediate is out-of-bounds.
11261     setValue(&I, DAG.getUNDEF(VT));
11262     return;
11263   }
11264 
11265   uint64_t Idx = (NumElts + Imm) % NumElts;
11266 
11267   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11268   SmallVector<int, 8> Mask;
11269   for (unsigned i = 0; i < NumElts; ++i)
11270     Mask.push_back(Idx + i);
11271   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11272 }
11273