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