xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 3067520bf463d93b17c4a92508e28df6b9bb90a9)
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/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/MC/MCSymbol.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Target/TargetIntrinsicInfo.h"
100 #include "llvm/Target/TargetMachine.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <cstring>
105 #include <iterator>
106 #include <limits>
107 #include <numeric>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       Optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
165                                 const SDValue *Parts, unsigned NumParts,
166                                 MVT PartVT, EVT ValueVT, const Value *V,
167                                 Optional<CallingConv::ID> CC = None,
168                                 Optional<ISD::NodeType> AssertOp = None) {
169   // Let the target assemble the parts if it wants to
170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
171   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
172                                                    PartVT, ValueVT, CC))
173     return Val;
174 
175   if (ValueVT.isVector())
176     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
177                                   CC);
178 
179   assert(NumParts > 0 && "No parts to assemble!");
180   SDValue Val = Parts[0];
181 
182   if (NumParts > 1) {
183     // Assemble the value from multiple parts.
184     if (ValueVT.isInteger()) {
185       unsigned PartBits = PartVT.getSizeInBits();
186       unsigned ValueBits = ValueVT.getSizeInBits();
187 
188       // Assemble the power of 2 part.
189       unsigned RoundParts =
190           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
200                               PartVT, HalfVT, V);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
202                               RoundParts / 2, PartVT, HalfVT, V);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi =
227             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                         TLI.getPointerTy(DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
249     }
250   }
251 
252   // There is now one part, held in Val.  Correct it to match ValueVT.
253   // PartEVT is the type of the register class that holds the value.
254   // ValueVT is the type of the inline asm operation.
255   EVT PartEVT = Val.getValueType();
256 
257   if (PartEVT == ValueVT)
258     return Val;
259 
260   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
261       ValueVT.bitsLT(PartEVT)) {
262     // For an FP value in an integer part, we need to truncate to the right
263     // width first.
264     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
265     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
266   }
267 
268   // Handle types that have the same size.
269   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
270     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
271 
272   // Handle types with different sizes.
273   if (PartEVT.isInteger() && ValueVT.isInteger()) {
274     if (ValueVT.bitsLT(PartEVT)) {
275       // For a truncate, see if we have any information to
276       // indicate whether the truncated bits will always be
277       // zero or sign-extension.
278       if (AssertOp.hasValue())
279         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
280                           DAG.getValueType(ValueVT));
281       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
282     }
283     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
284   }
285 
286   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
287     // FP_ROUND's are always exact here.
288     if (ValueVT.bitsLT(Val.getValueType()))
289       return DAG.getNode(
290           ISD::FP_ROUND, DL, ValueVT, Val,
291           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
292 
293     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
294   }
295 
296   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
297   // then truncating.
298   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
299       ValueVT.bitsLT(PartEVT)) {
300     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
301     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
302   }
303 
304   report_fatal_error("Unknown mismatch in getCopyFromParts!");
305 }
306 
307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
308                                               const Twine &ErrMsg) {
309   const Instruction *I = dyn_cast_or_null<Instruction>(V);
310   if (!V)
311     return Ctx.emitError(ErrMsg);
312 
313   const char *AsmError = ", possible invalid constraint for vector type";
314   if (const CallInst *CI = dyn_cast<CallInst>(I))
315     if (CI->isInlineAsm())
316       return Ctx.emitError(I, ErrMsg + AsmError);
317 
318   return Ctx.emitError(I, ErrMsg);
319 }
320 
321 /// getCopyFromPartsVector - Create a value that contains the specified legal
322 /// parts combined into the value they represent.  If the parts combine to a
323 /// type larger than ValueVT then AssertOp can be used to specify whether the
324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
325 /// ValueVT (ISD::AssertSext).
326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
327                                       const SDValue *Parts, unsigned NumParts,
328                                       MVT PartVT, EVT ValueVT, const Value *V,
329                                       Optional<CallingConv::ID> CallConv) {
330   assert(ValueVT.isVector() && "Not a vector value");
331   assert(NumParts > 0 && "No parts to assemble!");
332   const bool IsABIRegCopy = CallConv.hasValue();
333 
334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335   SDValue Val = Parts[0];
336 
337   // Handle a multi-element vector.
338   if (NumParts > 1) {
339     EVT IntermediateVT;
340     MVT RegisterVT;
341     unsigned NumIntermediates;
342     unsigned NumRegs;
343 
344     if (IsABIRegCopy) {
345       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
346           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
347           NumIntermediates, RegisterVT);
348     } else {
349       NumRegs =
350           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
351                                      NumIntermediates, RegisterVT);
352     }
353 
354     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
355     NumParts = NumRegs; // Silence a compiler warning.
356     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
357     assert(RegisterVT.getSizeInBits() ==
358            Parts[0].getSimpleValueType().getSizeInBits() &&
359            "Part type sizes don't match!");
360 
361     // Assemble the parts into intermediate operands.
362     SmallVector<SDValue, 8> Ops(NumIntermediates);
363     if (NumIntermediates == NumParts) {
364       // If the register was not expanded, truncate or copy the value,
365       // as appropriate.
366       for (unsigned i = 0; i != NumParts; ++i)
367         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
368                                   PartVT, IntermediateVT, V, CallConv);
369     } else if (NumParts > 0) {
370       // If the intermediate type was expanded, build the intermediate
371       // operands from the parts.
372       assert(NumParts % NumIntermediates == 0 &&
373              "Must expand into a divisible number of parts!");
374       unsigned Factor = NumParts / NumIntermediates;
375       for (unsigned i = 0; i != NumIntermediates; ++i)
376         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
377                                   PartVT, IntermediateVT, V, CallConv);
378     }
379 
380     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
381     // intermediate operands.
382     EVT BuiltVectorTy =
383         IntermediateVT.isVector()
384             ? EVT::getVectorVT(
385                   *DAG.getContext(), IntermediateVT.getScalarType(),
386                   IntermediateVT.getVectorElementCount() * NumParts)
387             : EVT::getVectorVT(*DAG.getContext(),
388                                IntermediateVT.getScalarType(),
389                                NumIntermediates);
390     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
391                                                 : ISD::BUILD_VECTOR,
392                       DL, BuiltVectorTy, Ops);
393   }
394 
395   // There is now one part, held in Val.  Correct it to match ValueVT.
396   EVT PartEVT = Val.getValueType();
397 
398   if (PartEVT == ValueVT)
399     return Val;
400 
401   if (PartEVT.isVector()) {
402     // If the element type of the source/dest vectors are the same, but the
403     // parts vector has more elements than the value vector, then we have a
404     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
405     // elements we want.
406     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
413                          DAG.getVectorIdxConstant(0, DL));
414     }
415 
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
421       "Cannot handle this kind of promotion");
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
440        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
441        // Drop the extra bits.
442        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
443        return DAG.getBitcast(ValueVT, Val);
444      }
445 
446      diagnosePossiblyInvalidConstraint(
447          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
448      return DAG.getUNDEF(ValueVT);
449   }
450 
451   // Handle cases such as i8 -> <1 x i1>
452   EVT ValueSVT = ValueVT.getVectorElementType();
453   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
454     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
455       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456     else
457       Val = ValueVT.isFloatingPoint()
458                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
459                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
460   }
461 
462   return DAG.getBuildVector(ValueVT, DL, Val);
463 }
464 
465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
466                                  SDValue Val, SDValue *Parts, unsigned NumParts,
467                                  MVT PartVT, const Value *V,
468                                  Optional<CallingConv::ID> CallConv);
469 
470 /// getCopyToParts - Create a series of nodes that contain the specified value
471 /// split into legal parts.  If the parts contain more bits than Val, then, for
472 /// integers, ExtendKind can be used to specify how to generate the extra bits.
473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
474                            SDValue *Parts, unsigned NumParts, MVT PartVT,
475                            const Value *V,
476                            Optional<CallingConv::ID> CallConv = None,
477                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
478   // Let the target split the parts if it wants to
479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
481                                       CallConv))
482     return;
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 CallConv);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
567 
568     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
569                    CallConv);
570 
571     if (DAG.getDataLayout().isBigEndian())
572       // The odd parts were reversed by getCopyToParts - unreverse them.
573       std::reverse(Parts + RoundParts, Parts + NumParts);
574 
575     NumParts = RoundParts;
576     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
577     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
578   }
579 
580   // The number of parts is a power of 2.  Repeatedly bisect the value using
581   // EXTRACT_ELEMENT.
582   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
583                          EVT::getIntegerVT(*DAG.getContext(),
584                                            ValueVT.getSizeInBits()),
585                          Val);
586 
587   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
588     for (unsigned i = 0; i < NumParts; i += StepSize) {
589       unsigned ThisBits = StepSize * PartBits / 2;
590       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
591       SDValue &Part0 = Parts[i];
592       SDValue &Part1 = Parts[i+StepSize/2];
593 
594       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
596       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
597                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
598 
599       if (ThisBits == PartBits && ThisVT != PartVT) {
600         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
601         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
602       }
603     }
604   }
605 
606   if (DAG.getDataLayout().isBigEndian())
607     std::reverse(Parts, Parts + OrigNumParts);
608 }
609 
610 static SDValue widenVectorToPartType(SelectionDAG &DAG,
611                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
612   if (!PartVT.isFixedLengthVector())
613     return SDValue();
614 
615   EVT ValueVT = Val.getValueType();
616   unsigned PartNumElts = PartVT.getVectorNumElements();
617   unsigned ValueNumElts = ValueVT.getVectorNumElements();
618   if (PartNumElts > ValueNumElts &&
619       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
620     EVT ElementVT = PartVT.getVectorElementType();
621     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
622     // undef elements.
623     SmallVector<SDValue, 16> Ops;
624     DAG.ExtractVectorElements(Val, Ops);
625     SDValue EltUndef = DAG.getUNDEF(ElementVT);
626     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
627       Ops.push_back(EltUndef);
628 
629     // FIXME: Use CONCAT for 2x -> 4x.
630     return DAG.getBuildVector(PartVT, DL, Ops);
631   }
632 
633   return SDValue();
634 }
635 
636 /// getCopyToPartsVector - Create a series of nodes that contain the specified
637 /// value split into legal parts.
638 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
639                                  SDValue Val, SDValue *Parts, unsigned NumParts,
640                                  MVT PartVT, const Value *V,
641                                  Optional<CallingConv::ID> CallConv) {
642   EVT ValueVT = Val.getValueType();
643   assert(ValueVT.isVector() && "Not a vector");
644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
645   const bool IsABIRegCopy = CallConv.hasValue();
646 
647   if (NumParts == 1) {
648     EVT PartEVT = PartVT;
649     if (PartEVT == ValueVT) {
650       // Nothing to do.
651     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
652       // Bitconvert vector->vector case.
653       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
654     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
655       Val = Widened;
656     } else if (PartVT.isVector() &&
657                PartEVT.getVectorElementType().bitsGE(
658                    ValueVT.getVectorElementType()) &&
659                PartEVT.getVectorElementCount() ==
660                    ValueVT.getVectorElementCount()) {
661 
662       // Promoted vector extract
663       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
664     } else {
665       if (ValueVT.getVectorElementCount().isScalar()) {
666         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
667                           DAG.getVectorIdxConstant(0, DL));
668       } else {
669         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
670         assert(PartVT.getFixedSizeInBits() > ValueSize &&
671                "lossy conversion of vector to scalar type");
672         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
673         Val = DAG.getBitcast(IntermediateType, Val);
674         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
675       }
676     }
677 
678     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
679     Parts[0] = Val;
680     return;
681   }
682 
683   // Handle a multi-element vector.
684   EVT IntermediateVT;
685   MVT RegisterVT;
686   unsigned NumIntermediates;
687   unsigned NumRegs;
688   if (IsABIRegCopy) {
689     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
690         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
691         NumIntermediates, RegisterVT);
692   } else {
693     NumRegs =
694         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
695                                    NumIntermediates, RegisterVT);
696   }
697 
698   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
699   NumParts = NumRegs; // Silence a compiler warning.
700   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
701 
702   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
703          "Mixing scalable and fixed vectors when copying in parts");
704 
705   Optional<ElementCount> DestEltCnt;
706 
707   if (IntermediateVT.isVector())
708     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
709   else
710     DestEltCnt = ElementCount::getFixed(NumIntermediates);
711 
712   EVT BuiltVectorTy = EVT::getVectorVT(
713       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
714 
715   if (ValueVT == BuiltVectorTy) {
716     // Nothing to do.
717   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
718     // Bitconvert vector->vector case.
719     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
720   } else if (SDValue Widened =
721                  widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
722     Val = Widened;
723   } else if (BuiltVectorTy.getVectorElementType().bitsGE(
724                  ValueVT.getVectorElementType()) &&
725              BuiltVectorTy.getVectorElementCount() ==
726                  ValueVT.getVectorElementCount()) {
727     // Promoted vector extract
728     Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy);
729   }
730 
731   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
732 
733   // Split the vector into intermediate operands.
734   SmallVector<SDValue, 8> Ops(NumIntermediates);
735   for (unsigned i = 0; i != NumIntermediates; ++i) {
736     if (IntermediateVT.isVector()) {
737       // This does something sensible for scalable vectors - see the
738       // definition of EXTRACT_SUBVECTOR for further details.
739       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
740       Ops[i] =
741           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
742                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
743     } else {
744       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
745                            DAG.getVectorIdxConstant(i, DL));
746     }
747   }
748 
749   // Split the intermediate operands into legal parts.
750   if (NumParts == NumIntermediates) {
751     // If the register was not expanded, promote or copy the value,
752     // as appropriate.
753     for (unsigned i = 0; i != NumParts; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
755   } else if (NumParts > 0) {
756     // If the intermediate type was expanded, split each the value into
757     // legal parts.
758     assert(NumIntermediates != 0 && "division by zero");
759     assert(NumParts % NumIntermediates == 0 &&
760            "Must expand into a divisible number of parts!");
761     unsigned Factor = NumParts / NumIntermediates;
762     for (unsigned i = 0; i != NumIntermediates; ++i)
763       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
764                      CallConv);
765   }
766 }
767 
768 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
769                            EVT valuevt, Optional<CallingConv::ID> CC)
770     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
771       RegCount(1, regs.size()), CallConv(CC) {}
772 
773 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
774                            const DataLayout &DL, unsigned Reg, Type *Ty,
775                            Optional<CallingConv::ID> CC) {
776   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
777 
778   CallConv = CC;
779 
780   for (EVT ValueVT : ValueVTs) {
781     unsigned NumRegs =
782         isABIMangled()
783             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
784             : TLI.getNumRegisters(Context, ValueVT);
785     MVT RegisterVT =
786         isABIMangled()
787             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
788             : TLI.getRegisterType(Context, ValueVT);
789     for (unsigned i = 0; i != NumRegs; ++i)
790       Regs.push_back(Reg + i);
791     RegVTs.push_back(RegisterVT);
792     RegCount.push_back(NumRegs);
793     Reg += NumRegs;
794   }
795 }
796 
797 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
798                                       FunctionLoweringInfo &FuncInfo,
799                                       const SDLoc &dl, SDValue &Chain,
800                                       SDValue *Flag, const Value *V) const {
801   // A Value with type {} or [0 x %t] needs no registers.
802   if (ValueVTs.empty())
803     return SDValue();
804 
805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
806 
807   // Assemble the legal parts into the final values.
808   SmallVector<SDValue, 4> Values(ValueVTs.size());
809   SmallVector<SDValue, 8> Parts;
810   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
811     // Copy the legal parts from the registers.
812     EVT ValueVT = ValueVTs[Value];
813     unsigned NumRegs = RegCount[Value];
814     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
815                                           *DAG.getContext(),
816                                           CallConv.getValue(), RegVTs[Value])
817                                     : RegVTs[Value];
818 
819     Parts.resize(NumRegs);
820     for (unsigned i = 0; i != NumRegs; ++i) {
821       SDValue P;
822       if (!Flag) {
823         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
824       } else {
825         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
826         *Flag = P.getValue(2);
827       }
828 
829       Chain = P.getValue(1);
830       Parts[i] = P;
831 
832       // If the source register was virtual and if we know something about it,
833       // add an assert node.
834       if (!Register::isVirtualRegister(Regs[Part + i]) ||
835           !RegisterVT.isInteger())
836         continue;
837 
838       const FunctionLoweringInfo::LiveOutInfo *LOI =
839         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
840       if (!LOI)
841         continue;
842 
843       unsigned RegSize = RegisterVT.getScalarSizeInBits();
844       unsigned NumSignBits = LOI->NumSignBits;
845       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
846 
847       if (NumZeroBits == RegSize) {
848         // The current value is a zero.
849         // Explicitly express that as it would be easier for
850         // optimizations to kick in.
851         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
852         continue;
853       }
854 
855       // FIXME: We capture more information than the dag can represent.  For
856       // now, just use the tightest assertzext/assertsext possible.
857       bool isSExt;
858       EVT FromVT(MVT::Other);
859       if (NumZeroBits) {
860         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
861         isSExt = false;
862       } else if (NumSignBits > 1) {
863         FromVT =
864             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
865         isSExt = true;
866       } else {
867         continue;
868       }
869       // Add an assertion node.
870       assert(FromVT != MVT::Other);
871       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
872                              RegisterVT, P, DAG.getValueType(FromVT));
873     }
874 
875     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
876                                      RegisterVT, ValueVT, V, CallConv);
877     Part += NumRegs;
878     Parts.clear();
879   }
880 
881   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
882 }
883 
884 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
885                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
886                                  const Value *V,
887                                  ISD::NodeType PreferredExtendType) const {
888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
889   ISD::NodeType ExtendKind = PreferredExtendType;
890 
891   // Get the list of the values's legal parts.
892   unsigned NumRegs = Regs.size();
893   SmallVector<SDValue, 8> Parts(NumRegs);
894   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
895     unsigned NumParts = RegCount[Value];
896 
897     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
898                                           *DAG.getContext(),
899                                           CallConv.getValue(), RegVTs[Value])
900                                     : RegVTs[Value];
901 
902     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
903       ExtendKind = ISD::ZERO_EXTEND;
904 
905     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
906                    NumParts, RegisterVT, V, CallConv, ExtendKind);
907     Part += NumParts;
908   }
909 
910   // Copy the parts into the registers.
911   SmallVector<SDValue, 8> Chains(NumRegs);
912   for (unsigned i = 0; i != NumRegs; ++i) {
913     SDValue Part;
914     if (!Flag) {
915       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
916     } else {
917       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
918       *Flag = Part.getValue(1);
919     }
920 
921     Chains[i] = Part.getValue(0);
922   }
923 
924   if (NumRegs == 1 || Flag)
925     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
926     // flagged to it. That is the CopyToReg nodes and the user are considered
927     // a single scheduling unit. If we create a TokenFactor and return it as
928     // chain, then the TokenFactor is both a predecessor (operand) of the
929     // user as well as a successor (the TF operands are flagged to the user).
930     // c1, f1 = CopyToReg
931     // c2, f2 = CopyToReg
932     // c3     = TokenFactor c1, c2
933     // ...
934     //        = op c3, ..., f2
935     Chain = Chains[NumRegs-1];
936   else
937     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
938 }
939 
940 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
941                                         unsigned MatchingIdx, const SDLoc &dl,
942                                         SelectionDAG &DAG,
943                                         std::vector<SDValue> &Ops) const {
944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
945 
946   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
947   if (HasMatching)
948     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
949   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
950     // Put the register class of the virtual registers in the flag word.  That
951     // way, later passes can recompute register class constraints for inline
952     // assembly as well as normal instructions.
953     // Don't do this for tied operands that can use the regclass information
954     // from the def.
955     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
956     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
957     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
958   }
959 
960   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
961   Ops.push_back(Res);
962 
963   if (Code == InlineAsm::Kind_Clobber) {
964     // Clobbers should always have a 1:1 mapping with registers, and may
965     // reference registers that have illegal (e.g. vector) types. Hence, we
966     // shouldn't try to apply any sort of splitting logic to them.
967     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
968            "No 1:1 mapping from clobbers to regs?");
969     Register SP = TLI.getStackPointerRegisterToSaveRestore();
970     (void)SP;
971     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
972       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
973       assert(
974           (Regs[I] != SP ||
975            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
976           "If we clobbered the stack pointer, MFI should know about it.");
977     }
978     return;
979   }
980 
981   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
982     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
983     MVT RegisterVT = RegVTs[Value];
984     for (unsigned i = 0; i != NumRegs; ++i) {
985       assert(Reg < Regs.size() && "Mismatch in # registers expected");
986       unsigned TheReg = Regs[Reg++];
987       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
988     }
989   }
990 }
991 
992 SmallVector<std::pair<unsigned, TypeSize>, 4>
993 RegsForValue::getRegsAndSizes() const {
994   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
995   unsigned I = 0;
996   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
997     unsigned RegCount = std::get<0>(CountAndVT);
998     MVT RegisterVT = std::get<1>(CountAndVT);
999     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1000     for (unsigned E = I + RegCount; I != E; ++I)
1001       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1002   }
1003   return OutVec;
1004 }
1005 
1006 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1007                                const TargetLibraryInfo *li) {
1008   AA = aa;
1009   GFI = gfi;
1010   LibInfo = li;
1011   DL = &DAG.getDataLayout();
1012   Context = DAG.getContext();
1013   LPadToCallSiteMap.clear();
1014   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1015 }
1016 
1017 void SelectionDAGBuilder::clear() {
1018   NodeMap.clear();
1019   UnusedArgNodeMap.clear();
1020   PendingLoads.clear();
1021   PendingExports.clear();
1022   PendingConstrainedFP.clear();
1023   PendingConstrainedFPStrict.clear();
1024   CurInst = nullptr;
1025   HasTailCall = false;
1026   SDNodeOrder = LowestSDNodeOrder;
1027   StatepointLowering.clear();
1028 }
1029 
1030 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1031   DanglingDebugInfoMap.clear();
1032 }
1033 
1034 // Update DAG root to include dependencies on Pending chains.
1035 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1036   SDValue Root = DAG.getRoot();
1037 
1038   if (Pending.empty())
1039     return Root;
1040 
1041   // Add current root to PendingChains, unless we already indirectly
1042   // depend on it.
1043   if (Root.getOpcode() != ISD::EntryToken) {
1044     unsigned i = 0, e = Pending.size();
1045     for (; i != e; ++i) {
1046       assert(Pending[i].getNode()->getNumOperands() > 1);
1047       if (Pending[i].getNode()->getOperand(0) == Root)
1048         break;  // Don't add the root if we already indirectly depend on it.
1049     }
1050 
1051     if (i == e)
1052       Pending.push_back(Root);
1053   }
1054 
1055   if (Pending.size() == 1)
1056     Root = Pending[0];
1057   else
1058     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1059 
1060   DAG.setRoot(Root);
1061   Pending.clear();
1062   return Root;
1063 }
1064 
1065 SDValue SelectionDAGBuilder::getMemoryRoot() {
1066   return updateRoot(PendingLoads);
1067 }
1068 
1069 SDValue SelectionDAGBuilder::getRoot() {
1070   // Chain up all pending constrained intrinsics together with all
1071   // pending loads, by simply appending them to PendingLoads and
1072   // then calling getMemoryRoot().
1073   PendingLoads.reserve(PendingLoads.size() +
1074                        PendingConstrainedFP.size() +
1075                        PendingConstrainedFPStrict.size());
1076   PendingLoads.append(PendingConstrainedFP.begin(),
1077                       PendingConstrainedFP.end());
1078   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1079                       PendingConstrainedFPStrict.end());
1080   PendingConstrainedFP.clear();
1081   PendingConstrainedFPStrict.clear();
1082   return getMemoryRoot();
1083 }
1084 
1085 SDValue SelectionDAGBuilder::getControlRoot() {
1086   // We need to emit pending fpexcept.strict constrained intrinsics,
1087   // so append them to the PendingExports list.
1088   PendingExports.append(PendingConstrainedFPStrict.begin(),
1089                         PendingConstrainedFPStrict.end());
1090   PendingConstrainedFPStrict.clear();
1091   return updateRoot(PendingExports);
1092 }
1093 
1094 void SelectionDAGBuilder::visit(const Instruction &I) {
1095   // Set up outgoing PHI node register values before emitting the terminator.
1096   if (I.isTerminator()) {
1097     HandlePHINodesInSuccessorBlocks(I.getParent());
1098   }
1099 
1100   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1101   if (!isa<DbgInfoIntrinsic>(I))
1102     ++SDNodeOrder;
1103 
1104   CurInst = &I;
1105 
1106   visit(I.getOpcode(), I);
1107 
1108   if (!I.isTerminator() && !HasTailCall &&
1109       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1110     CopyToExportRegsIfNeeded(&I);
1111 
1112   CurInst = nullptr;
1113 }
1114 
1115 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1116   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1117 }
1118 
1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1120   // Note: this doesn't use InstVisitor, because it has to work with
1121   // ConstantExpr's in addition to instructions.
1122   switch (Opcode) {
1123   default: llvm_unreachable("Unknown instruction type encountered!");
1124     // Build the switch statement using the Instruction.def file.
1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1126     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1127 #include "llvm/IR/Instruction.def"
1128   }
1129 }
1130 
1131 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1132                                                DebugLoc DL, unsigned Order) {
1133   // We treat variadic dbg_values differently at this stage.
1134   if (DI->hasArgList()) {
1135     // For variadic dbg_values we will now insert an undef.
1136     // FIXME: We can potentially recover these!
1137     SmallVector<SDDbgOperand, 2> Locs;
1138     for (const Value *V : DI->getValues()) {
1139       auto Undef = UndefValue::get(V->getType());
1140       Locs.push_back(SDDbgOperand::fromConst(Undef));
1141     }
1142     SDDbgValue *SDV = DAG.getDbgValueList(
1143         DI->getVariable(), DI->getExpression(), Locs, {},
1144         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1145     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1146   } else {
1147     // TODO: Dangling debug info will eventually either be resolved or produce
1148     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1149     // between the original dbg.value location and its resolved DBG_VALUE,
1150     // which we should ideally fill with an extra Undef DBG_VALUE.
1151     assert(DI->getNumVariableLocationOps() == 1 &&
1152            "DbgValueInst without an ArgList should have a single location "
1153            "operand.");
1154     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1155   }
1156 }
1157 
1158 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1159                                                 const DIExpression *Expr) {
1160   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1161     const DbgValueInst *DI = DDI.getDI();
1162     DIVariable *DanglingVariable = DI->getVariable();
1163     DIExpression *DanglingExpr = DI->getExpression();
1164     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1165       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1166       return true;
1167     }
1168     return false;
1169   };
1170 
1171   for (auto &DDIMI : DanglingDebugInfoMap) {
1172     DanglingDebugInfoVector &DDIV = DDIMI.second;
1173 
1174     // If debug info is to be dropped, run it through final checks to see
1175     // whether it can be salvaged.
1176     for (auto &DDI : DDIV)
1177       if (isMatchingDbgValue(DDI))
1178         salvageUnresolvedDbgValue(DDI);
1179 
1180     erase_if(DDIV, isMatchingDbgValue);
1181   }
1182 }
1183 
1184 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1185 // generate the debug data structures now that we've seen its definition.
1186 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1187                                                    SDValue Val) {
1188   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1189   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1190     return;
1191 
1192   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1193   for (auto &DDI : DDIV) {
1194     const DbgValueInst *DI = DDI.getDI();
1195     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1196     assert(DI && "Ill-formed DanglingDebugInfo");
1197     DebugLoc dl = DDI.getdl();
1198     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1199     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1200     DILocalVariable *Variable = DI->getVariable();
1201     DIExpression *Expr = DI->getExpression();
1202     assert(Variable->isValidLocationForIntrinsic(dl) &&
1203            "Expected inlined-at fields to agree");
1204     SDDbgValue *SDV;
1205     if (Val.getNode()) {
1206       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1207       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1208       // we couldn't resolve it directly when examining the DbgValue intrinsic
1209       // in the first place we should not be more successful here). Unless we
1210       // have some test case that prove this to be correct we should avoid
1211       // calling EmitFuncArgumentDbgValue here.
1212       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1213         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1214                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1215         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1216         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1217         // inserted after the definition of Val when emitting the instructions
1218         // after ISel. An alternative could be to teach
1219         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1220         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1221                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1222                    << ValSDNodeOrder << "\n");
1223         SDV = getDbgValue(Val, Variable, Expr, dl,
1224                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1225         DAG.AddDbgValue(SDV, false);
1226       } else
1227         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1228                           << "in EmitFuncArgumentDbgValue\n");
1229     } else {
1230       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1231       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1232       auto SDV =
1233           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1234       DAG.AddDbgValue(SDV, false);
1235     }
1236   }
1237   DDIV.clear();
1238 }
1239 
1240 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1241   // TODO: For the variadic implementation, instead of only checking the fail
1242   // state of `handleDebugValue`, we need know specifically which values were
1243   // invalid, so that we attempt to salvage only those values when processing
1244   // a DIArgList.
1245   assert(!DDI.getDI()->hasArgList() &&
1246          "Not implemented for variadic dbg_values");
1247   Value *V = DDI.getDI()->getValue(0);
1248   DILocalVariable *Var = DDI.getDI()->getVariable();
1249   DIExpression *Expr = DDI.getDI()->getExpression();
1250   DebugLoc DL = DDI.getdl();
1251   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1252   unsigned SDOrder = DDI.getSDNodeOrder();
1253   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1254   // that DW_OP_stack_value is desired.
1255   assert(isa<DbgValueInst>(DDI.getDI()));
1256   bool StackValue = true;
1257 
1258   // Can this Value can be encoded without any further work?
1259   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1260     return;
1261 
1262   // Attempt to salvage back through as many instructions as possible. Bail if
1263   // a non-instruction is seen, such as a constant expression or global
1264   // variable. FIXME: Further work could recover those too.
1265   while (isa<Instruction>(V)) {
1266     Instruction &VAsInst = *cast<Instruction>(V);
1267     // Temporary "0", awaiting real implementation.
1268     SmallVector<Value *, 4> AdditionalValues;
1269     DIExpression *SalvagedExpr =
1270         salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0, AdditionalValues);
1271 
1272     // If we cannot salvage any further, and haven't yet found a suitable debug
1273     // expression, bail out.
1274     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1275     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1276     // here for variadic dbg_values, remove that condition.
1277     if (!SalvagedExpr || !AdditionalValues.empty())
1278       break;
1279 
1280     // New value and expr now represent this debuginfo.
1281     V = VAsInst.getOperand(0);
1282     Expr = SalvagedExpr;
1283 
1284     // Some kind of simplification occurred: check whether the operand of the
1285     // salvaged debug expression can be encoded in this DAG.
1286     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1287                          /*IsVariadic=*/false)) {
1288       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1289                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1290       return;
1291     }
1292   }
1293 
1294   // This was the final opportunity to salvage this debug information, and it
1295   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1296   // any earlier variable location.
1297   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1298   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1299   DAG.AddDbgValue(SDV, false);
1300 
1301   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1302                     << "\n");
1303   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1304                     << "\n");
1305 }
1306 
1307 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1308                                            DILocalVariable *Var,
1309                                            DIExpression *Expr, DebugLoc dl,
1310                                            DebugLoc InstDL, unsigned Order,
1311                                            bool IsVariadic) {
1312   if (Values.empty())
1313     return true;
1314   SmallVector<SDDbgOperand> LocationOps;
1315   SmallVector<SDNode *> Dependencies;
1316   for (const Value *V : Values) {
1317     // Constant value.
1318     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1319         isa<ConstantPointerNull>(V)) {
1320       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1321       continue;
1322     }
1323 
1324     // If the Value is a frame index, we can create a FrameIndex debug value
1325     // without relying on the DAG at all.
1326     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1327       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1328       if (SI != FuncInfo.StaticAllocaMap.end()) {
1329         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1330         continue;
1331       }
1332     }
1333 
1334     // Do not use getValue() in here; we don't want to generate code at
1335     // this point if it hasn't been done yet.
1336     SDValue N = NodeMap[V];
1337     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1338       N = UnusedArgNodeMap[V];
1339     if (N.getNode()) {
1340       // Only emit func arg dbg value for non-variadic dbg.values for now.
1341       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1342         return true;
1343       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1344         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1345         // describe stack slot locations.
1346         //
1347         // Consider "int x = 0; int *px = &x;". There are two kinds of
1348         // interesting debug values here after optimization:
1349         //
1350         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1351         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1352         //
1353         // Both describe the direct values of their associated variables.
1354         Dependencies.push_back(N.getNode());
1355         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1356         continue;
1357       }
1358       LocationOps.emplace_back(
1359           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1360       continue;
1361     }
1362 
1363     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1364     // Special rules apply for the first dbg.values of parameter variables in a
1365     // function. Identify them by the fact they reference Argument Values, that
1366     // they're parameters, and they are parameters of the current function. We
1367     // need to let them dangle until they get an SDNode.
1368     bool IsParamOfFunc =
1369         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1370     if (IsParamOfFunc)
1371       return false;
1372 
1373     // The value is not used in this block yet (or it would have an SDNode).
1374     // We still want the value to appear for the user if possible -- if it has
1375     // an associated VReg, we can refer to that instead.
1376     auto VMI = FuncInfo.ValueMap.find(V);
1377     if (VMI != FuncInfo.ValueMap.end()) {
1378       unsigned Reg = VMI->second;
1379       // If this is a PHI node, it may be split up into several MI PHI nodes
1380       // (in FunctionLoweringInfo::set).
1381       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1382                        V->getType(), None);
1383       if (RFV.occupiesMultipleRegs()) {
1384         // FIXME: We could potentially support variadic dbg_values here.
1385         if (IsVariadic)
1386           return false;
1387         unsigned Offset = 0;
1388         unsigned BitsToDescribe = 0;
1389         if (auto VarSize = Var->getSizeInBits())
1390           BitsToDescribe = *VarSize;
1391         if (auto Fragment = Expr->getFragmentInfo())
1392           BitsToDescribe = Fragment->SizeInBits;
1393         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1394           // Bail out if all bits are described already.
1395           if (Offset >= BitsToDescribe)
1396             break;
1397           // TODO: handle scalable vectors.
1398           unsigned RegisterSize = RegAndSize.second;
1399           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1400                                       ? BitsToDescribe - Offset
1401                                       : RegisterSize;
1402           auto FragmentExpr = DIExpression::createFragmentExpression(
1403               Expr, Offset, FragmentSize);
1404           if (!FragmentExpr)
1405             continue;
1406           SDDbgValue *SDV = DAG.getVRegDbgValue(
1407               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1408           DAG.AddDbgValue(SDV, false);
1409           Offset += RegisterSize;
1410         }
1411         return true;
1412       }
1413       // We can use simple vreg locations for variadic dbg_values as well.
1414       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1415       continue;
1416     }
1417     // We failed to create a SDDbgOperand for V.
1418     return false;
1419   }
1420 
1421   // We have created a SDDbgOperand for each Value in Values.
1422   // Should use Order instead of SDNodeOrder?
1423   assert(!LocationOps.empty());
1424   SDDbgValue *SDV =
1425       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1426                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1427   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1428   return true;
1429 }
1430 
1431 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1432   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1433   for (auto &Pair : DanglingDebugInfoMap)
1434     for (auto &DDI : Pair.second)
1435       salvageUnresolvedDbgValue(DDI);
1436   clearDanglingDebugInfo();
1437 }
1438 
1439 /// getCopyFromRegs - If there was virtual register allocated for the value V
1440 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1441 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1442   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1443   SDValue Result;
1444 
1445   if (It != FuncInfo.ValueMap.end()) {
1446     Register InReg = It->second;
1447 
1448     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1449                      DAG.getDataLayout(), InReg, Ty,
1450                      None); // This is not an ABI copy.
1451     SDValue Chain = DAG.getEntryNode();
1452     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1453                                  V);
1454     resolveDanglingDebugInfo(V, Result);
1455   }
1456 
1457   return Result;
1458 }
1459 
1460 /// getValue - Return an SDValue for the given Value.
1461 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1462   // If we already have an SDValue for this value, use it. It's important
1463   // to do this first, so that we don't create a CopyFromReg if we already
1464   // have a regular SDValue.
1465   SDValue &N = NodeMap[V];
1466   if (N.getNode()) return N;
1467 
1468   // If there's a virtual register allocated and initialized for this
1469   // value, use it.
1470   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1471     return copyFromReg;
1472 
1473   // Otherwise create a new SDValue and remember it.
1474   SDValue Val = getValueImpl(V);
1475   NodeMap[V] = Val;
1476   resolveDanglingDebugInfo(V, Val);
1477   return Val;
1478 }
1479 
1480 /// getNonRegisterValue - Return an SDValue for the given Value, but
1481 /// don't look in FuncInfo.ValueMap for a virtual register.
1482 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1483   // If we already have an SDValue for this value, use it.
1484   SDValue &N = NodeMap[V];
1485   if (N.getNode()) {
1486     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1487       // Remove the debug location from the node as the node is about to be used
1488       // in a location which may differ from the original debug location.  This
1489       // is relevant to Constant and ConstantFP nodes because they can appear
1490       // as constant expressions inside PHI nodes.
1491       N->setDebugLoc(DebugLoc());
1492     }
1493     return N;
1494   }
1495 
1496   // Otherwise create a new SDValue and remember it.
1497   SDValue Val = getValueImpl(V);
1498   NodeMap[V] = Val;
1499   resolveDanglingDebugInfo(V, Val);
1500   return Val;
1501 }
1502 
1503 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1504 /// Create an SDValue for the given value.
1505 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1507 
1508   if (const Constant *C = dyn_cast<Constant>(V)) {
1509     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1510 
1511     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1512       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1513 
1514     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1515       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1516 
1517     if (isa<ConstantPointerNull>(C)) {
1518       unsigned AS = V->getType()->getPointerAddressSpace();
1519       return DAG.getConstant(0, getCurSDLoc(),
1520                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1521     }
1522 
1523     if (match(C, m_VScale(DAG.getDataLayout())))
1524       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1525 
1526     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1527       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1528 
1529     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1530       return DAG.getUNDEF(VT);
1531 
1532     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1533       visit(CE->getOpcode(), *CE);
1534       SDValue N1 = NodeMap[V];
1535       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1536       return N1;
1537     }
1538 
1539     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1540       SmallVector<SDValue, 4> Constants;
1541       for (const Use &U : C->operands()) {
1542         SDNode *Val = getValue(U).getNode();
1543         // If the operand is an empty aggregate, there are no values.
1544         if (!Val) continue;
1545         // Add each leaf value from the operand to the Constants list
1546         // to form a flattened list of all the values.
1547         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1548           Constants.push_back(SDValue(Val, i));
1549       }
1550 
1551       return DAG.getMergeValues(Constants, getCurSDLoc());
1552     }
1553 
1554     if (const ConstantDataSequential *CDS =
1555           dyn_cast<ConstantDataSequential>(C)) {
1556       SmallVector<SDValue, 4> Ops;
1557       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1558         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1559         // Add each leaf value from the operand to the Constants list
1560         // to form a flattened list of all the values.
1561         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1562           Ops.push_back(SDValue(Val, i));
1563       }
1564 
1565       if (isa<ArrayType>(CDS->getType()))
1566         return DAG.getMergeValues(Ops, getCurSDLoc());
1567       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1568     }
1569 
1570     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1571       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1572              "Unknown struct or array constant!");
1573 
1574       SmallVector<EVT, 4> ValueVTs;
1575       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1576       unsigned NumElts = ValueVTs.size();
1577       if (NumElts == 0)
1578         return SDValue(); // empty struct
1579       SmallVector<SDValue, 4> Constants(NumElts);
1580       for (unsigned i = 0; i != NumElts; ++i) {
1581         EVT EltVT = ValueVTs[i];
1582         if (isa<UndefValue>(C))
1583           Constants[i] = DAG.getUNDEF(EltVT);
1584         else if (EltVT.isFloatingPoint())
1585           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1586         else
1587           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1588       }
1589 
1590       return DAG.getMergeValues(Constants, getCurSDLoc());
1591     }
1592 
1593     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1594       return DAG.getBlockAddress(BA, VT);
1595 
1596     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1597       return getValue(Equiv->getGlobalValue());
1598 
1599     VectorType *VecTy = cast<VectorType>(V->getType());
1600 
1601     // Now that we know the number and type of the elements, get that number of
1602     // elements into the Ops array based on what kind of constant it is.
1603     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1604       SmallVector<SDValue, 16> Ops;
1605       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1606       for (unsigned i = 0; i != NumElements; ++i)
1607         Ops.push_back(getValue(CV->getOperand(i)));
1608 
1609       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1610     } else if (isa<ConstantAggregateZero>(C)) {
1611       EVT EltVT =
1612           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1613 
1614       SDValue Op;
1615       if (EltVT.isFloatingPoint())
1616         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1617       else
1618         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1619 
1620       if (isa<ScalableVectorType>(VecTy))
1621         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1622       else {
1623         SmallVector<SDValue, 16> Ops;
1624         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1625         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1626       }
1627     }
1628     llvm_unreachable("Unknown vector constant");
1629   }
1630 
1631   // If this is a static alloca, generate it as the frameindex instead of
1632   // computation.
1633   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1634     DenseMap<const AllocaInst*, int>::iterator SI =
1635       FuncInfo.StaticAllocaMap.find(AI);
1636     if (SI != FuncInfo.StaticAllocaMap.end())
1637       return DAG.getFrameIndex(SI->second,
1638                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1639   }
1640 
1641   // If this is an instruction which fast-isel has deferred, select it now.
1642   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1643     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1644 
1645     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1646                      Inst->getType(), None);
1647     SDValue Chain = DAG.getEntryNode();
1648     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1649   }
1650 
1651   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1652     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1653   }
1654   llvm_unreachable("Can't get register for value!");
1655 }
1656 
1657 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1658   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1659   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1660   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1661   bool IsSEH = isAsynchronousEHPersonality(Pers);
1662   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1663   if (!IsSEH)
1664     CatchPadMBB->setIsEHScopeEntry();
1665   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1666   if (IsMSVCCXX || IsCoreCLR)
1667     CatchPadMBB->setIsEHFuncletEntry();
1668 }
1669 
1670 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1671   // Update machine-CFG edge.
1672   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1673   FuncInfo.MBB->addSuccessor(TargetMBB);
1674   TargetMBB->setIsEHCatchretTarget(true);
1675   DAG.getMachineFunction().setHasEHCatchret(true);
1676 
1677   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1678   bool IsSEH = isAsynchronousEHPersonality(Pers);
1679   if (IsSEH) {
1680     // If this is not a fall-through branch or optimizations are switched off,
1681     // emit the branch.
1682     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1683         TM.getOptLevel() == CodeGenOpt::None)
1684       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1685                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1686     return;
1687   }
1688 
1689   // Figure out the funclet membership for the catchret's successor.
1690   // This will be used by the FuncletLayout pass to determine how to order the
1691   // BB's.
1692   // A 'catchret' returns to the outer scope's color.
1693   Value *ParentPad = I.getCatchSwitchParentPad();
1694   const BasicBlock *SuccessorColor;
1695   if (isa<ConstantTokenNone>(ParentPad))
1696     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1697   else
1698     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1699   assert(SuccessorColor && "No parent funclet for catchret!");
1700   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1701   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1702 
1703   // Create the terminator node.
1704   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1705                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1706                             DAG.getBasicBlock(SuccessorColorMBB));
1707   DAG.setRoot(Ret);
1708 }
1709 
1710 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1711   // Don't emit any special code for the cleanuppad instruction. It just marks
1712   // the start of an EH scope/funclet.
1713   FuncInfo.MBB->setIsEHScopeEntry();
1714   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1715   if (Pers != EHPersonality::Wasm_CXX) {
1716     FuncInfo.MBB->setIsEHFuncletEntry();
1717     FuncInfo.MBB->setIsCleanupFuncletEntry();
1718   }
1719 }
1720 
1721 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1722 // not match, it is OK to add only the first unwind destination catchpad to the
1723 // successors, because there will be at least one invoke instruction within the
1724 // catch scope that points to the next unwind destination, if one exists, so
1725 // CFGSort cannot mess up with BB sorting order.
1726 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1727 // call within them, and catchpads only consisting of 'catch (...)' have a
1728 // '__cxa_end_catch' call within them, both of which generate invokes in case
1729 // the next unwind destination exists, i.e., the next unwind destination is not
1730 // the caller.)
1731 //
1732 // Having at most one EH pad successor is also simpler and helps later
1733 // transformations.
1734 //
1735 // For example,
1736 // current:
1737 //   invoke void @foo to ... unwind label %catch.dispatch
1738 // catch.dispatch:
1739 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1740 // catch.start:
1741 //   ...
1742 //   ... in this BB or some other child BB dominated by this BB there will be an
1743 //   invoke that points to 'next' BB as an unwind destination
1744 //
1745 // next: ; We don't need to add this to 'current' BB's successor
1746 //   ...
1747 static void findWasmUnwindDestinations(
1748     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1749     BranchProbability Prob,
1750     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1751         &UnwindDests) {
1752   while (EHPadBB) {
1753     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1754     if (isa<CleanupPadInst>(Pad)) {
1755       // Stop on cleanup pads.
1756       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1757       UnwindDests.back().first->setIsEHScopeEntry();
1758       break;
1759     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1760       // Add the catchpad handlers to the possible destinations. We don't
1761       // continue to the unwind destination of the catchswitch for wasm.
1762       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1763         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1764         UnwindDests.back().first->setIsEHScopeEntry();
1765       }
1766       break;
1767     } else {
1768       continue;
1769     }
1770   }
1771 }
1772 
1773 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1774 /// many places it could ultimately go. In the IR, we have a single unwind
1775 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1776 /// This function skips over imaginary basic blocks that hold catchswitch
1777 /// instructions, and finds all the "real" machine
1778 /// basic block destinations. As those destinations may not be successors of
1779 /// EHPadBB, here we also calculate the edge probability to those destinations.
1780 /// The passed-in Prob is the edge probability to EHPadBB.
1781 static void findUnwindDestinations(
1782     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1783     BranchProbability Prob,
1784     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1785         &UnwindDests) {
1786   EHPersonality Personality =
1787     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1788   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1789   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1790   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1791   bool IsSEH = isAsynchronousEHPersonality(Personality);
1792 
1793   if (IsWasmCXX) {
1794     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1795     assert(UnwindDests.size() <= 1 &&
1796            "There should be at most one unwind destination for wasm");
1797     return;
1798   }
1799 
1800   while (EHPadBB) {
1801     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1802     BasicBlock *NewEHPadBB = nullptr;
1803     if (isa<LandingPadInst>(Pad)) {
1804       // Stop on landingpads. They are not funclets.
1805       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1806       break;
1807     } else if (isa<CleanupPadInst>(Pad)) {
1808       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1809       // personalities.
1810       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1811       UnwindDests.back().first->setIsEHScopeEntry();
1812       UnwindDests.back().first->setIsEHFuncletEntry();
1813       break;
1814     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1815       // Add the catchpad handlers to the possible destinations.
1816       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1817         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1818         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1819         if (IsMSVCCXX || IsCoreCLR)
1820           UnwindDests.back().first->setIsEHFuncletEntry();
1821         if (!IsSEH)
1822           UnwindDests.back().first->setIsEHScopeEntry();
1823       }
1824       NewEHPadBB = CatchSwitch->getUnwindDest();
1825     } else {
1826       continue;
1827     }
1828 
1829     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1830     if (BPI && NewEHPadBB)
1831       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1832     EHPadBB = NewEHPadBB;
1833   }
1834 }
1835 
1836 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1837   // Update successor info.
1838   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1839   auto UnwindDest = I.getUnwindDest();
1840   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1841   BranchProbability UnwindDestProb =
1842       (BPI && UnwindDest)
1843           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1844           : BranchProbability::getZero();
1845   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1846   for (auto &UnwindDest : UnwindDests) {
1847     UnwindDest.first->setIsEHPad();
1848     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1849   }
1850   FuncInfo.MBB->normalizeSuccProbs();
1851 
1852   // Create the terminator node.
1853   SDValue Ret =
1854       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1855   DAG.setRoot(Ret);
1856 }
1857 
1858 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1859   report_fatal_error("visitCatchSwitch not yet implemented!");
1860 }
1861 
1862 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1863   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1864   auto &DL = DAG.getDataLayout();
1865   SDValue Chain = getControlRoot();
1866   SmallVector<ISD::OutputArg, 8> Outs;
1867   SmallVector<SDValue, 8> OutVals;
1868 
1869   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1870   // lower
1871   //
1872   //   %val = call <ty> @llvm.experimental.deoptimize()
1873   //   ret <ty> %val
1874   //
1875   // differently.
1876   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1877     LowerDeoptimizingReturn();
1878     return;
1879   }
1880 
1881   if (!FuncInfo.CanLowerReturn) {
1882     unsigned DemoteReg = FuncInfo.DemoteRegister;
1883     const Function *F = I.getParent()->getParent();
1884 
1885     // Emit a store of the return value through the virtual register.
1886     // Leave Outs empty so that LowerReturn won't try to load return
1887     // registers the usual way.
1888     SmallVector<EVT, 1> PtrValueVTs;
1889     ComputeValueVTs(TLI, DL,
1890                     F->getReturnType()->getPointerTo(
1891                         DAG.getDataLayout().getAllocaAddrSpace()),
1892                     PtrValueVTs);
1893 
1894     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1895                                         DemoteReg, PtrValueVTs[0]);
1896     SDValue RetOp = getValue(I.getOperand(0));
1897 
1898     SmallVector<EVT, 4> ValueVTs, MemVTs;
1899     SmallVector<uint64_t, 4> Offsets;
1900     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1901                     &Offsets);
1902     unsigned NumValues = ValueVTs.size();
1903 
1904     SmallVector<SDValue, 4> Chains(NumValues);
1905     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1906     for (unsigned i = 0; i != NumValues; ++i) {
1907       // An aggregate return value cannot wrap around the address space, so
1908       // offsets to its parts don't wrap either.
1909       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1910                                            TypeSize::Fixed(Offsets[i]));
1911 
1912       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1913       if (MemVTs[i] != ValueVTs[i])
1914         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1915       Chains[i] = DAG.getStore(
1916           Chain, getCurSDLoc(), Val,
1917           // FIXME: better loc info would be nice.
1918           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1919           commonAlignment(BaseAlign, Offsets[i]));
1920     }
1921 
1922     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1923                         MVT::Other, Chains);
1924   } else if (I.getNumOperands() != 0) {
1925     SmallVector<EVT, 4> ValueVTs;
1926     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1927     unsigned NumValues = ValueVTs.size();
1928     if (NumValues) {
1929       SDValue RetOp = getValue(I.getOperand(0));
1930 
1931       const Function *F = I.getParent()->getParent();
1932 
1933       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1934           I.getOperand(0)->getType(), F->getCallingConv(),
1935           /*IsVarArg*/ false);
1936 
1937       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1938       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1939                                           Attribute::SExt))
1940         ExtendKind = ISD::SIGN_EXTEND;
1941       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1942                                                Attribute::ZExt))
1943         ExtendKind = ISD::ZERO_EXTEND;
1944 
1945       LLVMContext &Context = F->getContext();
1946       bool RetInReg = F->getAttributes().hasAttribute(
1947           AttributeList::ReturnIndex, Attribute::InReg);
1948 
1949       for (unsigned j = 0; j != NumValues; ++j) {
1950         EVT VT = ValueVTs[j];
1951 
1952         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1953           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1954 
1955         CallingConv::ID CC = F->getCallingConv();
1956 
1957         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1958         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1959         SmallVector<SDValue, 4> Parts(NumParts);
1960         getCopyToParts(DAG, getCurSDLoc(),
1961                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1962                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1963 
1964         // 'inreg' on function refers to return value
1965         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1966         if (RetInReg)
1967           Flags.setInReg();
1968 
1969         if (I.getOperand(0)->getType()->isPointerTy()) {
1970           Flags.setPointer();
1971           Flags.setPointerAddrSpace(
1972               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1973         }
1974 
1975         if (NeedsRegBlock) {
1976           Flags.setInConsecutiveRegs();
1977           if (j == NumValues - 1)
1978             Flags.setInConsecutiveRegsLast();
1979         }
1980 
1981         // Propagate extension type if any
1982         if (ExtendKind == ISD::SIGN_EXTEND)
1983           Flags.setSExt();
1984         else if (ExtendKind == ISD::ZERO_EXTEND)
1985           Flags.setZExt();
1986 
1987         for (unsigned i = 0; i < NumParts; ++i) {
1988           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1989                                         VT, /*isfixed=*/true, 0, 0));
1990           OutVals.push_back(Parts[i]);
1991         }
1992       }
1993     }
1994   }
1995 
1996   // Push in swifterror virtual register as the last element of Outs. This makes
1997   // sure swifterror virtual register will be returned in the swifterror
1998   // physical register.
1999   const Function *F = I.getParent()->getParent();
2000   if (TLI.supportSwiftError() &&
2001       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2002     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2003     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2004     Flags.setSwiftError();
2005     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
2006                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
2007                                   true /*isfixed*/, 1 /*origidx*/,
2008                                   0 /*partOffs*/));
2009     // Create SDNode for the swifterror virtual register.
2010     OutVals.push_back(
2011         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2012                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2013                         EVT(TLI.getPointerTy(DL))));
2014   }
2015 
2016   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2017   CallingConv::ID CallConv =
2018     DAG.getMachineFunction().getFunction().getCallingConv();
2019   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2020       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2021 
2022   // Verify that the target's LowerReturn behaved as expected.
2023   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2024          "LowerReturn didn't return a valid chain!");
2025 
2026   // Update the DAG with the new chain value resulting from return lowering.
2027   DAG.setRoot(Chain);
2028 }
2029 
2030 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2031 /// created for it, emit nodes to copy the value into the virtual
2032 /// registers.
2033 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2034   // Skip empty types
2035   if (V->getType()->isEmptyTy())
2036     return;
2037 
2038   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2039   if (VMI != FuncInfo.ValueMap.end()) {
2040     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2041     CopyValueToVirtualRegister(V, VMI->second);
2042   }
2043 }
2044 
2045 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2046 /// the current basic block, add it to ValueMap now so that we'll get a
2047 /// CopyTo/FromReg.
2048 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2049   // No need to export constants.
2050   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2051 
2052   // Already exported?
2053   if (FuncInfo.isExportedInst(V)) return;
2054 
2055   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2056   CopyValueToVirtualRegister(V, Reg);
2057 }
2058 
2059 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2060                                                      const BasicBlock *FromBB) {
2061   // The operands of the setcc have to be in this block.  We don't know
2062   // how to export them from some other block.
2063   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2064     // Can export from current BB.
2065     if (VI->getParent() == FromBB)
2066       return true;
2067 
2068     // Is already exported, noop.
2069     return FuncInfo.isExportedInst(V);
2070   }
2071 
2072   // If this is an argument, we can export it if the BB is the entry block or
2073   // if it is already exported.
2074   if (isa<Argument>(V)) {
2075     if (FromBB == &FromBB->getParent()->getEntryBlock())
2076       return true;
2077 
2078     // Otherwise, can only export this if it is already exported.
2079     return FuncInfo.isExportedInst(V);
2080   }
2081 
2082   // Otherwise, constants can always be exported.
2083   return true;
2084 }
2085 
2086 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2087 BranchProbability
2088 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2089                                         const MachineBasicBlock *Dst) const {
2090   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2091   const BasicBlock *SrcBB = Src->getBasicBlock();
2092   const BasicBlock *DstBB = Dst->getBasicBlock();
2093   if (!BPI) {
2094     // If BPI is not available, set the default probability as 1 / N, where N is
2095     // the number of successors.
2096     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2097     return BranchProbability(1, SuccSize);
2098   }
2099   return BPI->getEdgeProbability(SrcBB, DstBB);
2100 }
2101 
2102 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2103                                                MachineBasicBlock *Dst,
2104                                                BranchProbability Prob) {
2105   if (!FuncInfo.BPI)
2106     Src->addSuccessorWithoutProb(Dst);
2107   else {
2108     if (Prob.isUnknown())
2109       Prob = getEdgeProbability(Src, Dst);
2110     Src->addSuccessor(Dst, Prob);
2111   }
2112 }
2113 
2114 static bool InBlock(const Value *V, const BasicBlock *BB) {
2115   if (const Instruction *I = dyn_cast<Instruction>(V))
2116     return I->getParent() == BB;
2117   return true;
2118 }
2119 
2120 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2121 /// This function emits a branch and is used at the leaves of an OR or an
2122 /// AND operator tree.
2123 void
2124 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2125                                                   MachineBasicBlock *TBB,
2126                                                   MachineBasicBlock *FBB,
2127                                                   MachineBasicBlock *CurBB,
2128                                                   MachineBasicBlock *SwitchBB,
2129                                                   BranchProbability TProb,
2130                                                   BranchProbability FProb,
2131                                                   bool InvertCond) {
2132   const BasicBlock *BB = CurBB->getBasicBlock();
2133 
2134   // If the leaf of the tree is a comparison, merge the condition into
2135   // the caseblock.
2136   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2137     // The operands of the cmp have to be in this block.  We don't know
2138     // how to export them from some other block.  If this is the first block
2139     // of the sequence, no exporting is needed.
2140     if (CurBB == SwitchBB ||
2141         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2142          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2143       ISD::CondCode Condition;
2144       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2145         ICmpInst::Predicate Pred =
2146             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2147         Condition = getICmpCondCode(Pred);
2148       } else {
2149         const FCmpInst *FC = cast<FCmpInst>(Cond);
2150         FCmpInst::Predicate Pred =
2151             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2152         Condition = getFCmpCondCode(Pred);
2153         if (TM.Options.NoNaNsFPMath)
2154           Condition = getFCmpCodeWithoutNaN(Condition);
2155       }
2156 
2157       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2158                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2159       SL->SwitchCases.push_back(CB);
2160       return;
2161     }
2162   }
2163 
2164   // Create a CaseBlock record representing this branch.
2165   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2166   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2167                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2168   SL->SwitchCases.push_back(CB);
2169 }
2170 
2171 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2172                                                MachineBasicBlock *TBB,
2173                                                MachineBasicBlock *FBB,
2174                                                MachineBasicBlock *CurBB,
2175                                                MachineBasicBlock *SwitchBB,
2176                                                Instruction::BinaryOps Opc,
2177                                                BranchProbability TProb,
2178                                                BranchProbability FProb,
2179                                                bool InvertCond) {
2180   // Skip over not part of the tree and remember to invert op and operands at
2181   // next level.
2182   Value *NotCond;
2183   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2184       InBlock(NotCond, CurBB->getBasicBlock())) {
2185     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2186                          !InvertCond);
2187     return;
2188   }
2189 
2190   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2191   const Value *BOpOp0, *BOpOp1;
2192   // Compute the effective opcode for Cond, taking into account whether it needs
2193   // to be inverted, e.g.
2194   //   and (not (or A, B)), C
2195   // gets lowered as
2196   //   and (and (not A, not B), C)
2197   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2198   if (BOp) {
2199     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2200                ? Instruction::And
2201                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2202                       ? Instruction::Or
2203                       : (Instruction::BinaryOps)0);
2204     if (InvertCond) {
2205       if (BOpc == Instruction::And)
2206         BOpc = Instruction::Or;
2207       else if (BOpc == Instruction::Or)
2208         BOpc = Instruction::And;
2209     }
2210   }
2211 
2212   // If this node is not part of the or/and tree, emit it as a branch.
2213   // Note that all nodes in the tree should have same opcode.
2214   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2215   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2216       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2217       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2218     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2219                                  TProb, FProb, InvertCond);
2220     return;
2221   }
2222 
2223   //  Create TmpBB after CurBB.
2224   MachineFunction::iterator BBI(CurBB);
2225   MachineFunction &MF = DAG.getMachineFunction();
2226   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2227   CurBB->getParent()->insert(++BBI, TmpBB);
2228 
2229   if (Opc == Instruction::Or) {
2230     // Codegen X | Y as:
2231     // BB1:
2232     //   jmp_if_X TBB
2233     //   jmp TmpBB
2234     // TmpBB:
2235     //   jmp_if_Y TBB
2236     //   jmp FBB
2237     //
2238 
2239     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2240     // The requirement is that
2241     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2242     //     = TrueProb for original BB.
2243     // Assuming the original probabilities are A and B, one choice is to set
2244     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2245     // A/(1+B) and 2B/(1+B). This choice assumes that
2246     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2247     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2248     // TmpBB, but the math is more complicated.
2249 
2250     auto NewTrueProb = TProb / 2;
2251     auto NewFalseProb = TProb / 2 + FProb;
2252     // Emit the LHS condition.
2253     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2254                          NewFalseProb, InvertCond);
2255 
2256     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2257     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2258     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2259     // Emit the RHS condition into TmpBB.
2260     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2261                          Probs[1], InvertCond);
2262   } else {
2263     assert(Opc == Instruction::And && "Unknown merge op!");
2264     // Codegen X & Y as:
2265     // BB1:
2266     //   jmp_if_X TmpBB
2267     //   jmp FBB
2268     // TmpBB:
2269     //   jmp_if_Y TBB
2270     //   jmp FBB
2271     //
2272     //  This requires creation of TmpBB after CurBB.
2273 
2274     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2275     // The requirement is that
2276     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2277     //     = FalseProb for original BB.
2278     // Assuming the original probabilities are A and B, one choice is to set
2279     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2280     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2281     // TrueProb for BB1 * FalseProb for TmpBB.
2282 
2283     auto NewTrueProb = TProb + FProb / 2;
2284     auto NewFalseProb = FProb / 2;
2285     // Emit the LHS condition.
2286     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2287                          NewFalseProb, InvertCond);
2288 
2289     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2290     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2291     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2292     // Emit the RHS condition into TmpBB.
2293     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2294                          Probs[1], InvertCond);
2295   }
2296 }
2297 
2298 /// If the set of cases should be emitted as a series of branches, return true.
2299 /// If we should emit this as a bunch of and/or'd together conditions, return
2300 /// false.
2301 bool
2302 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2303   if (Cases.size() != 2) return true;
2304 
2305   // If this is two comparisons of the same values or'd or and'd together, they
2306   // will get folded into a single comparison, so don't emit two blocks.
2307   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2308        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2309       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2310        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2311     return false;
2312   }
2313 
2314   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2315   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2316   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2317       Cases[0].CC == Cases[1].CC &&
2318       isa<Constant>(Cases[0].CmpRHS) &&
2319       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2320     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2321       return false;
2322     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2323       return false;
2324   }
2325 
2326   return true;
2327 }
2328 
2329 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2330   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2331 
2332   // Update machine-CFG edges.
2333   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2334 
2335   if (I.isUnconditional()) {
2336     // Update machine-CFG edges.
2337     BrMBB->addSuccessor(Succ0MBB);
2338 
2339     // If this is not a fall-through branch or optimizations are switched off,
2340     // emit the branch.
2341     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2342       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2343                               MVT::Other, getControlRoot(),
2344                               DAG.getBasicBlock(Succ0MBB)));
2345 
2346     return;
2347   }
2348 
2349   // If this condition is one of the special cases we handle, do special stuff
2350   // now.
2351   const Value *CondVal = I.getCondition();
2352   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2353 
2354   // If this is a series of conditions that are or'd or and'd together, emit
2355   // this as a sequence of branches instead of setcc's with and/or operations.
2356   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2357   // unpredictable branches, and vector extracts because those jumps are likely
2358   // expensive for any target), this should improve performance.
2359   // For example, instead of something like:
2360   //     cmp A, B
2361   //     C = seteq
2362   //     cmp D, E
2363   //     F = setle
2364   //     or C, F
2365   //     jnz foo
2366   // Emit:
2367   //     cmp A, B
2368   //     je foo
2369   //     cmp D, E
2370   //     jle foo
2371   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2372   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2373       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2374     Value *Vec;
2375     const Value *BOp0, *BOp1;
2376     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2377     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2378       Opcode = Instruction::And;
2379     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2380       Opcode = Instruction::Or;
2381 
2382     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2383                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2384       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2385                            getEdgeProbability(BrMBB, Succ0MBB),
2386                            getEdgeProbability(BrMBB, Succ1MBB),
2387                            /*InvertCond=*/false);
2388       // If the compares in later blocks need to use values not currently
2389       // exported from this block, export them now.  This block should always
2390       // be the first entry.
2391       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2392 
2393       // Allow some cases to be rejected.
2394       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2395         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2396           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2397           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2398         }
2399 
2400         // Emit the branch for this block.
2401         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2402         SL->SwitchCases.erase(SL->SwitchCases.begin());
2403         return;
2404       }
2405 
2406       // Okay, we decided not to do this, remove any inserted MBB's and clear
2407       // SwitchCases.
2408       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2409         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2410 
2411       SL->SwitchCases.clear();
2412     }
2413   }
2414 
2415   // Create a CaseBlock record representing this branch.
2416   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2417                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2418 
2419   // Use visitSwitchCase to actually insert the fast branch sequence for this
2420   // cond branch.
2421   visitSwitchCase(CB, BrMBB);
2422 }
2423 
2424 /// visitSwitchCase - Emits the necessary code to represent a single node in
2425 /// the binary search tree resulting from lowering a switch instruction.
2426 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2427                                           MachineBasicBlock *SwitchBB) {
2428   SDValue Cond;
2429   SDValue CondLHS = getValue(CB.CmpLHS);
2430   SDLoc dl = CB.DL;
2431 
2432   if (CB.CC == ISD::SETTRUE) {
2433     // Branch or fall through to TrueBB.
2434     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2435     SwitchBB->normalizeSuccProbs();
2436     if (CB.TrueBB != NextBlock(SwitchBB)) {
2437       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2438                               DAG.getBasicBlock(CB.TrueBB)));
2439     }
2440     return;
2441   }
2442 
2443   auto &TLI = DAG.getTargetLoweringInfo();
2444   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2445 
2446   // Build the setcc now.
2447   if (!CB.CmpMHS) {
2448     // Fold "(X == true)" to X and "(X == false)" to !X to
2449     // handle common cases produced by branch lowering.
2450     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2451         CB.CC == ISD::SETEQ)
2452       Cond = CondLHS;
2453     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2454              CB.CC == ISD::SETEQ) {
2455       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2456       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2457     } else {
2458       SDValue CondRHS = getValue(CB.CmpRHS);
2459 
2460       // If a pointer's DAG type is larger than its memory type then the DAG
2461       // values are zero-extended. This breaks signed comparisons so truncate
2462       // back to the underlying type before doing the compare.
2463       if (CondLHS.getValueType() != MemVT) {
2464         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2465         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2466       }
2467       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2468     }
2469   } else {
2470     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2471 
2472     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2473     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2474 
2475     SDValue CmpOp = getValue(CB.CmpMHS);
2476     EVT VT = CmpOp.getValueType();
2477 
2478     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2479       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2480                           ISD::SETLE);
2481     } else {
2482       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2483                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2484       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2485                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2486     }
2487   }
2488 
2489   // Update successor info
2490   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2491   // TrueBB and FalseBB are always different unless the incoming IR is
2492   // degenerate. This only happens when running llc on weird IR.
2493   if (CB.TrueBB != CB.FalseBB)
2494     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2495   SwitchBB->normalizeSuccProbs();
2496 
2497   // If the lhs block is the next block, invert the condition so that we can
2498   // fall through to the lhs instead of the rhs block.
2499   if (CB.TrueBB == NextBlock(SwitchBB)) {
2500     std::swap(CB.TrueBB, CB.FalseBB);
2501     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2502     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2503   }
2504 
2505   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2506                                MVT::Other, getControlRoot(), Cond,
2507                                DAG.getBasicBlock(CB.TrueBB));
2508 
2509   // Insert the false branch. Do this even if it's a fall through branch,
2510   // this makes it easier to do DAG optimizations which require inverting
2511   // the branch condition.
2512   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2513                        DAG.getBasicBlock(CB.FalseBB));
2514 
2515   DAG.setRoot(BrCond);
2516 }
2517 
2518 /// visitJumpTable - Emit JumpTable node in the current MBB
2519 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2520   // Emit the code for the jump table
2521   assert(JT.Reg != -1U && "Should lower JT Header first!");
2522   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2523   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2524                                      JT.Reg, PTy);
2525   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2526   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2527                                     MVT::Other, Index.getValue(1),
2528                                     Table, Index);
2529   DAG.setRoot(BrJumpTable);
2530 }
2531 
2532 /// visitJumpTableHeader - This function emits necessary code to produce index
2533 /// in the JumpTable from switch case.
2534 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2535                                                JumpTableHeader &JTH,
2536                                                MachineBasicBlock *SwitchBB) {
2537   SDLoc dl = getCurSDLoc();
2538 
2539   // Subtract the lowest switch case value from the value being switched on.
2540   SDValue SwitchOp = getValue(JTH.SValue);
2541   EVT VT = SwitchOp.getValueType();
2542   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2543                             DAG.getConstant(JTH.First, dl, VT));
2544 
2545   // The SDNode we just created, which holds the value being switched on minus
2546   // the smallest case value, needs to be copied to a virtual register so it
2547   // can be used as an index into the jump table in a subsequent basic block.
2548   // This value may be smaller or larger than the target's pointer type, and
2549   // therefore require extension or truncating.
2550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2551   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2552 
2553   unsigned JumpTableReg =
2554       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2555   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2556                                     JumpTableReg, SwitchOp);
2557   JT.Reg = JumpTableReg;
2558 
2559   if (!JTH.OmitRangeCheck) {
2560     // Emit the range check for the jump table, and branch to the default block
2561     // for the switch statement if the value being switched on exceeds the
2562     // largest case in the switch.
2563     SDValue CMP = DAG.getSetCC(
2564         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2565                                    Sub.getValueType()),
2566         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2567 
2568     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2569                                  MVT::Other, CopyTo, CMP,
2570                                  DAG.getBasicBlock(JT.Default));
2571 
2572     // Avoid emitting unnecessary branches to the next block.
2573     if (JT.MBB != NextBlock(SwitchBB))
2574       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2575                            DAG.getBasicBlock(JT.MBB));
2576 
2577     DAG.setRoot(BrCond);
2578   } else {
2579     // Avoid emitting unnecessary branches to the next block.
2580     if (JT.MBB != NextBlock(SwitchBB))
2581       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2582                               DAG.getBasicBlock(JT.MBB)));
2583     else
2584       DAG.setRoot(CopyTo);
2585   }
2586 }
2587 
2588 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2589 /// variable if there exists one.
2590 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2591                                  SDValue &Chain) {
2592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2593   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2594   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2595   MachineFunction &MF = DAG.getMachineFunction();
2596   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2597   MachineSDNode *Node =
2598       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2599   if (Global) {
2600     MachinePointerInfo MPInfo(Global);
2601     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2602                  MachineMemOperand::MODereferenceable;
2603     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2604         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2605     DAG.setNodeMemRefs(Node, {MemRef});
2606   }
2607   if (PtrTy != PtrMemTy)
2608     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2609   return SDValue(Node, 0);
2610 }
2611 
2612 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2613 /// tail spliced into a stack protector check success bb.
2614 ///
2615 /// For a high level explanation of how this fits into the stack protector
2616 /// generation see the comment on the declaration of class
2617 /// StackProtectorDescriptor.
2618 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2619                                                   MachineBasicBlock *ParentBB) {
2620 
2621   // First create the loads to the guard/stack slot for the comparison.
2622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2623   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2624   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2625 
2626   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2627   int FI = MFI.getStackProtectorIndex();
2628 
2629   SDValue Guard;
2630   SDLoc dl = getCurSDLoc();
2631   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2632   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2633   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2634 
2635   // Generate code to load the content of the guard slot.
2636   SDValue GuardVal = DAG.getLoad(
2637       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2638       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2639       MachineMemOperand::MOVolatile);
2640 
2641   if (TLI.useStackGuardXorFP())
2642     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2643 
2644   // Retrieve guard check function, nullptr if instrumentation is inlined.
2645   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2646     // The target provides a guard check function to validate the guard value.
2647     // Generate a call to that function with the content of the guard slot as
2648     // argument.
2649     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2650     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2651 
2652     TargetLowering::ArgListTy Args;
2653     TargetLowering::ArgListEntry Entry;
2654     Entry.Node = GuardVal;
2655     Entry.Ty = FnTy->getParamType(0);
2656     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2657       Entry.IsInReg = true;
2658     Args.push_back(Entry);
2659 
2660     TargetLowering::CallLoweringInfo CLI(DAG);
2661     CLI.setDebugLoc(getCurSDLoc())
2662         .setChain(DAG.getEntryNode())
2663         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2664                    getValue(GuardCheckFn), std::move(Args));
2665 
2666     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2667     DAG.setRoot(Result.second);
2668     return;
2669   }
2670 
2671   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2672   // Otherwise, emit a volatile load to retrieve the stack guard value.
2673   SDValue Chain = DAG.getEntryNode();
2674   if (TLI.useLoadStackGuardNode()) {
2675     Guard = getLoadStackGuard(DAG, dl, Chain);
2676   } else {
2677     const Value *IRGuard = TLI.getSDagStackGuard(M);
2678     SDValue GuardPtr = getValue(IRGuard);
2679 
2680     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2681                         MachinePointerInfo(IRGuard, 0), Align,
2682                         MachineMemOperand::MOVolatile);
2683   }
2684 
2685   // Perform the comparison via a getsetcc.
2686   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2687                                                         *DAG.getContext(),
2688                                                         Guard.getValueType()),
2689                              Guard, GuardVal, ISD::SETNE);
2690 
2691   // If the guard/stackslot do not equal, branch to failure MBB.
2692   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2693                                MVT::Other, GuardVal.getOperand(0),
2694                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2695   // Otherwise branch to success MBB.
2696   SDValue Br = DAG.getNode(ISD::BR, dl,
2697                            MVT::Other, BrCond,
2698                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2699 
2700   DAG.setRoot(Br);
2701 }
2702 
2703 /// Codegen the failure basic block for a stack protector check.
2704 ///
2705 /// A failure stack protector machine basic block consists simply of a call to
2706 /// __stack_chk_fail().
2707 ///
2708 /// For a high level explanation of how this fits into the stack protector
2709 /// generation see the comment on the declaration of class
2710 /// StackProtectorDescriptor.
2711 void
2712 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2714   TargetLowering::MakeLibCallOptions CallOptions;
2715   CallOptions.setDiscardResult(true);
2716   SDValue Chain =
2717       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2718                       None, CallOptions, getCurSDLoc()).second;
2719   // On PS4, the "return address" must still be within the calling function,
2720   // even if it's at the very end, so emit an explicit TRAP here.
2721   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2722   if (TM.getTargetTriple().isPS4CPU())
2723     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2724   // WebAssembly needs an unreachable instruction after a non-returning call,
2725   // because the function return type can be different from __stack_chk_fail's
2726   // return type (void).
2727   if (TM.getTargetTriple().isWasm())
2728     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2729 
2730   DAG.setRoot(Chain);
2731 }
2732 
2733 /// visitBitTestHeader - This function emits necessary code to produce value
2734 /// suitable for "bit tests"
2735 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2736                                              MachineBasicBlock *SwitchBB) {
2737   SDLoc dl = getCurSDLoc();
2738 
2739   // Subtract the minimum value.
2740   SDValue SwitchOp = getValue(B.SValue);
2741   EVT VT = SwitchOp.getValueType();
2742   SDValue RangeSub =
2743       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2744 
2745   // Determine the type of the test operands.
2746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2747   bool UsePtrType = false;
2748   if (!TLI.isTypeLegal(VT)) {
2749     UsePtrType = true;
2750   } else {
2751     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2752       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2753         // Switch table case range are encoded into series of masks.
2754         // Just use pointer type, it's guaranteed to fit.
2755         UsePtrType = true;
2756         break;
2757       }
2758   }
2759   SDValue Sub = RangeSub;
2760   if (UsePtrType) {
2761     VT = TLI.getPointerTy(DAG.getDataLayout());
2762     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2763   }
2764 
2765   B.RegVT = VT.getSimpleVT();
2766   B.Reg = FuncInfo.CreateReg(B.RegVT);
2767   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2768 
2769   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2770 
2771   if (!B.OmitRangeCheck)
2772     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2773   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2774   SwitchBB->normalizeSuccProbs();
2775 
2776   SDValue Root = CopyTo;
2777   if (!B.OmitRangeCheck) {
2778     // Conditional branch to the default block.
2779     SDValue RangeCmp = DAG.getSetCC(dl,
2780         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2781                                RangeSub.getValueType()),
2782         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2783         ISD::SETUGT);
2784 
2785     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2786                        DAG.getBasicBlock(B.Default));
2787   }
2788 
2789   // Avoid emitting unnecessary branches to the next block.
2790   if (MBB != NextBlock(SwitchBB))
2791     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2792 
2793   DAG.setRoot(Root);
2794 }
2795 
2796 /// visitBitTestCase - this function produces one "bit test"
2797 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2798                                            MachineBasicBlock* NextMBB,
2799                                            BranchProbability BranchProbToNext,
2800                                            unsigned Reg,
2801                                            BitTestCase &B,
2802                                            MachineBasicBlock *SwitchBB) {
2803   SDLoc dl = getCurSDLoc();
2804   MVT VT = BB.RegVT;
2805   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2806   SDValue Cmp;
2807   unsigned PopCount = countPopulation(B.Mask);
2808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2809   if (PopCount == 1) {
2810     // Testing for a single bit; just compare the shift count with what it
2811     // would need to be to shift a 1 bit in that position.
2812     Cmp = DAG.getSetCC(
2813         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2814         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2815         ISD::SETEQ);
2816   } else if (PopCount == BB.Range) {
2817     // There is only one zero bit in the range, test for it directly.
2818     Cmp = DAG.getSetCC(
2819         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2820         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2821         ISD::SETNE);
2822   } else {
2823     // Make desired shift
2824     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2825                                     DAG.getConstant(1, dl, VT), ShiftOp);
2826 
2827     // Emit bit tests and jumps
2828     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2829                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2830     Cmp = DAG.getSetCC(
2831         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2832         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2833   }
2834 
2835   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2836   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2837   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2838   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2839   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2840   // one as they are relative probabilities (and thus work more like weights),
2841   // and hence we need to normalize them to let the sum of them become one.
2842   SwitchBB->normalizeSuccProbs();
2843 
2844   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2845                               MVT::Other, getControlRoot(),
2846                               Cmp, DAG.getBasicBlock(B.TargetBB));
2847 
2848   // Avoid emitting unnecessary branches to the next block.
2849   if (NextMBB != NextBlock(SwitchBB))
2850     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2851                         DAG.getBasicBlock(NextMBB));
2852 
2853   DAG.setRoot(BrAnd);
2854 }
2855 
2856 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2857   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2858 
2859   // Retrieve successors. Look through artificial IR level blocks like
2860   // catchswitch for successors.
2861   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2862   const BasicBlock *EHPadBB = I.getSuccessor(1);
2863 
2864   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2865   // have to do anything here to lower funclet bundles.
2866   assert(!I.hasOperandBundlesOtherThan(
2867              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2868               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2869               LLVMContext::OB_cfguardtarget,
2870               LLVMContext::OB_clang_arc_attachedcall}) &&
2871          "Cannot lower invokes with arbitrary operand bundles yet!");
2872 
2873   const Value *Callee(I.getCalledOperand());
2874   const Function *Fn = dyn_cast<Function>(Callee);
2875   if (isa<InlineAsm>(Callee))
2876     visitInlineAsm(I);
2877   else if (Fn && Fn->isIntrinsic()) {
2878     switch (Fn->getIntrinsicID()) {
2879     default:
2880       llvm_unreachable("Cannot invoke this intrinsic");
2881     case Intrinsic::donothing:
2882       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2883       break;
2884     case Intrinsic::experimental_patchpoint_void:
2885     case Intrinsic::experimental_patchpoint_i64:
2886       visitPatchpoint(I, EHPadBB);
2887       break;
2888     case Intrinsic::experimental_gc_statepoint:
2889       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2890       break;
2891     case Intrinsic::wasm_rethrow: {
2892       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2893       // special because it can be invoked, so we manually lower it to a DAG
2894       // node here.
2895       SmallVector<SDValue, 8> Ops;
2896       Ops.push_back(getRoot()); // inchain
2897       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2898       Ops.push_back(
2899           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2900                                 TLI.getPointerTy(DAG.getDataLayout())));
2901       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2902       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2903       break;
2904     }
2905     }
2906   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2907     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2908     // Eventually we will support lowering the @llvm.experimental.deoptimize
2909     // intrinsic, and right now there are no plans to support other intrinsics
2910     // with deopt state.
2911     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2912   } else {
2913     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2914   }
2915 
2916   // If the value of the invoke is used outside of its defining block, make it
2917   // available as a virtual register.
2918   // We already took care of the exported value for the statepoint instruction
2919   // during call to the LowerStatepoint.
2920   if (!isa<GCStatepointInst>(I)) {
2921     CopyToExportRegsIfNeeded(&I);
2922   }
2923 
2924   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2925   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2926   BranchProbability EHPadBBProb =
2927       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2928           : BranchProbability::getZero();
2929   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2930 
2931   // Update successor info.
2932   addSuccessorWithProb(InvokeMBB, Return);
2933   for (auto &UnwindDest : UnwindDests) {
2934     UnwindDest.first->setIsEHPad();
2935     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2936   }
2937   InvokeMBB->normalizeSuccProbs();
2938 
2939   // Drop into normal successor.
2940   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2941                           DAG.getBasicBlock(Return)));
2942 }
2943 
2944 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2945   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2946 
2947   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2948   // have to do anything here to lower funclet bundles.
2949   assert(!I.hasOperandBundlesOtherThan(
2950              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2951          "Cannot lower callbrs with arbitrary operand bundles yet!");
2952 
2953   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2954   visitInlineAsm(I);
2955   CopyToExportRegsIfNeeded(&I);
2956 
2957   // Retrieve successors.
2958   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2959 
2960   // Update successor info.
2961   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2962   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2963     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2964     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2965     Target->setIsInlineAsmBrIndirectTarget();
2966   }
2967   CallBrMBB->normalizeSuccProbs();
2968 
2969   // Drop into default successor.
2970   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2971                           MVT::Other, getControlRoot(),
2972                           DAG.getBasicBlock(Return)));
2973 }
2974 
2975 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2976   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2977 }
2978 
2979 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2980   assert(FuncInfo.MBB->isEHPad() &&
2981          "Call to landingpad not in landing pad!");
2982 
2983   // If there aren't registers to copy the values into (e.g., during SjLj
2984   // exceptions), then don't bother to create these DAG nodes.
2985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2986   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2987   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2988       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2989     return;
2990 
2991   // If landingpad's return type is token type, we don't create DAG nodes
2992   // for its exception pointer and selector value. The extraction of exception
2993   // pointer or selector value from token type landingpads is not currently
2994   // supported.
2995   if (LP.getType()->isTokenTy())
2996     return;
2997 
2998   SmallVector<EVT, 2> ValueVTs;
2999   SDLoc dl = getCurSDLoc();
3000   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3001   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3002 
3003   // Get the two live-in registers as SDValues. The physregs have already been
3004   // copied into virtual registers.
3005   SDValue Ops[2];
3006   if (FuncInfo.ExceptionPointerVirtReg) {
3007     Ops[0] = DAG.getZExtOrTrunc(
3008         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3009                            FuncInfo.ExceptionPointerVirtReg,
3010                            TLI.getPointerTy(DAG.getDataLayout())),
3011         dl, ValueVTs[0]);
3012   } else {
3013     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3014   }
3015   Ops[1] = DAG.getZExtOrTrunc(
3016       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3017                          FuncInfo.ExceptionSelectorVirtReg,
3018                          TLI.getPointerTy(DAG.getDataLayout())),
3019       dl, ValueVTs[1]);
3020 
3021   // Merge into one.
3022   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3023                             DAG.getVTList(ValueVTs), Ops);
3024   setValue(&LP, Res);
3025 }
3026 
3027 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3028                                            MachineBasicBlock *Last) {
3029   // Update JTCases.
3030   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3031     if (SL->JTCases[i].first.HeaderBB == First)
3032       SL->JTCases[i].first.HeaderBB = Last;
3033 
3034   // Update BitTestCases.
3035   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3036     if (SL->BitTestCases[i].Parent == First)
3037       SL->BitTestCases[i].Parent = Last;
3038 }
3039 
3040 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3041   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3042 
3043   // Update machine-CFG edges with unique successors.
3044   SmallSet<BasicBlock*, 32> Done;
3045   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3046     BasicBlock *BB = I.getSuccessor(i);
3047     bool Inserted = Done.insert(BB).second;
3048     if (!Inserted)
3049         continue;
3050 
3051     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3052     addSuccessorWithProb(IndirectBrMBB, Succ);
3053   }
3054   IndirectBrMBB->normalizeSuccProbs();
3055 
3056   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3057                           MVT::Other, getControlRoot(),
3058                           getValue(I.getAddress())));
3059 }
3060 
3061 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3062   if (!DAG.getTarget().Options.TrapUnreachable)
3063     return;
3064 
3065   // We may be able to ignore unreachable behind a noreturn call.
3066   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3067     const BasicBlock &BB = *I.getParent();
3068     if (&I != &BB.front()) {
3069       BasicBlock::const_iterator PredI =
3070         std::prev(BasicBlock::const_iterator(&I));
3071       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3072         if (Call->doesNotReturn())
3073           return;
3074       }
3075     }
3076   }
3077 
3078   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3079 }
3080 
3081 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3082   SDNodeFlags Flags;
3083 
3084   SDValue Op = getValue(I.getOperand(0));
3085   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3086                                     Op, Flags);
3087   setValue(&I, UnNodeValue);
3088 }
3089 
3090 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3091   SDNodeFlags Flags;
3092   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3093     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3094     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3095   }
3096   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3097     Flags.setExact(ExactOp->isExact());
3098   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3099     Flags.copyFMF(*FPOp);
3100 
3101   SDValue Op1 = getValue(I.getOperand(0));
3102   SDValue Op2 = getValue(I.getOperand(1));
3103   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3104                                      Op1, Op2, Flags);
3105   setValue(&I, BinNodeValue);
3106 }
3107 
3108 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3109   SDValue Op1 = getValue(I.getOperand(0));
3110   SDValue Op2 = getValue(I.getOperand(1));
3111 
3112   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3113       Op1.getValueType(), DAG.getDataLayout());
3114 
3115   // Coerce the shift amount to the right type if we can.
3116   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3117     unsigned ShiftSize = ShiftTy.getSizeInBits();
3118     unsigned Op2Size = Op2.getValueSizeInBits();
3119     SDLoc DL = getCurSDLoc();
3120 
3121     // If the operand is smaller than the shift count type, promote it.
3122     if (ShiftSize > Op2Size)
3123       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3124 
3125     // If the operand is larger than the shift count type but the shift
3126     // count type has enough bits to represent any shift value, truncate
3127     // it now. This is a common case and it exposes the truncate to
3128     // optimization early.
3129     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3130       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3131     // Otherwise we'll need to temporarily settle for some other convenient
3132     // type.  Type legalization will make adjustments once the shiftee is split.
3133     else
3134       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3135   }
3136 
3137   bool nuw = false;
3138   bool nsw = false;
3139   bool exact = false;
3140 
3141   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3142 
3143     if (const OverflowingBinaryOperator *OFBinOp =
3144             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3145       nuw = OFBinOp->hasNoUnsignedWrap();
3146       nsw = OFBinOp->hasNoSignedWrap();
3147     }
3148     if (const PossiblyExactOperator *ExactOp =
3149             dyn_cast<const PossiblyExactOperator>(&I))
3150       exact = ExactOp->isExact();
3151   }
3152   SDNodeFlags Flags;
3153   Flags.setExact(exact);
3154   Flags.setNoSignedWrap(nsw);
3155   Flags.setNoUnsignedWrap(nuw);
3156   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3157                             Flags);
3158   setValue(&I, Res);
3159 }
3160 
3161 void SelectionDAGBuilder::visitSDiv(const User &I) {
3162   SDValue Op1 = getValue(I.getOperand(0));
3163   SDValue Op2 = getValue(I.getOperand(1));
3164 
3165   SDNodeFlags Flags;
3166   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3167                  cast<PossiblyExactOperator>(&I)->isExact());
3168   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3169                            Op2, Flags));
3170 }
3171 
3172 void SelectionDAGBuilder::visitICmp(const User &I) {
3173   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3174   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3175     predicate = IC->getPredicate();
3176   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3177     predicate = ICmpInst::Predicate(IC->getPredicate());
3178   SDValue Op1 = getValue(I.getOperand(0));
3179   SDValue Op2 = getValue(I.getOperand(1));
3180   ISD::CondCode Opcode = getICmpCondCode(predicate);
3181 
3182   auto &TLI = DAG.getTargetLoweringInfo();
3183   EVT MemVT =
3184       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3185 
3186   // If a pointer's DAG type is larger than its memory type then the DAG values
3187   // are zero-extended. This breaks signed comparisons so truncate back to the
3188   // underlying type before doing the compare.
3189   if (Op1.getValueType() != MemVT) {
3190     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3191     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3192   }
3193 
3194   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3195                                                         I.getType());
3196   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3197 }
3198 
3199 void SelectionDAGBuilder::visitFCmp(const User &I) {
3200   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3201   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3202     predicate = FC->getPredicate();
3203   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3204     predicate = FCmpInst::Predicate(FC->getPredicate());
3205   SDValue Op1 = getValue(I.getOperand(0));
3206   SDValue Op2 = getValue(I.getOperand(1));
3207 
3208   ISD::CondCode Condition = getFCmpCondCode(predicate);
3209   auto *FPMO = cast<FPMathOperator>(&I);
3210   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3211     Condition = getFCmpCodeWithoutNaN(Condition);
3212 
3213   SDNodeFlags Flags;
3214   Flags.copyFMF(*FPMO);
3215   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3216 
3217   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3218                                                         I.getType());
3219   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3220 }
3221 
3222 // Check if the condition of the select has one use or two users that are both
3223 // selects with the same condition.
3224 static bool hasOnlySelectUsers(const Value *Cond) {
3225   return llvm::all_of(Cond->users(), [](const Value *V) {
3226     return isa<SelectInst>(V);
3227   });
3228 }
3229 
3230 void SelectionDAGBuilder::visitSelect(const User &I) {
3231   SmallVector<EVT, 4> ValueVTs;
3232   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3233                   ValueVTs);
3234   unsigned NumValues = ValueVTs.size();
3235   if (NumValues == 0) return;
3236 
3237   SmallVector<SDValue, 4> Values(NumValues);
3238   SDValue Cond     = getValue(I.getOperand(0));
3239   SDValue LHSVal   = getValue(I.getOperand(1));
3240   SDValue RHSVal   = getValue(I.getOperand(2));
3241   SmallVector<SDValue, 1> BaseOps(1, Cond);
3242   ISD::NodeType OpCode =
3243       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3244 
3245   bool IsUnaryAbs = false;
3246   bool Negate = false;
3247 
3248   SDNodeFlags Flags;
3249   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3250     Flags.copyFMF(*FPOp);
3251 
3252   // Min/max matching is only viable if all output VTs are the same.
3253   if (is_splat(ValueVTs)) {
3254     EVT VT = ValueVTs[0];
3255     LLVMContext &Ctx = *DAG.getContext();
3256     auto &TLI = DAG.getTargetLoweringInfo();
3257 
3258     // We care about the legality of the operation after it has been type
3259     // legalized.
3260     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3261       VT = TLI.getTypeToTransformTo(Ctx, VT);
3262 
3263     // If the vselect is legal, assume we want to leave this as a vector setcc +
3264     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3265     // min/max is legal on the scalar type.
3266     bool UseScalarMinMax = VT.isVector() &&
3267       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3268 
3269     Value *LHS, *RHS;
3270     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3271     ISD::NodeType Opc = ISD::DELETED_NODE;
3272     switch (SPR.Flavor) {
3273     case SPF_UMAX:    Opc = ISD::UMAX; break;
3274     case SPF_UMIN:    Opc = ISD::UMIN; break;
3275     case SPF_SMAX:    Opc = ISD::SMAX; break;
3276     case SPF_SMIN:    Opc = ISD::SMIN; break;
3277     case SPF_FMINNUM:
3278       switch (SPR.NaNBehavior) {
3279       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3280       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3281       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3282       case SPNB_RETURNS_ANY: {
3283         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3284           Opc = ISD::FMINNUM;
3285         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3286           Opc = ISD::FMINIMUM;
3287         else if (UseScalarMinMax)
3288           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3289             ISD::FMINNUM : ISD::FMINIMUM;
3290         break;
3291       }
3292       }
3293       break;
3294     case SPF_FMAXNUM:
3295       switch (SPR.NaNBehavior) {
3296       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3297       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3298       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3299       case SPNB_RETURNS_ANY:
3300 
3301         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3302           Opc = ISD::FMAXNUM;
3303         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3304           Opc = ISD::FMAXIMUM;
3305         else if (UseScalarMinMax)
3306           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3307             ISD::FMAXNUM : ISD::FMAXIMUM;
3308         break;
3309       }
3310       break;
3311     case SPF_NABS:
3312       Negate = true;
3313       LLVM_FALLTHROUGH;
3314     case SPF_ABS:
3315       IsUnaryAbs = true;
3316       Opc = ISD::ABS;
3317       break;
3318     default: break;
3319     }
3320 
3321     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3322         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3323          (UseScalarMinMax &&
3324           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3325         // If the underlying comparison instruction is used by any other
3326         // instruction, the consumed instructions won't be destroyed, so it is
3327         // not profitable to convert to a min/max.
3328         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3329       OpCode = Opc;
3330       LHSVal = getValue(LHS);
3331       RHSVal = getValue(RHS);
3332       BaseOps.clear();
3333     }
3334 
3335     if (IsUnaryAbs) {
3336       OpCode = Opc;
3337       LHSVal = getValue(LHS);
3338       BaseOps.clear();
3339     }
3340   }
3341 
3342   if (IsUnaryAbs) {
3343     for (unsigned i = 0; i != NumValues; ++i) {
3344       SDLoc dl = getCurSDLoc();
3345       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3346       Values[i] =
3347           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3348       if (Negate)
3349         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3350                                 Values[i]);
3351     }
3352   } else {
3353     for (unsigned i = 0; i != NumValues; ++i) {
3354       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3355       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3356       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3357       Values[i] = DAG.getNode(
3358           OpCode, getCurSDLoc(),
3359           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3360     }
3361   }
3362 
3363   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3364                            DAG.getVTList(ValueVTs), Values));
3365 }
3366 
3367 void SelectionDAGBuilder::visitTrunc(const User &I) {
3368   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3369   SDValue N = getValue(I.getOperand(0));
3370   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3371                                                         I.getType());
3372   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3373 }
3374 
3375 void SelectionDAGBuilder::visitZExt(const User &I) {
3376   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3377   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3378   SDValue N = getValue(I.getOperand(0));
3379   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3380                                                         I.getType());
3381   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3382 }
3383 
3384 void SelectionDAGBuilder::visitSExt(const User &I) {
3385   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3386   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3387   SDValue N = getValue(I.getOperand(0));
3388   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3389                                                         I.getType());
3390   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3391 }
3392 
3393 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3394   // FPTrunc is never a no-op cast, no need to check
3395   SDValue N = getValue(I.getOperand(0));
3396   SDLoc dl = getCurSDLoc();
3397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3398   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3399   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3400                            DAG.getTargetConstant(
3401                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3402 }
3403 
3404 void SelectionDAGBuilder::visitFPExt(const User &I) {
3405   // FPExt is never a no-op cast, no need to check
3406   SDValue N = getValue(I.getOperand(0));
3407   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3408                                                         I.getType());
3409   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3410 }
3411 
3412 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3413   // FPToUI is never a no-op cast, no need to check
3414   SDValue N = getValue(I.getOperand(0));
3415   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3416                                                         I.getType());
3417   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3418 }
3419 
3420 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3421   // FPToSI is never a no-op cast, no need to check
3422   SDValue N = getValue(I.getOperand(0));
3423   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3424                                                         I.getType());
3425   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3426 }
3427 
3428 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3429   // UIToFP is never a no-op cast, no need to check
3430   SDValue N = getValue(I.getOperand(0));
3431   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3432                                                         I.getType());
3433   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3434 }
3435 
3436 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3437   // SIToFP is never a no-op cast, no need to check
3438   SDValue N = getValue(I.getOperand(0));
3439   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3440                                                         I.getType());
3441   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3442 }
3443 
3444 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3445   // What to do depends on the size of the integer and the size of the pointer.
3446   // We can either truncate, zero extend, or no-op, accordingly.
3447   SDValue N = getValue(I.getOperand(0));
3448   auto &TLI = DAG.getTargetLoweringInfo();
3449   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3450                                                         I.getType());
3451   EVT PtrMemVT =
3452       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3453   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3454   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3455   setValue(&I, N);
3456 }
3457 
3458 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3459   // What to do depends on the size of the integer and the size of the pointer.
3460   // We can either truncate, zero extend, or no-op, accordingly.
3461   SDValue N = getValue(I.getOperand(0));
3462   auto &TLI = DAG.getTargetLoweringInfo();
3463   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3464   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3465   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3466   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3467   setValue(&I, N);
3468 }
3469 
3470 void SelectionDAGBuilder::visitBitCast(const User &I) {
3471   SDValue N = getValue(I.getOperand(0));
3472   SDLoc dl = getCurSDLoc();
3473   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3474                                                         I.getType());
3475 
3476   // BitCast assures us that source and destination are the same size so this is
3477   // either a BITCAST or a no-op.
3478   if (DestVT != N.getValueType())
3479     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3480                              DestVT, N)); // convert types.
3481   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3482   // might fold any kind of constant expression to an integer constant and that
3483   // is not what we are looking for. Only recognize a bitcast of a genuine
3484   // constant integer as an opaque constant.
3485   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3486     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3487                                  /*isOpaque*/true));
3488   else
3489     setValue(&I, N);            // noop cast.
3490 }
3491 
3492 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3494   const Value *SV = I.getOperand(0);
3495   SDValue N = getValue(SV);
3496   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3497 
3498   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3499   unsigned DestAS = I.getType()->getPointerAddressSpace();
3500 
3501   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3502     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3503 
3504   setValue(&I, N);
3505 }
3506 
3507 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3509   SDValue InVec = getValue(I.getOperand(0));
3510   SDValue InVal = getValue(I.getOperand(1));
3511   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3512                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3513   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3514                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3515                            InVec, InVal, InIdx));
3516 }
3517 
3518 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3520   SDValue InVec = getValue(I.getOperand(0));
3521   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3522                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3523   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3524                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3525                            InVec, InIdx));
3526 }
3527 
3528 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3529   SDValue Src1 = getValue(I.getOperand(0));
3530   SDValue Src2 = getValue(I.getOperand(1));
3531   ArrayRef<int> Mask;
3532   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3533     Mask = SVI->getShuffleMask();
3534   else
3535     Mask = cast<ConstantExpr>(I).getShuffleMask();
3536   SDLoc DL = getCurSDLoc();
3537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3538   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3539   EVT SrcVT = Src1.getValueType();
3540 
3541   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3542       VT.isScalableVector()) {
3543     // Canonical splat form of first element of first input vector.
3544     SDValue FirstElt =
3545         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3546                     DAG.getVectorIdxConstant(0, DL));
3547     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3548     return;
3549   }
3550 
3551   // For now, we only handle splats for scalable vectors.
3552   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3553   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3554   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3555 
3556   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3557   unsigned MaskNumElts = Mask.size();
3558 
3559   if (SrcNumElts == MaskNumElts) {
3560     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3561     return;
3562   }
3563 
3564   // Normalize the shuffle vector since mask and vector length don't match.
3565   if (SrcNumElts < MaskNumElts) {
3566     // Mask is longer than the source vectors. We can use concatenate vector to
3567     // make the mask and vectors lengths match.
3568 
3569     if (MaskNumElts % SrcNumElts == 0) {
3570       // Mask length is a multiple of the source vector length.
3571       // Check if the shuffle is some kind of concatenation of the input
3572       // vectors.
3573       unsigned NumConcat = MaskNumElts / SrcNumElts;
3574       bool IsConcat = true;
3575       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3576       for (unsigned i = 0; i != MaskNumElts; ++i) {
3577         int Idx = Mask[i];
3578         if (Idx < 0)
3579           continue;
3580         // Ensure the indices in each SrcVT sized piece are sequential and that
3581         // the same source is used for the whole piece.
3582         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3583             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3584              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3585           IsConcat = false;
3586           break;
3587         }
3588         // Remember which source this index came from.
3589         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3590       }
3591 
3592       // The shuffle is concatenating multiple vectors together. Just emit
3593       // a CONCAT_VECTORS operation.
3594       if (IsConcat) {
3595         SmallVector<SDValue, 8> ConcatOps;
3596         for (auto Src : ConcatSrcs) {
3597           if (Src < 0)
3598             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3599           else if (Src == 0)
3600             ConcatOps.push_back(Src1);
3601           else
3602             ConcatOps.push_back(Src2);
3603         }
3604         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3605         return;
3606       }
3607     }
3608 
3609     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3610     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3611     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3612                                     PaddedMaskNumElts);
3613 
3614     // Pad both vectors with undefs to make them the same length as the mask.
3615     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3616 
3617     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3618     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3619     MOps1[0] = Src1;
3620     MOps2[0] = Src2;
3621 
3622     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3623     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3624 
3625     // Readjust mask for new input vector length.
3626     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3627     for (unsigned i = 0; i != MaskNumElts; ++i) {
3628       int Idx = Mask[i];
3629       if (Idx >= (int)SrcNumElts)
3630         Idx -= SrcNumElts - PaddedMaskNumElts;
3631       MappedOps[i] = Idx;
3632     }
3633 
3634     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3635 
3636     // If the concatenated vector was padded, extract a subvector with the
3637     // correct number of elements.
3638     if (MaskNumElts != PaddedMaskNumElts)
3639       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3640                            DAG.getVectorIdxConstant(0, DL));
3641 
3642     setValue(&I, Result);
3643     return;
3644   }
3645 
3646   if (SrcNumElts > MaskNumElts) {
3647     // Analyze the access pattern of the vector to see if we can extract
3648     // two subvectors and do the shuffle.
3649     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3650     bool CanExtract = true;
3651     for (int Idx : Mask) {
3652       unsigned Input = 0;
3653       if (Idx < 0)
3654         continue;
3655 
3656       if (Idx >= (int)SrcNumElts) {
3657         Input = 1;
3658         Idx -= SrcNumElts;
3659       }
3660 
3661       // If all the indices come from the same MaskNumElts sized portion of
3662       // the sources we can use extract. Also make sure the extract wouldn't
3663       // extract past the end of the source.
3664       int NewStartIdx = alignDown(Idx, MaskNumElts);
3665       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3666           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3667         CanExtract = false;
3668       // Make sure we always update StartIdx as we use it to track if all
3669       // elements are undef.
3670       StartIdx[Input] = NewStartIdx;
3671     }
3672 
3673     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3674       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3675       return;
3676     }
3677     if (CanExtract) {
3678       // Extract appropriate subvector and generate a vector shuffle
3679       for (unsigned Input = 0; Input < 2; ++Input) {
3680         SDValue &Src = Input == 0 ? Src1 : Src2;
3681         if (StartIdx[Input] < 0)
3682           Src = DAG.getUNDEF(VT);
3683         else {
3684           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3685                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3686         }
3687       }
3688 
3689       // Calculate new mask.
3690       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3691       for (int &Idx : MappedOps) {
3692         if (Idx >= (int)SrcNumElts)
3693           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3694         else if (Idx >= 0)
3695           Idx -= StartIdx[0];
3696       }
3697 
3698       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3699       return;
3700     }
3701   }
3702 
3703   // We can't use either concat vectors or extract subvectors so fall back to
3704   // replacing the shuffle with extract and build vector.
3705   // to insert and build vector.
3706   EVT EltVT = VT.getVectorElementType();
3707   SmallVector<SDValue,8> Ops;
3708   for (int Idx : Mask) {
3709     SDValue Res;
3710 
3711     if (Idx < 0) {
3712       Res = DAG.getUNDEF(EltVT);
3713     } else {
3714       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3715       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3716 
3717       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3718                         DAG.getVectorIdxConstant(Idx, DL));
3719     }
3720 
3721     Ops.push_back(Res);
3722   }
3723 
3724   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3725 }
3726 
3727 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3728   ArrayRef<unsigned> Indices;
3729   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3730     Indices = IV->getIndices();
3731   else
3732     Indices = cast<ConstantExpr>(&I)->getIndices();
3733 
3734   const Value *Op0 = I.getOperand(0);
3735   const Value *Op1 = I.getOperand(1);
3736   Type *AggTy = I.getType();
3737   Type *ValTy = Op1->getType();
3738   bool IntoUndef = isa<UndefValue>(Op0);
3739   bool FromUndef = isa<UndefValue>(Op1);
3740 
3741   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3742 
3743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3744   SmallVector<EVT, 4> AggValueVTs;
3745   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3746   SmallVector<EVT, 4> ValValueVTs;
3747   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3748 
3749   unsigned NumAggValues = AggValueVTs.size();
3750   unsigned NumValValues = ValValueVTs.size();
3751   SmallVector<SDValue, 4> Values(NumAggValues);
3752 
3753   // Ignore an insertvalue that produces an empty object
3754   if (!NumAggValues) {
3755     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3756     return;
3757   }
3758 
3759   SDValue Agg = getValue(Op0);
3760   unsigned i = 0;
3761   // Copy the beginning value(s) from the original aggregate.
3762   for (; i != LinearIndex; ++i)
3763     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3764                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3765   // Copy values from the inserted value(s).
3766   if (NumValValues) {
3767     SDValue Val = getValue(Op1);
3768     for (; i != LinearIndex + NumValValues; ++i)
3769       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3770                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3771   }
3772   // Copy remaining value(s) from the original aggregate.
3773   for (; i != NumAggValues; ++i)
3774     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3775                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3776 
3777   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3778                            DAG.getVTList(AggValueVTs), Values));
3779 }
3780 
3781 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3782   ArrayRef<unsigned> Indices;
3783   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3784     Indices = EV->getIndices();
3785   else
3786     Indices = cast<ConstantExpr>(&I)->getIndices();
3787 
3788   const Value *Op0 = I.getOperand(0);
3789   Type *AggTy = Op0->getType();
3790   Type *ValTy = I.getType();
3791   bool OutOfUndef = isa<UndefValue>(Op0);
3792 
3793   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3794 
3795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3796   SmallVector<EVT, 4> ValValueVTs;
3797   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3798 
3799   unsigned NumValValues = ValValueVTs.size();
3800 
3801   // Ignore a extractvalue that produces an empty object
3802   if (!NumValValues) {
3803     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3804     return;
3805   }
3806 
3807   SmallVector<SDValue, 4> Values(NumValValues);
3808 
3809   SDValue Agg = getValue(Op0);
3810   // Copy out the selected value(s).
3811   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3812     Values[i - LinearIndex] =
3813       OutOfUndef ?
3814         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3815         SDValue(Agg.getNode(), Agg.getResNo() + i);
3816 
3817   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3818                            DAG.getVTList(ValValueVTs), Values));
3819 }
3820 
3821 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3822   Value *Op0 = I.getOperand(0);
3823   // Note that the pointer operand may be a vector of pointers. Take the scalar
3824   // element which holds a pointer.
3825   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3826   SDValue N = getValue(Op0);
3827   SDLoc dl = getCurSDLoc();
3828   auto &TLI = DAG.getTargetLoweringInfo();
3829 
3830   // Normalize Vector GEP - all scalar operands should be converted to the
3831   // splat vector.
3832   bool IsVectorGEP = I.getType()->isVectorTy();
3833   ElementCount VectorElementCount =
3834       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3835                   : ElementCount::getFixed(0);
3836 
3837   if (IsVectorGEP && !N.getValueType().isVector()) {
3838     LLVMContext &Context = *DAG.getContext();
3839     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3840     if (VectorElementCount.isScalable())
3841       N = DAG.getSplatVector(VT, dl, N);
3842     else
3843       N = DAG.getSplatBuildVector(VT, dl, N);
3844   }
3845 
3846   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3847        GTI != E; ++GTI) {
3848     const Value *Idx = GTI.getOperand();
3849     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3850       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3851       if (Field) {
3852         // N = N + Offset
3853         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3854 
3855         // In an inbounds GEP with an offset that is nonnegative even when
3856         // interpreted as signed, assume there is no unsigned overflow.
3857         SDNodeFlags Flags;
3858         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3859           Flags.setNoUnsignedWrap(true);
3860 
3861         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3862                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3863       }
3864     } else {
3865       // IdxSize is the width of the arithmetic according to IR semantics.
3866       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3867       // (and fix up the result later).
3868       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3869       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3870       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3871       // We intentionally mask away the high bits here; ElementSize may not
3872       // fit in IdxTy.
3873       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3874       bool ElementScalable = ElementSize.isScalable();
3875 
3876       // If this is a scalar constant or a splat vector of constants,
3877       // handle it quickly.
3878       const auto *C = dyn_cast<Constant>(Idx);
3879       if (C && isa<VectorType>(C->getType()))
3880         C = C->getSplatValue();
3881 
3882       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3883       if (CI && CI->isZero())
3884         continue;
3885       if (CI && !ElementScalable) {
3886         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3887         LLVMContext &Context = *DAG.getContext();
3888         SDValue OffsVal;
3889         if (IsVectorGEP)
3890           OffsVal = DAG.getConstant(
3891               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3892         else
3893           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3894 
3895         // In an inbounds GEP with an offset that is nonnegative even when
3896         // interpreted as signed, assume there is no unsigned overflow.
3897         SDNodeFlags Flags;
3898         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3899           Flags.setNoUnsignedWrap(true);
3900 
3901         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3902 
3903         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3904         continue;
3905       }
3906 
3907       // N = N + Idx * ElementMul;
3908       SDValue IdxN = getValue(Idx);
3909 
3910       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3911         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3912                                   VectorElementCount);
3913         if (VectorElementCount.isScalable())
3914           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3915         else
3916           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3917       }
3918 
3919       // If the index is smaller or larger than intptr_t, truncate or extend
3920       // it.
3921       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3922 
3923       if (ElementScalable) {
3924         EVT VScaleTy = N.getValueType().getScalarType();
3925         SDValue VScale = DAG.getNode(
3926             ISD::VSCALE, dl, VScaleTy,
3927             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3928         if (IsVectorGEP)
3929           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3930         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3931       } else {
3932         // If this is a multiply by a power of two, turn it into a shl
3933         // immediately.  This is a very common case.
3934         if (ElementMul != 1) {
3935           if (ElementMul.isPowerOf2()) {
3936             unsigned Amt = ElementMul.logBase2();
3937             IdxN = DAG.getNode(ISD::SHL, dl,
3938                                N.getValueType(), IdxN,
3939                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3940           } else {
3941             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3942                                             IdxN.getValueType());
3943             IdxN = DAG.getNode(ISD::MUL, dl,
3944                                N.getValueType(), IdxN, Scale);
3945           }
3946         }
3947       }
3948 
3949       N = DAG.getNode(ISD::ADD, dl,
3950                       N.getValueType(), N, IdxN);
3951     }
3952   }
3953 
3954   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3955   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3956   if (IsVectorGEP) {
3957     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3958     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3959   }
3960 
3961   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3962     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3963 
3964   setValue(&I, N);
3965 }
3966 
3967 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3968   // If this is a fixed sized alloca in the entry block of the function,
3969   // allocate it statically on the stack.
3970   if (FuncInfo.StaticAllocaMap.count(&I))
3971     return;   // getValue will auto-populate this.
3972 
3973   SDLoc dl = getCurSDLoc();
3974   Type *Ty = I.getAllocatedType();
3975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3976   auto &DL = DAG.getDataLayout();
3977   uint64_t TySize = DL.getTypeAllocSize(Ty);
3978   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3979 
3980   SDValue AllocSize = getValue(I.getArraySize());
3981 
3982   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3983   if (AllocSize.getValueType() != IntPtr)
3984     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3985 
3986   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3987                           AllocSize,
3988                           DAG.getConstant(TySize, dl, IntPtr));
3989 
3990   // Handle alignment.  If the requested alignment is less than or equal to
3991   // the stack alignment, ignore it.  If the size is greater than or equal to
3992   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3993   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3994   if (*Alignment <= StackAlign)
3995     Alignment = None;
3996 
3997   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3998   // Round the size of the allocation up to the stack alignment size
3999   // by add SA-1 to the size. This doesn't overflow because we're computing
4000   // an address inside an alloca.
4001   SDNodeFlags Flags;
4002   Flags.setNoUnsignedWrap(true);
4003   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4004                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4005 
4006   // Mask out the low bits for alignment purposes.
4007   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4008                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4009 
4010   SDValue Ops[] = {
4011       getRoot(), AllocSize,
4012       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4013   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4014   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4015   setValue(&I, DSA);
4016   DAG.setRoot(DSA.getValue(1));
4017 
4018   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4019 }
4020 
4021 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4022   if (I.isAtomic())
4023     return visitAtomicLoad(I);
4024 
4025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4026   const Value *SV = I.getOperand(0);
4027   if (TLI.supportSwiftError()) {
4028     // Swifterror values can come from either a function parameter with
4029     // swifterror attribute or an alloca with swifterror attribute.
4030     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4031       if (Arg->hasSwiftErrorAttr())
4032         return visitLoadFromSwiftError(I);
4033     }
4034 
4035     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4036       if (Alloca->isSwiftError())
4037         return visitLoadFromSwiftError(I);
4038     }
4039   }
4040 
4041   SDValue Ptr = getValue(SV);
4042 
4043   Type *Ty = I.getType();
4044   Align Alignment = I.getAlign();
4045 
4046   AAMDNodes AAInfo;
4047   I.getAAMetadata(AAInfo);
4048   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4049 
4050   SmallVector<EVT, 4> ValueVTs, MemVTs;
4051   SmallVector<uint64_t, 4> Offsets;
4052   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4053   unsigned NumValues = ValueVTs.size();
4054   if (NumValues == 0)
4055     return;
4056 
4057   bool isVolatile = I.isVolatile();
4058 
4059   SDValue Root;
4060   bool ConstantMemory = false;
4061   if (isVolatile)
4062     // Serialize volatile loads with other side effects.
4063     Root = getRoot();
4064   else if (NumValues > MaxParallelChains)
4065     Root = getMemoryRoot();
4066   else if (AA &&
4067            AA->pointsToConstantMemory(MemoryLocation(
4068                SV,
4069                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4070                AAInfo))) {
4071     // Do not serialize (non-volatile) loads of constant memory with anything.
4072     Root = DAG.getEntryNode();
4073     ConstantMemory = true;
4074   } else {
4075     // Do not serialize non-volatile loads against each other.
4076     Root = DAG.getRoot();
4077   }
4078 
4079   SDLoc dl = getCurSDLoc();
4080 
4081   if (isVolatile)
4082     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4083 
4084   // An aggregate load cannot wrap around the address space, so offsets to its
4085   // parts don't wrap either.
4086   SDNodeFlags Flags;
4087   Flags.setNoUnsignedWrap(true);
4088 
4089   SmallVector<SDValue, 4> Values(NumValues);
4090   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4091   EVT PtrVT = Ptr.getValueType();
4092 
4093   MachineMemOperand::Flags MMOFlags
4094     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4095 
4096   unsigned ChainI = 0;
4097   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4098     // Serializing loads here may result in excessive register pressure, and
4099     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4100     // could recover a bit by hoisting nodes upward in the chain by recognizing
4101     // they are side-effect free or do not alias. The optimizer should really
4102     // avoid this case by converting large object/array copies to llvm.memcpy
4103     // (MaxParallelChains should always remain as failsafe).
4104     if (ChainI == MaxParallelChains) {
4105       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4106       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4107                                   makeArrayRef(Chains.data(), ChainI));
4108       Root = Chain;
4109       ChainI = 0;
4110     }
4111     SDValue A = DAG.getNode(ISD::ADD, dl,
4112                             PtrVT, Ptr,
4113                             DAG.getConstant(Offsets[i], dl, PtrVT),
4114                             Flags);
4115 
4116     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4117                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4118                             MMOFlags, AAInfo, Ranges);
4119     Chains[ChainI] = L.getValue(1);
4120 
4121     if (MemVTs[i] != ValueVTs[i])
4122       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4123 
4124     Values[i] = L;
4125   }
4126 
4127   if (!ConstantMemory) {
4128     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4129                                 makeArrayRef(Chains.data(), ChainI));
4130     if (isVolatile)
4131       DAG.setRoot(Chain);
4132     else
4133       PendingLoads.push_back(Chain);
4134   }
4135 
4136   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4137                            DAG.getVTList(ValueVTs), Values));
4138 }
4139 
4140 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4141   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4142          "call visitStoreToSwiftError when backend supports swifterror");
4143 
4144   SmallVector<EVT, 4> ValueVTs;
4145   SmallVector<uint64_t, 4> Offsets;
4146   const Value *SrcV = I.getOperand(0);
4147   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4148                   SrcV->getType(), ValueVTs, &Offsets);
4149   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4150          "expect a single EVT for swifterror");
4151 
4152   SDValue Src = getValue(SrcV);
4153   // Create a virtual register, then update the virtual register.
4154   Register VReg =
4155       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4156   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4157   // Chain can be getRoot or getControlRoot.
4158   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4159                                       SDValue(Src.getNode(), Src.getResNo()));
4160   DAG.setRoot(CopyNode);
4161 }
4162 
4163 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4164   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4165          "call visitLoadFromSwiftError when backend supports swifterror");
4166 
4167   assert(!I.isVolatile() &&
4168          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4169          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4170          "Support volatile, non temporal, invariant for load_from_swift_error");
4171 
4172   const Value *SV = I.getOperand(0);
4173   Type *Ty = I.getType();
4174   AAMDNodes AAInfo;
4175   I.getAAMetadata(AAInfo);
4176   assert(
4177       (!AA ||
4178        !AA->pointsToConstantMemory(MemoryLocation(
4179            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4180            AAInfo))) &&
4181       "load_from_swift_error should not be constant memory");
4182 
4183   SmallVector<EVT, 4> ValueVTs;
4184   SmallVector<uint64_t, 4> Offsets;
4185   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4186                   ValueVTs, &Offsets);
4187   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4188          "expect a single EVT for swifterror");
4189 
4190   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4191   SDValue L = DAG.getCopyFromReg(
4192       getRoot(), getCurSDLoc(),
4193       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4194 
4195   setValue(&I, L);
4196 }
4197 
4198 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4199   if (I.isAtomic())
4200     return visitAtomicStore(I);
4201 
4202   const Value *SrcV = I.getOperand(0);
4203   const Value *PtrV = I.getOperand(1);
4204 
4205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4206   if (TLI.supportSwiftError()) {
4207     // Swifterror values can come from either a function parameter with
4208     // swifterror attribute or an alloca with swifterror attribute.
4209     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4210       if (Arg->hasSwiftErrorAttr())
4211         return visitStoreToSwiftError(I);
4212     }
4213 
4214     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4215       if (Alloca->isSwiftError())
4216         return visitStoreToSwiftError(I);
4217     }
4218   }
4219 
4220   SmallVector<EVT, 4> ValueVTs, MemVTs;
4221   SmallVector<uint64_t, 4> Offsets;
4222   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4223                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4224   unsigned NumValues = ValueVTs.size();
4225   if (NumValues == 0)
4226     return;
4227 
4228   // Get the lowered operands. Note that we do this after
4229   // checking if NumResults is zero, because with zero results
4230   // the operands won't have values in the map.
4231   SDValue Src = getValue(SrcV);
4232   SDValue Ptr = getValue(PtrV);
4233 
4234   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4235   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4236   SDLoc dl = getCurSDLoc();
4237   Align Alignment = I.getAlign();
4238   AAMDNodes AAInfo;
4239   I.getAAMetadata(AAInfo);
4240 
4241   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4242 
4243   // An aggregate load cannot wrap around the address space, so offsets to its
4244   // parts don't wrap either.
4245   SDNodeFlags Flags;
4246   Flags.setNoUnsignedWrap(true);
4247 
4248   unsigned ChainI = 0;
4249   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4250     // See visitLoad comments.
4251     if (ChainI == MaxParallelChains) {
4252       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4253                                   makeArrayRef(Chains.data(), ChainI));
4254       Root = Chain;
4255       ChainI = 0;
4256     }
4257     SDValue Add =
4258         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4259     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4260     if (MemVTs[i] != ValueVTs[i])
4261       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4262     SDValue St =
4263         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4264                      Alignment, MMOFlags, AAInfo);
4265     Chains[ChainI] = St;
4266   }
4267 
4268   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4269                                   makeArrayRef(Chains.data(), ChainI));
4270   DAG.setRoot(StoreNode);
4271 }
4272 
4273 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4274                                            bool IsCompressing) {
4275   SDLoc sdl = getCurSDLoc();
4276 
4277   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4278                                MaybeAlign &Alignment) {
4279     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4280     Src0 = I.getArgOperand(0);
4281     Ptr = I.getArgOperand(1);
4282     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4283     Mask = I.getArgOperand(3);
4284   };
4285   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4286                                     MaybeAlign &Alignment) {
4287     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4288     Src0 = I.getArgOperand(0);
4289     Ptr = I.getArgOperand(1);
4290     Mask = I.getArgOperand(2);
4291     Alignment = None;
4292   };
4293 
4294   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4295   MaybeAlign Alignment;
4296   if (IsCompressing)
4297     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4298   else
4299     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4300 
4301   SDValue Ptr = getValue(PtrOperand);
4302   SDValue Src0 = getValue(Src0Operand);
4303   SDValue Mask = getValue(MaskOperand);
4304   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4305 
4306   EVT VT = Src0.getValueType();
4307   if (!Alignment)
4308     Alignment = DAG.getEVTAlign(VT);
4309 
4310   AAMDNodes AAInfo;
4311   I.getAAMetadata(AAInfo);
4312 
4313   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4314       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4315       // TODO: Make MachineMemOperands aware of scalable
4316       // vectors.
4317       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4318   SDValue StoreNode =
4319       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4320                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4321   DAG.setRoot(StoreNode);
4322   setValue(&I, StoreNode);
4323 }
4324 
4325 // Get a uniform base for the Gather/Scatter intrinsic.
4326 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4327 // We try to represent it as a base pointer + vector of indices.
4328 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4329 // The first operand of the GEP may be a single pointer or a vector of pointers
4330 // Example:
4331 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4332 //  or
4333 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4334 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4335 //
4336 // When the first GEP operand is a single pointer - it is the uniform base we
4337 // are looking for. If first operand of the GEP is a splat vector - we
4338 // extract the splat value and use it as a uniform base.
4339 // In all other cases the function returns 'false'.
4340 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4341                            ISD::MemIndexType &IndexType, SDValue &Scale,
4342                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4343   SelectionDAG& DAG = SDB->DAG;
4344   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4345   const DataLayout &DL = DAG.getDataLayout();
4346 
4347   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4348 
4349   // Handle splat constant pointer.
4350   if (auto *C = dyn_cast<Constant>(Ptr)) {
4351     C = C->getSplatValue();
4352     if (!C)
4353       return false;
4354 
4355     Base = SDB->getValue(C);
4356 
4357     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4358     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4359     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4360     IndexType = ISD::SIGNED_SCALED;
4361     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4362     return true;
4363   }
4364 
4365   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4366   if (!GEP || GEP->getParent() != CurBB)
4367     return false;
4368 
4369   if (GEP->getNumOperands() != 2)
4370     return false;
4371 
4372   const Value *BasePtr = GEP->getPointerOperand();
4373   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4374 
4375   // Make sure the base is scalar and the index is a vector.
4376   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4377     return false;
4378 
4379   Base = SDB->getValue(BasePtr);
4380   Index = SDB->getValue(IndexVal);
4381   IndexType = ISD::SIGNED_SCALED;
4382   Scale = DAG.getTargetConstant(
4383               DL.getTypeAllocSize(GEP->getResultElementType()),
4384               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4385   return true;
4386 }
4387 
4388 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4389   SDLoc sdl = getCurSDLoc();
4390 
4391   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4392   const Value *Ptr = I.getArgOperand(1);
4393   SDValue Src0 = getValue(I.getArgOperand(0));
4394   SDValue Mask = getValue(I.getArgOperand(3));
4395   EVT VT = Src0.getValueType();
4396   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4397                         ->getMaybeAlignValue()
4398                         .getValueOr(DAG.getEVTAlign(VT));
4399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4400 
4401   AAMDNodes AAInfo;
4402   I.getAAMetadata(AAInfo);
4403 
4404   SDValue Base;
4405   SDValue Index;
4406   ISD::MemIndexType IndexType;
4407   SDValue Scale;
4408   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4409                                     I.getParent());
4410 
4411   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4412   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4413       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4414       // TODO: Make MachineMemOperands aware of scalable
4415       // vectors.
4416       MemoryLocation::UnknownSize, Alignment, AAInfo);
4417   if (!UniformBase) {
4418     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4419     Index = getValue(Ptr);
4420     IndexType = ISD::SIGNED_UNSCALED;
4421     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4422   }
4423 
4424   EVT IdxVT = Index.getValueType();
4425   EVT EltTy = IdxVT.getVectorElementType();
4426   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4427     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4428     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4429   }
4430 
4431   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4432   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4433                                          Ops, MMO, IndexType, false);
4434   DAG.setRoot(Scatter);
4435   setValue(&I, Scatter);
4436 }
4437 
4438 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4439   SDLoc sdl = getCurSDLoc();
4440 
4441   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4442                               MaybeAlign &Alignment) {
4443     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4444     Ptr = I.getArgOperand(0);
4445     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4446     Mask = I.getArgOperand(2);
4447     Src0 = I.getArgOperand(3);
4448   };
4449   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4450                                  MaybeAlign &Alignment) {
4451     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4452     Ptr = I.getArgOperand(0);
4453     Alignment = None;
4454     Mask = I.getArgOperand(1);
4455     Src0 = I.getArgOperand(2);
4456   };
4457 
4458   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4459   MaybeAlign Alignment;
4460   if (IsExpanding)
4461     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4462   else
4463     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4464 
4465   SDValue Ptr = getValue(PtrOperand);
4466   SDValue Src0 = getValue(Src0Operand);
4467   SDValue Mask = getValue(MaskOperand);
4468   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4469 
4470   EVT VT = Src0.getValueType();
4471   if (!Alignment)
4472     Alignment = DAG.getEVTAlign(VT);
4473 
4474   AAMDNodes AAInfo;
4475   I.getAAMetadata(AAInfo);
4476   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4477 
4478   // Do not serialize masked loads of constant memory with anything.
4479   MemoryLocation ML;
4480   if (VT.isScalableVector())
4481     ML = MemoryLocation::getAfter(PtrOperand);
4482   else
4483     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4484                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4485                            AAInfo);
4486   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4487 
4488   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4489 
4490   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4491       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4492       // TODO: Make MachineMemOperands aware of scalable
4493       // vectors.
4494       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4495 
4496   SDValue Load =
4497       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4498                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4499   if (AddToChain)
4500     PendingLoads.push_back(Load.getValue(1));
4501   setValue(&I, Load);
4502 }
4503 
4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4505   SDLoc sdl = getCurSDLoc();
4506 
4507   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4508   const Value *Ptr = I.getArgOperand(0);
4509   SDValue Src0 = getValue(I.getArgOperand(3));
4510   SDValue Mask = getValue(I.getArgOperand(2));
4511 
4512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4513   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4514   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4515                         ->getMaybeAlignValue()
4516                         .getValueOr(DAG.getEVTAlign(VT));
4517 
4518   AAMDNodes AAInfo;
4519   I.getAAMetadata(AAInfo);
4520   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4521 
4522   SDValue Root = DAG.getRoot();
4523   SDValue Base;
4524   SDValue Index;
4525   ISD::MemIndexType IndexType;
4526   SDValue Scale;
4527   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4528                                     I.getParent());
4529   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4530   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4531       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4532       // TODO: Make MachineMemOperands aware of scalable
4533       // vectors.
4534       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4535 
4536   if (!UniformBase) {
4537     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4538     Index = getValue(Ptr);
4539     IndexType = ISD::SIGNED_UNSCALED;
4540     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4541   }
4542 
4543   EVT IdxVT = Index.getValueType();
4544   EVT EltTy = IdxVT.getVectorElementType();
4545   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4546     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4547     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4548   }
4549 
4550   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4551   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4552                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4553 
4554   PendingLoads.push_back(Gather.getValue(1));
4555   setValue(&I, Gather);
4556 }
4557 
4558 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4559   SDLoc dl = getCurSDLoc();
4560   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4561   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4562   SyncScope::ID SSID = I.getSyncScopeID();
4563 
4564   SDValue InChain = getRoot();
4565 
4566   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4567   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4568 
4569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4570   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4571 
4572   MachineFunction &MF = DAG.getMachineFunction();
4573   MachineMemOperand *MMO = MF.getMachineMemOperand(
4574       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4575       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4576       FailureOrdering);
4577 
4578   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4579                                    dl, MemVT, VTs, InChain,
4580                                    getValue(I.getPointerOperand()),
4581                                    getValue(I.getCompareOperand()),
4582                                    getValue(I.getNewValOperand()), MMO);
4583 
4584   SDValue OutChain = L.getValue(2);
4585 
4586   setValue(&I, L);
4587   DAG.setRoot(OutChain);
4588 }
4589 
4590 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4591   SDLoc dl = getCurSDLoc();
4592   ISD::NodeType NT;
4593   switch (I.getOperation()) {
4594   default: llvm_unreachable("Unknown atomicrmw operation");
4595   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4596   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4597   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4598   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4599   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4600   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4601   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4602   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4603   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4604   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4605   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4606   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4607   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4608   }
4609   AtomicOrdering Ordering = I.getOrdering();
4610   SyncScope::ID SSID = I.getSyncScopeID();
4611 
4612   SDValue InChain = getRoot();
4613 
4614   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4616   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4617 
4618   MachineFunction &MF = DAG.getMachineFunction();
4619   MachineMemOperand *MMO = MF.getMachineMemOperand(
4620       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4621       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4622 
4623   SDValue L =
4624     DAG.getAtomic(NT, dl, MemVT, InChain,
4625                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4626                   MMO);
4627 
4628   SDValue OutChain = L.getValue(1);
4629 
4630   setValue(&I, L);
4631   DAG.setRoot(OutChain);
4632 }
4633 
4634 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4635   SDLoc dl = getCurSDLoc();
4636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4637   SDValue Ops[3];
4638   Ops[0] = getRoot();
4639   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4640                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4641   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4642                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4643   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4644 }
4645 
4646 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4647   SDLoc dl = getCurSDLoc();
4648   AtomicOrdering Order = I.getOrdering();
4649   SyncScope::ID SSID = I.getSyncScopeID();
4650 
4651   SDValue InChain = getRoot();
4652 
4653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4654   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4655   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4656 
4657   if (!TLI.supportsUnalignedAtomics() &&
4658       I.getAlignment() < MemVT.getSizeInBits() / 8)
4659     report_fatal_error("Cannot generate unaligned atomic load");
4660 
4661   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4662 
4663   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4664       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4665       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4666 
4667   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4668 
4669   SDValue Ptr = getValue(I.getPointerOperand());
4670 
4671   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4672     // TODO: Once this is better exercised by tests, it should be merged with
4673     // the normal path for loads to prevent future divergence.
4674     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4675     if (MemVT != VT)
4676       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4677 
4678     setValue(&I, L);
4679     SDValue OutChain = L.getValue(1);
4680     if (!I.isUnordered())
4681       DAG.setRoot(OutChain);
4682     else
4683       PendingLoads.push_back(OutChain);
4684     return;
4685   }
4686 
4687   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4688                             Ptr, MMO);
4689 
4690   SDValue OutChain = L.getValue(1);
4691   if (MemVT != VT)
4692     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4693 
4694   setValue(&I, L);
4695   DAG.setRoot(OutChain);
4696 }
4697 
4698 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4699   SDLoc dl = getCurSDLoc();
4700 
4701   AtomicOrdering Ordering = I.getOrdering();
4702   SyncScope::ID SSID = I.getSyncScopeID();
4703 
4704   SDValue InChain = getRoot();
4705 
4706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4707   EVT MemVT =
4708       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4709 
4710   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4711     report_fatal_error("Cannot generate unaligned atomic store");
4712 
4713   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4714 
4715   MachineFunction &MF = DAG.getMachineFunction();
4716   MachineMemOperand *MMO = MF.getMachineMemOperand(
4717       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4718       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4719 
4720   SDValue Val = getValue(I.getValueOperand());
4721   if (Val.getValueType() != MemVT)
4722     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4723   SDValue Ptr = getValue(I.getPointerOperand());
4724 
4725   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4726     // TODO: Once this is better exercised by tests, it should be merged with
4727     // the normal path for stores to prevent future divergence.
4728     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4729     DAG.setRoot(S);
4730     return;
4731   }
4732   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4733                                    Ptr, Val, MMO);
4734 
4735 
4736   DAG.setRoot(OutChain);
4737 }
4738 
4739 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4740 /// node.
4741 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4742                                                unsigned Intrinsic) {
4743   // Ignore the callsite's attributes. A specific call site may be marked with
4744   // readnone, but the lowering code will expect the chain based on the
4745   // definition.
4746   const Function *F = I.getCalledFunction();
4747   bool HasChain = !F->doesNotAccessMemory();
4748   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4749 
4750   // Build the operand list.
4751   SmallVector<SDValue, 8> Ops;
4752   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4753     if (OnlyLoad) {
4754       // We don't need to serialize loads against other loads.
4755       Ops.push_back(DAG.getRoot());
4756     } else {
4757       Ops.push_back(getRoot());
4758     }
4759   }
4760 
4761   // Info is set by getTgtMemInstrinsic
4762   TargetLowering::IntrinsicInfo Info;
4763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4764   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4765                                                DAG.getMachineFunction(),
4766                                                Intrinsic);
4767 
4768   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4769   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4770       Info.opc == ISD::INTRINSIC_W_CHAIN)
4771     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4772                                         TLI.getPointerTy(DAG.getDataLayout())));
4773 
4774   // Add all operands of the call to the operand list.
4775   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4776     const Value *Arg = I.getArgOperand(i);
4777     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4778       Ops.push_back(getValue(Arg));
4779       continue;
4780     }
4781 
4782     // Use TargetConstant instead of a regular constant for immarg.
4783     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4784     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4785       assert(CI->getBitWidth() <= 64 &&
4786              "large intrinsic immediates not handled");
4787       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4788     } else {
4789       Ops.push_back(
4790           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4791     }
4792   }
4793 
4794   SmallVector<EVT, 4> ValueVTs;
4795   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4796 
4797   if (HasChain)
4798     ValueVTs.push_back(MVT::Other);
4799 
4800   SDVTList VTs = DAG.getVTList(ValueVTs);
4801 
4802   // Create the node.
4803   SDValue Result;
4804   if (IsTgtIntrinsic) {
4805     // This is target intrinsic that touches memory
4806     AAMDNodes AAInfo;
4807     I.getAAMetadata(AAInfo);
4808     Result =
4809         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4810                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4811                                 Info.align, Info.flags, Info.size, AAInfo);
4812   } else if (!HasChain) {
4813     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4814   } else if (!I.getType()->isVoidTy()) {
4815     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4816   } else {
4817     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4818   }
4819 
4820   if (HasChain) {
4821     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4822     if (OnlyLoad)
4823       PendingLoads.push_back(Chain);
4824     else
4825       DAG.setRoot(Chain);
4826   }
4827 
4828   if (!I.getType()->isVoidTy()) {
4829     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4830       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4831       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4832     } else
4833       Result = lowerRangeToAssertZExt(DAG, I, Result);
4834 
4835     MaybeAlign Alignment = I.getRetAlign();
4836     if (!Alignment)
4837       Alignment = F->getAttributes().getRetAlignment();
4838     // Insert `assertalign` node if there's an alignment.
4839     if (InsertAssertAlign && Alignment) {
4840       Result =
4841           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4842     }
4843 
4844     setValue(&I, Result);
4845   }
4846 }
4847 
4848 /// GetSignificand - Get the significand and build it into a floating-point
4849 /// number with exponent of 1:
4850 ///
4851 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4852 ///
4853 /// where Op is the hexadecimal representation of floating point value.
4854 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4855   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4856                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4857   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4858                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4859   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4860 }
4861 
4862 /// GetExponent - Get the exponent:
4863 ///
4864 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4865 ///
4866 /// where Op is the hexadecimal representation of floating point value.
4867 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4868                            const TargetLowering &TLI, const SDLoc &dl) {
4869   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4870                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4871   SDValue t1 = DAG.getNode(
4872       ISD::SRL, dl, MVT::i32, t0,
4873       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4874   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4875                            DAG.getConstant(127, dl, MVT::i32));
4876   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4877 }
4878 
4879 /// getF32Constant - Get 32-bit floating point constant.
4880 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4881                               const SDLoc &dl) {
4882   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4883                            MVT::f32);
4884 }
4885 
4886 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4887                                        SelectionDAG &DAG) {
4888   // TODO: What fast-math-flags should be set on the floating-point nodes?
4889 
4890   //   IntegerPartOfX = ((int32_t)(t0);
4891   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4892 
4893   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4894   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4895   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4896 
4897   //   IntegerPartOfX <<= 23;
4898   IntegerPartOfX = DAG.getNode(
4899       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4900       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4901                                   DAG.getDataLayout())));
4902 
4903   SDValue TwoToFractionalPartOfX;
4904   if (LimitFloatPrecision <= 6) {
4905     // For floating-point precision of 6:
4906     //
4907     //   TwoToFractionalPartOfX =
4908     //     0.997535578f +
4909     //       (0.735607626f + 0.252464424f * x) * x;
4910     //
4911     // error 0.0144103317, which is 6 bits
4912     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4913                              getF32Constant(DAG, 0x3e814304, dl));
4914     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4915                              getF32Constant(DAG, 0x3f3c50c8, dl));
4916     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4917     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4918                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4919   } else if (LimitFloatPrecision <= 12) {
4920     // For floating-point precision of 12:
4921     //
4922     //   TwoToFractionalPartOfX =
4923     //     0.999892986f +
4924     //       (0.696457318f +
4925     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4926     //
4927     // error 0.000107046256, which is 13 to 14 bits
4928     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4929                              getF32Constant(DAG, 0x3da235e3, dl));
4930     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4931                              getF32Constant(DAG, 0x3e65b8f3, dl));
4932     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4933     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4934                              getF32Constant(DAG, 0x3f324b07, dl));
4935     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4936     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4937                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4938   } else { // LimitFloatPrecision <= 18
4939     // For floating-point precision of 18:
4940     //
4941     //   TwoToFractionalPartOfX =
4942     //     0.999999982f +
4943     //       (0.693148872f +
4944     //         (0.240227044f +
4945     //           (0.554906021e-1f +
4946     //             (0.961591928e-2f +
4947     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4948     // error 2.47208000*10^(-7), which is better than 18 bits
4949     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4950                              getF32Constant(DAG, 0x3924b03e, dl));
4951     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4952                              getF32Constant(DAG, 0x3ab24b87, dl));
4953     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4954     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4955                              getF32Constant(DAG, 0x3c1d8c17, dl));
4956     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4957     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4958                              getF32Constant(DAG, 0x3d634a1d, dl));
4959     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4960     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4961                              getF32Constant(DAG, 0x3e75fe14, dl));
4962     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4963     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4964                               getF32Constant(DAG, 0x3f317234, dl));
4965     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4966     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4967                                          getF32Constant(DAG, 0x3f800000, dl));
4968   }
4969 
4970   // Add the exponent into the result in integer domain.
4971   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4972   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4973                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4974 }
4975 
4976 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4977 /// limited-precision mode.
4978 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4979                          const TargetLowering &TLI, SDNodeFlags Flags) {
4980   if (Op.getValueType() == MVT::f32 &&
4981       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4982 
4983     // Put the exponent in the right bit position for later addition to the
4984     // final result:
4985     //
4986     // t0 = Op * log2(e)
4987 
4988     // TODO: What fast-math-flags should be set here?
4989     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4990                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4991     return getLimitedPrecisionExp2(t0, dl, DAG);
4992   }
4993 
4994   // No special expansion.
4995   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4996 }
4997 
4998 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4999 /// limited-precision mode.
5000 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5001                          const TargetLowering &TLI, SDNodeFlags Flags) {
5002   // TODO: What fast-math-flags should be set on the floating-point nodes?
5003 
5004   if (Op.getValueType() == MVT::f32 &&
5005       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5006     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5007 
5008     // Scale the exponent by log(2).
5009     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5010     SDValue LogOfExponent =
5011         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5012                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5013 
5014     // Get the significand and build it into a floating-point number with
5015     // exponent of 1.
5016     SDValue X = GetSignificand(DAG, Op1, dl);
5017 
5018     SDValue LogOfMantissa;
5019     if (LimitFloatPrecision <= 6) {
5020       // For floating-point precision of 6:
5021       //
5022       //   LogofMantissa =
5023       //     -1.1609546f +
5024       //       (1.4034025f - 0.23903021f * x) * x;
5025       //
5026       // error 0.0034276066, which is better than 8 bits
5027       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5028                                getF32Constant(DAG, 0xbe74c456, dl));
5029       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5030                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5031       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5032       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5033                                   getF32Constant(DAG, 0x3f949a29, dl));
5034     } else if (LimitFloatPrecision <= 12) {
5035       // For floating-point precision of 12:
5036       //
5037       //   LogOfMantissa =
5038       //     -1.7417939f +
5039       //       (2.8212026f +
5040       //         (-1.4699568f +
5041       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5042       //
5043       // error 0.000061011436, which is 14 bits
5044       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5045                                getF32Constant(DAG, 0xbd67b6d6, dl));
5046       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5047                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5048       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5049       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5050                                getF32Constant(DAG, 0x3fbc278b, dl));
5051       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5052       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5053                                getF32Constant(DAG, 0x40348e95, dl));
5054       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5055       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5056                                   getF32Constant(DAG, 0x3fdef31a, dl));
5057     } else { // LimitFloatPrecision <= 18
5058       // For floating-point precision of 18:
5059       //
5060       //   LogOfMantissa =
5061       //     -2.1072184f +
5062       //       (4.2372794f +
5063       //         (-3.7029485f +
5064       //           (2.2781945f +
5065       //             (-0.87823314f +
5066       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5067       //
5068       // error 0.0000023660568, which is better than 18 bits
5069       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5070                                getF32Constant(DAG, 0xbc91e5ac, dl));
5071       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5072                                getF32Constant(DAG, 0x3e4350aa, dl));
5073       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5074       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5075                                getF32Constant(DAG, 0x3f60d3e3, dl));
5076       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5077       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5078                                getF32Constant(DAG, 0x4011cdf0, dl));
5079       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5080       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5081                                getF32Constant(DAG, 0x406cfd1c, dl));
5082       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5083       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5084                                getF32Constant(DAG, 0x408797cb, dl));
5085       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5086       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5087                                   getF32Constant(DAG, 0x4006dcab, dl));
5088     }
5089 
5090     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5091   }
5092 
5093   // No special expansion.
5094   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5095 }
5096 
5097 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5098 /// limited-precision mode.
5099 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5100                           const TargetLowering &TLI, SDNodeFlags Flags) {
5101   // TODO: What fast-math-flags should be set on the floating-point nodes?
5102 
5103   if (Op.getValueType() == MVT::f32 &&
5104       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5105     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5106 
5107     // Get the exponent.
5108     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5109 
5110     // Get the significand and build it into a floating-point number with
5111     // exponent of 1.
5112     SDValue X = GetSignificand(DAG, Op1, dl);
5113 
5114     // Different possible minimax approximations of significand in
5115     // floating-point for various degrees of accuracy over [1,2].
5116     SDValue Log2ofMantissa;
5117     if (LimitFloatPrecision <= 6) {
5118       // For floating-point precision of 6:
5119       //
5120       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5121       //
5122       // error 0.0049451742, which is more than 7 bits
5123       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5124                                getF32Constant(DAG, 0xbeb08fe0, dl));
5125       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5126                                getF32Constant(DAG, 0x40019463, dl));
5127       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5128       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5129                                    getF32Constant(DAG, 0x3fd6633d, dl));
5130     } else if (LimitFloatPrecision <= 12) {
5131       // For floating-point precision of 12:
5132       //
5133       //   Log2ofMantissa =
5134       //     -2.51285454f +
5135       //       (4.07009056f +
5136       //         (-2.12067489f +
5137       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5138       //
5139       // error 0.0000876136000, which is better than 13 bits
5140       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5141                                getF32Constant(DAG, 0xbda7262e, dl));
5142       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5143                                getF32Constant(DAG, 0x3f25280b, dl));
5144       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5145       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5146                                getF32Constant(DAG, 0x4007b923, dl));
5147       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5148       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5149                                getF32Constant(DAG, 0x40823e2f, dl));
5150       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5151       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5152                                    getF32Constant(DAG, 0x4020d29c, dl));
5153     } else { // LimitFloatPrecision <= 18
5154       // For floating-point precision of 18:
5155       //
5156       //   Log2ofMantissa =
5157       //     -3.0400495f +
5158       //       (6.1129976f +
5159       //         (-5.3420409f +
5160       //           (3.2865683f +
5161       //             (-1.2669343f +
5162       //               (0.27515199f -
5163       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5164       //
5165       // error 0.0000018516, which is better than 18 bits
5166       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5167                                getF32Constant(DAG, 0xbcd2769e, dl));
5168       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5169                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5170       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5171       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5172                                getF32Constant(DAG, 0x3fa22ae7, dl));
5173       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5174       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5175                                getF32Constant(DAG, 0x40525723, dl));
5176       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5177       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5178                                getF32Constant(DAG, 0x40aaf200, dl));
5179       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5180       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5181                                getF32Constant(DAG, 0x40c39dad, dl));
5182       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5183       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5184                                    getF32Constant(DAG, 0x4042902c, dl));
5185     }
5186 
5187     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5188   }
5189 
5190   // No special expansion.
5191   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5192 }
5193 
5194 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5195 /// limited-precision mode.
5196 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5197                            const TargetLowering &TLI, SDNodeFlags Flags) {
5198   // TODO: What fast-math-flags should be set on the floating-point nodes?
5199 
5200   if (Op.getValueType() == MVT::f32 &&
5201       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5202     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5203 
5204     // Scale the exponent by log10(2) [0.30102999f].
5205     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5206     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5207                                         getF32Constant(DAG, 0x3e9a209a, dl));
5208 
5209     // Get the significand and build it into a floating-point number with
5210     // exponent of 1.
5211     SDValue X = GetSignificand(DAG, Op1, dl);
5212 
5213     SDValue Log10ofMantissa;
5214     if (LimitFloatPrecision <= 6) {
5215       // For floating-point precision of 6:
5216       //
5217       //   Log10ofMantissa =
5218       //     -0.50419619f +
5219       //       (0.60948995f - 0.10380950f * x) * x;
5220       //
5221       // error 0.0014886165, which is 6 bits
5222       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5223                                getF32Constant(DAG, 0xbdd49a13, dl));
5224       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5225                                getF32Constant(DAG, 0x3f1c0789, dl));
5226       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5227       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5228                                     getF32Constant(DAG, 0x3f011300, dl));
5229     } else if (LimitFloatPrecision <= 12) {
5230       // For floating-point precision of 12:
5231       //
5232       //   Log10ofMantissa =
5233       //     -0.64831180f +
5234       //       (0.91751397f +
5235       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5236       //
5237       // error 0.00019228036, which is better than 12 bits
5238       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5239                                getF32Constant(DAG, 0x3d431f31, dl));
5240       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5241                                getF32Constant(DAG, 0x3ea21fb2, dl));
5242       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5243       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5244                                getF32Constant(DAG, 0x3f6ae232, dl));
5245       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5246       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5247                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5248     } else { // LimitFloatPrecision <= 18
5249       // For floating-point precision of 18:
5250       //
5251       //   Log10ofMantissa =
5252       //     -0.84299375f +
5253       //       (1.5327582f +
5254       //         (-1.0688956f +
5255       //           (0.49102474f +
5256       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5257       //
5258       // error 0.0000037995730, which is better than 18 bits
5259       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5260                                getF32Constant(DAG, 0x3c5d51ce, dl));
5261       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5262                                getF32Constant(DAG, 0x3e00685a, dl));
5263       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5264       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5265                                getF32Constant(DAG, 0x3efb6798, dl));
5266       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5267       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5268                                getF32Constant(DAG, 0x3f88d192, dl));
5269       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5270       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5271                                getF32Constant(DAG, 0x3fc4316c, dl));
5272       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5273       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5274                                     getF32Constant(DAG, 0x3f57ce70, dl));
5275     }
5276 
5277     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5278   }
5279 
5280   // No special expansion.
5281   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5282 }
5283 
5284 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5285 /// limited-precision mode.
5286 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5287                           const TargetLowering &TLI, SDNodeFlags Flags) {
5288   if (Op.getValueType() == MVT::f32 &&
5289       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5290     return getLimitedPrecisionExp2(Op, dl, DAG);
5291 
5292   // No special expansion.
5293   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5294 }
5295 
5296 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5297 /// limited-precision mode with x == 10.0f.
5298 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5299                          SelectionDAG &DAG, const TargetLowering &TLI,
5300                          SDNodeFlags Flags) {
5301   bool IsExp10 = false;
5302   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5303       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5304     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5305       APFloat Ten(10.0f);
5306       IsExp10 = LHSC->isExactlyValue(Ten);
5307     }
5308   }
5309 
5310   // TODO: What fast-math-flags should be set on the FMUL node?
5311   if (IsExp10) {
5312     // Put the exponent in the right bit position for later addition to the
5313     // final result:
5314     //
5315     //   #define LOG2OF10 3.3219281f
5316     //   t0 = Op * LOG2OF10;
5317     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5318                              getF32Constant(DAG, 0x40549a78, dl));
5319     return getLimitedPrecisionExp2(t0, dl, DAG);
5320   }
5321 
5322   // No special expansion.
5323   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5324 }
5325 
5326 /// ExpandPowI - Expand a llvm.powi intrinsic.
5327 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5328                           SelectionDAG &DAG) {
5329   // If RHS is a constant, we can expand this out to a multiplication tree,
5330   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5331   // optimizing for size, we only want to do this if the expansion would produce
5332   // a small number of multiplies, otherwise we do the full expansion.
5333   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5334     // Get the exponent as a positive value.
5335     unsigned Val = RHSC->getSExtValue();
5336     if ((int)Val < 0) Val = -Val;
5337 
5338     // powi(x, 0) -> 1.0
5339     if (Val == 0)
5340       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5341 
5342     bool OptForSize = DAG.shouldOptForSize();
5343     if (!OptForSize ||
5344         // If optimizing for size, don't insert too many multiplies.
5345         // This inserts up to 5 multiplies.
5346         countPopulation(Val) + Log2_32(Val) < 7) {
5347       // We use the simple binary decomposition method to generate the multiply
5348       // sequence.  There are more optimal ways to do this (for example,
5349       // powi(x,15) generates one more multiply than it should), but this has
5350       // the benefit of being both really simple and much better than a libcall.
5351       SDValue Res;  // Logically starts equal to 1.0
5352       SDValue CurSquare = LHS;
5353       // TODO: Intrinsics should have fast-math-flags that propagate to these
5354       // nodes.
5355       while (Val) {
5356         if (Val & 1) {
5357           if (Res.getNode())
5358             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5359           else
5360             Res = CurSquare;  // 1.0*CurSquare.
5361         }
5362 
5363         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5364                                 CurSquare, CurSquare);
5365         Val >>= 1;
5366       }
5367 
5368       // If the original was negative, invert the result, producing 1/(x*x*x).
5369       if (RHSC->getSExtValue() < 0)
5370         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5371                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5372       return Res;
5373     }
5374   }
5375 
5376   // Otherwise, expand to a libcall.
5377   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5378 }
5379 
5380 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5381                             SDValue LHS, SDValue RHS, SDValue Scale,
5382                             SelectionDAG &DAG, const TargetLowering &TLI) {
5383   EVT VT = LHS.getValueType();
5384   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5385   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5386   LLVMContext &Ctx = *DAG.getContext();
5387 
5388   // If the type is legal but the operation isn't, this node might survive all
5389   // the way to operation legalization. If we end up there and we do not have
5390   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5391   // node.
5392 
5393   // Coax the legalizer into expanding the node during type legalization instead
5394   // by bumping the size by one bit. This will force it to Promote, enabling the
5395   // early expansion and avoiding the need to expand later.
5396 
5397   // We don't have to do this if Scale is 0; that can always be expanded, unless
5398   // it's a saturating signed operation. Those can experience true integer
5399   // division overflow, a case which we must avoid.
5400 
5401   // FIXME: We wouldn't have to do this (or any of the early
5402   // expansion/promotion) if it was possible to expand a libcall of an
5403   // illegal type during operation legalization. But it's not, so things
5404   // get a bit hacky.
5405   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5406   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5407       (TLI.isTypeLegal(VT) ||
5408        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5409     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5410         Opcode, VT, ScaleInt);
5411     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5412       EVT PromVT;
5413       if (VT.isScalarInteger())
5414         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5415       else if (VT.isVector()) {
5416         PromVT = VT.getVectorElementType();
5417         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5418         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5419       } else
5420         llvm_unreachable("Wrong VT for DIVFIX?");
5421       if (Signed) {
5422         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5423         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5424       } else {
5425         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5426         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5427       }
5428       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5429       // For saturating operations, we need to shift up the LHS to get the
5430       // proper saturation width, and then shift down again afterwards.
5431       if (Saturating)
5432         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5433                           DAG.getConstant(1, DL, ShiftTy));
5434       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5435       if (Saturating)
5436         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5437                           DAG.getConstant(1, DL, ShiftTy));
5438       return DAG.getZExtOrTrunc(Res, DL, VT);
5439     }
5440   }
5441 
5442   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5443 }
5444 
5445 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5446 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5447 static void
5448 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5449                      const SDValue &N) {
5450   switch (N.getOpcode()) {
5451   case ISD::CopyFromReg: {
5452     SDValue Op = N.getOperand(1);
5453     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5454                       Op.getValueType().getSizeInBits());
5455     return;
5456   }
5457   case ISD::BITCAST:
5458   case ISD::AssertZext:
5459   case ISD::AssertSext:
5460   case ISD::TRUNCATE:
5461     getUnderlyingArgRegs(Regs, N.getOperand(0));
5462     return;
5463   case ISD::BUILD_PAIR:
5464   case ISD::BUILD_VECTOR:
5465   case ISD::CONCAT_VECTORS:
5466     for (SDValue Op : N->op_values())
5467       getUnderlyingArgRegs(Regs, Op);
5468     return;
5469   default:
5470     return;
5471   }
5472 }
5473 
5474 /// If the DbgValueInst is a dbg_value of a function argument, create the
5475 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5476 /// instruction selection, they will be inserted to the entry BB.
5477 /// We don't currently support this for variadic dbg_values, as they shouldn't
5478 /// appear for function arguments or in the prologue.
5479 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5480     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5481     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5482   const Argument *Arg = dyn_cast<Argument>(V);
5483   if (!Arg)
5484     return false;
5485 
5486   if (!IsDbgDeclare) {
5487     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5488     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5489     // the entry block.
5490     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5491     if (!IsInEntryBlock)
5492       return false;
5493 
5494     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5495     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5496     // variable that also is a param.
5497     //
5498     // Although, if we are at the top of the entry block already, we can still
5499     // emit using ArgDbgValue. This might catch some situations when the
5500     // dbg.value refers to an argument that isn't used in the entry block, so
5501     // any CopyToReg node would be optimized out and the only way to express
5502     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5503     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5504     // we should only emit as ArgDbgValue if the Variable is an argument to the
5505     // current function, and the dbg.value intrinsic is found in the entry
5506     // block.
5507     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5508         !DL->getInlinedAt();
5509     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5510     if (!IsInPrologue && !VariableIsFunctionInputArg)
5511       return false;
5512 
5513     // Here we assume that a function argument on IR level only can be used to
5514     // describe one input parameter on source level. If we for example have
5515     // source code like this
5516     //
5517     //    struct A { long x, y; };
5518     //    void foo(struct A a, long b) {
5519     //      ...
5520     //      b = a.x;
5521     //      ...
5522     //    }
5523     //
5524     // and IR like this
5525     //
5526     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5527     //  entry:
5528     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5529     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5530     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5531     //    ...
5532     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5533     //    ...
5534     //
5535     // then the last dbg.value is describing a parameter "b" using a value that
5536     // is an argument. But since we already has used %a1 to describe a parameter
5537     // we should not handle that last dbg.value here (that would result in an
5538     // incorrect hoisting of the DBG_VALUE to the function entry).
5539     // Notice that we allow one dbg.value per IR level argument, to accommodate
5540     // for the situation with fragments above.
5541     if (VariableIsFunctionInputArg) {
5542       unsigned ArgNo = Arg->getArgNo();
5543       if (ArgNo >= FuncInfo.DescribedArgs.size())
5544         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5545       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5546         return false;
5547       FuncInfo.DescribedArgs.set(ArgNo);
5548     }
5549   }
5550 
5551   MachineFunction &MF = DAG.getMachineFunction();
5552   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5553 
5554   bool IsIndirect = false;
5555   Optional<MachineOperand> Op;
5556   // Some arguments' frame index is recorded during argument lowering.
5557   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5558   if (FI != std::numeric_limits<int>::max())
5559     Op = MachineOperand::CreateFI(FI);
5560 
5561   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5562   if (!Op && N.getNode()) {
5563     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5564     Register Reg;
5565     if (ArgRegsAndSizes.size() == 1)
5566       Reg = ArgRegsAndSizes.front().first;
5567 
5568     if (Reg && Reg.isVirtual()) {
5569       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5570       Register PR = RegInfo.getLiveInPhysReg(Reg);
5571       if (PR)
5572         Reg = PR;
5573     }
5574     if (Reg) {
5575       Op = MachineOperand::CreateReg(Reg, false);
5576       IsIndirect = IsDbgDeclare;
5577     }
5578   }
5579 
5580   if (!Op && N.getNode()) {
5581     // Check if frame index is available.
5582     SDValue LCandidate = peekThroughBitcasts(N);
5583     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5584       if (FrameIndexSDNode *FINode =
5585           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5586         Op = MachineOperand::CreateFI(FINode->getIndex());
5587   }
5588 
5589   if (!Op) {
5590     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5591     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5592                                          SplitRegs) {
5593       unsigned Offset = 0;
5594       for (auto RegAndSize : SplitRegs) {
5595         // If the expression is already a fragment, the current register
5596         // offset+size might extend beyond the fragment. In this case, only
5597         // the register bits that are inside the fragment are relevant.
5598         int RegFragmentSizeInBits = RegAndSize.second;
5599         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5600           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5601           // The register is entirely outside the expression fragment,
5602           // so is irrelevant for debug info.
5603           if (Offset >= ExprFragmentSizeInBits)
5604             break;
5605           // The register is partially outside the expression fragment, only
5606           // the low bits within the fragment are relevant for debug info.
5607           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5608             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5609           }
5610         }
5611 
5612         auto FragmentExpr = DIExpression::createFragmentExpression(
5613             Expr, Offset, RegFragmentSizeInBits);
5614         Offset += RegAndSize.second;
5615         // If a valid fragment expression cannot be created, the variable's
5616         // correct value cannot be determined and so it is set as Undef.
5617         if (!FragmentExpr) {
5618           SDDbgValue *SDV = DAG.getConstantDbgValue(
5619               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5620           DAG.AddDbgValue(SDV, false);
5621           continue;
5622         }
5623         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5624         FuncInfo.ArgDbgValues.push_back(
5625           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5626                   RegAndSize.first, Variable, *FragmentExpr));
5627       }
5628     };
5629 
5630     // Check if ValueMap has reg number.
5631     DenseMap<const Value *, Register>::const_iterator
5632       VMI = FuncInfo.ValueMap.find(V);
5633     if (VMI != FuncInfo.ValueMap.end()) {
5634       const auto &TLI = DAG.getTargetLoweringInfo();
5635       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5636                        V->getType(), None);
5637       if (RFV.occupiesMultipleRegs()) {
5638         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5639         return true;
5640       }
5641 
5642       Op = MachineOperand::CreateReg(VMI->second, false);
5643       IsIndirect = IsDbgDeclare;
5644     } else if (ArgRegsAndSizes.size() > 1) {
5645       // This was split due to the calling convention, and no virtual register
5646       // mapping exists for the value.
5647       splitMultiRegDbgValue(ArgRegsAndSizes);
5648       return true;
5649     }
5650   }
5651 
5652   if (!Op)
5653     return false;
5654 
5655   assert(Variable->isValidLocationForIntrinsic(DL) &&
5656          "Expected inlined-at fields to agree");
5657   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5658   FuncInfo.ArgDbgValues.push_back(
5659       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5660               *Op, Variable, Expr));
5661 
5662   return true;
5663 }
5664 
5665 /// Return the appropriate SDDbgValue based on N.
5666 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5667                                              DILocalVariable *Variable,
5668                                              DIExpression *Expr,
5669                                              const DebugLoc &dl,
5670                                              unsigned DbgSDNodeOrder) {
5671   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5672     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5673     // stack slot locations.
5674     //
5675     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5676     // debug values here after optimization:
5677     //
5678     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5679     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5680     //
5681     // Both describe the direct values of their associated variables.
5682     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5683                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5684   }
5685   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5686                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5687 }
5688 
5689 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5690   switch (Intrinsic) {
5691   case Intrinsic::smul_fix:
5692     return ISD::SMULFIX;
5693   case Intrinsic::umul_fix:
5694     return ISD::UMULFIX;
5695   case Intrinsic::smul_fix_sat:
5696     return ISD::SMULFIXSAT;
5697   case Intrinsic::umul_fix_sat:
5698     return ISD::UMULFIXSAT;
5699   case Intrinsic::sdiv_fix:
5700     return ISD::SDIVFIX;
5701   case Intrinsic::udiv_fix:
5702     return ISD::UDIVFIX;
5703   case Intrinsic::sdiv_fix_sat:
5704     return ISD::SDIVFIXSAT;
5705   case Intrinsic::udiv_fix_sat:
5706     return ISD::UDIVFIXSAT;
5707   default:
5708     llvm_unreachable("Unhandled fixed point intrinsic");
5709   }
5710 }
5711 
5712 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5713                                            const char *FunctionName) {
5714   assert(FunctionName && "FunctionName must not be nullptr");
5715   SDValue Callee = DAG.getExternalSymbol(
5716       FunctionName,
5717       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5718   LowerCallTo(I, Callee, I.isTailCall());
5719 }
5720 
5721 /// Given a @llvm.call.preallocated.setup, return the corresponding
5722 /// preallocated call.
5723 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5724   assert(cast<CallBase>(PreallocatedSetup)
5725                  ->getCalledFunction()
5726                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5727          "expected call_preallocated_setup Value");
5728   for (auto *U : PreallocatedSetup->users()) {
5729     auto *UseCall = cast<CallBase>(U);
5730     const Function *Fn = UseCall->getCalledFunction();
5731     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5732       return UseCall;
5733     }
5734   }
5735   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5736 }
5737 
5738 /// Lower the call to the specified intrinsic function.
5739 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5740                                              unsigned Intrinsic) {
5741   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5742   SDLoc sdl = getCurSDLoc();
5743   DebugLoc dl = getCurDebugLoc();
5744   SDValue Res;
5745 
5746   SDNodeFlags Flags;
5747   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5748     Flags.copyFMF(*FPOp);
5749 
5750   switch (Intrinsic) {
5751   default:
5752     // By default, turn this into a target intrinsic node.
5753     visitTargetIntrinsic(I, Intrinsic);
5754     return;
5755   case Intrinsic::vscale: {
5756     match(&I, m_VScale(DAG.getDataLayout()));
5757     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5758     setValue(&I,
5759              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5760     return;
5761   }
5762   case Intrinsic::vastart:  visitVAStart(I); return;
5763   case Intrinsic::vaend:    visitVAEnd(I); return;
5764   case Intrinsic::vacopy:   visitVACopy(I); return;
5765   case Intrinsic::returnaddress:
5766     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5767                              TLI.getPointerTy(DAG.getDataLayout()),
5768                              getValue(I.getArgOperand(0))));
5769     return;
5770   case Intrinsic::addressofreturnaddress:
5771     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5772                              TLI.getPointerTy(DAG.getDataLayout())));
5773     return;
5774   case Intrinsic::sponentry:
5775     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5776                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5777     return;
5778   case Intrinsic::frameaddress:
5779     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5780                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5781                              getValue(I.getArgOperand(0))));
5782     return;
5783   case Intrinsic::read_volatile_register:
5784   case Intrinsic::read_register: {
5785     Value *Reg = I.getArgOperand(0);
5786     SDValue Chain = getRoot();
5787     SDValue RegName =
5788         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5789     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5790     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5791       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5792     setValue(&I, Res);
5793     DAG.setRoot(Res.getValue(1));
5794     return;
5795   }
5796   case Intrinsic::write_register: {
5797     Value *Reg = I.getArgOperand(0);
5798     Value *RegValue = I.getArgOperand(1);
5799     SDValue Chain = getRoot();
5800     SDValue RegName =
5801         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5802     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5803                             RegName, getValue(RegValue)));
5804     return;
5805   }
5806   case Intrinsic::memcpy: {
5807     const auto &MCI = cast<MemCpyInst>(I);
5808     SDValue Op1 = getValue(I.getArgOperand(0));
5809     SDValue Op2 = getValue(I.getArgOperand(1));
5810     SDValue Op3 = getValue(I.getArgOperand(2));
5811     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5812     Align DstAlign = MCI.getDestAlign().valueOrOne();
5813     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5814     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5815     bool isVol = MCI.isVolatile();
5816     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5817     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5818     // node.
5819     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5820     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5821                                /* AlwaysInline */ false, isTC,
5822                                MachinePointerInfo(I.getArgOperand(0)),
5823                                MachinePointerInfo(I.getArgOperand(1)));
5824     updateDAGForMaybeTailCall(MC);
5825     return;
5826   }
5827   case Intrinsic::memcpy_inline: {
5828     const auto &MCI = cast<MemCpyInlineInst>(I);
5829     SDValue Dst = getValue(I.getArgOperand(0));
5830     SDValue Src = getValue(I.getArgOperand(1));
5831     SDValue Size = getValue(I.getArgOperand(2));
5832     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5833     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5834     Align DstAlign = MCI.getDestAlign().valueOrOne();
5835     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5836     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5837     bool isVol = MCI.isVolatile();
5838     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5839     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5840     // node.
5841     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5842                                /* AlwaysInline */ true, isTC,
5843                                MachinePointerInfo(I.getArgOperand(0)),
5844                                MachinePointerInfo(I.getArgOperand(1)));
5845     updateDAGForMaybeTailCall(MC);
5846     return;
5847   }
5848   case Intrinsic::memset: {
5849     const auto &MSI = cast<MemSetInst>(I);
5850     SDValue Op1 = getValue(I.getArgOperand(0));
5851     SDValue Op2 = getValue(I.getArgOperand(1));
5852     SDValue Op3 = getValue(I.getArgOperand(2));
5853     // @llvm.memset defines 0 and 1 to both mean no alignment.
5854     Align Alignment = MSI.getDestAlign().valueOrOne();
5855     bool isVol = MSI.isVolatile();
5856     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5857     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5858     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5859                                MachinePointerInfo(I.getArgOperand(0)));
5860     updateDAGForMaybeTailCall(MS);
5861     return;
5862   }
5863   case Intrinsic::memmove: {
5864     const auto &MMI = cast<MemMoveInst>(I);
5865     SDValue Op1 = getValue(I.getArgOperand(0));
5866     SDValue Op2 = getValue(I.getArgOperand(1));
5867     SDValue Op3 = getValue(I.getArgOperand(2));
5868     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5869     Align DstAlign = MMI.getDestAlign().valueOrOne();
5870     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5871     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5872     bool isVol = MMI.isVolatile();
5873     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5874     // FIXME: Support passing different dest/src alignments to the memmove DAG
5875     // node.
5876     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5877     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5878                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5879                                 MachinePointerInfo(I.getArgOperand(1)));
5880     updateDAGForMaybeTailCall(MM);
5881     return;
5882   }
5883   case Intrinsic::memcpy_element_unordered_atomic: {
5884     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5885     SDValue Dst = getValue(MI.getRawDest());
5886     SDValue Src = getValue(MI.getRawSource());
5887     SDValue Length = getValue(MI.getLength());
5888 
5889     unsigned DstAlign = MI.getDestAlignment();
5890     unsigned SrcAlign = MI.getSourceAlignment();
5891     Type *LengthTy = MI.getLength()->getType();
5892     unsigned ElemSz = MI.getElementSizeInBytes();
5893     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5894     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5895                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5896                                      MachinePointerInfo(MI.getRawDest()),
5897                                      MachinePointerInfo(MI.getRawSource()));
5898     updateDAGForMaybeTailCall(MC);
5899     return;
5900   }
5901   case Intrinsic::memmove_element_unordered_atomic: {
5902     auto &MI = cast<AtomicMemMoveInst>(I);
5903     SDValue Dst = getValue(MI.getRawDest());
5904     SDValue Src = getValue(MI.getRawSource());
5905     SDValue Length = getValue(MI.getLength());
5906 
5907     unsigned DstAlign = MI.getDestAlignment();
5908     unsigned SrcAlign = MI.getSourceAlignment();
5909     Type *LengthTy = MI.getLength()->getType();
5910     unsigned ElemSz = MI.getElementSizeInBytes();
5911     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5912     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5913                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5914                                       MachinePointerInfo(MI.getRawDest()),
5915                                       MachinePointerInfo(MI.getRawSource()));
5916     updateDAGForMaybeTailCall(MC);
5917     return;
5918   }
5919   case Intrinsic::memset_element_unordered_atomic: {
5920     auto &MI = cast<AtomicMemSetInst>(I);
5921     SDValue Dst = getValue(MI.getRawDest());
5922     SDValue Val = getValue(MI.getValue());
5923     SDValue Length = getValue(MI.getLength());
5924 
5925     unsigned DstAlign = MI.getDestAlignment();
5926     Type *LengthTy = MI.getLength()->getType();
5927     unsigned ElemSz = MI.getElementSizeInBytes();
5928     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5929     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5930                                      LengthTy, ElemSz, isTC,
5931                                      MachinePointerInfo(MI.getRawDest()));
5932     updateDAGForMaybeTailCall(MC);
5933     return;
5934   }
5935   case Intrinsic::call_preallocated_setup: {
5936     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5937     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5938     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5939                               getRoot(), SrcValue);
5940     setValue(&I, Res);
5941     DAG.setRoot(Res);
5942     return;
5943   }
5944   case Intrinsic::call_preallocated_arg: {
5945     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5946     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5947     SDValue Ops[3];
5948     Ops[0] = getRoot();
5949     Ops[1] = SrcValue;
5950     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5951                                    MVT::i32); // arg index
5952     SDValue Res = DAG.getNode(
5953         ISD::PREALLOCATED_ARG, sdl,
5954         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5955     setValue(&I, Res);
5956     DAG.setRoot(Res.getValue(1));
5957     return;
5958   }
5959   case Intrinsic::dbg_addr:
5960   case Intrinsic::dbg_declare: {
5961     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
5962     // they are non-variadic.
5963     const auto &DI = cast<DbgVariableIntrinsic>(I);
5964     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
5965     DILocalVariable *Variable = DI.getVariable();
5966     DIExpression *Expression = DI.getExpression();
5967     dropDanglingDebugInfo(Variable, Expression);
5968     assert(Variable && "Missing variable");
5969     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5970                       << "\n");
5971     // Check if address has undef value.
5972     const Value *Address = DI.getVariableLocationOp(0);
5973     if (!Address || isa<UndefValue>(Address) ||
5974         (Address->use_empty() && !isa<Argument>(Address))) {
5975       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5976                         << " (bad/undef/unused-arg address)\n");
5977       return;
5978     }
5979 
5980     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5981 
5982     // Check if this variable can be described by a frame index, typically
5983     // either as a static alloca or a byval parameter.
5984     int FI = std::numeric_limits<int>::max();
5985     if (const auto *AI =
5986             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5987       if (AI->isStaticAlloca()) {
5988         auto I = FuncInfo.StaticAllocaMap.find(AI);
5989         if (I != FuncInfo.StaticAllocaMap.end())
5990           FI = I->second;
5991       }
5992     } else if (const auto *Arg = dyn_cast<Argument>(
5993                    Address->stripInBoundsConstantOffsets())) {
5994       FI = FuncInfo.getArgumentFrameIndex(Arg);
5995     }
5996 
5997     // llvm.dbg.addr is control dependent and always generates indirect
5998     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5999     // the MachineFunction variable table.
6000     if (FI != std::numeric_limits<int>::max()) {
6001       if (Intrinsic == Intrinsic::dbg_addr) {
6002         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6003             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6004             dl, SDNodeOrder);
6005         DAG.AddDbgValue(SDV, isParameter);
6006       } else {
6007         LLVM_DEBUG(dbgs() << "Skipping " << DI
6008                           << " (variable info stashed in MF side table)\n");
6009       }
6010       return;
6011     }
6012 
6013     SDValue &N = NodeMap[Address];
6014     if (!N.getNode() && isa<Argument>(Address))
6015       // Check unused arguments map.
6016       N = UnusedArgNodeMap[Address];
6017     SDDbgValue *SDV;
6018     if (N.getNode()) {
6019       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6020         Address = BCI->getOperand(0);
6021       // Parameters are handled specially.
6022       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6023       if (isParameter && FINode) {
6024         // Byval parameter. We have a frame index at this point.
6025         SDV =
6026             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6027                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6028       } else if (isa<Argument>(Address)) {
6029         // Address is an argument, so try to emit its dbg value using
6030         // virtual register info from the FuncInfo.ValueMap.
6031         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6032         return;
6033       } else {
6034         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6035                               true, dl, SDNodeOrder);
6036       }
6037       DAG.AddDbgValue(SDV, isParameter);
6038     } else {
6039       // If Address is an argument then try to emit its dbg value using
6040       // virtual register info from the FuncInfo.ValueMap.
6041       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6042                                     N)) {
6043         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6044                           << " (could not emit func-arg dbg_value)\n");
6045       }
6046     }
6047     return;
6048   }
6049   case Intrinsic::dbg_label: {
6050     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6051     DILabel *Label = DI.getLabel();
6052     assert(Label && "Missing label");
6053 
6054     SDDbgLabel *SDV;
6055     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6056     DAG.AddDbgLabel(SDV);
6057     return;
6058   }
6059   case Intrinsic::dbg_value: {
6060     const DbgValueInst &DI = cast<DbgValueInst>(I);
6061     assert(DI.getVariable() && "Missing variable");
6062 
6063     DILocalVariable *Variable = DI.getVariable();
6064     DIExpression *Expression = DI.getExpression();
6065     dropDanglingDebugInfo(Variable, Expression);
6066     SmallVector<Value *, 4> Values(DI.getValues());
6067     if (Values.empty())
6068       return;
6069 
6070     if (std::count(Values.begin(), Values.end(), nullptr))
6071       return;
6072 
6073     bool IsVariadic = DI.hasArgList();
6074     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6075                           SDNodeOrder, IsVariadic))
6076       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6077     return;
6078   }
6079 
6080   case Intrinsic::eh_typeid_for: {
6081     // Find the type id for the given typeinfo.
6082     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6083     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6084     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6085     setValue(&I, Res);
6086     return;
6087   }
6088 
6089   case Intrinsic::eh_return_i32:
6090   case Intrinsic::eh_return_i64:
6091     DAG.getMachineFunction().setCallsEHReturn(true);
6092     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6093                             MVT::Other,
6094                             getControlRoot(),
6095                             getValue(I.getArgOperand(0)),
6096                             getValue(I.getArgOperand(1))));
6097     return;
6098   case Intrinsic::eh_unwind_init:
6099     DAG.getMachineFunction().setCallsUnwindInit(true);
6100     return;
6101   case Intrinsic::eh_dwarf_cfa:
6102     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6103                              TLI.getPointerTy(DAG.getDataLayout()),
6104                              getValue(I.getArgOperand(0))));
6105     return;
6106   case Intrinsic::eh_sjlj_callsite: {
6107     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6108     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6109     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6110     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6111 
6112     MMI.setCurrentCallSite(CI->getZExtValue());
6113     return;
6114   }
6115   case Intrinsic::eh_sjlj_functioncontext: {
6116     // Get and store the index of the function context.
6117     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6118     AllocaInst *FnCtx =
6119       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6120     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6121     MFI.setFunctionContextIndex(FI);
6122     return;
6123   }
6124   case Intrinsic::eh_sjlj_setjmp: {
6125     SDValue Ops[2];
6126     Ops[0] = getRoot();
6127     Ops[1] = getValue(I.getArgOperand(0));
6128     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6129                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6130     setValue(&I, Op.getValue(0));
6131     DAG.setRoot(Op.getValue(1));
6132     return;
6133   }
6134   case Intrinsic::eh_sjlj_longjmp:
6135     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6136                             getRoot(), getValue(I.getArgOperand(0))));
6137     return;
6138   case Intrinsic::eh_sjlj_setup_dispatch:
6139     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6140                             getRoot()));
6141     return;
6142   case Intrinsic::masked_gather:
6143     visitMaskedGather(I);
6144     return;
6145   case Intrinsic::masked_load:
6146     visitMaskedLoad(I);
6147     return;
6148   case Intrinsic::masked_scatter:
6149     visitMaskedScatter(I);
6150     return;
6151   case Intrinsic::masked_store:
6152     visitMaskedStore(I);
6153     return;
6154   case Intrinsic::masked_expandload:
6155     visitMaskedLoad(I, true /* IsExpanding */);
6156     return;
6157   case Intrinsic::masked_compressstore:
6158     visitMaskedStore(I, true /* IsCompressing */);
6159     return;
6160   case Intrinsic::powi:
6161     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6162                             getValue(I.getArgOperand(1)), DAG));
6163     return;
6164   case Intrinsic::log:
6165     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6166     return;
6167   case Intrinsic::log2:
6168     setValue(&I,
6169              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6170     return;
6171   case Intrinsic::log10:
6172     setValue(&I,
6173              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6174     return;
6175   case Intrinsic::exp:
6176     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6177     return;
6178   case Intrinsic::exp2:
6179     setValue(&I,
6180              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6181     return;
6182   case Intrinsic::pow:
6183     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6184                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6185     return;
6186   case Intrinsic::sqrt:
6187   case Intrinsic::fabs:
6188   case Intrinsic::sin:
6189   case Intrinsic::cos:
6190   case Intrinsic::floor:
6191   case Intrinsic::ceil:
6192   case Intrinsic::trunc:
6193   case Intrinsic::rint:
6194   case Intrinsic::nearbyint:
6195   case Intrinsic::round:
6196   case Intrinsic::roundeven:
6197   case Intrinsic::canonicalize: {
6198     unsigned Opcode;
6199     switch (Intrinsic) {
6200     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6201     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6202     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6203     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6204     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6205     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6206     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6207     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6208     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6209     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6210     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6211     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6212     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6213     }
6214 
6215     setValue(&I, DAG.getNode(Opcode, sdl,
6216                              getValue(I.getArgOperand(0)).getValueType(),
6217                              getValue(I.getArgOperand(0)), Flags));
6218     return;
6219   }
6220   case Intrinsic::lround:
6221   case Intrinsic::llround:
6222   case Intrinsic::lrint:
6223   case Intrinsic::llrint: {
6224     unsigned Opcode;
6225     switch (Intrinsic) {
6226     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6227     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6228     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6229     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6230     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6231     }
6232 
6233     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6234     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6235                              getValue(I.getArgOperand(0))));
6236     return;
6237   }
6238   case Intrinsic::minnum:
6239     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6240                              getValue(I.getArgOperand(0)).getValueType(),
6241                              getValue(I.getArgOperand(0)),
6242                              getValue(I.getArgOperand(1)), Flags));
6243     return;
6244   case Intrinsic::maxnum:
6245     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6246                              getValue(I.getArgOperand(0)).getValueType(),
6247                              getValue(I.getArgOperand(0)),
6248                              getValue(I.getArgOperand(1)), Flags));
6249     return;
6250   case Intrinsic::minimum:
6251     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6252                              getValue(I.getArgOperand(0)).getValueType(),
6253                              getValue(I.getArgOperand(0)),
6254                              getValue(I.getArgOperand(1)), Flags));
6255     return;
6256   case Intrinsic::maximum:
6257     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6258                              getValue(I.getArgOperand(0)).getValueType(),
6259                              getValue(I.getArgOperand(0)),
6260                              getValue(I.getArgOperand(1)), Flags));
6261     return;
6262   case Intrinsic::copysign:
6263     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6264                              getValue(I.getArgOperand(0)).getValueType(),
6265                              getValue(I.getArgOperand(0)),
6266                              getValue(I.getArgOperand(1)), Flags));
6267     return;
6268   case Intrinsic::fma:
6269     setValue(&I, DAG.getNode(
6270                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6271                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6272                      getValue(I.getArgOperand(2)), Flags));
6273     return;
6274 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6275   case Intrinsic::INTRINSIC:
6276 #include "llvm/IR/ConstrainedOps.def"
6277     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6278     return;
6279 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6280 #include "llvm/IR/VPIntrinsics.def"
6281     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6282     return;
6283   case Intrinsic::fmuladd: {
6284     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6285     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6286         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6287       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6288                                getValue(I.getArgOperand(0)).getValueType(),
6289                                getValue(I.getArgOperand(0)),
6290                                getValue(I.getArgOperand(1)),
6291                                getValue(I.getArgOperand(2)), Flags));
6292     } else {
6293       // TODO: Intrinsic calls should have fast-math-flags.
6294       SDValue Mul = DAG.getNode(
6295           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6296           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6297       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6298                                 getValue(I.getArgOperand(0)).getValueType(),
6299                                 Mul, getValue(I.getArgOperand(2)), Flags);
6300       setValue(&I, Add);
6301     }
6302     return;
6303   }
6304   case Intrinsic::convert_to_fp16:
6305     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6306                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6307                                          getValue(I.getArgOperand(0)),
6308                                          DAG.getTargetConstant(0, sdl,
6309                                                                MVT::i32))));
6310     return;
6311   case Intrinsic::convert_from_fp16:
6312     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6313                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6314                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6315                                          getValue(I.getArgOperand(0)))));
6316     return;
6317   case Intrinsic::fptosi_sat: {
6318     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6319     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6320                              getValue(I.getArgOperand(0)),
6321                              DAG.getValueType(VT.getScalarType())));
6322     return;
6323   }
6324   case Intrinsic::fptoui_sat: {
6325     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6326     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6327                              getValue(I.getArgOperand(0)),
6328                              DAG.getValueType(VT.getScalarType())));
6329     return;
6330   }
6331   case Intrinsic::set_rounding:
6332     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6333                       {getRoot(), getValue(I.getArgOperand(0))});
6334     setValue(&I, Res);
6335     DAG.setRoot(Res.getValue(0));
6336     return;
6337   case Intrinsic::pcmarker: {
6338     SDValue Tmp = getValue(I.getArgOperand(0));
6339     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6340     return;
6341   }
6342   case Intrinsic::readcyclecounter: {
6343     SDValue Op = getRoot();
6344     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6345                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6346     setValue(&I, Res);
6347     DAG.setRoot(Res.getValue(1));
6348     return;
6349   }
6350   case Intrinsic::bitreverse:
6351     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6352                              getValue(I.getArgOperand(0)).getValueType(),
6353                              getValue(I.getArgOperand(0))));
6354     return;
6355   case Intrinsic::bswap:
6356     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6357                              getValue(I.getArgOperand(0)).getValueType(),
6358                              getValue(I.getArgOperand(0))));
6359     return;
6360   case Intrinsic::cttz: {
6361     SDValue Arg = getValue(I.getArgOperand(0));
6362     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6363     EVT Ty = Arg.getValueType();
6364     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6365                              sdl, Ty, Arg));
6366     return;
6367   }
6368   case Intrinsic::ctlz: {
6369     SDValue Arg = getValue(I.getArgOperand(0));
6370     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6371     EVT Ty = Arg.getValueType();
6372     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6373                              sdl, Ty, Arg));
6374     return;
6375   }
6376   case Intrinsic::ctpop: {
6377     SDValue Arg = getValue(I.getArgOperand(0));
6378     EVT Ty = Arg.getValueType();
6379     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6380     return;
6381   }
6382   case Intrinsic::fshl:
6383   case Intrinsic::fshr: {
6384     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6385     SDValue X = getValue(I.getArgOperand(0));
6386     SDValue Y = getValue(I.getArgOperand(1));
6387     SDValue Z = getValue(I.getArgOperand(2));
6388     EVT VT = X.getValueType();
6389 
6390     if (X == Y) {
6391       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6392       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6393     } else {
6394       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6395       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6396     }
6397     return;
6398   }
6399   case Intrinsic::sadd_sat: {
6400     SDValue Op1 = getValue(I.getArgOperand(0));
6401     SDValue Op2 = getValue(I.getArgOperand(1));
6402     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6403     return;
6404   }
6405   case Intrinsic::uadd_sat: {
6406     SDValue Op1 = getValue(I.getArgOperand(0));
6407     SDValue Op2 = getValue(I.getArgOperand(1));
6408     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6409     return;
6410   }
6411   case Intrinsic::ssub_sat: {
6412     SDValue Op1 = getValue(I.getArgOperand(0));
6413     SDValue Op2 = getValue(I.getArgOperand(1));
6414     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6415     return;
6416   }
6417   case Intrinsic::usub_sat: {
6418     SDValue Op1 = getValue(I.getArgOperand(0));
6419     SDValue Op2 = getValue(I.getArgOperand(1));
6420     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6421     return;
6422   }
6423   case Intrinsic::sshl_sat: {
6424     SDValue Op1 = getValue(I.getArgOperand(0));
6425     SDValue Op2 = getValue(I.getArgOperand(1));
6426     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6427     return;
6428   }
6429   case Intrinsic::ushl_sat: {
6430     SDValue Op1 = getValue(I.getArgOperand(0));
6431     SDValue Op2 = getValue(I.getArgOperand(1));
6432     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6433     return;
6434   }
6435   case Intrinsic::smul_fix:
6436   case Intrinsic::umul_fix:
6437   case Intrinsic::smul_fix_sat:
6438   case Intrinsic::umul_fix_sat: {
6439     SDValue Op1 = getValue(I.getArgOperand(0));
6440     SDValue Op2 = getValue(I.getArgOperand(1));
6441     SDValue Op3 = getValue(I.getArgOperand(2));
6442     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6443                              Op1.getValueType(), Op1, Op2, Op3));
6444     return;
6445   }
6446   case Intrinsic::sdiv_fix:
6447   case Intrinsic::udiv_fix:
6448   case Intrinsic::sdiv_fix_sat:
6449   case Intrinsic::udiv_fix_sat: {
6450     SDValue Op1 = getValue(I.getArgOperand(0));
6451     SDValue Op2 = getValue(I.getArgOperand(1));
6452     SDValue Op3 = getValue(I.getArgOperand(2));
6453     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6454                               Op1, Op2, Op3, DAG, TLI));
6455     return;
6456   }
6457   case Intrinsic::smax: {
6458     SDValue Op1 = getValue(I.getArgOperand(0));
6459     SDValue Op2 = getValue(I.getArgOperand(1));
6460     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6461     return;
6462   }
6463   case Intrinsic::smin: {
6464     SDValue Op1 = getValue(I.getArgOperand(0));
6465     SDValue Op2 = getValue(I.getArgOperand(1));
6466     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6467     return;
6468   }
6469   case Intrinsic::umax: {
6470     SDValue Op1 = getValue(I.getArgOperand(0));
6471     SDValue Op2 = getValue(I.getArgOperand(1));
6472     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6473     return;
6474   }
6475   case Intrinsic::umin: {
6476     SDValue Op1 = getValue(I.getArgOperand(0));
6477     SDValue Op2 = getValue(I.getArgOperand(1));
6478     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6479     return;
6480   }
6481   case Intrinsic::abs: {
6482     // TODO: Preserve "int min is poison" arg in SDAG?
6483     SDValue Op1 = getValue(I.getArgOperand(0));
6484     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6485     return;
6486   }
6487   case Intrinsic::stacksave: {
6488     SDValue Op = getRoot();
6489     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6490     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6491     setValue(&I, Res);
6492     DAG.setRoot(Res.getValue(1));
6493     return;
6494   }
6495   case Intrinsic::stackrestore:
6496     Res = getValue(I.getArgOperand(0));
6497     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6498     return;
6499   case Intrinsic::get_dynamic_area_offset: {
6500     SDValue Op = getRoot();
6501     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6502     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6503     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6504     // target.
6505     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6506       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6507                          " intrinsic!");
6508     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6509                       Op);
6510     DAG.setRoot(Op);
6511     setValue(&I, Res);
6512     return;
6513   }
6514   case Intrinsic::stackguard: {
6515     MachineFunction &MF = DAG.getMachineFunction();
6516     const Module &M = *MF.getFunction().getParent();
6517     SDValue Chain = getRoot();
6518     if (TLI.useLoadStackGuardNode()) {
6519       Res = getLoadStackGuard(DAG, sdl, Chain);
6520     } else {
6521       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6522       const Value *Global = TLI.getSDagStackGuard(M);
6523       Align Align = DL->getPrefTypeAlign(Global->getType());
6524       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6525                         MachinePointerInfo(Global, 0), Align,
6526                         MachineMemOperand::MOVolatile);
6527     }
6528     if (TLI.useStackGuardXorFP())
6529       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6530     DAG.setRoot(Chain);
6531     setValue(&I, Res);
6532     return;
6533   }
6534   case Intrinsic::stackprotector: {
6535     // Emit code into the DAG to store the stack guard onto the stack.
6536     MachineFunction &MF = DAG.getMachineFunction();
6537     MachineFrameInfo &MFI = MF.getFrameInfo();
6538     SDValue Src, Chain = getRoot();
6539 
6540     if (TLI.useLoadStackGuardNode())
6541       Src = getLoadStackGuard(DAG, sdl, Chain);
6542     else
6543       Src = getValue(I.getArgOperand(0));   // The guard's value.
6544 
6545     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6546 
6547     int FI = FuncInfo.StaticAllocaMap[Slot];
6548     MFI.setStackProtectorIndex(FI);
6549     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6550 
6551     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6552 
6553     // Store the stack protector onto the stack.
6554     Res = DAG.getStore(
6555         Chain, sdl, Src, FIN,
6556         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6557         MaybeAlign(), MachineMemOperand::MOVolatile);
6558     setValue(&I, Res);
6559     DAG.setRoot(Res);
6560     return;
6561   }
6562   case Intrinsic::objectsize:
6563     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6564 
6565   case Intrinsic::is_constant:
6566     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6567 
6568   case Intrinsic::annotation:
6569   case Intrinsic::ptr_annotation:
6570   case Intrinsic::launder_invariant_group:
6571   case Intrinsic::strip_invariant_group:
6572     // Drop the intrinsic, but forward the value
6573     setValue(&I, getValue(I.getOperand(0)));
6574     return;
6575 
6576   case Intrinsic::assume:
6577   case Intrinsic::experimental_noalias_scope_decl:
6578   case Intrinsic::var_annotation:
6579   case Intrinsic::sideeffect:
6580     // Discard annotate attributes, noalias scope declarations, assumptions, and
6581     // artificial side-effects.
6582     return;
6583 
6584   case Intrinsic::codeview_annotation: {
6585     // Emit a label associated with this metadata.
6586     MachineFunction &MF = DAG.getMachineFunction();
6587     MCSymbol *Label =
6588         MF.getMMI().getContext().createTempSymbol("annotation", true);
6589     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6590     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6591     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6592     DAG.setRoot(Res);
6593     return;
6594   }
6595 
6596   case Intrinsic::init_trampoline: {
6597     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6598 
6599     SDValue Ops[6];
6600     Ops[0] = getRoot();
6601     Ops[1] = getValue(I.getArgOperand(0));
6602     Ops[2] = getValue(I.getArgOperand(1));
6603     Ops[3] = getValue(I.getArgOperand(2));
6604     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6605     Ops[5] = DAG.getSrcValue(F);
6606 
6607     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6608 
6609     DAG.setRoot(Res);
6610     return;
6611   }
6612   case Intrinsic::adjust_trampoline:
6613     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6614                              TLI.getPointerTy(DAG.getDataLayout()),
6615                              getValue(I.getArgOperand(0))));
6616     return;
6617   case Intrinsic::gcroot: {
6618     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6619            "only valid in functions with gc specified, enforced by Verifier");
6620     assert(GFI && "implied by previous");
6621     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6622     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6623 
6624     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6625     GFI->addStackRoot(FI->getIndex(), TypeMap);
6626     return;
6627   }
6628   case Intrinsic::gcread:
6629   case Intrinsic::gcwrite:
6630     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6631   case Intrinsic::flt_rounds:
6632     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6633     setValue(&I, Res);
6634     DAG.setRoot(Res.getValue(1));
6635     return;
6636 
6637   case Intrinsic::expect:
6638     // Just replace __builtin_expect(exp, c) with EXP.
6639     setValue(&I, getValue(I.getArgOperand(0)));
6640     return;
6641 
6642   case Intrinsic::ubsantrap:
6643   case Intrinsic::debugtrap:
6644   case Intrinsic::trap: {
6645     StringRef TrapFuncName =
6646         I.getAttributes()
6647             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6648             .getValueAsString();
6649     if (TrapFuncName.empty()) {
6650       switch (Intrinsic) {
6651       case Intrinsic::trap:
6652         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6653         break;
6654       case Intrinsic::debugtrap:
6655         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6656         break;
6657       case Intrinsic::ubsantrap:
6658         DAG.setRoot(DAG.getNode(
6659             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6660             DAG.getTargetConstant(
6661                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6662                 MVT::i32)));
6663         break;
6664       default: llvm_unreachable("unknown trap intrinsic");
6665       }
6666       return;
6667     }
6668     TargetLowering::ArgListTy Args;
6669     if (Intrinsic == Intrinsic::ubsantrap) {
6670       Args.push_back(TargetLoweringBase::ArgListEntry());
6671       Args[0].Val = I.getArgOperand(0);
6672       Args[0].Node = getValue(Args[0].Val);
6673       Args[0].Ty = Args[0].Val->getType();
6674     }
6675 
6676     TargetLowering::CallLoweringInfo CLI(DAG);
6677     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6678         CallingConv::C, I.getType(),
6679         DAG.getExternalSymbol(TrapFuncName.data(),
6680                               TLI.getPointerTy(DAG.getDataLayout())),
6681         std::move(Args));
6682 
6683     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6684     DAG.setRoot(Result.second);
6685     return;
6686   }
6687 
6688   case Intrinsic::uadd_with_overflow:
6689   case Intrinsic::sadd_with_overflow:
6690   case Intrinsic::usub_with_overflow:
6691   case Intrinsic::ssub_with_overflow:
6692   case Intrinsic::umul_with_overflow:
6693   case Intrinsic::smul_with_overflow: {
6694     ISD::NodeType Op;
6695     switch (Intrinsic) {
6696     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6697     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6698     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6699     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6700     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6701     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6702     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6703     }
6704     SDValue Op1 = getValue(I.getArgOperand(0));
6705     SDValue Op2 = getValue(I.getArgOperand(1));
6706 
6707     EVT ResultVT = Op1.getValueType();
6708     EVT OverflowVT = MVT::i1;
6709     if (ResultVT.isVector())
6710       OverflowVT = EVT::getVectorVT(
6711           *Context, OverflowVT, ResultVT.getVectorElementCount());
6712 
6713     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6714     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6715     return;
6716   }
6717   case Intrinsic::prefetch: {
6718     SDValue Ops[5];
6719     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6720     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6721     Ops[0] = DAG.getRoot();
6722     Ops[1] = getValue(I.getArgOperand(0));
6723     Ops[2] = getValue(I.getArgOperand(1));
6724     Ops[3] = getValue(I.getArgOperand(2));
6725     Ops[4] = getValue(I.getArgOperand(3));
6726     SDValue Result = DAG.getMemIntrinsicNode(
6727         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6728         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6729         /* align */ None, Flags);
6730 
6731     // Chain the prefetch in parallell with any pending loads, to stay out of
6732     // the way of later optimizations.
6733     PendingLoads.push_back(Result);
6734     Result = getRoot();
6735     DAG.setRoot(Result);
6736     return;
6737   }
6738   case Intrinsic::lifetime_start:
6739   case Intrinsic::lifetime_end: {
6740     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6741     // Stack coloring is not enabled in O0, discard region information.
6742     if (TM.getOptLevel() == CodeGenOpt::None)
6743       return;
6744 
6745     const int64_t ObjectSize =
6746         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6747     Value *const ObjectPtr = I.getArgOperand(1);
6748     SmallVector<const Value *, 4> Allocas;
6749     getUnderlyingObjects(ObjectPtr, Allocas);
6750 
6751     for (const Value *Alloca : Allocas) {
6752       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6753 
6754       // Could not find an Alloca.
6755       if (!LifetimeObject)
6756         continue;
6757 
6758       // First check that the Alloca is static, otherwise it won't have a
6759       // valid frame index.
6760       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6761       if (SI == FuncInfo.StaticAllocaMap.end())
6762         return;
6763 
6764       const int FrameIndex = SI->second;
6765       int64_t Offset;
6766       if (GetPointerBaseWithConstantOffset(
6767               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6768         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6769       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6770                                 Offset);
6771       DAG.setRoot(Res);
6772     }
6773     return;
6774   }
6775   case Intrinsic::pseudoprobe: {
6776     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6777     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6778     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6779     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6780     DAG.setRoot(Res);
6781     return;
6782   }
6783   case Intrinsic::invariant_start:
6784     // Discard region information.
6785     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6786     return;
6787   case Intrinsic::invariant_end:
6788     // Discard region information.
6789     return;
6790   case Intrinsic::clear_cache:
6791     /// FunctionName may be null.
6792     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6793       lowerCallToExternalSymbol(I, FunctionName);
6794     return;
6795   case Intrinsic::donothing:
6796     // ignore
6797     return;
6798   case Intrinsic::experimental_stackmap:
6799     visitStackmap(I);
6800     return;
6801   case Intrinsic::experimental_patchpoint_void:
6802   case Intrinsic::experimental_patchpoint_i64:
6803     visitPatchpoint(I);
6804     return;
6805   case Intrinsic::experimental_gc_statepoint:
6806     LowerStatepoint(cast<GCStatepointInst>(I));
6807     return;
6808   case Intrinsic::experimental_gc_result:
6809     visitGCResult(cast<GCResultInst>(I));
6810     return;
6811   case Intrinsic::experimental_gc_relocate:
6812     visitGCRelocate(cast<GCRelocateInst>(I));
6813     return;
6814   case Intrinsic::instrprof_increment:
6815     llvm_unreachable("instrprof failed to lower an increment");
6816   case Intrinsic::instrprof_value_profile:
6817     llvm_unreachable("instrprof failed to lower a value profiling call");
6818   case Intrinsic::localescape: {
6819     MachineFunction &MF = DAG.getMachineFunction();
6820     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6821 
6822     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6823     // is the same on all targets.
6824     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6825       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6826       if (isa<ConstantPointerNull>(Arg))
6827         continue; // Skip null pointers. They represent a hole in index space.
6828       AllocaInst *Slot = cast<AllocaInst>(Arg);
6829       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6830              "can only escape static allocas");
6831       int FI = FuncInfo.StaticAllocaMap[Slot];
6832       MCSymbol *FrameAllocSym =
6833           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6834               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6835       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6836               TII->get(TargetOpcode::LOCAL_ESCAPE))
6837           .addSym(FrameAllocSym)
6838           .addFrameIndex(FI);
6839     }
6840 
6841     return;
6842   }
6843 
6844   case Intrinsic::localrecover: {
6845     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6846     MachineFunction &MF = DAG.getMachineFunction();
6847 
6848     // Get the symbol that defines the frame offset.
6849     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6850     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6851     unsigned IdxVal =
6852         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6853     MCSymbol *FrameAllocSym =
6854         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6855             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6856 
6857     Value *FP = I.getArgOperand(1);
6858     SDValue FPVal = getValue(FP);
6859     EVT PtrVT = FPVal.getValueType();
6860 
6861     // Create a MCSymbol for the label to avoid any target lowering
6862     // that would make this PC relative.
6863     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6864     SDValue OffsetVal =
6865         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6866 
6867     // Add the offset to the FP.
6868     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6869     setValue(&I, Add);
6870 
6871     return;
6872   }
6873 
6874   case Intrinsic::eh_exceptionpointer:
6875   case Intrinsic::eh_exceptioncode: {
6876     // Get the exception pointer vreg, copy from it, and resize it to fit.
6877     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6878     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6879     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6880     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6881     SDValue N =
6882         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6883     if (Intrinsic == Intrinsic::eh_exceptioncode)
6884       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6885     setValue(&I, N);
6886     return;
6887   }
6888   case Intrinsic::xray_customevent: {
6889     // Here we want to make sure that the intrinsic behaves as if it has a
6890     // specific calling convention, and only for x86_64.
6891     // FIXME: Support other platforms later.
6892     const auto &Triple = DAG.getTarget().getTargetTriple();
6893     if (Triple.getArch() != Triple::x86_64)
6894       return;
6895 
6896     SDLoc DL = getCurSDLoc();
6897     SmallVector<SDValue, 8> Ops;
6898 
6899     // We want to say that we always want the arguments in registers.
6900     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6901     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6902     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6903     SDValue Chain = getRoot();
6904     Ops.push_back(LogEntryVal);
6905     Ops.push_back(StrSizeVal);
6906     Ops.push_back(Chain);
6907 
6908     // We need to enforce the calling convention for the callsite, so that
6909     // argument ordering is enforced correctly, and that register allocation can
6910     // see that some registers may be assumed clobbered and have to preserve
6911     // them across calls to the intrinsic.
6912     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6913                                            DL, NodeTys, Ops);
6914     SDValue patchableNode = SDValue(MN, 0);
6915     DAG.setRoot(patchableNode);
6916     setValue(&I, patchableNode);
6917     return;
6918   }
6919   case Intrinsic::xray_typedevent: {
6920     // Here we want to make sure that the intrinsic behaves as if it has a
6921     // specific calling convention, and only for x86_64.
6922     // FIXME: Support other platforms later.
6923     const auto &Triple = DAG.getTarget().getTargetTriple();
6924     if (Triple.getArch() != Triple::x86_64)
6925       return;
6926 
6927     SDLoc DL = getCurSDLoc();
6928     SmallVector<SDValue, 8> Ops;
6929 
6930     // We want to say that we always want the arguments in registers.
6931     // It's unclear to me how manipulating the selection DAG here forces callers
6932     // to provide arguments in registers instead of on the stack.
6933     SDValue LogTypeId = getValue(I.getArgOperand(0));
6934     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6935     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6936     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6937     SDValue Chain = getRoot();
6938     Ops.push_back(LogTypeId);
6939     Ops.push_back(LogEntryVal);
6940     Ops.push_back(StrSizeVal);
6941     Ops.push_back(Chain);
6942 
6943     // We need to enforce the calling convention for the callsite, so that
6944     // argument ordering is enforced correctly, and that register allocation can
6945     // see that some registers may be assumed clobbered and have to preserve
6946     // them across calls to the intrinsic.
6947     MachineSDNode *MN = DAG.getMachineNode(
6948         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6949     SDValue patchableNode = SDValue(MN, 0);
6950     DAG.setRoot(patchableNode);
6951     setValue(&I, patchableNode);
6952     return;
6953   }
6954   case Intrinsic::experimental_deoptimize:
6955     LowerDeoptimizeCall(&I);
6956     return;
6957   case Intrinsic::experimental_stepvector:
6958     visitStepVector(I);
6959     return;
6960   case Intrinsic::vector_reduce_fadd:
6961   case Intrinsic::vector_reduce_fmul:
6962   case Intrinsic::vector_reduce_add:
6963   case Intrinsic::vector_reduce_mul:
6964   case Intrinsic::vector_reduce_and:
6965   case Intrinsic::vector_reduce_or:
6966   case Intrinsic::vector_reduce_xor:
6967   case Intrinsic::vector_reduce_smax:
6968   case Intrinsic::vector_reduce_smin:
6969   case Intrinsic::vector_reduce_umax:
6970   case Intrinsic::vector_reduce_umin:
6971   case Intrinsic::vector_reduce_fmax:
6972   case Intrinsic::vector_reduce_fmin:
6973     visitVectorReduce(I, Intrinsic);
6974     return;
6975 
6976   case Intrinsic::icall_branch_funnel: {
6977     SmallVector<SDValue, 16> Ops;
6978     Ops.push_back(getValue(I.getArgOperand(0)));
6979 
6980     int64_t Offset;
6981     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6982         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6983     if (!Base)
6984       report_fatal_error(
6985           "llvm.icall.branch.funnel operand must be a GlobalValue");
6986     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6987 
6988     struct BranchFunnelTarget {
6989       int64_t Offset;
6990       SDValue Target;
6991     };
6992     SmallVector<BranchFunnelTarget, 8> Targets;
6993 
6994     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6995       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6996           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6997       if (ElemBase != Base)
6998         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6999                            "to the same GlobalValue");
7000 
7001       SDValue Val = getValue(I.getArgOperand(Op + 1));
7002       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7003       if (!GA)
7004         report_fatal_error(
7005             "llvm.icall.branch.funnel operand must be a GlobalValue");
7006       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7007                                      GA->getGlobal(), getCurSDLoc(),
7008                                      Val.getValueType(), GA->getOffset())});
7009     }
7010     llvm::sort(Targets,
7011                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7012                  return T1.Offset < T2.Offset;
7013                });
7014 
7015     for (auto &T : Targets) {
7016       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7017       Ops.push_back(T.Target);
7018     }
7019 
7020     Ops.push_back(DAG.getRoot()); // Chain
7021     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7022                                  getCurSDLoc(), MVT::Other, Ops),
7023               0);
7024     DAG.setRoot(N);
7025     setValue(&I, N);
7026     HasTailCall = true;
7027     return;
7028   }
7029 
7030   case Intrinsic::wasm_landingpad_index:
7031     // Information this intrinsic contained has been transferred to
7032     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7033     // delete it now.
7034     return;
7035 
7036   case Intrinsic::aarch64_settag:
7037   case Intrinsic::aarch64_settag_zero: {
7038     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7039     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7040     SDValue Val = TSI.EmitTargetCodeForSetTag(
7041         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7042         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7043         ZeroMemory);
7044     DAG.setRoot(Val);
7045     setValue(&I, Val);
7046     return;
7047   }
7048   case Intrinsic::ptrmask: {
7049     SDValue Ptr = getValue(I.getOperand(0));
7050     SDValue Const = getValue(I.getOperand(1));
7051 
7052     EVT PtrVT = Ptr.getValueType();
7053     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7054                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7055     return;
7056   }
7057   case Intrinsic::get_active_lane_mask: {
7058     auto DL = getCurSDLoc();
7059     SDValue Index = getValue(I.getOperand(0));
7060     SDValue TripCount = getValue(I.getOperand(1));
7061     Type *ElementTy = I.getOperand(0)->getType();
7062     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7063     unsigned VecWidth = VT.getVectorNumElements();
7064 
7065     SmallVector<SDValue, 16> OpsTripCount;
7066     SmallVector<SDValue, 16> OpsIndex;
7067     SmallVector<SDValue, 16> OpsStepConstants;
7068     for (unsigned i = 0; i < VecWidth; i++) {
7069       OpsTripCount.push_back(TripCount);
7070       OpsIndex.push_back(Index);
7071       OpsStepConstants.push_back(
7072           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7073     }
7074 
7075     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7076 
7077     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7078     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7079     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7080     SDValue VectorInduction = DAG.getNode(
7081        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7082     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7083     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7084                                  VectorTripCount, ISD::CondCode::SETULT);
7085     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7086                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7087                              SetCC));
7088     return;
7089   }
7090   case Intrinsic::experimental_vector_insert: {
7091     auto DL = getCurSDLoc();
7092 
7093     SDValue Vec = getValue(I.getOperand(0));
7094     SDValue SubVec = getValue(I.getOperand(1));
7095     SDValue Index = getValue(I.getOperand(2));
7096 
7097     // The intrinsic's index type is i64, but the SDNode requires an index type
7098     // suitable for the target. Convert the index as required.
7099     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7100     if (Index.getValueType() != VectorIdxTy)
7101       Index = DAG.getVectorIdxConstant(
7102           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7103 
7104     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7105     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7106                              Index));
7107     return;
7108   }
7109   case Intrinsic::experimental_vector_extract: {
7110     auto DL = getCurSDLoc();
7111 
7112     SDValue Vec = getValue(I.getOperand(0));
7113     SDValue Index = getValue(I.getOperand(1));
7114     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7115 
7116     // The intrinsic's index type is i64, but the SDNode requires an index type
7117     // suitable for the target. Convert the index as required.
7118     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7119     if (Index.getValueType() != VectorIdxTy)
7120       Index = DAG.getVectorIdxConstant(
7121           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7122 
7123     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7124     return;
7125   }
7126   case Intrinsic::experimental_vector_reverse:
7127     visitVectorReverse(I);
7128     return;
7129   case Intrinsic::experimental_vector_splice:
7130     visitVectorSplice(I);
7131     return;
7132   }
7133 }
7134 
7135 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7136     const ConstrainedFPIntrinsic &FPI) {
7137   SDLoc sdl = getCurSDLoc();
7138 
7139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7140   SmallVector<EVT, 4> ValueVTs;
7141   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7142   ValueVTs.push_back(MVT::Other); // Out chain
7143 
7144   // We do not need to serialize constrained FP intrinsics against
7145   // each other or against (nonvolatile) loads, so they can be
7146   // chained like loads.
7147   SDValue Chain = DAG.getRoot();
7148   SmallVector<SDValue, 4> Opers;
7149   Opers.push_back(Chain);
7150   if (FPI.isUnaryOp()) {
7151     Opers.push_back(getValue(FPI.getArgOperand(0)));
7152   } else if (FPI.isTernaryOp()) {
7153     Opers.push_back(getValue(FPI.getArgOperand(0)));
7154     Opers.push_back(getValue(FPI.getArgOperand(1)));
7155     Opers.push_back(getValue(FPI.getArgOperand(2)));
7156   } else {
7157     Opers.push_back(getValue(FPI.getArgOperand(0)));
7158     Opers.push_back(getValue(FPI.getArgOperand(1)));
7159   }
7160 
7161   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7162     assert(Result.getNode()->getNumValues() == 2);
7163 
7164     // Push node to the appropriate list so that future instructions can be
7165     // chained up correctly.
7166     SDValue OutChain = Result.getValue(1);
7167     switch (EB) {
7168     case fp::ExceptionBehavior::ebIgnore:
7169       // The only reason why ebIgnore nodes still need to be chained is that
7170       // they might depend on the current rounding mode, and therefore must
7171       // not be moved across instruction that may change that mode.
7172       LLVM_FALLTHROUGH;
7173     case fp::ExceptionBehavior::ebMayTrap:
7174       // These must not be moved across calls or instructions that may change
7175       // floating-point exception masks.
7176       PendingConstrainedFP.push_back(OutChain);
7177       break;
7178     case fp::ExceptionBehavior::ebStrict:
7179       // These must not be moved across calls or instructions that may change
7180       // floating-point exception masks or read floating-point exception flags.
7181       // In addition, they cannot be optimized out even if unused.
7182       PendingConstrainedFPStrict.push_back(OutChain);
7183       break;
7184     }
7185   };
7186 
7187   SDVTList VTs = DAG.getVTList(ValueVTs);
7188   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7189 
7190   SDNodeFlags Flags;
7191   if (EB == fp::ExceptionBehavior::ebIgnore)
7192     Flags.setNoFPExcept(true);
7193 
7194   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7195     Flags.copyFMF(*FPOp);
7196 
7197   unsigned Opcode;
7198   switch (FPI.getIntrinsicID()) {
7199   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7200 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7201   case Intrinsic::INTRINSIC:                                                   \
7202     Opcode = ISD::STRICT_##DAGN;                                               \
7203     break;
7204 #include "llvm/IR/ConstrainedOps.def"
7205   case Intrinsic::experimental_constrained_fmuladd: {
7206     Opcode = ISD::STRICT_FMA;
7207     // Break fmuladd into fmul and fadd.
7208     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7209         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7210                                         ValueVTs[0])) {
7211       Opers.pop_back();
7212       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7213       pushOutChain(Mul, EB);
7214       Opcode = ISD::STRICT_FADD;
7215       Opers.clear();
7216       Opers.push_back(Mul.getValue(1));
7217       Opers.push_back(Mul.getValue(0));
7218       Opers.push_back(getValue(FPI.getArgOperand(2)));
7219     }
7220     break;
7221   }
7222   }
7223 
7224   // A few strict DAG nodes carry additional operands that are not
7225   // set up by the default code above.
7226   switch (Opcode) {
7227   default: break;
7228   case ISD::STRICT_FP_ROUND:
7229     Opers.push_back(
7230         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7231     break;
7232   case ISD::STRICT_FSETCC:
7233   case ISD::STRICT_FSETCCS: {
7234     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7235     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7236     if (TM.Options.NoNaNsFPMath)
7237       Condition = getFCmpCodeWithoutNaN(Condition);
7238     Opers.push_back(DAG.getCondCode(Condition));
7239     break;
7240   }
7241   }
7242 
7243   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7244   pushOutChain(Result, EB);
7245 
7246   SDValue FPResult = Result.getValue(0);
7247   setValue(&FPI, FPResult);
7248 }
7249 
7250 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7251   Optional<unsigned> ResOPC;
7252   switch (VPIntrin.getIntrinsicID()) {
7253 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7254 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7255 #define END_REGISTER_VP_INTRINSIC(...) break;
7256 #include "llvm/IR/VPIntrinsics.def"
7257   }
7258 
7259   if (!ResOPC.hasValue())
7260     llvm_unreachable(
7261         "Inconsistency: no SDNode available for this VPIntrinsic!");
7262 
7263   return ResOPC.getValue();
7264 }
7265 
7266 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7267     const VPIntrinsic &VPIntrin) {
7268   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7269 
7270   SmallVector<EVT, 4> ValueVTs;
7271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7272   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7273   SDVTList VTs = DAG.getVTList(ValueVTs);
7274 
7275   // Request operands.
7276   SmallVector<SDValue, 7> OpValues;
7277   for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
7278     OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
7279 
7280   SDLoc DL = getCurSDLoc();
7281   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7282   setValue(&VPIntrin, Result);
7283 }
7284 
7285 std::pair<SDValue, SDValue>
7286 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7287                                     const BasicBlock *EHPadBB) {
7288   MachineFunction &MF = DAG.getMachineFunction();
7289   MachineModuleInfo &MMI = MF.getMMI();
7290   MCSymbol *BeginLabel = nullptr;
7291 
7292   if (EHPadBB) {
7293     // Insert a label before the invoke call to mark the try range.  This can be
7294     // used to detect deletion of the invoke via the MachineModuleInfo.
7295     BeginLabel = MMI.getContext().createTempSymbol();
7296 
7297     // For SjLj, keep track of which landing pads go with which invokes
7298     // so as to maintain the ordering of pads in the LSDA.
7299     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7300     if (CallSiteIndex) {
7301       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7302       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7303 
7304       // Now that the call site is handled, stop tracking it.
7305       MMI.setCurrentCallSite(0);
7306     }
7307 
7308     // Both PendingLoads and PendingExports must be flushed here;
7309     // this call might not return.
7310     (void)getRoot();
7311     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7312 
7313     CLI.setChain(getRoot());
7314   }
7315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7316   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7317 
7318   assert((CLI.IsTailCall || Result.second.getNode()) &&
7319          "Non-null chain expected with non-tail call!");
7320   assert((Result.second.getNode() || !Result.first.getNode()) &&
7321          "Null value expected with tail call!");
7322 
7323   if (!Result.second.getNode()) {
7324     // As a special case, a null chain means that a tail call has been emitted
7325     // and the DAG root is already updated.
7326     HasTailCall = true;
7327 
7328     // Since there's no actual continuation from this block, nothing can be
7329     // relying on us setting vregs for them.
7330     PendingExports.clear();
7331   } else {
7332     DAG.setRoot(Result.second);
7333   }
7334 
7335   if (EHPadBB) {
7336     // Insert a label at the end of the invoke call to mark the try range.  This
7337     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7338     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7339     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7340 
7341     // Inform MachineModuleInfo of range.
7342     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7343     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7344     // actually use outlined funclets and their LSDA info style.
7345     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7346       assert(CLI.CB);
7347       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7348       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7349     } else if (!isScopedEHPersonality(Pers)) {
7350       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7351     }
7352   }
7353 
7354   return Result;
7355 }
7356 
7357 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7358                                       bool isTailCall,
7359                                       const BasicBlock *EHPadBB) {
7360   auto &DL = DAG.getDataLayout();
7361   FunctionType *FTy = CB.getFunctionType();
7362   Type *RetTy = CB.getType();
7363 
7364   TargetLowering::ArgListTy Args;
7365   Args.reserve(CB.arg_size());
7366 
7367   const Value *SwiftErrorVal = nullptr;
7368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7369 
7370   if (isTailCall) {
7371     // Avoid emitting tail calls in functions with the disable-tail-calls
7372     // attribute.
7373     auto *Caller = CB.getParent()->getParent();
7374     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7375         "true")
7376       isTailCall = false;
7377 
7378     // We can't tail call inside a function with a swifterror argument. Lowering
7379     // does not support this yet. It would have to move into the swifterror
7380     // register before the call.
7381     if (TLI.supportSwiftError() &&
7382         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7383       isTailCall = false;
7384   }
7385 
7386   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7387     TargetLowering::ArgListEntry Entry;
7388     const Value *V = *I;
7389 
7390     // Skip empty types
7391     if (V->getType()->isEmptyTy())
7392       continue;
7393 
7394     SDValue ArgNode = getValue(V);
7395     Entry.Node = ArgNode; Entry.Ty = V->getType();
7396 
7397     Entry.setAttributes(&CB, I - CB.arg_begin());
7398 
7399     // Use swifterror virtual register as input to the call.
7400     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7401       SwiftErrorVal = V;
7402       // We find the virtual register for the actual swifterror argument.
7403       // Instead of using the Value, we use the virtual register instead.
7404       Entry.Node =
7405           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7406                           EVT(TLI.getPointerTy(DL)));
7407     }
7408 
7409     Args.push_back(Entry);
7410 
7411     // If we have an explicit sret argument that is an Instruction, (i.e., it
7412     // might point to function-local memory), we can't meaningfully tail-call.
7413     if (Entry.IsSRet && isa<Instruction>(V))
7414       isTailCall = false;
7415   }
7416 
7417   // If call site has a cfguardtarget operand bundle, create and add an
7418   // additional ArgListEntry.
7419   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7420     TargetLowering::ArgListEntry Entry;
7421     Value *V = Bundle->Inputs[0];
7422     SDValue ArgNode = getValue(V);
7423     Entry.Node = ArgNode;
7424     Entry.Ty = V->getType();
7425     Entry.IsCFGuardTarget = true;
7426     Args.push_back(Entry);
7427   }
7428 
7429   // Check if target-independent constraints permit a tail call here.
7430   // Target-dependent constraints are checked within TLI->LowerCallTo.
7431   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7432     isTailCall = false;
7433 
7434   // Disable tail calls if there is an swifterror argument. Targets have not
7435   // been updated to support tail calls.
7436   if (TLI.supportSwiftError() && SwiftErrorVal)
7437     isTailCall = false;
7438 
7439   TargetLowering::CallLoweringInfo CLI(DAG);
7440   CLI.setDebugLoc(getCurSDLoc())
7441       .setChain(getRoot())
7442       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7443       .setTailCall(isTailCall)
7444       .setConvergent(CB.isConvergent())
7445       .setIsPreallocated(
7446           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7447   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7448 
7449   if (Result.first.getNode()) {
7450     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7451     setValue(&CB, Result.first);
7452   }
7453 
7454   // The last element of CLI.InVals has the SDValue for swifterror return.
7455   // Here we copy it to a virtual register and update SwiftErrorMap for
7456   // book-keeping.
7457   if (SwiftErrorVal && TLI.supportSwiftError()) {
7458     // Get the last element of InVals.
7459     SDValue Src = CLI.InVals.back();
7460     Register VReg =
7461         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7462     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7463     DAG.setRoot(CopyNode);
7464   }
7465 }
7466 
7467 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7468                              SelectionDAGBuilder &Builder) {
7469   // Check to see if this load can be trivially constant folded, e.g. if the
7470   // input is from a string literal.
7471   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7472     // Cast pointer to the type we really want to load.
7473     Type *LoadTy =
7474         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7475     if (LoadVT.isVector())
7476       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7477 
7478     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7479                                          PointerType::getUnqual(LoadTy));
7480 
7481     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7482             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7483       return Builder.getValue(LoadCst);
7484   }
7485 
7486   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7487   // still constant memory, the input chain can be the entry node.
7488   SDValue Root;
7489   bool ConstantMemory = false;
7490 
7491   // Do not serialize (non-volatile) loads of constant memory with anything.
7492   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7493     Root = Builder.DAG.getEntryNode();
7494     ConstantMemory = true;
7495   } else {
7496     // Do not serialize non-volatile loads against each other.
7497     Root = Builder.DAG.getRoot();
7498   }
7499 
7500   SDValue Ptr = Builder.getValue(PtrVal);
7501   SDValue LoadVal =
7502       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7503                           MachinePointerInfo(PtrVal), Align(1));
7504 
7505   if (!ConstantMemory)
7506     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7507   return LoadVal;
7508 }
7509 
7510 /// Record the value for an instruction that produces an integer result,
7511 /// converting the type where necessary.
7512 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7513                                                   SDValue Value,
7514                                                   bool IsSigned) {
7515   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7516                                                     I.getType(), true);
7517   if (IsSigned)
7518     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7519   else
7520     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7521   setValue(&I, Value);
7522 }
7523 
7524 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7525 /// true and lower it. Otherwise return false, and it will be lowered like a
7526 /// normal call.
7527 /// The caller already checked that \p I calls the appropriate LibFunc with a
7528 /// correct prototype.
7529 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7530   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7531   const Value *Size = I.getArgOperand(2);
7532   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7533   if (CSize && CSize->getZExtValue() == 0) {
7534     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7535                                                           I.getType(), true);
7536     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7537     return true;
7538   }
7539 
7540   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7541   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7542       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7543       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7544   if (Res.first.getNode()) {
7545     processIntegerCallValue(I, Res.first, true);
7546     PendingLoads.push_back(Res.second);
7547     return true;
7548   }
7549 
7550   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7551   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7552   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7553     return false;
7554 
7555   // If the target has a fast compare for the given size, it will return a
7556   // preferred load type for that size. Require that the load VT is legal and
7557   // that the target supports unaligned loads of that type. Otherwise, return
7558   // INVALID.
7559   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7560     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7561     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7562     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7563       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7564       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7565       // TODO: Check alignment of src and dest ptrs.
7566       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7567       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7568       if (!TLI.isTypeLegal(LVT) ||
7569           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7570           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7571         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7572     }
7573 
7574     return LVT;
7575   };
7576 
7577   // This turns into unaligned loads. We only do this if the target natively
7578   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7579   // we'll only produce a small number of byte loads.
7580   MVT LoadVT;
7581   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7582   switch (NumBitsToCompare) {
7583   default:
7584     return false;
7585   case 16:
7586     LoadVT = MVT::i16;
7587     break;
7588   case 32:
7589     LoadVT = MVT::i32;
7590     break;
7591   case 64:
7592   case 128:
7593   case 256:
7594     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7595     break;
7596   }
7597 
7598   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7599     return false;
7600 
7601   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7602   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7603 
7604   // Bitcast to a wide integer type if the loads are vectors.
7605   if (LoadVT.isVector()) {
7606     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7607     LoadL = DAG.getBitcast(CmpVT, LoadL);
7608     LoadR = DAG.getBitcast(CmpVT, LoadR);
7609   }
7610 
7611   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7612   processIntegerCallValue(I, Cmp, false);
7613   return true;
7614 }
7615 
7616 /// See if we can lower a memchr call into an optimized form. If so, return
7617 /// true and lower it. Otherwise return false, and it will be lowered like a
7618 /// normal call.
7619 /// The caller already checked that \p I calls the appropriate LibFunc with a
7620 /// correct prototype.
7621 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7622   const Value *Src = I.getArgOperand(0);
7623   const Value *Char = I.getArgOperand(1);
7624   const Value *Length = I.getArgOperand(2);
7625 
7626   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7627   std::pair<SDValue, SDValue> Res =
7628     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7629                                 getValue(Src), getValue(Char), getValue(Length),
7630                                 MachinePointerInfo(Src));
7631   if (Res.first.getNode()) {
7632     setValue(&I, Res.first);
7633     PendingLoads.push_back(Res.second);
7634     return true;
7635   }
7636 
7637   return false;
7638 }
7639 
7640 /// See if we can lower a mempcpy call into an optimized form. If so, return
7641 /// true and lower it. Otherwise return false, and it will be lowered like a
7642 /// normal call.
7643 /// The caller already checked that \p I calls the appropriate LibFunc with a
7644 /// correct prototype.
7645 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7646   SDValue Dst = getValue(I.getArgOperand(0));
7647   SDValue Src = getValue(I.getArgOperand(1));
7648   SDValue Size = getValue(I.getArgOperand(2));
7649 
7650   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7651   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7652   // DAG::getMemcpy needs Alignment to be defined.
7653   Align Alignment = std::min(DstAlign, SrcAlign);
7654 
7655   bool isVol = false;
7656   SDLoc sdl = getCurSDLoc();
7657 
7658   // In the mempcpy context we need to pass in a false value for isTailCall
7659   // because the return pointer needs to be adjusted by the size of
7660   // the copied memory.
7661   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7662   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7663                              /*isTailCall=*/false,
7664                              MachinePointerInfo(I.getArgOperand(0)),
7665                              MachinePointerInfo(I.getArgOperand(1)));
7666   assert(MC.getNode() != nullptr &&
7667          "** memcpy should not be lowered as TailCall in mempcpy context **");
7668   DAG.setRoot(MC);
7669 
7670   // Check if Size needs to be truncated or extended.
7671   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7672 
7673   // Adjust return pointer to point just past the last dst byte.
7674   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7675                                     Dst, Size);
7676   setValue(&I, DstPlusSize);
7677   return true;
7678 }
7679 
7680 /// See if we can lower a strcpy call into an optimized form.  If so, return
7681 /// true and lower it, otherwise return false and it will be lowered like a
7682 /// normal call.
7683 /// The caller already checked that \p I calls the appropriate LibFunc with a
7684 /// correct prototype.
7685 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7686   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7687 
7688   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7689   std::pair<SDValue, SDValue> Res =
7690     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7691                                 getValue(Arg0), getValue(Arg1),
7692                                 MachinePointerInfo(Arg0),
7693                                 MachinePointerInfo(Arg1), isStpcpy);
7694   if (Res.first.getNode()) {
7695     setValue(&I, Res.first);
7696     DAG.setRoot(Res.second);
7697     return true;
7698   }
7699 
7700   return false;
7701 }
7702 
7703 /// See if we can lower a strcmp call into an optimized form.  If so, return
7704 /// true and lower it, otherwise return false and it will be lowered like a
7705 /// normal call.
7706 /// The caller already checked that \p I calls the appropriate LibFunc with a
7707 /// correct prototype.
7708 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7709   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7710 
7711   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7712   std::pair<SDValue, SDValue> Res =
7713     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7714                                 getValue(Arg0), getValue(Arg1),
7715                                 MachinePointerInfo(Arg0),
7716                                 MachinePointerInfo(Arg1));
7717   if (Res.first.getNode()) {
7718     processIntegerCallValue(I, Res.first, true);
7719     PendingLoads.push_back(Res.second);
7720     return true;
7721   }
7722 
7723   return false;
7724 }
7725 
7726 /// See if we can lower a strlen call into an optimized form.  If so, return
7727 /// true and lower it, otherwise return false and it will be lowered like a
7728 /// normal call.
7729 /// The caller already checked that \p I calls the appropriate LibFunc with a
7730 /// correct prototype.
7731 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7732   const Value *Arg0 = I.getArgOperand(0);
7733 
7734   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7735   std::pair<SDValue, SDValue> Res =
7736     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7737                                 getValue(Arg0), MachinePointerInfo(Arg0));
7738   if (Res.first.getNode()) {
7739     processIntegerCallValue(I, Res.first, false);
7740     PendingLoads.push_back(Res.second);
7741     return true;
7742   }
7743 
7744   return false;
7745 }
7746 
7747 /// See if we can lower a strnlen call into an optimized form.  If so, return
7748 /// true and lower it, otherwise return false and it will be lowered like a
7749 /// normal call.
7750 /// The caller already checked that \p I calls the appropriate LibFunc with a
7751 /// correct prototype.
7752 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7753   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7754 
7755   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7756   std::pair<SDValue, SDValue> Res =
7757     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7758                                  getValue(Arg0), getValue(Arg1),
7759                                  MachinePointerInfo(Arg0));
7760   if (Res.first.getNode()) {
7761     processIntegerCallValue(I, Res.first, false);
7762     PendingLoads.push_back(Res.second);
7763     return true;
7764   }
7765 
7766   return false;
7767 }
7768 
7769 /// See if we can lower a unary floating-point operation into an SDNode with
7770 /// the specified Opcode.  If so, return true and lower it, otherwise return
7771 /// false and it will be lowered like a normal call.
7772 /// The caller already checked that \p I calls the appropriate LibFunc with a
7773 /// correct prototype.
7774 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7775                                               unsigned Opcode) {
7776   // We already checked this call's prototype; verify it doesn't modify errno.
7777   if (!I.onlyReadsMemory())
7778     return false;
7779 
7780   SDNodeFlags Flags;
7781   Flags.copyFMF(cast<FPMathOperator>(I));
7782 
7783   SDValue Tmp = getValue(I.getArgOperand(0));
7784   setValue(&I,
7785            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7786   return true;
7787 }
7788 
7789 /// See if we can lower a binary floating-point operation into an SDNode with
7790 /// the specified Opcode. If so, return true and lower it. Otherwise return
7791 /// false, and it will be lowered like a normal call.
7792 /// The caller already checked that \p I calls the appropriate LibFunc with a
7793 /// correct prototype.
7794 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7795                                                unsigned Opcode) {
7796   // We already checked this call's prototype; verify it doesn't modify errno.
7797   if (!I.onlyReadsMemory())
7798     return false;
7799 
7800   SDNodeFlags Flags;
7801   Flags.copyFMF(cast<FPMathOperator>(I));
7802 
7803   SDValue Tmp0 = getValue(I.getArgOperand(0));
7804   SDValue Tmp1 = getValue(I.getArgOperand(1));
7805   EVT VT = Tmp0.getValueType();
7806   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7807   return true;
7808 }
7809 
7810 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7811   // Handle inline assembly differently.
7812   if (I.isInlineAsm()) {
7813     visitInlineAsm(I);
7814     return;
7815   }
7816 
7817   if (Function *F = I.getCalledFunction()) {
7818     if (F->isDeclaration()) {
7819       // Is this an LLVM intrinsic or a target-specific intrinsic?
7820       unsigned IID = F->getIntrinsicID();
7821       if (!IID)
7822         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7823           IID = II->getIntrinsicID(F);
7824 
7825       if (IID) {
7826         visitIntrinsicCall(I, IID);
7827         return;
7828       }
7829     }
7830 
7831     // Check for well-known libc/libm calls.  If the function is internal, it
7832     // can't be a library call.  Don't do the check if marked as nobuiltin for
7833     // some reason or the call site requires strict floating point semantics.
7834     LibFunc Func;
7835     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7836         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7837         LibInfo->hasOptimizedCodeGen(Func)) {
7838       switch (Func) {
7839       default: break;
7840       case LibFunc_bcmp:
7841         if (visitMemCmpBCmpCall(I))
7842           return;
7843         break;
7844       case LibFunc_copysign:
7845       case LibFunc_copysignf:
7846       case LibFunc_copysignl:
7847         // We already checked this call's prototype; verify it doesn't modify
7848         // errno.
7849         if (I.onlyReadsMemory()) {
7850           SDValue LHS = getValue(I.getArgOperand(0));
7851           SDValue RHS = getValue(I.getArgOperand(1));
7852           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7853                                    LHS.getValueType(), LHS, RHS));
7854           return;
7855         }
7856         break;
7857       case LibFunc_fabs:
7858       case LibFunc_fabsf:
7859       case LibFunc_fabsl:
7860         if (visitUnaryFloatCall(I, ISD::FABS))
7861           return;
7862         break;
7863       case LibFunc_fmin:
7864       case LibFunc_fminf:
7865       case LibFunc_fminl:
7866         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7867           return;
7868         break;
7869       case LibFunc_fmax:
7870       case LibFunc_fmaxf:
7871       case LibFunc_fmaxl:
7872         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7873           return;
7874         break;
7875       case LibFunc_sin:
7876       case LibFunc_sinf:
7877       case LibFunc_sinl:
7878         if (visitUnaryFloatCall(I, ISD::FSIN))
7879           return;
7880         break;
7881       case LibFunc_cos:
7882       case LibFunc_cosf:
7883       case LibFunc_cosl:
7884         if (visitUnaryFloatCall(I, ISD::FCOS))
7885           return;
7886         break;
7887       case LibFunc_sqrt:
7888       case LibFunc_sqrtf:
7889       case LibFunc_sqrtl:
7890       case LibFunc_sqrt_finite:
7891       case LibFunc_sqrtf_finite:
7892       case LibFunc_sqrtl_finite:
7893         if (visitUnaryFloatCall(I, ISD::FSQRT))
7894           return;
7895         break;
7896       case LibFunc_floor:
7897       case LibFunc_floorf:
7898       case LibFunc_floorl:
7899         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7900           return;
7901         break;
7902       case LibFunc_nearbyint:
7903       case LibFunc_nearbyintf:
7904       case LibFunc_nearbyintl:
7905         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7906           return;
7907         break;
7908       case LibFunc_ceil:
7909       case LibFunc_ceilf:
7910       case LibFunc_ceill:
7911         if (visitUnaryFloatCall(I, ISD::FCEIL))
7912           return;
7913         break;
7914       case LibFunc_rint:
7915       case LibFunc_rintf:
7916       case LibFunc_rintl:
7917         if (visitUnaryFloatCall(I, ISD::FRINT))
7918           return;
7919         break;
7920       case LibFunc_round:
7921       case LibFunc_roundf:
7922       case LibFunc_roundl:
7923         if (visitUnaryFloatCall(I, ISD::FROUND))
7924           return;
7925         break;
7926       case LibFunc_trunc:
7927       case LibFunc_truncf:
7928       case LibFunc_truncl:
7929         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7930           return;
7931         break;
7932       case LibFunc_log2:
7933       case LibFunc_log2f:
7934       case LibFunc_log2l:
7935         if (visitUnaryFloatCall(I, ISD::FLOG2))
7936           return;
7937         break;
7938       case LibFunc_exp2:
7939       case LibFunc_exp2f:
7940       case LibFunc_exp2l:
7941         if (visitUnaryFloatCall(I, ISD::FEXP2))
7942           return;
7943         break;
7944       case LibFunc_memcmp:
7945         if (visitMemCmpBCmpCall(I))
7946           return;
7947         break;
7948       case LibFunc_mempcpy:
7949         if (visitMemPCpyCall(I))
7950           return;
7951         break;
7952       case LibFunc_memchr:
7953         if (visitMemChrCall(I))
7954           return;
7955         break;
7956       case LibFunc_strcpy:
7957         if (visitStrCpyCall(I, false))
7958           return;
7959         break;
7960       case LibFunc_stpcpy:
7961         if (visitStrCpyCall(I, true))
7962           return;
7963         break;
7964       case LibFunc_strcmp:
7965         if (visitStrCmpCall(I))
7966           return;
7967         break;
7968       case LibFunc_strlen:
7969         if (visitStrLenCall(I))
7970           return;
7971         break;
7972       case LibFunc_strnlen:
7973         if (visitStrNLenCall(I))
7974           return;
7975         break;
7976       }
7977     }
7978   }
7979 
7980   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7981   // have to do anything here to lower funclet bundles.
7982   // CFGuardTarget bundles are lowered in LowerCallTo.
7983   assert(!I.hasOperandBundlesOtherThan(
7984              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7985               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
7986               LLVMContext::OB_clang_arc_attachedcall}) &&
7987          "Cannot lower calls with arbitrary operand bundles!");
7988 
7989   SDValue Callee = getValue(I.getCalledOperand());
7990 
7991   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7992     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7993   else
7994     // Check if we can potentially perform a tail call. More detailed checking
7995     // is be done within LowerCallTo, after more information about the call is
7996     // known.
7997     LowerCallTo(I, Callee, I.isTailCall());
7998 }
7999 
8000 namespace {
8001 
8002 /// AsmOperandInfo - This contains information for each constraint that we are
8003 /// lowering.
8004 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8005 public:
8006   /// CallOperand - If this is the result output operand or a clobber
8007   /// this is null, otherwise it is the incoming operand to the CallInst.
8008   /// This gets modified as the asm is processed.
8009   SDValue CallOperand;
8010 
8011   /// AssignedRegs - If this is a register or register class operand, this
8012   /// contains the set of register corresponding to the operand.
8013   RegsForValue AssignedRegs;
8014 
8015   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8016     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8017   }
8018 
8019   /// Whether or not this operand accesses memory
8020   bool hasMemory(const TargetLowering &TLI) const {
8021     // Indirect operand accesses access memory.
8022     if (isIndirect)
8023       return true;
8024 
8025     for (const auto &Code : Codes)
8026       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8027         return true;
8028 
8029     return false;
8030   }
8031 
8032   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8033   /// corresponds to.  If there is no Value* for this operand, it returns
8034   /// MVT::Other.
8035   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8036                            const DataLayout &DL) const {
8037     if (!CallOperandVal) return MVT::Other;
8038 
8039     if (isa<BasicBlock>(CallOperandVal))
8040       return TLI.getProgramPointerTy(DL);
8041 
8042     llvm::Type *OpTy = CallOperandVal->getType();
8043 
8044     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8045     // If this is an indirect operand, the operand is a pointer to the
8046     // accessed type.
8047     if (isIndirect) {
8048       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8049       if (!PtrTy)
8050         report_fatal_error("Indirect operand for inline asm not a pointer!");
8051       OpTy = PtrTy->getElementType();
8052     }
8053 
8054     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8055     if (StructType *STy = dyn_cast<StructType>(OpTy))
8056       if (STy->getNumElements() == 1)
8057         OpTy = STy->getElementType(0);
8058 
8059     // If OpTy is not a single value, it may be a struct/union that we
8060     // can tile with integers.
8061     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8062       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8063       switch (BitSize) {
8064       default: break;
8065       case 1:
8066       case 8:
8067       case 16:
8068       case 32:
8069       case 64:
8070       case 128:
8071         OpTy = IntegerType::get(Context, BitSize);
8072         break;
8073       }
8074     }
8075 
8076     return TLI.getValueType(DL, OpTy, true);
8077   }
8078 };
8079 
8080 
8081 } // end anonymous namespace
8082 
8083 /// Make sure that the output operand \p OpInfo and its corresponding input
8084 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8085 /// out).
8086 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8087                                SDISelAsmOperandInfo &MatchingOpInfo,
8088                                SelectionDAG &DAG) {
8089   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8090     return;
8091 
8092   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8093   const auto &TLI = DAG.getTargetLoweringInfo();
8094 
8095   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8096       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8097                                        OpInfo.ConstraintVT);
8098   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8099       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8100                                        MatchingOpInfo.ConstraintVT);
8101   if ((OpInfo.ConstraintVT.isInteger() !=
8102        MatchingOpInfo.ConstraintVT.isInteger()) ||
8103       (MatchRC.second != InputRC.second)) {
8104     // FIXME: error out in a more elegant fashion
8105     report_fatal_error("Unsupported asm: input constraint"
8106                        " with a matching output constraint of"
8107                        " incompatible type!");
8108   }
8109   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8110 }
8111 
8112 /// Get a direct memory input to behave well as an indirect operand.
8113 /// This may introduce stores, hence the need for a \p Chain.
8114 /// \return The (possibly updated) chain.
8115 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8116                                         SDISelAsmOperandInfo &OpInfo,
8117                                         SelectionDAG &DAG) {
8118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8119 
8120   // If we don't have an indirect input, put it in the constpool if we can,
8121   // otherwise spill it to a stack slot.
8122   // TODO: This isn't quite right. We need to handle these according to
8123   // the addressing mode that the constraint wants. Also, this may take
8124   // an additional register for the computation and we don't want that
8125   // either.
8126 
8127   // If the operand is a float, integer, or vector constant, spill to a
8128   // constant pool entry to get its address.
8129   const Value *OpVal = OpInfo.CallOperandVal;
8130   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8131       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8132     OpInfo.CallOperand = DAG.getConstantPool(
8133         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8134     return Chain;
8135   }
8136 
8137   // Otherwise, create a stack slot and emit a store to it before the asm.
8138   Type *Ty = OpVal->getType();
8139   auto &DL = DAG.getDataLayout();
8140   uint64_t TySize = DL.getTypeAllocSize(Ty);
8141   MachineFunction &MF = DAG.getMachineFunction();
8142   int SSFI = MF.getFrameInfo().CreateStackObject(
8143       TySize, DL.getPrefTypeAlign(Ty), false);
8144   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8145   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8146                             MachinePointerInfo::getFixedStack(MF, SSFI),
8147                             TLI.getMemValueType(DL, Ty));
8148   OpInfo.CallOperand = StackSlot;
8149 
8150   return Chain;
8151 }
8152 
8153 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8154 /// specified operand.  We prefer to assign virtual registers, to allow the
8155 /// register allocator to handle the assignment process.  However, if the asm
8156 /// uses features that we can't model on machineinstrs, we have SDISel do the
8157 /// allocation.  This produces generally horrible, but correct, code.
8158 ///
8159 ///   OpInfo describes the operand
8160 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8161 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8162                                  SDISelAsmOperandInfo &OpInfo,
8163                                  SDISelAsmOperandInfo &RefOpInfo) {
8164   LLVMContext &Context = *DAG.getContext();
8165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8166 
8167   MachineFunction &MF = DAG.getMachineFunction();
8168   SmallVector<unsigned, 4> Regs;
8169   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8170 
8171   // No work to do for memory operations.
8172   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8173     return;
8174 
8175   // If this is a constraint for a single physreg, or a constraint for a
8176   // register class, find it.
8177   unsigned AssignedReg;
8178   const TargetRegisterClass *RC;
8179   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8180       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8181   // RC is unset only on failure. Return immediately.
8182   if (!RC)
8183     return;
8184 
8185   // Get the actual register value type.  This is important, because the user
8186   // may have asked for (e.g.) the AX register in i32 type.  We need to
8187   // remember that AX is actually i16 to get the right extension.
8188   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8189 
8190   if (OpInfo.ConstraintVT != MVT::Other) {
8191     // If this is an FP operand in an integer register (or visa versa), or more
8192     // generally if the operand value disagrees with the register class we plan
8193     // to stick it in, fix the operand type.
8194     //
8195     // If this is an input value, the bitcast to the new type is done now.
8196     // Bitcast for output value is done at the end of visitInlineAsm().
8197     if ((OpInfo.Type == InlineAsm::isOutput ||
8198          OpInfo.Type == InlineAsm::isInput) &&
8199         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8200       // Try to convert to the first EVT that the reg class contains.  If the
8201       // types are identical size, use a bitcast to convert (e.g. two differing
8202       // vector types).  Note: output bitcast is done at the end of
8203       // visitInlineAsm().
8204       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8205         // Exclude indirect inputs while they are unsupported because the code
8206         // to perform the load is missing and thus OpInfo.CallOperand still
8207         // refers to the input address rather than the pointed-to value.
8208         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8209           OpInfo.CallOperand =
8210               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8211         OpInfo.ConstraintVT = RegVT;
8212         // If the operand is an FP value and we want it in integer registers,
8213         // use the corresponding integer type. This turns an f64 value into
8214         // i64, which can be passed with two i32 values on a 32-bit machine.
8215       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8216         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8217         if (OpInfo.Type == InlineAsm::isInput)
8218           OpInfo.CallOperand =
8219               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8220         OpInfo.ConstraintVT = VT;
8221       }
8222     }
8223   }
8224 
8225   // No need to allocate a matching input constraint since the constraint it's
8226   // matching to has already been allocated.
8227   if (OpInfo.isMatchingInputConstraint())
8228     return;
8229 
8230   EVT ValueVT = OpInfo.ConstraintVT;
8231   if (OpInfo.ConstraintVT == MVT::Other)
8232     ValueVT = RegVT;
8233 
8234   // Initialize NumRegs.
8235   unsigned NumRegs = 1;
8236   if (OpInfo.ConstraintVT != MVT::Other)
8237     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8238 
8239   // If this is a constraint for a specific physical register, like {r17},
8240   // assign it now.
8241 
8242   // If this associated to a specific register, initialize iterator to correct
8243   // place. If virtual, make sure we have enough registers
8244 
8245   // Initialize iterator if necessary
8246   TargetRegisterClass::iterator I = RC->begin();
8247   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8248 
8249   // Do not check for single registers.
8250   if (AssignedReg) {
8251       for (; *I != AssignedReg; ++I)
8252         assert(I != RC->end() && "AssignedReg should be member of RC");
8253   }
8254 
8255   for (; NumRegs; --NumRegs, ++I) {
8256     assert(I != RC->end() && "Ran out of registers to allocate!");
8257     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8258     Regs.push_back(R);
8259   }
8260 
8261   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8262 }
8263 
8264 static unsigned
8265 findMatchingInlineAsmOperand(unsigned OperandNo,
8266                              const std::vector<SDValue> &AsmNodeOperands) {
8267   // Scan until we find the definition we already emitted of this operand.
8268   unsigned CurOp = InlineAsm::Op_FirstOperand;
8269   for (; OperandNo; --OperandNo) {
8270     // Advance to the next operand.
8271     unsigned OpFlag =
8272         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8273     assert((InlineAsm::isRegDefKind(OpFlag) ||
8274             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8275             InlineAsm::isMemKind(OpFlag)) &&
8276            "Skipped past definitions?");
8277     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8278   }
8279   return CurOp;
8280 }
8281 
8282 namespace {
8283 
8284 class ExtraFlags {
8285   unsigned Flags = 0;
8286 
8287 public:
8288   explicit ExtraFlags(const CallBase &Call) {
8289     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8290     if (IA->hasSideEffects())
8291       Flags |= InlineAsm::Extra_HasSideEffects;
8292     if (IA->isAlignStack())
8293       Flags |= InlineAsm::Extra_IsAlignStack;
8294     if (Call.isConvergent())
8295       Flags |= InlineAsm::Extra_IsConvergent;
8296     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8297   }
8298 
8299   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8300     // Ideally, we would only check against memory constraints.  However, the
8301     // meaning of an Other constraint can be target-specific and we can't easily
8302     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8303     // for Other constraints as well.
8304     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8305         OpInfo.ConstraintType == TargetLowering::C_Other) {
8306       if (OpInfo.Type == InlineAsm::isInput)
8307         Flags |= InlineAsm::Extra_MayLoad;
8308       else if (OpInfo.Type == InlineAsm::isOutput)
8309         Flags |= InlineAsm::Extra_MayStore;
8310       else if (OpInfo.Type == InlineAsm::isClobber)
8311         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8312     }
8313   }
8314 
8315   unsigned get() const { return Flags; }
8316 };
8317 
8318 } // end anonymous namespace
8319 
8320 /// visitInlineAsm - Handle a call to an InlineAsm object.
8321 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8322   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8323 
8324   /// ConstraintOperands - Information about all of the constraints.
8325   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8326 
8327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8328   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8329       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8330 
8331   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8332   // AsmDialect, MayLoad, MayStore).
8333   bool HasSideEffect = IA->hasSideEffects();
8334   ExtraFlags ExtraInfo(Call);
8335 
8336   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8337   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8338   unsigned NumMatchingOps = 0;
8339   for (auto &T : TargetConstraints) {
8340     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8341     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8342 
8343     // Compute the value type for each operand.
8344     if (OpInfo.Type == InlineAsm::isInput ||
8345         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8346       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8347 
8348       // Process the call argument. BasicBlocks are labels, currently appearing
8349       // only in asm's.
8350       if (isa<CallBrInst>(Call) &&
8351           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8352                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8353                         NumMatchingOps) &&
8354           (NumMatchingOps == 0 ||
8355            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8356                         NumMatchingOps))) {
8357         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8358         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8359         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8360       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8361         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8362       } else {
8363         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8364       }
8365 
8366       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8367                                            DAG.getDataLayout());
8368       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8369     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8370       // The return value of the call is this value.  As such, there is no
8371       // corresponding argument.
8372       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8373       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8374         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8375             DAG.getDataLayout(), STy->getElementType(ResNo));
8376       } else {
8377         assert(ResNo == 0 && "Asm only has one result!");
8378         OpInfo.ConstraintVT =
8379             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8380       }
8381       ++ResNo;
8382     } else {
8383       OpInfo.ConstraintVT = MVT::Other;
8384     }
8385 
8386     if (OpInfo.hasMatchingInput())
8387       ++NumMatchingOps;
8388 
8389     if (!HasSideEffect)
8390       HasSideEffect = OpInfo.hasMemory(TLI);
8391 
8392     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8393     // FIXME: Could we compute this on OpInfo rather than T?
8394 
8395     // Compute the constraint code and ConstraintType to use.
8396     TLI.ComputeConstraintToUse(T, SDValue());
8397 
8398     if (T.ConstraintType == TargetLowering::C_Immediate &&
8399         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8400       // We've delayed emitting a diagnostic like the "n" constraint because
8401       // inlining could cause an integer showing up.
8402       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8403                                           "' expects an integer constant "
8404                                           "expression");
8405 
8406     ExtraInfo.update(T);
8407   }
8408 
8409 
8410   // We won't need to flush pending loads if this asm doesn't touch
8411   // memory and is nonvolatile.
8412   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8413 
8414   bool IsCallBr = isa<CallBrInst>(Call);
8415   if (IsCallBr) {
8416     // If this is a callbr we need to flush pending exports since inlineasm_br
8417     // is a terminator. We need to do this before nodes are glued to
8418     // the inlineasm_br node.
8419     Chain = getControlRoot();
8420   }
8421 
8422   // Second pass over the constraints: compute which constraint option to use.
8423   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8424     // If this is an output operand with a matching input operand, look up the
8425     // matching input. If their types mismatch, e.g. one is an integer, the
8426     // other is floating point, or their sizes are different, flag it as an
8427     // error.
8428     if (OpInfo.hasMatchingInput()) {
8429       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8430       patchMatchingInput(OpInfo, Input, DAG);
8431     }
8432 
8433     // Compute the constraint code and ConstraintType to use.
8434     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8435 
8436     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8437         OpInfo.Type == InlineAsm::isClobber)
8438       continue;
8439 
8440     // If this is a memory input, and if the operand is not indirect, do what we
8441     // need to provide an address for the memory input.
8442     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8443         !OpInfo.isIndirect) {
8444       assert((OpInfo.isMultipleAlternative ||
8445               (OpInfo.Type == InlineAsm::isInput)) &&
8446              "Can only indirectify direct input operands!");
8447 
8448       // Memory operands really want the address of the value.
8449       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8450 
8451       // There is no longer a Value* corresponding to this operand.
8452       OpInfo.CallOperandVal = nullptr;
8453 
8454       // It is now an indirect operand.
8455       OpInfo.isIndirect = true;
8456     }
8457 
8458   }
8459 
8460   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8461   std::vector<SDValue> AsmNodeOperands;
8462   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8463   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8464       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8465 
8466   // If we have a !srcloc metadata node associated with it, we want to attach
8467   // this to the ultimately generated inline asm machineinstr.  To do this, we
8468   // pass in the third operand as this (potentially null) inline asm MDNode.
8469   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8470   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8471 
8472   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8473   // bits as operand 3.
8474   AsmNodeOperands.push_back(DAG.getTargetConstant(
8475       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8476 
8477   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8478   // this, assign virtual and physical registers for inputs and otput.
8479   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8480     // Assign Registers.
8481     SDISelAsmOperandInfo &RefOpInfo =
8482         OpInfo.isMatchingInputConstraint()
8483             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8484             : OpInfo;
8485     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8486 
8487     auto DetectWriteToReservedRegister = [&]() {
8488       const MachineFunction &MF = DAG.getMachineFunction();
8489       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8490       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8491         if (Register::isPhysicalRegister(Reg) &&
8492             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8493           const char *RegName = TRI.getName(Reg);
8494           emitInlineAsmError(Call, "write to reserved register '" +
8495                                        Twine(RegName) + "'");
8496           return true;
8497         }
8498       }
8499       return false;
8500     };
8501 
8502     switch (OpInfo.Type) {
8503     case InlineAsm::isOutput:
8504       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8505         unsigned ConstraintID =
8506             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8507         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8508                "Failed to convert memory constraint code to constraint id.");
8509 
8510         // Add information to the INLINEASM node to know about this output.
8511         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8512         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8513         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8514                                                         MVT::i32));
8515         AsmNodeOperands.push_back(OpInfo.CallOperand);
8516       } else {
8517         // Otherwise, this outputs to a register (directly for C_Register /
8518         // C_RegisterClass, and a target-defined fashion for
8519         // C_Immediate/C_Other). Find a register that we can use.
8520         if (OpInfo.AssignedRegs.Regs.empty()) {
8521           emitInlineAsmError(
8522               Call, "couldn't allocate output register for constraint '" +
8523                         Twine(OpInfo.ConstraintCode) + "'");
8524           return;
8525         }
8526 
8527         if (DetectWriteToReservedRegister())
8528           return;
8529 
8530         // Add information to the INLINEASM node to know that this register is
8531         // set.
8532         OpInfo.AssignedRegs.AddInlineAsmOperands(
8533             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8534                                   : InlineAsm::Kind_RegDef,
8535             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8536       }
8537       break;
8538 
8539     case InlineAsm::isInput: {
8540       SDValue InOperandVal = OpInfo.CallOperand;
8541 
8542       if (OpInfo.isMatchingInputConstraint()) {
8543         // If this is required to match an output register we have already set,
8544         // just use its register.
8545         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8546                                                   AsmNodeOperands);
8547         unsigned OpFlag =
8548           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8549         if (InlineAsm::isRegDefKind(OpFlag) ||
8550             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8551           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8552           if (OpInfo.isIndirect) {
8553             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8554             emitInlineAsmError(Call, "inline asm not supported yet: "
8555                                      "don't know how to handle tied "
8556                                      "indirect register inputs");
8557             return;
8558           }
8559 
8560           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8561           SmallVector<unsigned, 4> Regs;
8562 
8563           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8564             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8565             MachineRegisterInfo &RegInfo =
8566                 DAG.getMachineFunction().getRegInfo();
8567             for (unsigned i = 0; i != NumRegs; ++i)
8568               Regs.push_back(RegInfo.createVirtualRegister(RC));
8569           } else {
8570             emitInlineAsmError(Call,
8571                                "inline asm error: This value type register "
8572                                "class is not natively supported!");
8573             return;
8574           }
8575 
8576           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8577 
8578           SDLoc dl = getCurSDLoc();
8579           // Use the produced MatchedRegs object to
8580           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8581           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8582                                            true, OpInfo.getMatchedOperand(), dl,
8583                                            DAG, AsmNodeOperands);
8584           break;
8585         }
8586 
8587         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8588         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8589                "Unexpected number of operands");
8590         // Add information to the INLINEASM node to know about this input.
8591         // See InlineAsm.h isUseOperandTiedToDef.
8592         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8593         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8594                                                     OpInfo.getMatchedOperand());
8595         AsmNodeOperands.push_back(DAG.getTargetConstant(
8596             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8597         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8598         break;
8599       }
8600 
8601       // Treat indirect 'X' constraint as memory.
8602       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8603           OpInfo.isIndirect)
8604         OpInfo.ConstraintType = TargetLowering::C_Memory;
8605 
8606       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8607           OpInfo.ConstraintType == TargetLowering::C_Other) {
8608         std::vector<SDValue> Ops;
8609         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8610                                           Ops, DAG);
8611         if (Ops.empty()) {
8612           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8613             if (isa<ConstantSDNode>(InOperandVal)) {
8614               emitInlineAsmError(Call, "value out of range for constraint '" +
8615                                            Twine(OpInfo.ConstraintCode) + "'");
8616               return;
8617             }
8618 
8619           emitInlineAsmError(Call,
8620                              "invalid operand for inline asm constraint '" +
8621                                  Twine(OpInfo.ConstraintCode) + "'");
8622           return;
8623         }
8624 
8625         // Add information to the INLINEASM node to know about this input.
8626         unsigned ResOpType =
8627           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8628         AsmNodeOperands.push_back(DAG.getTargetConstant(
8629             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8630         llvm::append_range(AsmNodeOperands, Ops);
8631         break;
8632       }
8633 
8634       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8635         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8636         assert(InOperandVal.getValueType() ==
8637                    TLI.getPointerTy(DAG.getDataLayout()) &&
8638                "Memory operands expect pointer values");
8639 
8640         unsigned ConstraintID =
8641             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8642         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8643                "Failed to convert memory constraint code to constraint id.");
8644 
8645         // Add information to the INLINEASM node to know about this input.
8646         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8647         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8648         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8649                                                         getCurSDLoc(),
8650                                                         MVT::i32));
8651         AsmNodeOperands.push_back(InOperandVal);
8652         break;
8653       }
8654 
8655       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8656               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8657              "Unknown constraint type!");
8658 
8659       // TODO: Support this.
8660       if (OpInfo.isIndirect) {
8661         emitInlineAsmError(
8662             Call, "Don't know how to handle indirect register inputs yet "
8663                   "for constraint '" +
8664                       Twine(OpInfo.ConstraintCode) + "'");
8665         return;
8666       }
8667 
8668       // Copy the input into the appropriate registers.
8669       if (OpInfo.AssignedRegs.Regs.empty()) {
8670         emitInlineAsmError(Call,
8671                            "couldn't allocate input reg for constraint '" +
8672                                Twine(OpInfo.ConstraintCode) + "'");
8673         return;
8674       }
8675 
8676       if (DetectWriteToReservedRegister())
8677         return;
8678 
8679       SDLoc dl = getCurSDLoc();
8680 
8681       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8682                                         &Call);
8683 
8684       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8685                                                dl, DAG, AsmNodeOperands);
8686       break;
8687     }
8688     case InlineAsm::isClobber:
8689       // Add the clobbered value to the operand list, so that the register
8690       // allocator is aware that the physreg got clobbered.
8691       if (!OpInfo.AssignedRegs.Regs.empty())
8692         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8693                                                  false, 0, getCurSDLoc(), DAG,
8694                                                  AsmNodeOperands);
8695       break;
8696     }
8697   }
8698 
8699   // Finish up input operands.  Set the input chain and add the flag last.
8700   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8701   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8702 
8703   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8704   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8705                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8706   Flag = Chain.getValue(1);
8707 
8708   // Do additional work to generate outputs.
8709 
8710   SmallVector<EVT, 1> ResultVTs;
8711   SmallVector<SDValue, 1> ResultValues;
8712   SmallVector<SDValue, 8> OutChains;
8713 
8714   llvm::Type *CallResultType = Call.getType();
8715   ArrayRef<Type *> ResultTypes;
8716   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8717     ResultTypes = StructResult->elements();
8718   else if (!CallResultType->isVoidTy())
8719     ResultTypes = makeArrayRef(CallResultType);
8720 
8721   auto CurResultType = ResultTypes.begin();
8722   auto handleRegAssign = [&](SDValue V) {
8723     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8724     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8725     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8726     ++CurResultType;
8727     // If the type of the inline asm call site return value is different but has
8728     // same size as the type of the asm output bitcast it.  One example of this
8729     // is for vectors with different width / number of elements.  This can
8730     // happen for register classes that can contain multiple different value
8731     // types.  The preg or vreg allocated may not have the same VT as was
8732     // expected.
8733     //
8734     // This can also happen for a return value that disagrees with the register
8735     // class it is put in, eg. a double in a general-purpose register on a
8736     // 32-bit machine.
8737     if (ResultVT != V.getValueType() &&
8738         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8739       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8740     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8741              V.getValueType().isInteger()) {
8742       // If a result value was tied to an input value, the computed result
8743       // may have a wider width than the expected result.  Extract the
8744       // relevant portion.
8745       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8746     }
8747     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8748     ResultVTs.push_back(ResultVT);
8749     ResultValues.push_back(V);
8750   };
8751 
8752   // Deal with output operands.
8753   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8754     if (OpInfo.Type == InlineAsm::isOutput) {
8755       SDValue Val;
8756       // Skip trivial output operands.
8757       if (OpInfo.AssignedRegs.Regs.empty())
8758         continue;
8759 
8760       switch (OpInfo.ConstraintType) {
8761       case TargetLowering::C_Register:
8762       case TargetLowering::C_RegisterClass:
8763         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8764                                                   Chain, &Flag, &Call);
8765         break;
8766       case TargetLowering::C_Immediate:
8767       case TargetLowering::C_Other:
8768         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8769                                               OpInfo, DAG);
8770         break;
8771       case TargetLowering::C_Memory:
8772         break; // Already handled.
8773       case TargetLowering::C_Unknown:
8774         assert(false && "Unexpected unknown constraint");
8775       }
8776 
8777       // Indirect output manifest as stores. Record output chains.
8778       if (OpInfo.isIndirect) {
8779         const Value *Ptr = OpInfo.CallOperandVal;
8780         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8781         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8782                                      MachinePointerInfo(Ptr));
8783         OutChains.push_back(Store);
8784       } else {
8785         // generate CopyFromRegs to associated registers.
8786         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8787         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8788           for (const SDValue &V : Val->op_values())
8789             handleRegAssign(V);
8790         } else
8791           handleRegAssign(Val);
8792       }
8793     }
8794   }
8795 
8796   // Set results.
8797   if (!ResultValues.empty()) {
8798     assert(CurResultType == ResultTypes.end() &&
8799            "Mismatch in number of ResultTypes");
8800     assert(ResultValues.size() == ResultTypes.size() &&
8801            "Mismatch in number of output operands in asm result");
8802 
8803     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8804                             DAG.getVTList(ResultVTs), ResultValues);
8805     setValue(&Call, V);
8806   }
8807 
8808   // Collect store chains.
8809   if (!OutChains.empty())
8810     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8811 
8812   // Only Update Root if inline assembly has a memory effect.
8813   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8814     DAG.setRoot(Chain);
8815 }
8816 
8817 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8818                                              const Twine &Message) {
8819   LLVMContext &Ctx = *DAG.getContext();
8820   Ctx.emitError(&Call, Message);
8821 
8822   // Make sure we leave the DAG in a valid state
8823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8824   SmallVector<EVT, 1> ValueVTs;
8825   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8826 
8827   if (ValueVTs.empty())
8828     return;
8829 
8830   SmallVector<SDValue, 1> Ops;
8831   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8832     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8833 
8834   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8835 }
8836 
8837 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8838   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8839                           MVT::Other, getRoot(),
8840                           getValue(I.getArgOperand(0)),
8841                           DAG.getSrcValue(I.getArgOperand(0))));
8842 }
8843 
8844 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8846   const DataLayout &DL = DAG.getDataLayout();
8847   SDValue V = DAG.getVAArg(
8848       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8849       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8850       DL.getABITypeAlign(I.getType()).value());
8851   DAG.setRoot(V.getValue(1));
8852 
8853   if (I.getType()->isPointerTy())
8854     V = DAG.getPtrExtOrTrunc(
8855         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8856   setValue(&I, V);
8857 }
8858 
8859 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8860   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8861                           MVT::Other, getRoot(),
8862                           getValue(I.getArgOperand(0)),
8863                           DAG.getSrcValue(I.getArgOperand(0))));
8864 }
8865 
8866 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8867   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8868                           MVT::Other, getRoot(),
8869                           getValue(I.getArgOperand(0)),
8870                           getValue(I.getArgOperand(1)),
8871                           DAG.getSrcValue(I.getArgOperand(0)),
8872                           DAG.getSrcValue(I.getArgOperand(1))));
8873 }
8874 
8875 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8876                                                     const Instruction &I,
8877                                                     SDValue Op) {
8878   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8879   if (!Range)
8880     return Op;
8881 
8882   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8883   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8884     return Op;
8885 
8886   APInt Lo = CR.getUnsignedMin();
8887   if (!Lo.isMinValue())
8888     return Op;
8889 
8890   APInt Hi = CR.getUnsignedMax();
8891   unsigned Bits = std::max(Hi.getActiveBits(),
8892                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8893 
8894   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8895 
8896   SDLoc SL = getCurSDLoc();
8897 
8898   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8899                              DAG.getValueType(SmallVT));
8900   unsigned NumVals = Op.getNode()->getNumValues();
8901   if (NumVals == 1)
8902     return ZExt;
8903 
8904   SmallVector<SDValue, 4> Ops;
8905 
8906   Ops.push_back(ZExt);
8907   for (unsigned I = 1; I != NumVals; ++I)
8908     Ops.push_back(Op.getValue(I));
8909 
8910   return DAG.getMergeValues(Ops, SL);
8911 }
8912 
8913 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8914 /// the call being lowered.
8915 ///
8916 /// This is a helper for lowering intrinsics that follow a target calling
8917 /// convention or require stack pointer adjustment. Only a subset of the
8918 /// intrinsic's operands need to participate in the calling convention.
8919 void SelectionDAGBuilder::populateCallLoweringInfo(
8920     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8921     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8922     bool IsPatchPoint) {
8923   TargetLowering::ArgListTy Args;
8924   Args.reserve(NumArgs);
8925 
8926   // Populate the argument list.
8927   // Attributes for args start at offset 1, after the return attribute.
8928   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8929        ArgI != ArgE; ++ArgI) {
8930     const Value *V = Call->getOperand(ArgI);
8931 
8932     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8933 
8934     TargetLowering::ArgListEntry Entry;
8935     Entry.Node = getValue(V);
8936     Entry.Ty = V->getType();
8937     Entry.setAttributes(Call, ArgI);
8938     Args.push_back(Entry);
8939   }
8940 
8941   CLI.setDebugLoc(getCurSDLoc())
8942       .setChain(getRoot())
8943       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8944       .setDiscardResult(Call->use_empty())
8945       .setIsPatchPoint(IsPatchPoint)
8946       .setIsPreallocated(
8947           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8948 }
8949 
8950 /// Add a stack map intrinsic call's live variable operands to a stackmap
8951 /// or patchpoint target node's operand list.
8952 ///
8953 /// Constants are converted to TargetConstants purely as an optimization to
8954 /// avoid constant materialization and register allocation.
8955 ///
8956 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8957 /// generate addess computation nodes, and so FinalizeISel can convert the
8958 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8959 /// address materialization and register allocation, but may also be required
8960 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8961 /// alloca in the entry block, then the runtime may assume that the alloca's
8962 /// StackMap location can be read immediately after compilation and that the
8963 /// location is valid at any point during execution (this is similar to the
8964 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8965 /// only available in a register, then the runtime would need to trap when
8966 /// execution reaches the StackMap in order to read the alloca's location.
8967 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8968                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8969                                 SelectionDAGBuilder &Builder) {
8970   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8971     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8972     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8973       Ops.push_back(
8974         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8975       Ops.push_back(
8976         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8977     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8978       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8979       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8980           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8981     } else
8982       Ops.push_back(OpVal);
8983   }
8984 }
8985 
8986 /// Lower llvm.experimental.stackmap directly to its target opcode.
8987 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8988   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8989   //                                  [live variables...])
8990 
8991   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8992 
8993   SDValue Chain, InFlag, Callee, NullPtr;
8994   SmallVector<SDValue, 32> Ops;
8995 
8996   SDLoc DL = getCurSDLoc();
8997   Callee = getValue(CI.getCalledOperand());
8998   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8999 
9000   // The stackmap intrinsic only records the live variables (the arguments
9001   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9002   // intrinsic, this won't be lowered to a function call. This means we don't
9003   // have to worry about calling conventions and target specific lowering code.
9004   // Instead we perform the call lowering right here.
9005   //
9006   // chain, flag = CALLSEQ_START(chain, 0, 0)
9007   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9008   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9009   //
9010   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9011   InFlag = Chain.getValue(1);
9012 
9013   // Add the <id> and <numBytes> constants.
9014   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9015   Ops.push_back(DAG.getTargetConstant(
9016                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9017   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9018   Ops.push_back(DAG.getTargetConstant(
9019                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9020                   MVT::i32));
9021 
9022   // Push live variables for the stack map.
9023   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9024 
9025   // We are not pushing any register mask info here on the operands list,
9026   // because the stackmap doesn't clobber anything.
9027 
9028   // Push the chain and the glue flag.
9029   Ops.push_back(Chain);
9030   Ops.push_back(InFlag);
9031 
9032   // Create the STACKMAP node.
9033   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9034   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9035   Chain = SDValue(SM, 0);
9036   InFlag = Chain.getValue(1);
9037 
9038   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9039 
9040   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9041 
9042   // Set the root to the target-lowered call chain.
9043   DAG.setRoot(Chain);
9044 
9045   // Inform the Frame Information that we have a stackmap in this function.
9046   FuncInfo.MF->getFrameInfo().setHasStackMap();
9047 }
9048 
9049 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9050 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9051                                           const BasicBlock *EHPadBB) {
9052   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9053   //                                                 i32 <numBytes>,
9054   //                                                 i8* <target>,
9055   //                                                 i32 <numArgs>,
9056   //                                                 [Args...],
9057   //                                                 [live variables...])
9058 
9059   CallingConv::ID CC = CB.getCallingConv();
9060   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9061   bool HasDef = !CB.getType()->isVoidTy();
9062   SDLoc dl = getCurSDLoc();
9063   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9064 
9065   // Handle immediate and symbolic callees.
9066   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9067     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9068                                    /*isTarget=*/true);
9069   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9070     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9071                                          SDLoc(SymbolicCallee),
9072                                          SymbolicCallee->getValueType(0));
9073 
9074   // Get the real number of arguments participating in the call <numArgs>
9075   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9076   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9077 
9078   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9079   // Intrinsics include all meta-operands up to but not including CC.
9080   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9081   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9082          "Not enough arguments provided to the patchpoint intrinsic");
9083 
9084   // For AnyRegCC the arguments are lowered later on manually.
9085   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9086   Type *ReturnTy =
9087       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9088 
9089   TargetLowering::CallLoweringInfo CLI(DAG);
9090   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9091                            ReturnTy, true);
9092   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9093 
9094   SDNode *CallEnd = Result.second.getNode();
9095   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9096     CallEnd = CallEnd->getOperand(0).getNode();
9097 
9098   /// Get a call instruction from the call sequence chain.
9099   /// Tail calls are not allowed.
9100   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9101          "Expected a callseq node.");
9102   SDNode *Call = CallEnd->getOperand(0).getNode();
9103   bool HasGlue = Call->getGluedNode();
9104 
9105   // Replace the target specific call node with the patchable intrinsic.
9106   SmallVector<SDValue, 8> Ops;
9107 
9108   // Add the <id> and <numBytes> constants.
9109   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9110   Ops.push_back(DAG.getTargetConstant(
9111                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9112   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9113   Ops.push_back(DAG.getTargetConstant(
9114                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9115                   MVT::i32));
9116 
9117   // Add the callee.
9118   Ops.push_back(Callee);
9119 
9120   // Adjust <numArgs> to account for any arguments that have been passed on the
9121   // stack instead.
9122   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9123   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9124   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9125   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9126 
9127   // Add the calling convention
9128   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9129 
9130   // Add the arguments we omitted previously. The register allocator should
9131   // place these in any free register.
9132   if (IsAnyRegCC)
9133     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9134       Ops.push_back(getValue(CB.getArgOperand(i)));
9135 
9136   // Push the arguments from the call instruction up to the register mask.
9137   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9138   Ops.append(Call->op_begin() + 2, e);
9139 
9140   // Push live variables for the stack map.
9141   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9142 
9143   // Push the register mask info.
9144   if (HasGlue)
9145     Ops.push_back(*(Call->op_end()-2));
9146   else
9147     Ops.push_back(*(Call->op_end()-1));
9148 
9149   // Push the chain (this is originally the first operand of the call, but
9150   // becomes now the last or second to last operand).
9151   Ops.push_back(*(Call->op_begin()));
9152 
9153   // Push the glue flag (last operand).
9154   if (HasGlue)
9155     Ops.push_back(*(Call->op_end()-1));
9156 
9157   SDVTList NodeTys;
9158   if (IsAnyRegCC && HasDef) {
9159     // Create the return types based on the intrinsic definition
9160     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9161     SmallVector<EVT, 3> ValueVTs;
9162     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9163     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9164 
9165     // There is always a chain and a glue type at the end
9166     ValueVTs.push_back(MVT::Other);
9167     ValueVTs.push_back(MVT::Glue);
9168     NodeTys = DAG.getVTList(ValueVTs);
9169   } else
9170     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9171 
9172   // Replace the target specific call node with a PATCHPOINT node.
9173   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9174                                          dl, NodeTys, Ops);
9175 
9176   // Update the NodeMap.
9177   if (HasDef) {
9178     if (IsAnyRegCC)
9179       setValue(&CB, SDValue(MN, 0));
9180     else
9181       setValue(&CB, Result.first);
9182   }
9183 
9184   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9185   // call sequence. Furthermore the location of the chain and glue can change
9186   // when the AnyReg calling convention is used and the intrinsic returns a
9187   // value.
9188   if (IsAnyRegCC && HasDef) {
9189     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9190     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9191     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9192   } else
9193     DAG.ReplaceAllUsesWith(Call, MN);
9194   DAG.DeleteNode(Call);
9195 
9196   // Inform the Frame Information that we have a patchpoint in this function.
9197   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9198 }
9199 
9200 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9201                                             unsigned Intrinsic) {
9202   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9203   SDValue Op1 = getValue(I.getArgOperand(0));
9204   SDValue Op2;
9205   if (I.getNumArgOperands() > 1)
9206     Op2 = getValue(I.getArgOperand(1));
9207   SDLoc dl = getCurSDLoc();
9208   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9209   SDValue Res;
9210   SDNodeFlags SDFlags;
9211   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9212     SDFlags.copyFMF(*FPMO);
9213 
9214   switch (Intrinsic) {
9215   case Intrinsic::vector_reduce_fadd:
9216     if (SDFlags.hasAllowReassociation())
9217       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9218                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9219                         SDFlags);
9220     else
9221       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9222     break;
9223   case Intrinsic::vector_reduce_fmul:
9224     if (SDFlags.hasAllowReassociation())
9225       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9226                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9227                         SDFlags);
9228     else
9229       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9230     break;
9231   case Intrinsic::vector_reduce_add:
9232     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9233     break;
9234   case Intrinsic::vector_reduce_mul:
9235     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9236     break;
9237   case Intrinsic::vector_reduce_and:
9238     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9239     break;
9240   case Intrinsic::vector_reduce_or:
9241     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9242     break;
9243   case Intrinsic::vector_reduce_xor:
9244     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9245     break;
9246   case Intrinsic::vector_reduce_smax:
9247     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9248     break;
9249   case Intrinsic::vector_reduce_smin:
9250     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9251     break;
9252   case Intrinsic::vector_reduce_umax:
9253     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9254     break;
9255   case Intrinsic::vector_reduce_umin:
9256     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9257     break;
9258   case Intrinsic::vector_reduce_fmax:
9259     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9260     break;
9261   case Intrinsic::vector_reduce_fmin:
9262     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9263     break;
9264   default:
9265     llvm_unreachable("Unhandled vector reduce intrinsic");
9266   }
9267   setValue(&I, Res);
9268 }
9269 
9270 /// Returns an AttributeList representing the attributes applied to the return
9271 /// value of the given call.
9272 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9273   SmallVector<Attribute::AttrKind, 2> Attrs;
9274   if (CLI.RetSExt)
9275     Attrs.push_back(Attribute::SExt);
9276   if (CLI.RetZExt)
9277     Attrs.push_back(Attribute::ZExt);
9278   if (CLI.IsInReg)
9279     Attrs.push_back(Attribute::InReg);
9280 
9281   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9282                             Attrs);
9283 }
9284 
9285 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9286 /// implementation, which just calls LowerCall.
9287 /// FIXME: When all targets are
9288 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9289 std::pair<SDValue, SDValue>
9290 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9291   // Handle the incoming return values from the call.
9292   CLI.Ins.clear();
9293   Type *OrigRetTy = CLI.RetTy;
9294   SmallVector<EVT, 4> RetTys;
9295   SmallVector<uint64_t, 4> Offsets;
9296   auto &DL = CLI.DAG.getDataLayout();
9297   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9298 
9299   if (CLI.IsPostTypeLegalization) {
9300     // If we are lowering a libcall after legalization, split the return type.
9301     SmallVector<EVT, 4> OldRetTys;
9302     SmallVector<uint64_t, 4> OldOffsets;
9303     RetTys.swap(OldRetTys);
9304     Offsets.swap(OldOffsets);
9305 
9306     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9307       EVT RetVT = OldRetTys[i];
9308       uint64_t Offset = OldOffsets[i];
9309       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9310       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9311       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9312       RetTys.append(NumRegs, RegisterVT);
9313       for (unsigned j = 0; j != NumRegs; ++j)
9314         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9315     }
9316   }
9317 
9318   SmallVector<ISD::OutputArg, 4> Outs;
9319   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9320 
9321   bool CanLowerReturn =
9322       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9323                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9324 
9325   SDValue DemoteStackSlot;
9326   int DemoteStackIdx = -100;
9327   if (!CanLowerReturn) {
9328     // FIXME: equivalent assert?
9329     // assert(!CS.hasInAllocaArgument() &&
9330     //        "sret demotion is incompatible with inalloca");
9331     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9332     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9333     MachineFunction &MF = CLI.DAG.getMachineFunction();
9334     DemoteStackIdx =
9335         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9336     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9337                                               DL.getAllocaAddrSpace());
9338 
9339     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9340     ArgListEntry Entry;
9341     Entry.Node = DemoteStackSlot;
9342     Entry.Ty = StackSlotPtrType;
9343     Entry.IsSExt = false;
9344     Entry.IsZExt = false;
9345     Entry.IsInReg = false;
9346     Entry.IsSRet = true;
9347     Entry.IsNest = false;
9348     Entry.IsByVal = false;
9349     Entry.IsByRef = false;
9350     Entry.IsReturned = false;
9351     Entry.IsSwiftSelf = false;
9352     Entry.IsSwiftError = false;
9353     Entry.IsCFGuardTarget = false;
9354     Entry.Alignment = Alignment;
9355     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9356     CLI.NumFixedArgs += 1;
9357     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9358 
9359     // sret demotion isn't compatible with tail-calls, since the sret argument
9360     // points into the callers stack frame.
9361     CLI.IsTailCall = false;
9362   } else {
9363     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9364         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9365     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9366       ISD::ArgFlagsTy Flags;
9367       if (NeedsRegBlock) {
9368         Flags.setInConsecutiveRegs();
9369         if (I == RetTys.size() - 1)
9370           Flags.setInConsecutiveRegsLast();
9371       }
9372       EVT VT = RetTys[I];
9373       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9374                                                      CLI.CallConv, VT);
9375       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9376                                                        CLI.CallConv, VT);
9377       for (unsigned i = 0; i != NumRegs; ++i) {
9378         ISD::InputArg MyFlags;
9379         MyFlags.Flags = Flags;
9380         MyFlags.VT = RegisterVT;
9381         MyFlags.ArgVT = VT;
9382         MyFlags.Used = CLI.IsReturnValueUsed;
9383         if (CLI.RetTy->isPointerTy()) {
9384           MyFlags.Flags.setPointer();
9385           MyFlags.Flags.setPointerAddrSpace(
9386               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9387         }
9388         if (CLI.RetSExt)
9389           MyFlags.Flags.setSExt();
9390         if (CLI.RetZExt)
9391           MyFlags.Flags.setZExt();
9392         if (CLI.IsInReg)
9393           MyFlags.Flags.setInReg();
9394         CLI.Ins.push_back(MyFlags);
9395       }
9396     }
9397   }
9398 
9399   // We push in swifterror return as the last element of CLI.Ins.
9400   ArgListTy &Args = CLI.getArgs();
9401   if (supportSwiftError()) {
9402     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9403       if (Args[i].IsSwiftError) {
9404         ISD::InputArg MyFlags;
9405         MyFlags.VT = getPointerTy(DL);
9406         MyFlags.ArgVT = EVT(getPointerTy(DL));
9407         MyFlags.Flags.setSwiftError();
9408         CLI.Ins.push_back(MyFlags);
9409       }
9410     }
9411   }
9412 
9413   // Handle all of the outgoing arguments.
9414   CLI.Outs.clear();
9415   CLI.OutVals.clear();
9416   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9417     SmallVector<EVT, 4> ValueVTs;
9418     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9419     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9420     Type *FinalType = Args[i].Ty;
9421     if (Args[i].IsByVal)
9422       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9423     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9424         FinalType, CLI.CallConv, CLI.IsVarArg);
9425     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9426          ++Value) {
9427       EVT VT = ValueVTs[Value];
9428       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9429       SDValue Op = SDValue(Args[i].Node.getNode(),
9430                            Args[i].Node.getResNo() + Value);
9431       ISD::ArgFlagsTy Flags;
9432 
9433       // Certain targets (such as MIPS), may have a different ABI alignment
9434       // for a type depending on the context. Give the target a chance to
9435       // specify the alignment it wants.
9436       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9437       Flags.setOrigAlign(OriginalAlignment);
9438 
9439       if (Args[i].Ty->isPointerTy()) {
9440         Flags.setPointer();
9441         Flags.setPointerAddrSpace(
9442             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9443       }
9444       if (Args[i].IsZExt)
9445         Flags.setZExt();
9446       if (Args[i].IsSExt)
9447         Flags.setSExt();
9448       if (Args[i].IsInReg) {
9449         // If we are using vectorcall calling convention, a structure that is
9450         // passed InReg - is surely an HVA
9451         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9452             isa<StructType>(FinalType)) {
9453           // The first value of a structure is marked
9454           if (0 == Value)
9455             Flags.setHvaStart();
9456           Flags.setHva();
9457         }
9458         // Set InReg Flag
9459         Flags.setInReg();
9460       }
9461       if (Args[i].IsSRet)
9462         Flags.setSRet();
9463       if (Args[i].IsSwiftSelf)
9464         Flags.setSwiftSelf();
9465       if (Args[i].IsSwiftError)
9466         Flags.setSwiftError();
9467       if (Args[i].IsCFGuardTarget)
9468         Flags.setCFGuardTarget();
9469       if (Args[i].IsByVal)
9470         Flags.setByVal();
9471       if (Args[i].IsByRef)
9472         Flags.setByRef();
9473       if (Args[i].IsPreallocated) {
9474         Flags.setPreallocated();
9475         // Set the byval flag for CCAssignFn callbacks that don't know about
9476         // preallocated.  This way we can know how many bytes we should've
9477         // allocated and how many bytes a callee cleanup function will pop.  If
9478         // we port preallocated to more targets, we'll have to add custom
9479         // preallocated handling in the various CC lowering callbacks.
9480         Flags.setByVal();
9481       }
9482       if (Args[i].IsInAlloca) {
9483         Flags.setInAlloca();
9484         // Set the byval flag for CCAssignFn callbacks that don't know about
9485         // inalloca.  This way we can know how many bytes we should've allocated
9486         // and how many bytes a callee cleanup function will pop.  If we port
9487         // inalloca to more targets, we'll have to add custom inalloca handling
9488         // in the various CC lowering callbacks.
9489         Flags.setByVal();
9490       }
9491       Align MemAlign;
9492       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9493         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9494         Type *ElementTy = Ty->getElementType();
9495 
9496         unsigned FrameSize = DL.getTypeAllocSize(
9497             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9498         Flags.setByValSize(FrameSize);
9499 
9500         // info is not there but there are cases it cannot get right.
9501         if (auto MA = Args[i].Alignment)
9502           MemAlign = *MA;
9503         else
9504           MemAlign = Align(getByValTypeAlignment(ElementTy, DL));
9505       } else if (auto MA = Args[i].Alignment) {
9506         MemAlign = *MA;
9507       } else {
9508         MemAlign = OriginalAlignment;
9509       }
9510       Flags.setMemAlign(MemAlign);
9511       if (Args[i].IsNest)
9512         Flags.setNest();
9513       if (NeedsRegBlock)
9514         Flags.setInConsecutiveRegs();
9515 
9516       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9517                                                  CLI.CallConv, VT);
9518       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9519                                                         CLI.CallConv, VT);
9520       SmallVector<SDValue, 4> Parts(NumParts);
9521       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9522 
9523       if (Args[i].IsSExt)
9524         ExtendKind = ISD::SIGN_EXTEND;
9525       else if (Args[i].IsZExt)
9526         ExtendKind = ISD::ZERO_EXTEND;
9527 
9528       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9529       // for now.
9530       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9531           CanLowerReturn) {
9532         assert((CLI.RetTy == Args[i].Ty ||
9533                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9534                  CLI.RetTy->getPointerAddressSpace() ==
9535                      Args[i].Ty->getPointerAddressSpace())) &&
9536                RetTys.size() == NumValues && "unexpected use of 'returned'");
9537         // Before passing 'returned' to the target lowering code, ensure that
9538         // either the register MVT and the actual EVT are the same size or that
9539         // the return value and argument are extended in the same way; in these
9540         // cases it's safe to pass the argument register value unchanged as the
9541         // return register value (although it's at the target's option whether
9542         // to do so)
9543         // TODO: allow code generation to take advantage of partially preserved
9544         // registers rather than clobbering the entire register when the
9545         // parameter extension method is not compatible with the return
9546         // extension method
9547         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9548             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9549              CLI.RetZExt == Args[i].IsZExt))
9550           Flags.setReturned();
9551       }
9552 
9553       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9554                      CLI.CallConv, ExtendKind);
9555 
9556       for (unsigned j = 0; j != NumParts; ++j) {
9557         // if it isn't first piece, alignment must be 1
9558         // For scalable vectors the scalable part is currently handled
9559         // by individual targets, so we just use the known minimum size here.
9560         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9561                     i < CLI.NumFixedArgs, i,
9562                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9563         if (NumParts > 1 && j == 0)
9564           MyFlags.Flags.setSplit();
9565         else if (j != 0) {
9566           MyFlags.Flags.setOrigAlign(Align(1));
9567           if (j == NumParts - 1)
9568             MyFlags.Flags.setSplitEnd();
9569         }
9570 
9571         CLI.Outs.push_back(MyFlags);
9572         CLI.OutVals.push_back(Parts[j]);
9573       }
9574 
9575       if (NeedsRegBlock && Value == NumValues - 1)
9576         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9577     }
9578   }
9579 
9580   SmallVector<SDValue, 4> InVals;
9581   CLI.Chain = LowerCall(CLI, InVals);
9582 
9583   // Update CLI.InVals to use outside of this function.
9584   CLI.InVals = InVals;
9585 
9586   // Verify that the target's LowerCall behaved as expected.
9587   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9588          "LowerCall didn't return a valid chain!");
9589   assert((!CLI.IsTailCall || InVals.empty()) &&
9590          "LowerCall emitted a return value for a tail call!");
9591   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9592          "LowerCall didn't emit the correct number of values!");
9593 
9594   // For a tail call, the return value is merely live-out and there aren't
9595   // any nodes in the DAG representing it. Return a special value to
9596   // indicate that a tail call has been emitted and no more Instructions
9597   // should be processed in the current block.
9598   if (CLI.IsTailCall) {
9599     CLI.DAG.setRoot(CLI.Chain);
9600     return std::make_pair(SDValue(), SDValue());
9601   }
9602 
9603 #ifndef NDEBUG
9604   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9605     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9606     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9607            "LowerCall emitted a value with the wrong type!");
9608   }
9609 #endif
9610 
9611   SmallVector<SDValue, 4> ReturnValues;
9612   if (!CanLowerReturn) {
9613     // The instruction result is the result of loading from the
9614     // hidden sret parameter.
9615     SmallVector<EVT, 1> PVTs;
9616     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9617 
9618     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9619     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9620     EVT PtrVT = PVTs[0];
9621 
9622     unsigned NumValues = RetTys.size();
9623     ReturnValues.resize(NumValues);
9624     SmallVector<SDValue, 4> Chains(NumValues);
9625 
9626     // An aggregate return value cannot wrap around the address space, so
9627     // offsets to its parts don't wrap either.
9628     SDNodeFlags Flags;
9629     Flags.setNoUnsignedWrap(true);
9630 
9631     MachineFunction &MF = CLI.DAG.getMachineFunction();
9632     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9633     for (unsigned i = 0; i < NumValues; ++i) {
9634       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9635                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9636                                                         PtrVT), Flags);
9637       SDValue L = CLI.DAG.getLoad(
9638           RetTys[i], CLI.DL, CLI.Chain, Add,
9639           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9640                                             DemoteStackIdx, Offsets[i]),
9641           HiddenSRetAlign);
9642       ReturnValues[i] = L;
9643       Chains[i] = L.getValue(1);
9644     }
9645 
9646     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9647   } else {
9648     // Collect the legal value parts into potentially illegal values
9649     // that correspond to the original function's return values.
9650     Optional<ISD::NodeType> AssertOp;
9651     if (CLI.RetSExt)
9652       AssertOp = ISD::AssertSext;
9653     else if (CLI.RetZExt)
9654       AssertOp = ISD::AssertZext;
9655     unsigned CurReg = 0;
9656     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9657       EVT VT = RetTys[I];
9658       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9659                                                      CLI.CallConv, VT);
9660       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9661                                                        CLI.CallConv, VT);
9662 
9663       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9664                                               NumRegs, RegisterVT, VT, nullptr,
9665                                               CLI.CallConv, AssertOp));
9666       CurReg += NumRegs;
9667     }
9668 
9669     // For a function returning void, there is no return value. We can't create
9670     // such a node, so we just return a null return value in that case. In
9671     // that case, nothing will actually look at the value.
9672     if (ReturnValues.empty())
9673       return std::make_pair(SDValue(), CLI.Chain);
9674   }
9675 
9676   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9677                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9678   return std::make_pair(Res, CLI.Chain);
9679 }
9680 
9681 /// Places new result values for the node in Results (their number
9682 /// and types must exactly match those of the original return values of
9683 /// the node), or leaves Results empty, which indicates that the node is not
9684 /// to be custom lowered after all.
9685 void TargetLowering::LowerOperationWrapper(SDNode *N,
9686                                            SmallVectorImpl<SDValue> &Results,
9687                                            SelectionDAG &DAG) const {
9688   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9689 
9690   if (!Res.getNode())
9691     return;
9692 
9693   // If the original node has one result, take the return value from
9694   // LowerOperation as is. It might not be result number 0.
9695   if (N->getNumValues() == 1) {
9696     Results.push_back(Res);
9697     return;
9698   }
9699 
9700   // If the original node has multiple results, then the return node should
9701   // have the same number of results.
9702   assert((N->getNumValues() == Res->getNumValues()) &&
9703       "Lowering returned the wrong number of results!");
9704 
9705   // Places new result values base on N result number.
9706   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9707     Results.push_back(Res.getValue(I));
9708 }
9709 
9710 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9711   llvm_unreachable("LowerOperation not implemented for this target!");
9712 }
9713 
9714 void
9715 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9716   SDValue Op = getNonRegisterValue(V);
9717   assert((Op.getOpcode() != ISD::CopyFromReg ||
9718           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9719          "Copy from a reg to the same reg!");
9720   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9721 
9722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9723   // If this is an InlineAsm we have to match the registers required, not the
9724   // notional registers required by the type.
9725 
9726   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9727                    None); // This is not an ABI copy.
9728   SDValue Chain = DAG.getEntryNode();
9729 
9730   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9731                               FuncInfo.PreferredExtendType.end())
9732                                  ? ISD::ANY_EXTEND
9733                                  : FuncInfo.PreferredExtendType[V];
9734   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9735   PendingExports.push_back(Chain);
9736 }
9737 
9738 #include "llvm/CodeGen/SelectionDAGISel.h"
9739 
9740 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9741 /// entry block, return true.  This includes arguments used by switches, since
9742 /// the switch may expand into multiple basic blocks.
9743 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9744   // With FastISel active, we may be splitting blocks, so force creation
9745   // of virtual registers for all non-dead arguments.
9746   if (FastISel)
9747     return A->use_empty();
9748 
9749   const BasicBlock &Entry = A->getParent()->front();
9750   for (const User *U : A->users())
9751     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9752       return false;  // Use not in entry block.
9753 
9754   return true;
9755 }
9756 
9757 using ArgCopyElisionMapTy =
9758     DenseMap<const Argument *,
9759              std::pair<const AllocaInst *, const StoreInst *>>;
9760 
9761 /// Scan the entry block of the function in FuncInfo for arguments that look
9762 /// like copies into a local alloca. Record any copied arguments in
9763 /// ArgCopyElisionCandidates.
9764 static void
9765 findArgumentCopyElisionCandidates(const DataLayout &DL,
9766                                   FunctionLoweringInfo *FuncInfo,
9767                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9768   // Record the state of every static alloca used in the entry block. Argument
9769   // allocas are all used in the entry block, so we need approximately as many
9770   // entries as we have arguments.
9771   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9772   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9773   unsigned NumArgs = FuncInfo->Fn->arg_size();
9774   StaticAllocas.reserve(NumArgs * 2);
9775 
9776   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9777     if (!V)
9778       return nullptr;
9779     V = V->stripPointerCasts();
9780     const auto *AI = dyn_cast<AllocaInst>(V);
9781     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9782       return nullptr;
9783     auto Iter = StaticAllocas.insert({AI, Unknown});
9784     return &Iter.first->second;
9785   };
9786 
9787   // Look for stores of arguments to static allocas. Look through bitcasts and
9788   // GEPs to handle type coercions, as long as the alloca is fully initialized
9789   // by the store. Any non-store use of an alloca escapes it and any subsequent
9790   // unanalyzed store might write it.
9791   // FIXME: Handle structs initialized with multiple stores.
9792   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9793     // Look for stores, and handle non-store uses conservatively.
9794     const auto *SI = dyn_cast<StoreInst>(&I);
9795     if (!SI) {
9796       // We will look through cast uses, so ignore them completely.
9797       if (I.isCast())
9798         continue;
9799       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9800       // to allocas.
9801       if (I.isDebugOrPseudoInst())
9802         continue;
9803       // This is an unknown instruction. Assume it escapes or writes to all
9804       // static alloca operands.
9805       for (const Use &U : I.operands()) {
9806         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9807           *Info = StaticAllocaInfo::Clobbered;
9808       }
9809       continue;
9810     }
9811 
9812     // If the stored value is a static alloca, mark it as escaped.
9813     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9814       *Info = StaticAllocaInfo::Clobbered;
9815 
9816     // Check if the destination is a static alloca.
9817     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9818     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9819     if (!Info)
9820       continue;
9821     const AllocaInst *AI = cast<AllocaInst>(Dst);
9822 
9823     // Skip allocas that have been initialized or clobbered.
9824     if (*Info != StaticAllocaInfo::Unknown)
9825       continue;
9826 
9827     // Check if the stored value is an argument, and that this store fully
9828     // initializes the alloca. Don't elide copies from the same argument twice.
9829     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9830     const auto *Arg = dyn_cast<Argument>(Val);
9831     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9832         Arg->getType()->isEmptyTy() ||
9833         DL.getTypeStoreSize(Arg->getType()) !=
9834             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9835         ArgCopyElisionCandidates.count(Arg)) {
9836       *Info = StaticAllocaInfo::Clobbered;
9837       continue;
9838     }
9839 
9840     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9841                       << '\n');
9842 
9843     // Mark this alloca and store for argument copy elision.
9844     *Info = StaticAllocaInfo::Elidable;
9845     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9846 
9847     // Stop scanning if we've seen all arguments. This will happen early in -O0
9848     // builds, which is useful, because -O0 builds have large entry blocks and
9849     // many allocas.
9850     if (ArgCopyElisionCandidates.size() == NumArgs)
9851       break;
9852   }
9853 }
9854 
9855 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9856 /// ArgVal is a load from a suitable fixed stack object.
9857 static void tryToElideArgumentCopy(
9858     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9859     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9860     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9861     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9862     SDValue ArgVal, bool &ArgHasUses) {
9863   // Check if this is a load from a fixed stack object.
9864   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9865   if (!LNode)
9866     return;
9867   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9868   if (!FINode)
9869     return;
9870 
9871   // Check that the fixed stack object is the right size and alignment.
9872   // Look at the alignment that the user wrote on the alloca instead of looking
9873   // at the stack object.
9874   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9875   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9876   const AllocaInst *AI = ArgCopyIter->second.first;
9877   int FixedIndex = FINode->getIndex();
9878   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9879   int OldIndex = AllocaIndex;
9880   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9881   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9882     LLVM_DEBUG(
9883         dbgs() << "  argument copy elision failed due to bad fixed stack "
9884                   "object size\n");
9885     return;
9886   }
9887   Align RequiredAlignment = AI->getAlign();
9888   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9889     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9890                          "greater than stack argument alignment ("
9891                       << DebugStr(RequiredAlignment) << " vs "
9892                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9893     return;
9894   }
9895 
9896   // Perform the elision. Delete the old stack object and replace its only use
9897   // in the variable info map. Mark the stack object as mutable.
9898   LLVM_DEBUG({
9899     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9900            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9901            << '\n';
9902   });
9903   MFI.RemoveStackObject(OldIndex);
9904   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9905   AllocaIndex = FixedIndex;
9906   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9907   Chains.push_back(ArgVal.getValue(1));
9908 
9909   // Avoid emitting code for the store implementing the copy.
9910   const StoreInst *SI = ArgCopyIter->second.second;
9911   ElidedArgCopyInstrs.insert(SI);
9912 
9913   // Check for uses of the argument again so that we can avoid exporting ArgVal
9914   // if it is't used by anything other than the store.
9915   for (const Value *U : Arg.users()) {
9916     if (U != SI) {
9917       ArgHasUses = true;
9918       break;
9919     }
9920   }
9921 }
9922 
9923 void SelectionDAGISel::LowerArguments(const Function &F) {
9924   SelectionDAG &DAG = SDB->DAG;
9925   SDLoc dl = SDB->getCurSDLoc();
9926   const DataLayout &DL = DAG.getDataLayout();
9927   SmallVector<ISD::InputArg, 16> Ins;
9928 
9929   // In Naked functions we aren't going to save any registers.
9930   if (F.hasFnAttribute(Attribute::Naked))
9931     return;
9932 
9933   if (!FuncInfo->CanLowerReturn) {
9934     // Put in an sret pointer parameter before all the other parameters.
9935     SmallVector<EVT, 1> ValueVTs;
9936     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9937                     F.getReturnType()->getPointerTo(
9938                         DAG.getDataLayout().getAllocaAddrSpace()),
9939                     ValueVTs);
9940 
9941     // NOTE: Assuming that a pointer will never break down to more than one VT
9942     // or one register.
9943     ISD::ArgFlagsTy Flags;
9944     Flags.setSRet();
9945     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9946     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9947                          ISD::InputArg::NoArgIndex, 0);
9948     Ins.push_back(RetArg);
9949   }
9950 
9951   // Look for stores of arguments to static allocas. Mark such arguments with a
9952   // flag to ask the target to give us the memory location of that argument if
9953   // available.
9954   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9955   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9956                                     ArgCopyElisionCandidates);
9957 
9958   // Set up the incoming argument description vector.
9959   for (const Argument &Arg : F.args()) {
9960     unsigned ArgNo = Arg.getArgNo();
9961     SmallVector<EVT, 4> ValueVTs;
9962     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9963     bool isArgValueUsed = !Arg.use_empty();
9964     unsigned PartBase = 0;
9965     Type *FinalType = Arg.getType();
9966     if (Arg.hasAttribute(Attribute::ByVal))
9967       FinalType = Arg.getParamByValType();
9968     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9969         FinalType, F.getCallingConv(), F.isVarArg());
9970     for (unsigned Value = 0, NumValues = ValueVTs.size();
9971          Value != NumValues; ++Value) {
9972       EVT VT = ValueVTs[Value];
9973       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9974       ISD::ArgFlagsTy Flags;
9975 
9976 
9977       if (Arg.getType()->isPointerTy()) {
9978         Flags.setPointer();
9979         Flags.setPointerAddrSpace(
9980             cast<PointerType>(Arg.getType())->getAddressSpace());
9981       }
9982       if (Arg.hasAttribute(Attribute::ZExt))
9983         Flags.setZExt();
9984       if (Arg.hasAttribute(Attribute::SExt))
9985         Flags.setSExt();
9986       if (Arg.hasAttribute(Attribute::InReg)) {
9987         // If we are using vectorcall calling convention, a structure that is
9988         // passed InReg - is surely an HVA
9989         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9990             isa<StructType>(Arg.getType())) {
9991           // The first value of a structure is marked
9992           if (0 == Value)
9993             Flags.setHvaStart();
9994           Flags.setHva();
9995         }
9996         // Set InReg Flag
9997         Flags.setInReg();
9998       }
9999       if (Arg.hasAttribute(Attribute::StructRet))
10000         Flags.setSRet();
10001       if (Arg.hasAttribute(Attribute::SwiftSelf))
10002         Flags.setSwiftSelf();
10003       if (Arg.hasAttribute(Attribute::SwiftError))
10004         Flags.setSwiftError();
10005       if (Arg.hasAttribute(Attribute::ByVal))
10006         Flags.setByVal();
10007       if (Arg.hasAttribute(Attribute::ByRef))
10008         Flags.setByRef();
10009       if (Arg.hasAttribute(Attribute::InAlloca)) {
10010         Flags.setInAlloca();
10011         // Set the byval flag for CCAssignFn callbacks that don't know about
10012         // inalloca.  This way we can know how many bytes we should've allocated
10013         // and how many bytes a callee cleanup function will pop.  If we port
10014         // inalloca to more targets, we'll have to add custom inalloca handling
10015         // in the various CC lowering callbacks.
10016         Flags.setByVal();
10017       }
10018       if (Arg.hasAttribute(Attribute::Preallocated)) {
10019         Flags.setPreallocated();
10020         // Set the byval flag for CCAssignFn callbacks that don't know about
10021         // preallocated.  This way we can know how many bytes we should've
10022         // allocated and how many bytes a callee cleanup function will pop.  If
10023         // we port preallocated to more targets, we'll have to add custom
10024         // preallocated handling in the various CC lowering callbacks.
10025         Flags.setByVal();
10026       }
10027 
10028       // Certain targets (such as MIPS), may have a different ABI alignment
10029       // for a type depending on the context. Give the target a chance to
10030       // specify the alignment it wants.
10031       const Align OriginalAlignment(
10032           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10033       Flags.setOrigAlign(OriginalAlignment);
10034 
10035       Align MemAlign;
10036       Type *ArgMemTy = nullptr;
10037       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10038           Flags.isByRef()) {
10039         if (!ArgMemTy)
10040           ArgMemTy = Arg.getPointeeInMemoryValueType();
10041 
10042         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10043 
10044         // For in-memory arguments, size and alignment should be passed from FE.
10045         // BE will guess if this info is not there but there are cases it cannot
10046         // get right.
10047         if (auto ParamAlign = Arg.getParamStackAlign())
10048           MemAlign = *ParamAlign;
10049         else if ((ParamAlign = Arg.getParamAlign()))
10050           MemAlign = *ParamAlign;
10051         else
10052           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10053         if (Flags.isByRef())
10054           Flags.setByRefSize(MemSize);
10055         else
10056           Flags.setByValSize(MemSize);
10057       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10058         MemAlign = *ParamAlign;
10059       } else {
10060         MemAlign = OriginalAlignment;
10061       }
10062       Flags.setMemAlign(MemAlign);
10063 
10064       if (Arg.hasAttribute(Attribute::Nest))
10065         Flags.setNest();
10066       if (NeedsRegBlock)
10067         Flags.setInConsecutiveRegs();
10068       if (ArgCopyElisionCandidates.count(&Arg))
10069         Flags.setCopyElisionCandidate();
10070       if (Arg.hasAttribute(Attribute::Returned))
10071         Flags.setReturned();
10072 
10073       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10074           *CurDAG->getContext(), F.getCallingConv(), VT);
10075       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10076           *CurDAG->getContext(), F.getCallingConv(), VT);
10077       for (unsigned i = 0; i != NumRegs; ++i) {
10078         // For scalable vectors, use the minimum size; individual targets
10079         // are responsible for handling scalable vector arguments and
10080         // return values.
10081         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10082                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10083         if (NumRegs > 1 && i == 0)
10084           MyFlags.Flags.setSplit();
10085         // if it isn't first piece, alignment must be 1
10086         else if (i > 0) {
10087           MyFlags.Flags.setOrigAlign(Align(1));
10088           if (i == NumRegs - 1)
10089             MyFlags.Flags.setSplitEnd();
10090         }
10091         Ins.push_back(MyFlags);
10092       }
10093       if (NeedsRegBlock && Value == NumValues - 1)
10094         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10095       PartBase += VT.getStoreSize().getKnownMinSize();
10096     }
10097   }
10098 
10099   // Call the target to set up the argument values.
10100   SmallVector<SDValue, 8> InVals;
10101   SDValue NewRoot = TLI->LowerFormalArguments(
10102       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10103 
10104   // Verify that the target's LowerFormalArguments behaved as expected.
10105   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10106          "LowerFormalArguments didn't return a valid chain!");
10107   assert(InVals.size() == Ins.size() &&
10108          "LowerFormalArguments didn't emit the correct number of values!");
10109   LLVM_DEBUG({
10110     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10111       assert(InVals[i].getNode() &&
10112              "LowerFormalArguments emitted a null value!");
10113       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10114              "LowerFormalArguments emitted a value with the wrong type!");
10115     }
10116   });
10117 
10118   // Update the DAG with the new chain value resulting from argument lowering.
10119   DAG.setRoot(NewRoot);
10120 
10121   // Set up the argument values.
10122   unsigned i = 0;
10123   if (!FuncInfo->CanLowerReturn) {
10124     // Create a virtual register for the sret pointer, and put in a copy
10125     // from the sret argument into it.
10126     SmallVector<EVT, 1> ValueVTs;
10127     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10128                     F.getReturnType()->getPointerTo(
10129                         DAG.getDataLayout().getAllocaAddrSpace()),
10130                     ValueVTs);
10131     MVT VT = ValueVTs[0].getSimpleVT();
10132     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10133     Optional<ISD::NodeType> AssertOp = None;
10134     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10135                                         nullptr, F.getCallingConv(), AssertOp);
10136 
10137     MachineFunction& MF = SDB->DAG.getMachineFunction();
10138     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10139     Register SRetReg =
10140         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10141     FuncInfo->DemoteRegister = SRetReg;
10142     NewRoot =
10143         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10144     DAG.setRoot(NewRoot);
10145 
10146     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10147     ++i;
10148   }
10149 
10150   SmallVector<SDValue, 4> Chains;
10151   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10152   for (const Argument &Arg : F.args()) {
10153     SmallVector<SDValue, 4> ArgValues;
10154     SmallVector<EVT, 4> ValueVTs;
10155     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10156     unsigned NumValues = ValueVTs.size();
10157     if (NumValues == 0)
10158       continue;
10159 
10160     bool ArgHasUses = !Arg.use_empty();
10161 
10162     // Elide the copying store if the target loaded this argument from a
10163     // suitable fixed stack object.
10164     if (Ins[i].Flags.isCopyElisionCandidate()) {
10165       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10166                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10167                              InVals[i], ArgHasUses);
10168     }
10169 
10170     // If this argument is unused then remember its value. It is used to generate
10171     // debugging information.
10172     bool isSwiftErrorArg =
10173         TLI->supportSwiftError() &&
10174         Arg.hasAttribute(Attribute::SwiftError);
10175     if (!ArgHasUses && !isSwiftErrorArg) {
10176       SDB->setUnusedArgValue(&Arg, InVals[i]);
10177 
10178       // Also remember any frame index for use in FastISel.
10179       if (FrameIndexSDNode *FI =
10180           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10181         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10182     }
10183 
10184     for (unsigned Val = 0; Val != NumValues; ++Val) {
10185       EVT VT = ValueVTs[Val];
10186       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10187                                                       F.getCallingConv(), VT);
10188       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10189           *CurDAG->getContext(), F.getCallingConv(), VT);
10190 
10191       // Even an apparent 'unused' swifterror argument needs to be returned. So
10192       // we do generate a copy for it that can be used on return from the
10193       // function.
10194       if (ArgHasUses || isSwiftErrorArg) {
10195         Optional<ISD::NodeType> AssertOp;
10196         if (Arg.hasAttribute(Attribute::SExt))
10197           AssertOp = ISD::AssertSext;
10198         else if (Arg.hasAttribute(Attribute::ZExt))
10199           AssertOp = ISD::AssertZext;
10200 
10201         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10202                                              PartVT, VT, nullptr,
10203                                              F.getCallingConv(), AssertOp));
10204       }
10205 
10206       i += NumParts;
10207     }
10208 
10209     // We don't need to do anything else for unused arguments.
10210     if (ArgValues.empty())
10211       continue;
10212 
10213     // Note down frame index.
10214     if (FrameIndexSDNode *FI =
10215         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10216       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10217 
10218     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10219                                      SDB->getCurSDLoc());
10220 
10221     SDB->setValue(&Arg, Res);
10222     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10223       // We want to associate the argument with the frame index, among
10224       // involved operands, that correspond to the lowest address. The
10225       // getCopyFromParts function, called earlier, is swapping the order of
10226       // the operands to BUILD_PAIR depending on endianness. The result of
10227       // that swapping is that the least significant bits of the argument will
10228       // be in the first operand of the BUILD_PAIR node, and the most
10229       // significant bits will be in the second operand.
10230       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10231       if (LoadSDNode *LNode =
10232           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10233         if (FrameIndexSDNode *FI =
10234             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10235           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10236     }
10237 
10238     // Analyses past this point are naive and don't expect an assertion.
10239     if (Res.getOpcode() == ISD::AssertZext)
10240       Res = Res.getOperand(0);
10241 
10242     // Update the SwiftErrorVRegDefMap.
10243     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10244       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10245       if (Register::isVirtualRegister(Reg))
10246         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10247                                    Reg);
10248     }
10249 
10250     // If this argument is live outside of the entry block, insert a copy from
10251     // wherever we got it to the vreg that other BB's will reference it as.
10252     if (Res.getOpcode() == ISD::CopyFromReg) {
10253       // If we can, though, try to skip creating an unnecessary vreg.
10254       // FIXME: This isn't very clean... it would be nice to make this more
10255       // general.
10256       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10257       if (Register::isVirtualRegister(Reg)) {
10258         FuncInfo->ValueMap[&Arg] = Reg;
10259         continue;
10260       }
10261     }
10262     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10263       FuncInfo->InitializeRegForValue(&Arg);
10264       SDB->CopyToExportRegsIfNeeded(&Arg);
10265     }
10266   }
10267 
10268   if (!Chains.empty()) {
10269     Chains.push_back(NewRoot);
10270     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10271   }
10272 
10273   DAG.setRoot(NewRoot);
10274 
10275   assert(i == InVals.size() && "Argument register count mismatch!");
10276 
10277   // If any argument copy elisions occurred and we have debug info, update the
10278   // stale frame indices used in the dbg.declare variable info table.
10279   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10280   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10281     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10282       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10283       if (I != ArgCopyElisionFrameIndexMap.end())
10284         VI.Slot = I->second;
10285     }
10286   }
10287 
10288   // Finally, if the target has anything special to do, allow it to do so.
10289   emitFunctionEntryCode();
10290 }
10291 
10292 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10293 /// ensure constants are generated when needed.  Remember the virtual registers
10294 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10295 /// directly add them, because expansion might result in multiple MBB's for one
10296 /// BB.  As such, the start of the BB might correspond to a different MBB than
10297 /// the end.
10298 void
10299 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10300   const Instruction *TI = LLVMBB->getTerminator();
10301 
10302   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10303 
10304   // Check PHI nodes in successors that expect a value to be available from this
10305   // block.
10306   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10307     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10308     if (!isa<PHINode>(SuccBB->begin())) continue;
10309     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10310 
10311     // If this terminator has multiple identical successors (common for
10312     // switches), only handle each succ once.
10313     if (!SuccsHandled.insert(SuccMBB).second)
10314       continue;
10315 
10316     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10317 
10318     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10319     // nodes and Machine PHI nodes, but the incoming operands have not been
10320     // emitted yet.
10321     for (const PHINode &PN : SuccBB->phis()) {
10322       // Ignore dead phi's.
10323       if (PN.use_empty())
10324         continue;
10325 
10326       // Skip empty types
10327       if (PN.getType()->isEmptyTy())
10328         continue;
10329 
10330       unsigned Reg;
10331       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10332 
10333       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10334         unsigned &RegOut = ConstantsOut[C];
10335         if (RegOut == 0) {
10336           RegOut = FuncInfo.CreateRegs(C);
10337           CopyValueToVirtualRegister(C, RegOut);
10338         }
10339         Reg = RegOut;
10340       } else {
10341         DenseMap<const Value *, Register>::iterator I =
10342           FuncInfo.ValueMap.find(PHIOp);
10343         if (I != FuncInfo.ValueMap.end())
10344           Reg = I->second;
10345         else {
10346           assert(isa<AllocaInst>(PHIOp) &&
10347                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10348                  "Didn't codegen value into a register!??");
10349           Reg = FuncInfo.CreateRegs(PHIOp);
10350           CopyValueToVirtualRegister(PHIOp, Reg);
10351         }
10352       }
10353 
10354       // Remember that this register needs to added to the machine PHI node as
10355       // the input for this MBB.
10356       SmallVector<EVT, 4> ValueVTs;
10357       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10358       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10359       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10360         EVT VT = ValueVTs[vti];
10361         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10362         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10363           FuncInfo.PHINodesToUpdate.push_back(
10364               std::make_pair(&*MBBI++, Reg + i));
10365         Reg += NumRegisters;
10366       }
10367     }
10368   }
10369 
10370   ConstantsOut.clear();
10371 }
10372 
10373 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10374 /// is 0.
10375 MachineBasicBlock *
10376 SelectionDAGBuilder::StackProtectorDescriptor::
10377 AddSuccessorMBB(const BasicBlock *BB,
10378                 MachineBasicBlock *ParentMBB,
10379                 bool IsLikely,
10380                 MachineBasicBlock *SuccMBB) {
10381   // If SuccBB has not been created yet, create it.
10382   if (!SuccMBB) {
10383     MachineFunction *MF = ParentMBB->getParent();
10384     MachineFunction::iterator BBI(ParentMBB);
10385     SuccMBB = MF->CreateMachineBasicBlock(BB);
10386     MF->insert(++BBI, SuccMBB);
10387   }
10388   // Add it as a successor of ParentMBB.
10389   ParentMBB->addSuccessor(
10390       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10391   return SuccMBB;
10392 }
10393 
10394 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10395   MachineFunction::iterator I(MBB);
10396   if (++I == FuncInfo.MF->end())
10397     return nullptr;
10398   return &*I;
10399 }
10400 
10401 /// During lowering new call nodes can be created (such as memset, etc.).
10402 /// Those will become new roots of the current DAG, but complications arise
10403 /// when they are tail calls. In such cases, the call lowering will update
10404 /// the root, but the builder still needs to know that a tail call has been
10405 /// lowered in order to avoid generating an additional return.
10406 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10407   // If the node is null, we do have a tail call.
10408   if (MaybeTC.getNode() != nullptr)
10409     DAG.setRoot(MaybeTC);
10410   else
10411     HasTailCall = true;
10412 }
10413 
10414 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10415                                         MachineBasicBlock *SwitchMBB,
10416                                         MachineBasicBlock *DefaultMBB) {
10417   MachineFunction *CurMF = FuncInfo.MF;
10418   MachineBasicBlock *NextMBB = nullptr;
10419   MachineFunction::iterator BBI(W.MBB);
10420   if (++BBI != FuncInfo.MF->end())
10421     NextMBB = &*BBI;
10422 
10423   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10424 
10425   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10426 
10427   if (Size == 2 && W.MBB == SwitchMBB) {
10428     // If any two of the cases has the same destination, and if one value
10429     // is the same as the other, but has one bit unset that the other has set,
10430     // use bit manipulation to do two compares at once.  For example:
10431     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10432     // TODO: This could be extended to merge any 2 cases in switches with 3
10433     // cases.
10434     // TODO: Handle cases where W.CaseBB != SwitchBB.
10435     CaseCluster &Small = *W.FirstCluster;
10436     CaseCluster &Big = *W.LastCluster;
10437 
10438     if (Small.Low == Small.High && Big.Low == Big.High &&
10439         Small.MBB == Big.MBB) {
10440       const APInt &SmallValue = Small.Low->getValue();
10441       const APInt &BigValue = Big.Low->getValue();
10442 
10443       // Check that there is only one bit different.
10444       APInt CommonBit = BigValue ^ SmallValue;
10445       if (CommonBit.isPowerOf2()) {
10446         SDValue CondLHS = getValue(Cond);
10447         EVT VT = CondLHS.getValueType();
10448         SDLoc DL = getCurSDLoc();
10449 
10450         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10451                                  DAG.getConstant(CommonBit, DL, VT));
10452         SDValue Cond = DAG.getSetCC(
10453             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10454             ISD::SETEQ);
10455 
10456         // Update successor info.
10457         // Both Small and Big will jump to Small.BB, so we sum up the
10458         // probabilities.
10459         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10460         if (BPI)
10461           addSuccessorWithProb(
10462               SwitchMBB, DefaultMBB,
10463               // The default destination is the first successor in IR.
10464               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10465         else
10466           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10467 
10468         // Insert the true branch.
10469         SDValue BrCond =
10470             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10471                         DAG.getBasicBlock(Small.MBB));
10472         // Insert the false branch.
10473         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10474                              DAG.getBasicBlock(DefaultMBB));
10475 
10476         DAG.setRoot(BrCond);
10477         return;
10478       }
10479     }
10480   }
10481 
10482   if (TM.getOptLevel() != CodeGenOpt::None) {
10483     // Here, we order cases by probability so the most likely case will be
10484     // checked first. However, two clusters can have the same probability in
10485     // which case their relative ordering is non-deterministic. So we use Low
10486     // as a tie-breaker as clusters are guaranteed to never overlap.
10487     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10488                [](const CaseCluster &a, const CaseCluster &b) {
10489       return a.Prob != b.Prob ?
10490              a.Prob > b.Prob :
10491              a.Low->getValue().slt(b.Low->getValue());
10492     });
10493 
10494     // Rearrange the case blocks so that the last one falls through if possible
10495     // without changing the order of probabilities.
10496     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10497       --I;
10498       if (I->Prob > W.LastCluster->Prob)
10499         break;
10500       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10501         std::swap(*I, *W.LastCluster);
10502         break;
10503       }
10504     }
10505   }
10506 
10507   // Compute total probability.
10508   BranchProbability DefaultProb = W.DefaultProb;
10509   BranchProbability UnhandledProbs = DefaultProb;
10510   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10511     UnhandledProbs += I->Prob;
10512 
10513   MachineBasicBlock *CurMBB = W.MBB;
10514   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10515     bool FallthroughUnreachable = false;
10516     MachineBasicBlock *Fallthrough;
10517     if (I == W.LastCluster) {
10518       // For the last cluster, fall through to the default destination.
10519       Fallthrough = DefaultMBB;
10520       FallthroughUnreachable = isa<UnreachableInst>(
10521           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10522     } else {
10523       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10524       CurMF->insert(BBI, Fallthrough);
10525       // Put Cond in a virtual register to make it available from the new blocks.
10526       ExportFromCurrentBlock(Cond);
10527     }
10528     UnhandledProbs -= I->Prob;
10529 
10530     switch (I->Kind) {
10531       case CC_JumpTable: {
10532         // FIXME: Optimize away range check based on pivot comparisons.
10533         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10534         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10535 
10536         // The jump block hasn't been inserted yet; insert it here.
10537         MachineBasicBlock *JumpMBB = JT->MBB;
10538         CurMF->insert(BBI, JumpMBB);
10539 
10540         auto JumpProb = I->Prob;
10541         auto FallthroughProb = UnhandledProbs;
10542 
10543         // If the default statement is a target of the jump table, we evenly
10544         // distribute the default probability to successors of CurMBB. Also
10545         // update the probability on the edge from JumpMBB to Fallthrough.
10546         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10547                                               SE = JumpMBB->succ_end();
10548              SI != SE; ++SI) {
10549           if (*SI == DefaultMBB) {
10550             JumpProb += DefaultProb / 2;
10551             FallthroughProb -= DefaultProb / 2;
10552             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10553             JumpMBB->normalizeSuccProbs();
10554             break;
10555           }
10556         }
10557 
10558         if (FallthroughUnreachable) {
10559           // Skip the range check if the fallthrough block is unreachable.
10560           JTH->OmitRangeCheck = true;
10561         }
10562 
10563         if (!JTH->OmitRangeCheck)
10564           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10565         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10566         CurMBB->normalizeSuccProbs();
10567 
10568         // The jump table header will be inserted in our current block, do the
10569         // range check, and fall through to our fallthrough block.
10570         JTH->HeaderBB = CurMBB;
10571         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10572 
10573         // If we're in the right place, emit the jump table header right now.
10574         if (CurMBB == SwitchMBB) {
10575           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10576           JTH->Emitted = true;
10577         }
10578         break;
10579       }
10580       case CC_BitTests: {
10581         // FIXME: Optimize away range check based on pivot comparisons.
10582         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10583 
10584         // The bit test blocks haven't been inserted yet; insert them here.
10585         for (BitTestCase &BTC : BTB->Cases)
10586           CurMF->insert(BBI, BTC.ThisBB);
10587 
10588         // Fill in fields of the BitTestBlock.
10589         BTB->Parent = CurMBB;
10590         BTB->Default = Fallthrough;
10591 
10592         BTB->DefaultProb = UnhandledProbs;
10593         // If the cases in bit test don't form a contiguous range, we evenly
10594         // distribute the probability on the edge to Fallthrough to two
10595         // successors of CurMBB.
10596         if (!BTB->ContiguousRange) {
10597           BTB->Prob += DefaultProb / 2;
10598           BTB->DefaultProb -= DefaultProb / 2;
10599         }
10600 
10601         if (FallthroughUnreachable) {
10602           // Skip the range check if the fallthrough block is unreachable.
10603           BTB->OmitRangeCheck = true;
10604         }
10605 
10606         // If we're in the right place, emit the bit test header right now.
10607         if (CurMBB == SwitchMBB) {
10608           visitBitTestHeader(*BTB, SwitchMBB);
10609           BTB->Emitted = true;
10610         }
10611         break;
10612       }
10613       case CC_Range: {
10614         const Value *RHS, *LHS, *MHS;
10615         ISD::CondCode CC;
10616         if (I->Low == I->High) {
10617           // Check Cond == I->Low.
10618           CC = ISD::SETEQ;
10619           LHS = Cond;
10620           RHS=I->Low;
10621           MHS = nullptr;
10622         } else {
10623           // Check I->Low <= Cond <= I->High.
10624           CC = ISD::SETLE;
10625           LHS = I->Low;
10626           MHS = Cond;
10627           RHS = I->High;
10628         }
10629 
10630         // If Fallthrough is unreachable, fold away the comparison.
10631         if (FallthroughUnreachable)
10632           CC = ISD::SETTRUE;
10633 
10634         // The false probability is the sum of all unhandled cases.
10635         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10636                      getCurSDLoc(), I->Prob, UnhandledProbs);
10637 
10638         if (CurMBB == SwitchMBB)
10639           visitSwitchCase(CB, SwitchMBB);
10640         else
10641           SL->SwitchCases.push_back(CB);
10642 
10643         break;
10644       }
10645     }
10646     CurMBB = Fallthrough;
10647   }
10648 }
10649 
10650 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10651                                               CaseClusterIt First,
10652                                               CaseClusterIt Last) {
10653   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10654     if (X.Prob != CC.Prob)
10655       return X.Prob > CC.Prob;
10656 
10657     // Ties are broken by comparing the case value.
10658     return X.Low->getValue().slt(CC.Low->getValue());
10659   });
10660 }
10661 
10662 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10663                                         const SwitchWorkListItem &W,
10664                                         Value *Cond,
10665                                         MachineBasicBlock *SwitchMBB) {
10666   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10667          "Clusters not sorted?");
10668 
10669   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10670 
10671   // Balance the tree based on branch probabilities to create a near-optimal (in
10672   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10673   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10674   CaseClusterIt LastLeft = W.FirstCluster;
10675   CaseClusterIt FirstRight = W.LastCluster;
10676   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10677   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10678 
10679   // Move LastLeft and FirstRight towards each other from opposite directions to
10680   // find a partitioning of the clusters which balances the probability on both
10681   // sides. If LeftProb and RightProb are equal, alternate which side is
10682   // taken to ensure 0-probability nodes are distributed evenly.
10683   unsigned I = 0;
10684   while (LastLeft + 1 < FirstRight) {
10685     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10686       LeftProb += (++LastLeft)->Prob;
10687     else
10688       RightProb += (--FirstRight)->Prob;
10689     I++;
10690   }
10691 
10692   while (true) {
10693     // Our binary search tree differs from a typical BST in that ours can have up
10694     // to three values in each leaf. The pivot selection above doesn't take that
10695     // into account, which means the tree might require more nodes and be less
10696     // efficient. We compensate for this here.
10697 
10698     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10699     unsigned NumRight = W.LastCluster - FirstRight + 1;
10700 
10701     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10702       // If one side has less than 3 clusters, and the other has more than 3,
10703       // consider taking a cluster from the other side.
10704 
10705       if (NumLeft < NumRight) {
10706         // Consider moving the first cluster on the right to the left side.
10707         CaseCluster &CC = *FirstRight;
10708         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10709         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10710         if (LeftSideRank <= RightSideRank) {
10711           // Moving the cluster to the left does not demote it.
10712           ++LastLeft;
10713           ++FirstRight;
10714           continue;
10715         }
10716       } else {
10717         assert(NumRight < NumLeft);
10718         // Consider moving the last element on the left to the right side.
10719         CaseCluster &CC = *LastLeft;
10720         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10721         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10722         if (RightSideRank <= LeftSideRank) {
10723           // Moving the cluster to the right does not demot it.
10724           --LastLeft;
10725           --FirstRight;
10726           continue;
10727         }
10728       }
10729     }
10730     break;
10731   }
10732 
10733   assert(LastLeft + 1 == FirstRight);
10734   assert(LastLeft >= W.FirstCluster);
10735   assert(FirstRight <= W.LastCluster);
10736 
10737   // Use the first element on the right as pivot since we will make less-than
10738   // comparisons against it.
10739   CaseClusterIt PivotCluster = FirstRight;
10740   assert(PivotCluster > W.FirstCluster);
10741   assert(PivotCluster <= W.LastCluster);
10742 
10743   CaseClusterIt FirstLeft = W.FirstCluster;
10744   CaseClusterIt LastRight = W.LastCluster;
10745 
10746   const ConstantInt *Pivot = PivotCluster->Low;
10747 
10748   // New blocks will be inserted immediately after the current one.
10749   MachineFunction::iterator BBI(W.MBB);
10750   ++BBI;
10751 
10752   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10753   // we can branch to its destination directly if it's squeezed exactly in
10754   // between the known lower bound and Pivot - 1.
10755   MachineBasicBlock *LeftMBB;
10756   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10757       FirstLeft->Low == W.GE &&
10758       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10759     LeftMBB = FirstLeft->MBB;
10760   } else {
10761     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10762     FuncInfo.MF->insert(BBI, LeftMBB);
10763     WorkList.push_back(
10764         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10765     // Put Cond in a virtual register to make it available from the new blocks.
10766     ExportFromCurrentBlock(Cond);
10767   }
10768 
10769   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10770   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10771   // directly if RHS.High equals the current upper bound.
10772   MachineBasicBlock *RightMBB;
10773   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10774       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10775     RightMBB = FirstRight->MBB;
10776   } else {
10777     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10778     FuncInfo.MF->insert(BBI, RightMBB);
10779     WorkList.push_back(
10780         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10781     // Put Cond in a virtual register to make it available from the new blocks.
10782     ExportFromCurrentBlock(Cond);
10783   }
10784 
10785   // Create the CaseBlock record that will be used to lower the branch.
10786   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10787                getCurSDLoc(), LeftProb, RightProb);
10788 
10789   if (W.MBB == SwitchMBB)
10790     visitSwitchCase(CB, SwitchMBB);
10791   else
10792     SL->SwitchCases.push_back(CB);
10793 }
10794 
10795 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10796 // from the swith statement.
10797 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10798                                             BranchProbability PeeledCaseProb) {
10799   if (PeeledCaseProb == BranchProbability::getOne())
10800     return BranchProbability::getZero();
10801   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10802 
10803   uint32_t Numerator = CaseProb.getNumerator();
10804   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10805   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10806 }
10807 
10808 // Try to peel the top probability case if it exceeds the threshold.
10809 // Return current MachineBasicBlock for the switch statement if the peeling
10810 // does not occur.
10811 // If the peeling is performed, return the newly created MachineBasicBlock
10812 // for the peeled switch statement. Also update Clusters to remove the peeled
10813 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10814 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10815     const SwitchInst &SI, CaseClusterVector &Clusters,
10816     BranchProbability &PeeledCaseProb) {
10817   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10818   // Don't perform if there is only one cluster or optimizing for size.
10819   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10820       TM.getOptLevel() == CodeGenOpt::None ||
10821       SwitchMBB->getParent()->getFunction().hasMinSize())
10822     return SwitchMBB;
10823 
10824   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10825   unsigned PeeledCaseIndex = 0;
10826   bool SwitchPeeled = false;
10827   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10828     CaseCluster &CC = Clusters[Index];
10829     if (CC.Prob < TopCaseProb)
10830       continue;
10831     TopCaseProb = CC.Prob;
10832     PeeledCaseIndex = Index;
10833     SwitchPeeled = true;
10834   }
10835   if (!SwitchPeeled)
10836     return SwitchMBB;
10837 
10838   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10839                     << TopCaseProb << "\n");
10840 
10841   // Record the MBB for the peeled switch statement.
10842   MachineFunction::iterator BBI(SwitchMBB);
10843   ++BBI;
10844   MachineBasicBlock *PeeledSwitchMBB =
10845       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10846   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10847 
10848   ExportFromCurrentBlock(SI.getCondition());
10849   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10850   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10851                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10852   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10853 
10854   Clusters.erase(PeeledCaseIt);
10855   for (CaseCluster &CC : Clusters) {
10856     LLVM_DEBUG(
10857         dbgs() << "Scale the probablity for one cluster, before scaling: "
10858                << CC.Prob << "\n");
10859     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10860     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10861   }
10862   PeeledCaseProb = TopCaseProb;
10863   return PeeledSwitchMBB;
10864 }
10865 
10866 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10867   // Extract cases from the switch.
10868   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10869   CaseClusterVector Clusters;
10870   Clusters.reserve(SI.getNumCases());
10871   for (auto I : SI.cases()) {
10872     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10873     const ConstantInt *CaseVal = I.getCaseValue();
10874     BranchProbability Prob =
10875         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10876             : BranchProbability(1, SI.getNumCases() + 1);
10877     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10878   }
10879 
10880   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10881 
10882   // Cluster adjacent cases with the same destination. We do this at all
10883   // optimization levels because it's cheap to do and will make codegen faster
10884   // if there are many clusters.
10885   sortAndRangeify(Clusters);
10886 
10887   // The branch probablity of the peeled case.
10888   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10889   MachineBasicBlock *PeeledSwitchMBB =
10890       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10891 
10892   // If there is only the default destination, jump there directly.
10893   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10894   if (Clusters.empty()) {
10895     assert(PeeledSwitchMBB == SwitchMBB);
10896     SwitchMBB->addSuccessor(DefaultMBB);
10897     if (DefaultMBB != NextBlock(SwitchMBB)) {
10898       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10899                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10900     }
10901     return;
10902   }
10903 
10904   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10905   SL->findBitTestClusters(Clusters, &SI);
10906 
10907   LLVM_DEBUG({
10908     dbgs() << "Case clusters: ";
10909     for (const CaseCluster &C : Clusters) {
10910       if (C.Kind == CC_JumpTable)
10911         dbgs() << "JT:";
10912       if (C.Kind == CC_BitTests)
10913         dbgs() << "BT:";
10914 
10915       C.Low->getValue().print(dbgs(), true);
10916       if (C.Low != C.High) {
10917         dbgs() << '-';
10918         C.High->getValue().print(dbgs(), true);
10919       }
10920       dbgs() << ' ';
10921     }
10922     dbgs() << '\n';
10923   });
10924 
10925   assert(!Clusters.empty());
10926   SwitchWorkList WorkList;
10927   CaseClusterIt First = Clusters.begin();
10928   CaseClusterIt Last = Clusters.end() - 1;
10929   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10930   // Scale the branchprobability for DefaultMBB if the peel occurs and
10931   // DefaultMBB is not replaced.
10932   if (PeeledCaseProb != BranchProbability::getZero() &&
10933       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10934     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10935   WorkList.push_back(
10936       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10937 
10938   while (!WorkList.empty()) {
10939     SwitchWorkListItem W = WorkList.pop_back_val();
10940     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10941 
10942     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10943         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10944       // For optimized builds, lower large range as a balanced binary tree.
10945       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10946       continue;
10947     }
10948 
10949     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10950   }
10951 }
10952 
10953 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
10954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10955   auto DL = getCurSDLoc();
10956   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10957   EVT OpVT =
10958       TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType());
10959   SDValue Step = DAG.getConstant(1, DL, OpVT);
10960   setValue(&I, DAG.getStepVector(DL, ResultVT, Step));
10961 }
10962 
10963 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
10964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10965   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10966 
10967   SDLoc DL = getCurSDLoc();
10968   SDValue V = getValue(I.getOperand(0));
10969   assert(VT == V.getValueType() && "Malformed vector.reverse!");
10970 
10971   if (VT.isScalableVector()) {
10972     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
10973     return;
10974   }
10975 
10976   // Use VECTOR_SHUFFLE for the fixed-length vector
10977   // to maintain existing behavior.
10978   SmallVector<int, 8> Mask;
10979   unsigned NumElts = VT.getVectorMinNumElements();
10980   for (unsigned i = 0; i != NumElts; ++i)
10981     Mask.push_back(NumElts - 1 - i);
10982 
10983   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
10984 }
10985 
10986 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10987   SmallVector<EVT, 4> ValueVTs;
10988   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10989                   ValueVTs);
10990   unsigned NumValues = ValueVTs.size();
10991   if (NumValues == 0) return;
10992 
10993   SmallVector<SDValue, 4> Values(NumValues);
10994   SDValue Op = getValue(I.getOperand(0));
10995 
10996   for (unsigned i = 0; i != NumValues; ++i)
10997     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10998                             SDValue(Op.getNode(), Op.getResNo() + i));
10999 
11000   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11001                            DAG.getVTList(ValueVTs), Values));
11002 }
11003 
11004 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11006   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11007 
11008   SDLoc DL = getCurSDLoc();
11009   SDValue V1 = getValue(I.getOperand(0));
11010   SDValue V2 = getValue(I.getOperand(1));
11011   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11012 
11013   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11014   if (VT.isScalableVector()) {
11015     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11016     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11017                              DAG.getConstant(Imm, DL, IdxVT)));
11018     return;
11019   }
11020 
11021   unsigned NumElts = VT.getVectorNumElements();
11022 
11023   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11024     // Result is undefined if immediate is out-of-bounds.
11025     setValue(&I, DAG.getUNDEF(VT));
11026     return;
11027   }
11028 
11029   uint64_t Idx = (NumElts + Imm) % NumElts;
11030 
11031   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11032   SmallVector<int, 8> Mask;
11033   for (unsigned i = 0; i < NumElts; ++i)
11034     Mask.push_back(Idx + i);
11035   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11036 }
11037