xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 6718fda6ada87169f8ee4b8bebf13bf39b83533b)
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        // Bitcast Val back the original type and extract the corresponding
440        // vector we want.
441        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
442        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
443                                            ValueVT.getVectorElementType(), Elts);
444        Val = DAG.getBitcast(WiderVecType, Val);
445        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
446                           DAG.getVectorIdxConstant(0, DL));
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG,
614                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isFixedLengthVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   unsigned PartNumElts = PartVT.getVectorNumElements();
620   unsigned ValueNumElts = ValueVT.getVectorNumElements();
621   if (PartNumElts > ValueNumElts &&
622       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
623     EVT ElementVT = PartVT.getVectorElementType();
624     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
625     // undef elements.
626     SmallVector<SDValue, 16> Ops;
627     DAG.ExtractVectorElements(Val, Ops);
628     SDValue EltUndef = DAG.getUNDEF(ElementVT);
629     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
630       Ops.push_back(EltUndef);
631 
632     // FIXME: Use CONCAT for 2x -> 4x.
633     return DAG.getBuildVector(PartVT, DL, Ops);
634   }
635 
636   return SDValue();
637 }
638 
639 /// getCopyToPartsVector - Create a series of nodes that contain the specified
640 /// value split into legal parts.
641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
642                                  SDValue Val, SDValue *Parts, unsigned NumParts,
643                                  MVT PartVT, const Value *V,
644                                  Optional<CallingConv::ID> CallConv) {
645   EVT ValueVT = Val.getValueType();
646   assert(ValueVT.isVector() && "Not a vector");
647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
648   const bool IsABIRegCopy = CallConv.hasValue();
649 
650   if (NumParts == 1) {
651     EVT PartEVT = PartVT;
652     if (PartEVT == ValueVT) {
653       // Nothing to do.
654     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
655       // Bitconvert vector->vector case.
656       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
657     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
658       Val = Widened;
659     } else if (PartVT.isVector() &&
660                PartEVT.getVectorElementType().bitsGE(
661                    ValueVT.getVectorElementType()) &&
662                PartEVT.getVectorElementCount() ==
663                    ValueVT.getVectorElementCount()) {
664 
665       // Promoted vector extract
666       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667     } else {
668       if (ValueVT.getVectorElementCount().isScalar()) {
669         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
670                           DAG.getVectorIdxConstant(0, DL));
671       } else {
672         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
673         assert(PartVT.getFixedSizeInBits() > ValueSize &&
674                "lossy conversion of vector to scalar type");
675         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
676         Val = DAG.getBitcast(IntermediateType, Val);
677         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
678       }
679     }
680 
681     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
682     Parts[0] = Val;
683     return;
684   }
685 
686   // Handle a multi-element vector.
687   EVT IntermediateVT;
688   MVT RegisterVT;
689   unsigned NumIntermediates;
690   unsigned NumRegs;
691   if (IsABIRegCopy) {
692     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
693         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
694         NumIntermediates, RegisterVT);
695   } else {
696     NumRegs =
697         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
698                                    NumIntermediates, RegisterVT);
699   }
700 
701   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
702   NumParts = NumRegs; // Silence a compiler warning.
703   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
704 
705   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
706          "Mixing scalable and fixed vectors when copying in parts");
707 
708   Optional<ElementCount> DestEltCnt;
709 
710   if (IntermediateVT.isVector())
711     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
712   else
713     DestEltCnt = ElementCount::getFixed(NumIntermediates);
714 
715   EVT BuiltVectorTy = EVT::getVectorVT(
716       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
717   if (ValueVT != BuiltVectorTy) {
718     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
719       Val = Widened;
720 
721     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
722   }
723 
724   // Split the vector into intermediate operands.
725   SmallVector<SDValue, 8> Ops(NumIntermediates);
726   for (unsigned i = 0; i != NumIntermediates; ++i) {
727     if (IntermediateVT.isVector()) {
728       // This does something sensible for scalable vectors - see the
729       // definition of EXTRACT_SUBVECTOR for further details.
730       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
731       Ops[i] =
732           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
733                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
734     } else {
735       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736                            DAG.getVectorIdxConstant(i, DL));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!Register::isVirtualRegister(Regs[Part + i]) ||
826           !RegisterVT.isInteger())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getScalarSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     Register SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, TypeSize>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     TypeSize RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   PendingConstrainedFP.clear();
1014   PendingConstrainedFPStrict.clear();
1015   CurInst = nullptr;
1016   HasTailCall = false;
1017   SDNodeOrder = LowestSDNodeOrder;
1018   StatepointLowering.clear();
1019 }
1020 
1021 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1022   DanglingDebugInfoMap.clear();
1023 }
1024 
1025 // Update DAG root to include dependencies on Pending chains.
1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1027   SDValue Root = DAG.getRoot();
1028 
1029   if (Pending.empty())
1030     return Root;
1031 
1032   // Add current root to PendingChains, unless we already indirectly
1033   // depend on it.
1034   if (Root.getOpcode() != ISD::EntryToken) {
1035     unsigned i = 0, e = Pending.size();
1036     for (; i != e; ++i) {
1037       assert(Pending[i].getNode()->getNumOperands() > 1);
1038       if (Pending[i].getNode()->getOperand(0) == Root)
1039         break;  // Don't add the root if we already indirectly depend on it.
1040     }
1041 
1042     if (i == e)
1043       Pending.push_back(Root);
1044   }
1045 
1046   if (Pending.size() == 1)
1047     Root = Pending[0];
1048   else
1049     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1050 
1051   DAG.setRoot(Root);
1052   Pending.clear();
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getMemoryRoot() {
1057   return updateRoot(PendingLoads);
1058 }
1059 
1060 SDValue SelectionDAGBuilder::getRoot() {
1061   // Chain up all pending constrained intrinsics together with all
1062   // pending loads, by simply appending them to PendingLoads and
1063   // then calling getMemoryRoot().
1064   PendingLoads.reserve(PendingLoads.size() +
1065                        PendingConstrainedFP.size() +
1066                        PendingConstrainedFPStrict.size());
1067   PendingLoads.append(PendingConstrainedFP.begin(),
1068                       PendingConstrainedFP.end());
1069   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1070                       PendingConstrainedFPStrict.end());
1071   PendingConstrainedFP.clear();
1072   PendingConstrainedFPStrict.clear();
1073   return getMemoryRoot();
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getControlRoot() {
1077   // We need to emit pending fpexcept.strict constrained intrinsics,
1078   // so append them to the PendingExports list.
1079   PendingExports.append(PendingConstrainedFPStrict.begin(),
1080                         PendingConstrainedFPStrict.end());
1081   PendingConstrainedFPStrict.clear();
1082   return updateRoot(PendingExports);
1083 }
1084 
1085 void SelectionDAGBuilder::visit(const Instruction &I) {
1086   // Set up outgoing PHI node register values before emitting the terminator.
1087   if (I.isTerminator()) {
1088     HandlePHINodesInSuccessorBlocks(I.getParent());
1089   }
1090 
1091   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1092   if (!isa<DbgInfoIntrinsic>(I))
1093     ++SDNodeOrder;
1094 
1095   CurInst = &I;
1096 
1097   visit(I.getOpcode(), I);
1098 
1099   if (!I.isTerminator() && !HasTailCall &&
1100       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1101     CopyToExportRegsIfNeeded(&I);
1102 
1103   CurInst = nullptr;
1104 }
1105 
1106 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1107   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1108 }
1109 
1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1111   // Note: this doesn't use InstVisitor, because it has to work with
1112   // ConstantExpr's in addition to instructions.
1113   switch (Opcode) {
1114   default: llvm_unreachable("Unknown instruction type encountered!");
1115     // Build the switch statement using the Instruction.def file.
1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1117     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1118 #include "llvm/IR/Instruction.def"
1119   }
1120 }
1121 
1122 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1123                                                 const DIExpression *Expr) {
1124   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1125     const DbgValueInst *DI = DDI.getDI();
1126     DIVariable *DanglingVariable = DI->getVariable();
1127     DIExpression *DanglingExpr = DI->getExpression();
1128     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1129       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1130       return true;
1131     }
1132     return false;
1133   };
1134 
1135   for (auto &DDIMI : DanglingDebugInfoMap) {
1136     DanglingDebugInfoVector &DDIV = DDIMI.second;
1137 
1138     // If debug info is to be dropped, run it through final checks to see
1139     // whether it can be salvaged.
1140     for (auto &DDI : DDIV)
1141       if (isMatchingDbgValue(DDI))
1142         salvageUnresolvedDbgValue(DDI);
1143 
1144     erase_if(DDIV, isMatchingDbgValue);
1145   }
1146 }
1147 
1148 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1149 // generate the debug data structures now that we've seen its definition.
1150 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1151                                                    SDValue Val) {
1152   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1153   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1154     return;
1155 
1156   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1157   for (auto &DDI : DDIV) {
1158     const DbgValueInst *DI = DDI.getDI();
1159     assert(DI && "Ill-formed DanglingDebugInfo");
1160     DebugLoc dl = DDI.getdl();
1161     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1162     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1163     DILocalVariable *Variable = DI->getVariable();
1164     DIExpression *Expr = DI->getExpression();
1165     assert(Variable->isValidLocationForIntrinsic(dl) &&
1166            "Expected inlined-at fields to agree");
1167     SDDbgValue *SDV;
1168     if (Val.getNode()) {
1169       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1170       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1171       // we couldn't resolve it directly when examining the DbgValue intrinsic
1172       // in the first place we should not be more successful here). Unless we
1173       // have some test case that prove this to be correct we should avoid
1174       // calling EmitFuncArgumentDbgValue here.
1175       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1176         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1177                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1178         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1179         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1180         // inserted after the definition of Val when emitting the instructions
1181         // after ISel. An alternative could be to teach
1182         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1183         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1184                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1185                    << ValSDNodeOrder << "\n");
1186         SDV = getDbgValue(Val, Variable, Expr, dl,
1187                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1188         DAG.AddDbgValue(SDV, Val.getNode(), false);
1189       } else
1190         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1191                           << "in EmitFuncArgumentDbgValue\n");
1192     } else {
1193       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1194       auto Undef =
1195           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1196       auto SDV =
1197           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1198       DAG.AddDbgValue(SDV, nullptr, false);
1199     }
1200   }
1201   DDIV.clear();
1202 }
1203 
1204 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1205   Value *V = DDI.getDI()->getValue();
1206   DILocalVariable *Var = DDI.getDI()->getVariable();
1207   DIExpression *Expr = DDI.getDI()->getExpression();
1208   DebugLoc DL = DDI.getdl();
1209   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1210   unsigned SDOrder = DDI.getSDNodeOrder();
1211 
1212   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1213   // that DW_OP_stack_value is desired.
1214   assert(isa<DbgValueInst>(DDI.getDI()));
1215   bool StackValue = true;
1216 
1217   // Can this Value can be encoded without any further work?
1218   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1219     return;
1220 
1221   // Attempt to salvage back through as many instructions as possible. Bail if
1222   // a non-instruction is seen, such as a constant expression or global
1223   // variable. FIXME: Further work could recover those too.
1224   while (isa<Instruction>(V)) {
1225     Instruction &VAsInst = *cast<Instruction>(V);
1226     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1227 
1228     // If we cannot salvage any further, and haven't yet found a suitable debug
1229     // expression, bail out.
1230     if (!NewExpr)
1231       break;
1232 
1233     // New value and expr now represent this debuginfo.
1234     V = VAsInst.getOperand(0);
1235     Expr = NewExpr;
1236 
1237     // Some kind of simplification occurred: check whether the operand of the
1238     // salvaged debug expression can be encoded in this DAG.
1239     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1240       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1241                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1242       return;
1243     }
1244   }
1245 
1246   // This was the final opportunity to salvage this debug information, and it
1247   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1248   // any earlier variable location.
1249   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1250   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1251   DAG.AddDbgValue(SDV, nullptr, false);
1252 
1253   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1254                     << "\n");
1255   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1256                     << "\n");
1257 }
1258 
1259 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1260                                            DIExpression *Expr, DebugLoc dl,
1261                                            DebugLoc InstDL, unsigned Order) {
1262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1263   SDDbgValue *SDV;
1264   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1265       isa<ConstantPointerNull>(V)) {
1266     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1267     DAG.AddDbgValue(SDV, nullptr, false);
1268     return true;
1269   }
1270 
1271   // If the Value is a frame index, we can create a FrameIndex debug value
1272   // without relying on the DAG at all.
1273   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1274     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1275     if (SI != FuncInfo.StaticAllocaMap.end()) {
1276       auto SDV =
1277           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1278                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1279       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1280       // is still available even if the SDNode gets optimized out.
1281       DAG.AddDbgValue(SDV, nullptr, false);
1282       return true;
1283     }
1284   }
1285 
1286   // Do not use getValue() in here; we don't want to generate code at
1287   // this point if it hasn't been done yet.
1288   SDValue N = NodeMap[V];
1289   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1290     N = UnusedArgNodeMap[V];
1291   if (N.getNode()) {
1292     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1293       return true;
1294     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1295     DAG.AddDbgValue(SDV, N.getNode(), false);
1296     return true;
1297   }
1298 
1299   // Special rules apply for the first dbg.values of parameter variables in a
1300   // function. Identify them by the fact they reference Argument Values, that
1301   // they're parameters, and they are parameters of the current function. We
1302   // need to let them dangle until they get an SDNode.
1303   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1304                        !InstDL.getInlinedAt();
1305   if (!IsParamOfFunc) {
1306     // The value is not used in this block yet (or it would have an SDNode).
1307     // We still want the value to appear for the user if possible -- if it has
1308     // an associated VReg, we can refer to that instead.
1309     auto VMI = FuncInfo.ValueMap.find(V);
1310     if (VMI != FuncInfo.ValueMap.end()) {
1311       unsigned Reg = VMI->second;
1312       // If this is a PHI node, it may be split up into several MI PHI nodes
1313       // (in FunctionLoweringInfo::set).
1314       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1315                        V->getType(), None);
1316       if (RFV.occupiesMultipleRegs()) {
1317         unsigned Offset = 0;
1318         unsigned BitsToDescribe = 0;
1319         if (auto VarSize = Var->getSizeInBits())
1320           BitsToDescribe = *VarSize;
1321         if (auto Fragment = Expr->getFragmentInfo())
1322           BitsToDescribe = Fragment->SizeInBits;
1323         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1324           // Bail out if all bits are described already.
1325           if (Offset >= BitsToDescribe)
1326             break;
1327           // TODO: handle scalable vectors.
1328           unsigned RegisterSize = RegAndSize.second;
1329           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1330               ? BitsToDescribe - Offset
1331               : RegisterSize;
1332           auto FragmentExpr = DIExpression::createFragmentExpression(
1333               Expr, Offset, FragmentSize);
1334           if (!FragmentExpr)
1335               continue;
1336           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1337                                     false, dl, SDNodeOrder);
1338           DAG.AddDbgValue(SDV, nullptr, false);
1339           Offset += RegisterSize;
1340         }
1341       } else {
1342         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1343         DAG.AddDbgValue(SDV, nullptr, false);
1344       }
1345       return true;
1346     }
1347   }
1348 
1349   return false;
1350 }
1351 
1352 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1353   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1354   for (auto &Pair : DanglingDebugInfoMap)
1355     for (auto &DDI : Pair.second)
1356       salvageUnresolvedDbgValue(DDI);
1357   clearDanglingDebugInfo();
1358 }
1359 
1360 /// getCopyFromRegs - If there was virtual register allocated for the value V
1361 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1362 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1363   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1364   SDValue Result;
1365 
1366   if (It != FuncInfo.ValueMap.end()) {
1367     Register InReg = It->second;
1368 
1369     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1370                      DAG.getDataLayout(), InReg, Ty,
1371                      None); // This is not an ABI copy.
1372     SDValue Chain = DAG.getEntryNode();
1373     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1374                                  V);
1375     resolveDanglingDebugInfo(V, Result);
1376   }
1377 
1378   return Result;
1379 }
1380 
1381 /// getValue - Return an SDValue for the given Value.
1382 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1383   // If we already have an SDValue for this value, use it. It's important
1384   // to do this first, so that we don't create a CopyFromReg if we already
1385   // have a regular SDValue.
1386   SDValue &N = NodeMap[V];
1387   if (N.getNode()) return N;
1388 
1389   // If there's a virtual register allocated and initialized for this
1390   // value, use it.
1391   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1392     return copyFromReg;
1393 
1394   // Otherwise create a new SDValue and remember it.
1395   SDValue Val = getValueImpl(V);
1396   NodeMap[V] = Val;
1397   resolveDanglingDebugInfo(V, Val);
1398   return Val;
1399 }
1400 
1401 /// getNonRegisterValue - Return an SDValue for the given Value, but
1402 /// don't look in FuncInfo.ValueMap for a virtual register.
1403 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1404   // If we already have an SDValue for this value, use it.
1405   SDValue &N = NodeMap[V];
1406   if (N.getNode()) {
1407     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1408       // Remove the debug location from the node as the node is about to be used
1409       // in a location which may differ from the original debug location.  This
1410       // is relevant to Constant and ConstantFP nodes because they can appear
1411       // as constant expressions inside PHI nodes.
1412       N->setDebugLoc(DebugLoc());
1413     }
1414     return N;
1415   }
1416 
1417   // Otherwise create a new SDValue and remember it.
1418   SDValue Val = getValueImpl(V);
1419   NodeMap[V] = Val;
1420   resolveDanglingDebugInfo(V, Val);
1421   return Val;
1422 }
1423 
1424 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1425 /// Create an SDValue for the given value.
1426 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1428 
1429   if (const Constant *C = dyn_cast<Constant>(V)) {
1430     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1431 
1432     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1433       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1434 
1435     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1436       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1437 
1438     if (isa<ConstantPointerNull>(C)) {
1439       unsigned AS = V->getType()->getPointerAddressSpace();
1440       return DAG.getConstant(0, getCurSDLoc(),
1441                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1442     }
1443 
1444     if (match(C, m_VScale(DAG.getDataLayout())))
1445       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1446 
1447     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1448       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1449 
1450     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1451       return DAG.getUNDEF(VT);
1452 
1453     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1454       visit(CE->getOpcode(), *CE);
1455       SDValue N1 = NodeMap[V];
1456       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1457       return N1;
1458     }
1459 
1460     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1461       SmallVector<SDValue, 4> Constants;
1462       for (const Use &U : C->operands()) {
1463         SDNode *Val = getValue(U).getNode();
1464         // If the operand is an empty aggregate, there are no values.
1465         if (!Val) continue;
1466         // Add each leaf value from the operand to the Constants list
1467         // to form a flattened list of all the values.
1468         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1469           Constants.push_back(SDValue(Val, i));
1470       }
1471 
1472       return DAG.getMergeValues(Constants, getCurSDLoc());
1473     }
1474 
1475     if (const ConstantDataSequential *CDS =
1476           dyn_cast<ConstantDataSequential>(C)) {
1477       SmallVector<SDValue, 4> Ops;
1478       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1479         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1480         // Add each leaf value from the operand to the Constants list
1481         // to form a flattened list of all the values.
1482         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1483           Ops.push_back(SDValue(Val, i));
1484       }
1485 
1486       if (isa<ArrayType>(CDS->getType()))
1487         return DAG.getMergeValues(Ops, getCurSDLoc());
1488       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1489     }
1490 
1491     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1492       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1493              "Unknown struct or array constant!");
1494 
1495       SmallVector<EVT, 4> ValueVTs;
1496       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1497       unsigned NumElts = ValueVTs.size();
1498       if (NumElts == 0)
1499         return SDValue(); // empty struct
1500       SmallVector<SDValue, 4> Constants(NumElts);
1501       for (unsigned i = 0; i != NumElts; ++i) {
1502         EVT EltVT = ValueVTs[i];
1503         if (isa<UndefValue>(C))
1504           Constants[i] = DAG.getUNDEF(EltVT);
1505         else if (EltVT.isFloatingPoint())
1506           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1507         else
1508           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1509       }
1510 
1511       return DAG.getMergeValues(Constants, getCurSDLoc());
1512     }
1513 
1514     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1515       return DAG.getBlockAddress(BA, VT);
1516 
1517     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1518       return getValue(Equiv->getGlobalValue());
1519 
1520     VectorType *VecTy = cast<VectorType>(V->getType());
1521 
1522     // Now that we know the number and type of the elements, get that number of
1523     // elements into the Ops array based on what kind of constant it is.
1524     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1525       SmallVector<SDValue, 16> Ops;
1526       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1527       for (unsigned i = 0; i != NumElements; ++i)
1528         Ops.push_back(getValue(CV->getOperand(i)));
1529 
1530       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1531     } else if (isa<ConstantAggregateZero>(C)) {
1532       EVT EltVT =
1533           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1534 
1535       SDValue Op;
1536       if (EltVT.isFloatingPoint())
1537         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1538       else
1539         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1540 
1541       if (isa<ScalableVectorType>(VecTy))
1542         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1543       else {
1544         SmallVector<SDValue, 16> Ops;
1545         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1546         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1547       }
1548     }
1549     llvm_unreachable("Unknown vector constant");
1550   }
1551 
1552   // If this is a static alloca, generate it as the frameindex instead of
1553   // computation.
1554   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1555     DenseMap<const AllocaInst*, int>::iterator SI =
1556       FuncInfo.StaticAllocaMap.find(AI);
1557     if (SI != FuncInfo.StaticAllocaMap.end())
1558       return DAG.getFrameIndex(SI->second,
1559                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1560   }
1561 
1562   // If this is an instruction which fast-isel has deferred, select it now.
1563   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1564     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1565 
1566     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1567                      Inst->getType(), None);
1568     SDValue Chain = DAG.getEntryNode();
1569     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1570   }
1571 
1572   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1573     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1574   }
1575   llvm_unreachable("Can't get register for value!");
1576 }
1577 
1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1579   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1580   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1581   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1582   bool IsSEH = isAsynchronousEHPersonality(Pers);
1583   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1584   if (!IsSEH)
1585     CatchPadMBB->setIsEHScopeEntry();
1586   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1587   if (IsMSVCCXX || IsCoreCLR)
1588     CatchPadMBB->setIsEHFuncletEntry();
1589 }
1590 
1591 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1592   // Update machine-CFG edge.
1593   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1594   FuncInfo.MBB->addSuccessor(TargetMBB);
1595   TargetMBB->setIsEHCatchretTarget(true);
1596   DAG.getMachineFunction().setHasEHCatchret(true);
1597 
1598   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1599   bool IsSEH = isAsynchronousEHPersonality(Pers);
1600   if (IsSEH) {
1601     // If this is not a fall-through branch or optimizations are switched off,
1602     // emit the branch.
1603     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1604         TM.getOptLevel() == CodeGenOpt::None)
1605       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1606                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1607     return;
1608   }
1609 
1610   // Figure out the funclet membership for the catchret's successor.
1611   // This will be used by the FuncletLayout pass to determine how to order the
1612   // BB's.
1613   // A 'catchret' returns to the outer scope's color.
1614   Value *ParentPad = I.getCatchSwitchParentPad();
1615   const BasicBlock *SuccessorColor;
1616   if (isa<ConstantTokenNone>(ParentPad))
1617     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1618   else
1619     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1620   assert(SuccessorColor && "No parent funclet for catchret!");
1621   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1622   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1623 
1624   // Create the terminator node.
1625   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1626                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1627                             DAG.getBasicBlock(SuccessorColorMBB));
1628   DAG.setRoot(Ret);
1629 }
1630 
1631 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1632   // Don't emit any special code for the cleanuppad instruction. It just marks
1633   // the start of an EH scope/funclet.
1634   FuncInfo.MBB->setIsEHScopeEntry();
1635   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1636   if (Pers != EHPersonality::Wasm_CXX) {
1637     FuncInfo.MBB->setIsEHFuncletEntry();
1638     FuncInfo.MBB->setIsCleanupFuncletEntry();
1639   }
1640 }
1641 
1642 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1643 // not match, it is OK to add only the first unwind destination catchpad to the
1644 // successors, because there will be at least one invoke instruction within the
1645 // catch scope that points to the next unwind destination, if one exists, so
1646 // CFGSort cannot mess up with BB sorting order.
1647 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1648 // call within them, and catchpads only consisting of 'catch (...)' have a
1649 // '__cxa_end_catch' call within them, both of which generate invokes in case
1650 // the next unwind destination exists, i.e., the next unwind destination is not
1651 // the caller.)
1652 //
1653 // Having at most one EH pad successor is also simpler and helps later
1654 // transformations.
1655 //
1656 // For example,
1657 // current:
1658 //   invoke void @foo to ... unwind label %catch.dispatch
1659 // catch.dispatch:
1660 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1661 // catch.start:
1662 //   ...
1663 //   ... in this BB or some other child BB dominated by this BB there will be an
1664 //   invoke that points to 'next' BB as an unwind destination
1665 //
1666 // next: ; We don't need to add this to 'current' BB's successor
1667 //   ...
1668 static void findWasmUnwindDestinations(
1669     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1670     BranchProbability Prob,
1671     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1672         &UnwindDests) {
1673   while (EHPadBB) {
1674     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1675     if (isa<CleanupPadInst>(Pad)) {
1676       // Stop on cleanup pads.
1677       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1678       UnwindDests.back().first->setIsEHScopeEntry();
1679       break;
1680     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1681       // Add the catchpad handlers to the possible destinations. We don't
1682       // continue to the unwind destination of the catchswitch for wasm.
1683       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1684         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1685         UnwindDests.back().first->setIsEHScopeEntry();
1686       }
1687       break;
1688     } else {
1689       continue;
1690     }
1691   }
1692 }
1693 
1694 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1695 /// many places it could ultimately go. In the IR, we have a single unwind
1696 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1697 /// This function skips over imaginary basic blocks that hold catchswitch
1698 /// instructions, and finds all the "real" machine
1699 /// basic block destinations. As those destinations may not be successors of
1700 /// EHPadBB, here we also calculate the edge probability to those destinations.
1701 /// The passed-in Prob is the edge probability to EHPadBB.
1702 static void findUnwindDestinations(
1703     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1704     BranchProbability Prob,
1705     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1706         &UnwindDests) {
1707   EHPersonality Personality =
1708     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1709   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1710   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1711   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1712   bool IsSEH = isAsynchronousEHPersonality(Personality);
1713 
1714   if (IsWasmCXX) {
1715     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1716     assert(UnwindDests.size() <= 1 &&
1717            "There should be at most one unwind destination for wasm");
1718     return;
1719   }
1720 
1721   while (EHPadBB) {
1722     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1723     BasicBlock *NewEHPadBB = nullptr;
1724     if (isa<LandingPadInst>(Pad)) {
1725       // Stop on landingpads. They are not funclets.
1726       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1727       break;
1728     } else if (isa<CleanupPadInst>(Pad)) {
1729       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1730       // personalities.
1731       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1732       UnwindDests.back().first->setIsEHScopeEntry();
1733       UnwindDests.back().first->setIsEHFuncletEntry();
1734       break;
1735     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1736       // Add the catchpad handlers to the possible destinations.
1737       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1738         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1739         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1740         if (IsMSVCCXX || IsCoreCLR)
1741           UnwindDests.back().first->setIsEHFuncletEntry();
1742         if (!IsSEH)
1743           UnwindDests.back().first->setIsEHScopeEntry();
1744       }
1745       NewEHPadBB = CatchSwitch->getUnwindDest();
1746     } else {
1747       continue;
1748     }
1749 
1750     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1751     if (BPI && NewEHPadBB)
1752       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1753     EHPadBB = NewEHPadBB;
1754   }
1755 }
1756 
1757 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1758   // Update successor info.
1759   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1760   auto UnwindDest = I.getUnwindDest();
1761   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1762   BranchProbability UnwindDestProb =
1763       (BPI && UnwindDest)
1764           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1765           : BranchProbability::getZero();
1766   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1767   for (auto &UnwindDest : UnwindDests) {
1768     UnwindDest.first->setIsEHPad();
1769     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1770   }
1771   FuncInfo.MBB->normalizeSuccProbs();
1772 
1773   // Create the terminator node.
1774   SDValue Ret =
1775       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1776   DAG.setRoot(Ret);
1777 }
1778 
1779 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1780   report_fatal_error("visitCatchSwitch not yet implemented!");
1781 }
1782 
1783 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1785   auto &DL = DAG.getDataLayout();
1786   SDValue Chain = getControlRoot();
1787   SmallVector<ISD::OutputArg, 8> Outs;
1788   SmallVector<SDValue, 8> OutVals;
1789 
1790   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1791   // lower
1792   //
1793   //   %val = call <ty> @llvm.experimental.deoptimize()
1794   //   ret <ty> %val
1795   //
1796   // differently.
1797   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1798     LowerDeoptimizingReturn();
1799     return;
1800   }
1801 
1802   if (!FuncInfo.CanLowerReturn) {
1803     unsigned DemoteReg = FuncInfo.DemoteRegister;
1804     const Function *F = I.getParent()->getParent();
1805 
1806     // Emit a store of the return value through the virtual register.
1807     // Leave Outs empty so that LowerReturn won't try to load return
1808     // registers the usual way.
1809     SmallVector<EVT, 1> PtrValueVTs;
1810     ComputeValueVTs(TLI, DL,
1811                     F->getReturnType()->getPointerTo(
1812                         DAG.getDataLayout().getAllocaAddrSpace()),
1813                     PtrValueVTs);
1814 
1815     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1816                                         DemoteReg, PtrValueVTs[0]);
1817     SDValue RetOp = getValue(I.getOperand(0));
1818 
1819     SmallVector<EVT, 4> ValueVTs, MemVTs;
1820     SmallVector<uint64_t, 4> Offsets;
1821     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1822                     &Offsets);
1823     unsigned NumValues = ValueVTs.size();
1824 
1825     SmallVector<SDValue, 4> Chains(NumValues);
1826     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1827     for (unsigned i = 0; i != NumValues; ++i) {
1828       // An aggregate return value cannot wrap around the address space, so
1829       // offsets to its parts don't wrap either.
1830       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1831                                            TypeSize::Fixed(Offsets[i]));
1832 
1833       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1834       if (MemVTs[i] != ValueVTs[i])
1835         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1836       Chains[i] = DAG.getStore(
1837           Chain, getCurSDLoc(), Val,
1838           // FIXME: better loc info would be nice.
1839           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1840           commonAlignment(BaseAlign, Offsets[i]));
1841     }
1842 
1843     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1844                         MVT::Other, Chains);
1845   } else if (I.getNumOperands() != 0) {
1846     SmallVector<EVT, 4> ValueVTs;
1847     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1848     unsigned NumValues = ValueVTs.size();
1849     if (NumValues) {
1850       SDValue RetOp = getValue(I.getOperand(0));
1851 
1852       const Function *F = I.getParent()->getParent();
1853 
1854       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1855           I.getOperand(0)->getType(), F->getCallingConv(),
1856           /*IsVarArg*/ false);
1857 
1858       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1859       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1860                                           Attribute::SExt))
1861         ExtendKind = ISD::SIGN_EXTEND;
1862       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1863                                                Attribute::ZExt))
1864         ExtendKind = ISD::ZERO_EXTEND;
1865 
1866       LLVMContext &Context = F->getContext();
1867       bool RetInReg = F->getAttributes().hasAttribute(
1868           AttributeList::ReturnIndex, Attribute::InReg);
1869 
1870       for (unsigned j = 0; j != NumValues; ++j) {
1871         EVT VT = ValueVTs[j];
1872 
1873         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1874           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1875 
1876         CallingConv::ID CC = F->getCallingConv();
1877 
1878         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1879         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1880         SmallVector<SDValue, 4> Parts(NumParts);
1881         getCopyToParts(DAG, getCurSDLoc(),
1882                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1883                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1884 
1885         // 'inreg' on function refers to return value
1886         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1887         if (RetInReg)
1888           Flags.setInReg();
1889 
1890         if (I.getOperand(0)->getType()->isPointerTy()) {
1891           Flags.setPointer();
1892           Flags.setPointerAddrSpace(
1893               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1894         }
1895 
1896         if (NeedsRegBlock) {
1897           Flags.setInConsecutiveRegs();
1898           if (j == NumValues - 1)
1899             Flags.setInConsecutiveRegsLast();
1900         }
1901 
1902         // Propagate extension type if any
1903         if (ExtendKind == ISD::SIGN_EXTEND)
1904           Flags.setSExt();
1905         else if (ExtendKind == ISD::ZERO_EXTEND)
1906           Flags.setZExt();
1907 
1908         for (unsigned i = 0; i < NumParts; ++i) {
1909           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1910                                         VT, /*isfixed=*/true, 0, 0));
1911           OutVals.push_back(Parts[i]);
1912         }
1913       }
1914     }
1915   }
1916 
1917   // Push in swifterror virtual register as the last element of Outs. This makes
1918   // sure swifterror virtual register will be returned in the swifterror
1919   // physical register.
1920   const Function *F = I.getParent()->getParent();
1921   if (TLI.supportSwiftError() &&
1922       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1923     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1924     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1925     Flags.setSwiftError();
1926     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1927                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1928                                   true /*isfixed*/, 1 /*origidx*/,
1929                                   0 /*partOffs*/));
1930     // Create SDNode for the swifterror virtual register.
1931     OutVals.push_back(
1932         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1933                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1934                         EVT(TLI.getPointerTy(DL))));
1935   }
1936 
1937   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1938   CallingConv::ID CallConv =
1939     DAG.getMachineFunction().getFunction().getCallingConv();
1940   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1941       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1942 
1943   // Verify that the target's LowerReturn behaved as expected.
1944   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1945          "LowerReturn didn't return a valid chain!");
1946 
1947   // Update the DAG with the new chain value resulting from return lowering.
1948   DAG.setRoot(Chain);
1949 }
1950 
1951 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1952 /// created for it, emit nodes to copy the value into the virtual
1953 /// registers.
1954 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1955   // Skip empty types
1956   if (V->getType()->isEmptyTy())
1957     return;
1958 
1959   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1960   if (VMI != FuncInfo.ValueMap.end()) {
1961     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1962     CopyValueToVirtualRegister(V, VMI->second);
1963   }
1964 }
1965 
1966 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1967 /// the current basic block, add it to ValueMap now so that we'll get a
1968 /// CopyTo/FromReg.
1969 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1970   // No need to export constants.
1971   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1972 
1973   // Already exported?
1974   if (FuncInfo.isExportedInst(V)) return;
1975 
1976   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1977   CopyValueToVirtualRegister(V, Reg);
1978 }
1979 
1980 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1981                                                      const BasicBlock *FromBB) {
1982   // The operands of the setcc have to be in this block.  We don't know
1983   // how to export them from some other block.
1984   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1985     // Can export from current BB.
1986     if (VI->getParent() == FromBB)
1987       return true;
1988 
1989     // Is already exported, noop.
1990     return FuncInfo.isExportedInst(V);
1991   }
1992 
1993   // If this is an argument, we can export it if the BB is the entry block or
1994   // if it is already exported.
1995   if (isa<Argument>(V)) {
1996     if (FromBB == &FromBB->getParent()->getEntryBlock())
1997       return true;
1998 
1999     // Otherwise, can only export this if it is already exported.
2000     return FuncInfo.isExportedInst(V);
2001   }
2002 
2003   // Otherwise, constants can always be exported.
2004   return true;
2005 }
2006 
2007 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2008 BranchProbability
2009 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2010                                         const MachineBasicBlock *Dst) const {
2011   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2012   const BasicBlock *SrcBB = Src->getBasicBlock();
2013   const BasicBlock *DstBB = Dst->getBasicBlock();
2014   if (!BPI) {
2015     // If BPI is not available, set the default probability as 1 / N, where N is
2016     // the number of successors.
2017     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2018     return BranchProbability(1, SuccSize);
2019   }
2020   return BPI->getEdgeProbability(SrcBB, DstBB);
2021 }
2022 
2023 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2024                                                MachineBasicBlock *Dst,
2025                                                BranchProbability Prob) {
2026   if (!FuncInfo.BPI)
2027     Src->addSuccessorWithoutProb(Dst);
2028   else {
2029     if (Prob.isUnknown())
2030       Prob = getEdgeProbability(Src, Dst);
2031     Src->addSuccessor(Dst, Prob);
2032   }
2033 }
2034 
2035 static bool InBlock(const Value *V, const BasicBlock *BB) {
2036   if (const Instruction *I = dyn_cast<Instruction>(V))
2037     return I->getParent() == BB;
2038   return true;
2039 }
2040 
2041 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2042 /// This function emits a branch and is used at the leaves of an OR or an
2043 /// AND operator tree.
2044 void
2045 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2046                                                   MachineBasicBlock *TBB,
2047                                                   MachineBasicBlock *FBB,
2048                                                   MachineBasicBlock *CurBB,
2049                                                   MachineBasicBlock *SwitchBB,
2050                                                   BranchProbability TProb,
2051                                                   BranchProbability FProb,
2052                                                   bool InvertCond) {
2053   const BasicBlock *BB = CurBB->getBasicBlock();
2054 
2055   // If the leaf of the tree is a comparison, merge the condition into
2056   // the caseblock.
2057   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2058     // The operands of the cmp have to be in this block.  We don't know
2059     // how to export them from some other block.  If this is the first block
2060     // of the sequence, no exporting is needed.
2061     if (CurBB == SwitchBB ||
2062         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2063          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2064       ISD::CondCode Condition;
2065       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2066         ICmpInst::Predicate Pred =
2067             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2068         Condition = getICmpCondCode(Pred);
2069       } else {
2070         const FCmpInst *FC = cast<FCmpInst>(Cond);
2071         FCmpInst::Predicate Pred =
2072             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2073         Condition = getFCmpCondCode(Pred);
2074         if (TM.Options.NoNaNsFPMath)
2075           Condition = getFCmpCodeWithoutNaN(Condition);
2076       }
2077 
2078       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2079                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2080       SL->SwitchCases.push_back(CB);
2081       return;
2082     }
2083   }
2084 
2085   // Create a CaseBlock record representing this branch.
2086   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2087   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2088                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2089   SL->SwitchCases.push_back(CB);
2090 }
2091 
2092 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2093                                                MachineBasicBlock *TBB,
2094                                                MachineBasicBlock *FBB,
2095                                                MachineBasicBlock *CurBB,
2096                                                MachineBasicBlock *SwitchBB,
2097                                                Instruction::BinaryOps Opc,
2098                                                BranchProbability TProb,
2099                                                BranchProbability FProb,
2100                                                bool InvertCond) {
2101   // Skip over not part of the tree and remember to invert op and operands at
2102   // next level.
2103   Value *NotCond;
2104   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2105       InBlock(NotCond, CurBB->getBasicBlock())) {
2106     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2107                          !InvertCond);
2108     return;
2109   }
2110 
2111   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2112   const Value *BOpOp0, *BOpOp1;
2113   // Compute the effective opcode for Cond, taking into account whether it needs
2114   // to be inverted, e.g.
2115   //   and (not (or A, B)), C
2116   // gets lowered as
2117   //   and (and (not A, not B), C)
2118   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2119   if (BOp) {
2120     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2121                ? Instruction::And
2122                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2123                       ? Instruction::Or
2124                       : (Instruction::BinaryOps)0);
2125     if (InvertCond) {
2126       if (BOpc == Instruction::And)
2127         BOpc = Instruction::Or;
2128       else if (BOpc == Instruction::Or)
2129         BOpc = Instruction::And;
2130     }
2131   }
2132 
2133   // If this node is not part of the or/and tree, emit it as a branch.
2134   // Note that all nodes in the tree should have same opcode.
2135   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2136   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2137       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2138       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2139     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2140                                  TProb, FProb, InvertCond);
2141     return;
2142   }
2143 
2144   //  Create TmpBB after CurBB.
2145   MachineFunction::iterator BBI(CurBB);
2146   MachineFunction &MF = DAG.getMachineFunction();
2147   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2148   CurBB->getParent()->insert(++BBI, TmpBB);
2149 
2150   if (Opc == Instruction::Or) {
2151     // Codegen X | Y as:
2152     // BB1:
2153     //   jmp_if_X TBB
2154     //   jmp TmpBB
2155     // TmpBB:
2156     //   jmp_if_Y TBB
2157     //   jmp FBB
2158     //
2159 
2160     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2161     // The requirement is that
2162     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2163     //     = TrueProb for original BB.
2164     // Assuming the original probabilities are A and B, one choice is to set
2165     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2166     // A/(1+B) and 2B/(1+B). This choice assumes that
2167     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2168     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2169     // TmpBB, but the math is more complicated.
2170 
2171     auto NewTrueProb = TProb / 2;
2172     auto NewFalseProb = TProb / 2 + FProb;
2173     // Emit the LHS condition.
2174     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2175                          NewFalseProb, InvertCond);
2176 
2177     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2178     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2179     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2180     // Emit the RHS condition into TmpBB.
2181     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2182                          Probs[1], InvertCond);
2183   } else {
2184     assert(Opc == Instruction::And && "Unknown merge op!");
2185     // Codegen X & Y as:
2186     // BB1:
2187     //   jmp_if_X TmpBB
2188     //   jmp FBB
2189     // TmpBB:
2190     //   jmp_if_Y TBB
2191     //   jmp FBB
2192     //
2193     //  This requires creation of TmpBB after CurBB.
2194 
2195     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2196     // The requirement is that
2197     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2198     //     = FalseProb for original BB.
2199     // Assuming the original probabilities are A and B, one choice is to set
2200     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2201     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2202     // TrueProb for BB1 * FalseProb for TmpBB.
2203 
2204     auto NewTrueProb = TProb + FProb / 2;
2205     auto NewFalseProb = FProb / 2;
2206     // Emit the LHS condition.
2207     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2208                          NewFalseProb, InvertCond);
2209 
2210     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2211     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2212     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2213     // Emit the RHS condition into TmpBB.
2214     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2215                          Probs[1], InvertCond);
2216   }
2217 }
2218 
2219 /// If the set of cases should be emitted as a series of branches, return true.
2220 /// If we should emit this as a bunch of and/or'd together conditions, return
2221 /// false.
2222 bool
2223 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2224   if (Cases.size() != 2) return true;
2225 
2226   // If this is two comparisons of the same values or'd or and'd together, they
2227   // will get folded into a single comparison, so don't emit two blocks.
2228   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2229        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2230       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2231        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2232     return false;
2233   }
2234 
2235   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2236   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2237   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2238       Cases[0].CC == Cases[1].CC &&
2239       isa<Constant>(Cases[0].CmpRHS) &&
2240       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2241     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2242       return false;
2243     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2244       return false;
2245   }
2246 
2247   return true;
2248 }
2249 
2250 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2251   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2252 
2253   // Update machine-CFG edges.
2254   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2255 
2256   if (I.isUnconditional()) {
2257     // Update machine-CFG edges.
2258     BrMBB->addSuccessor(Succ0MBB);
2259 
2260     // If this is not a fall-through branch or optimizations are switched off,
2261     // emit the branch.
2262     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2263       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2264                               MVT::Other, getControlRoot(),
2265                               DAG.getBasicBlock(Succ0MBB)));
2266 
2267     return;
2268   }
2269 
2270   // If this condition is one of the special cases we handle, do special stuff
2271   // now.
2272   const Value *CondVal = I.getCondition();
2273   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2274 
2275   // If this is a series of conditions that are or'd or and'd together, emit
2276   // this as a sequence of branches instead of setcc's with and/or operations.
2277   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2278   // unpredictable branches, and vector extracts because those jumps are likely
2279   // expensive for any target), this should improve performance.
2280   // For example, instead of something like:
2281   //     cmp A, B
2282   //     C = seteq
2283   //     cmp D, E
2284   //     F = setle
2285   //     or C, F
2286   //     jnz foo
2287   // Emit:
2288   //     cmp A, B
2289   //     je foo
2290   //     cmp D, E
2291   //     jle foo
2292   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2293   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2294       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2295     Value *Vec;
2296     const Value *BOp0, *BOp1;
2297     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2298     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2299       Opcode = Instruction::And;
2300     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2301       Opcode = Instruction::Or;
2302 
2303     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2304                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2305       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2306                            getEdgeProbability(BrMBB, Succ0MBB),
2307                            getEdgeProbability(BrMBB, Succ1MBB),
2308                            /*InvertCond=*/false);
2309       // If the compares in later blocks need to use values not currently
2310       // exported from this block, export them now.  This block should always
2311       // be the first entry.
2312       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2313 
2314       // Allow some cases to be rejected.
2315       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2316         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2317           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2318           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2319         }
2320 
2321         // Emit the branch for this block.
2322         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2323         SL->SwitchCases.erase(SL->SwitchCases.begin());
2324         return;
2325       }
2326 
2327       // Okay, we decided not to do this, remove any inserted MBB's and clear
2328       // SwitchCases.
2329       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2330         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2331 
2332       SL->SwitchCases.clear();
2333     }
2334   }
2335 
2336   // Create a CaseBlock record representing this branch.
2337   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2338                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2339 
2340   // Use visitSwitchCase to actually insert the fast branch sequence for this
2341   // cond branch.
2342   visitSwitchCase(CB, BrMBB);
2343 }
2344 
2345 /// visitSwitchCase - Emits the necessary code to represent a single node in
2346 /// the binary search tree resulting from lowering a switch instruction.
2347 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2348                                           MachineBasicBlock *SwitchBB) {
2349   SDValue Cond;
2350   SDValue CondLHS = getValue(CB.CmpLHS);
2351   SDLoc dl = CB.DL;
2352 
2353   if (CB.CC == ISD::SETTRUE) {
2354     // Branch or fall through to TrueBB.
2355     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2356     SwitchBB->normalizeSuccProbs();
2357     if (CB.TrueBB != NextBlock(SwitchBB)) {
2358       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2359                               DAG.getBasicBlock(CB.TrueBB)));
2360     }
2361     return;
2362   }
2363 
2364   auto &TLI = DAG.getTargetLoweringInfo();
2365   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2366 
2367   // Build the setcc now.
2368   if (!CB.CmpMHS) {
2369     // Fold "(X == true)" to X and "(X == false)" to !X to
2370     // handle common cases produced by branch lowering.
2371     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2372         CB.CC == ISD::SETEQ)
2373       Cond = CondLHS;
2374     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2375              CB.CC == ISD::SETEQ) {
2376       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2377       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2378     } else {
2379       SDValue CondRHS = getValue(CB.CmpRHS);
2380 
2381       // If a pointer's DAG type is larger than its memory type then the DAG
2382       // values are zero-extended. This breaks signed comparisons so truncate
2383       // back to the underlying type before doing the compare.
2384       if (CondLHS.getValueType() != MemVT) {
2385         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2386         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2387       }
2388       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2389     }
2390   } else {
2391     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2392 
2393     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2394     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2395 
2396     SDValue CmpOp = getValue(CB.CmpMHS);
2397     EVT VT = CmpOp.getValueType();
2398 
2399     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2400       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2401                           ISD::SETLE);
2402     } else {
2403       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2404                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2405       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2406                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2407     }
2408   }
2409 
2410   // Update successor info
2411   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2412   // TrueBB and FalseBB are always different unless the incoming IR is
2413   // degenerate. This only happens when running llc on weird IR.
2414   if (CB.TrueBB != CB.FalseBB)
2415     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2416   SwitchBB->normalizeSuccProbs();
2417 
2418   // If the lhs block is the next block, invert the condition so that we can
2419   // fall through to the lhs instead of the rhs block.
2420   if (CB.TrueBB == NextBlock(SwitchBB)) {
2421     std::swap(CB.TrueBB, CB.FalseBB);
2422     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2423     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2424   }
2425 
2426   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2427                                MVT::Other, getControlRoot(), Cond,
2428                                DAG.getBasicBlock(CB.TrueBB));
2429 
2430   // Insert the false branch. Do this even if it's a fall through branch,
2431   // this makes it easier to do DAG optimizations which require inverting
2432   // the branch condition.
2433   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2434                        DAG.getBasicBlock(CB.FalseBB));
2435 
2436   DAG.setRoot(BrCond);
2437 }
2438 
2439 /// visitJumpTable - Emit JumpTable node in the current MBB
2440 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2441   // Emit the code for the jump table
2442   assert(JT.Reg != -1U && "Should lower JT Header first!");
2443   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2444   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2445                                      JT.Reg, PTy);
2446   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2447   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2448                                     MVT::Other, Index.getValue(1),
2449                                     Table, Index);
2450   DAG.setRoot(BrJumpTable);
2451 }
2452 
2453 /// visitJumpTableHeader - This function emits necessary code to produce index
2454 /// in the JumpTable from switch case.
2455 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2456                                                JumpTableHeader &JTH,
2457                                                MachineBasicBlock *SwitchBB) {
2458   SDLoc dl = getCurSDLoc();
2459 
2460   // Subtract the lowest switch case value from the value being switched on.
2461   SDValue SwitchOp = getValue(JTH.SValue);
2462   EVT VT = SwitchOp.getValueType();
2463   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2464                             DAG.getConstant(JTH.First, dl, VT));
2465 
2466   // The SDNode we just created, which holds the value being switched on minus
2467   // the smallest case value, needs to be copied to a virtual register so it
2468   // can be used as an index into the jump table in a subsequent basic block.
2469   // This value may be smaller or larger than the target's pointer type, and
2470   // therefore require extension or truncating.
2471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2472   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2473 
2474   unsigned JumpTableReg =
2475       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2476   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2477                                     JumpTableReg, SwitchOp);
2478   JT.Reg = JumpTableReg;
2479 
2480   if (!JTH.OmitRangeCheck) {
2481     // Emit the range check for the jump table, and branch to the default block
2482     // for the switch statement if the value being switched on exceeds the
2483     // largest case in the switch.
2484     SDValue CMP = DAG.getSetCC(
2485         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2486                                    Sub.getValueType()),
2487         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2488 
2489     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2490                                  MVT::Other, CopyTo, CMP,
2491                                  DAG.getBasicBlock(JT.Default));
2492 
2493     // Avoid emitting unnecessary branches to the next block.
2494     if (JT.MBB != NextBlock(SwitchBB))
2495       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2496                            DAG.getBasicBlock(JT.MBB));
2497 
2498     DAG.setRoot(BrCond);
2499   } else {
2500     // Avoid emitting unnecessary branches to the next block.
2501     if (JT.MBB != NextBlock(SwitchBB))
2502       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2503                               DAG.getBasicBlock(JT.MBB)));
2504     else
2505       DAG.setRoot(CopyTo);
2506   }
2507 }
2508 
2509 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2510 /// variable if there exists one.
2511 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2512                                  SDValue &Chain) {
2513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2514   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2515   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2516   MachineFunction &MF = DAG.getMachineFunction();
2517   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2518   MachineSDNode *Node =
2519       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2520   if (Global) {
2521     MachinePointerInfo MPInfo(Global);
2522     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2523                  MachineMemOperand::MODereferenceable;
2524     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2525         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2526     DAG.setNodeMemRefs(Node, {MemRef});
2527   }
2528   if (PtrTy != PtrMemTy)
2529     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2530   return SDValue(Node, 0);
2531 }
2532 
2533 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2534 /// tail spliced into a stack protector check success bb.
2535 ///
2536 /// For a high level explanation of how this fits into the stack protector
2537 /// generation see the comment on the declaration of class
2538 /// StackProtectorDescriptor.
2539 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2540                                                   MachineBasicBlock *ParentBB) {
2541 
2542   // First create the loads to the guard/stack slot for the comparison.
2543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2544   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2545   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2546 
2547   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2548   int FI = MFI.getStackProtectorIndex();
2549 
2550   SDValue Guard;
2551   SDLoc dl = getCurSDLoc();
2552   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2553   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2554   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2555 
2556   // Generate code to load the content of the guard slot.
2557   SDValue GuardVal = DAG.getLoad(
2558       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2559       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2560       MachineMemOperand::MOVolatile);
2561 
2562   if (TLI.useStackGuardXorFP())
2563     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2564 
2565   // Retrieve guard check function, nullptr if instrumentation is inlined.
2566   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2567     // The target provides a guard check function to validate the guard value.
2568     // Generate a call to that function with the content of the guard slot as
2569     // argument.
2570     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2571     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2572 
2573     TargetLowering::ArgListTy Args;
2574     TargetLowering::ArgListEntry Entry;
2575     Entry.Node = GuardVal;
2576     Entry.Ty = FnTy->getParamType(0);
2577     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2578       Entry.IsInReg = true;
2579     Args.push_back(Entry);
2580 
2581     TargetLowering::CallLoweringInfo CLI(DAG);
2582     CLI.setDebugLoc(getCurSDLoc())
2583         .setChain(DAG.getEntryNode())
2584         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2585                    getValue(GuardCheckFn), std::move(Args));
2586 
2587     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2588     DAG.setRoot(Result.second);
2589     return;
2590   }
2591 
2592   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2593   // Otherwise, emit a volatile load to retrieve the stack guard value.
2594   SDValue Chain = DAG.getEntryNode();
2595   if (TLI.useLoadStackGuardNode()) {
2596     Guard = getLoadStackGuard(DAG, dl, Chain);
2597   } else {
2598     const Value *IRGuard = TLI.getSDagStackGuard(M);
2599     SDValue GuardPtr = getValue(IRGuard);
2600 
2601     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2602                         MachinePointerInfo(IRGuard, 0), Align,
2603                         MachineMemOperand::MOVolatile);
2604   }
2605 
2606   // Perform the comparison via a getsetcc.
2607   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2608                                                         *DAG.getContext(),
2609                                                         Guard.getValueType()),
2610                              Guard, GuardVal, ISD::SETNE);
2611 
2612   // If the guard/stackslot do not equal, branch to failure MBB.
2613   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2614                                MVT::Other, GuardVal.getOperand(0),
2615                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2616   // Otherwise branch to success MBB.
2617   SDValue Br = DAG.getNode(ISD::BR, dl,
2618                            MVT::Other, BrCond,
2619                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2620 
2621   DAG.setRoot(Br);
2622 }
2623 
2624 /// Codegen the failure basic block for a stack protector check.
2625 ///
2626 /// A failure stack protector machine basic block consists simply of a call to
2627 /// __stack_chk_fail().
2628 ///
2629 /// For a high level explanation of how this fits into the stack protector
2630 /// generation see the comment on the declaration of class
2631 /// StackProtectorDescriptor.
2632 void
2633 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2635   TargetLowering::MakeLibCallOptions CallOptions;
2636   CallOptions.setDiscardResult(true);
2637   SDValue Chain =
2638       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2639                       None, CallOptions, getCurSDLoc()).second;
2640   // On PS4, the "return address" must still be within the calling function,
2641   // even if it's at the very end, so emit an explicit TRAP here.
2642   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2643   if (TM.getTargetTriple().isPS4CPU())
2644     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2645   // WebAssembly needs an unreachable instruction after a non-returning call,
2646   // because the function return type can be different from __stack_chk_fail's
2647   // return type (void).
2648   if (TM.getTargetTriple().isWasm())
2649     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2650 
2651   DAG.setRoot(Chain);
2652 }
2653 
2654 /// visitBitTestHeader - This function emits necessary code to produce value
2655 /// suitable for "bit tests"
2656 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2657                                              MachineBasicBlock *SwitchBB) {
2658   SDLoc dl = getCurSDLoc();
2659 
2660   // Subtract the minimum value.
2661   SDValue SwitchOp = getValue(B.SValue);
2662   EVT VT = SwitchOp.getValueType();
2663   SDValue RangeSub =
2664       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2665 
2666   // Determine the type of the test operands.
2667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2668   bool UsePtrType = false;
2669   if (!TLI.isTypeLegal(VT)) {
2670     UsePtrType = true;
2671   } else {
2672     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2673       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2674         // Switch table case range are encoded into series of masks.
2675         // Just use pointer type, it's guaranteed to fit.
2676         UsePtrType = true;
2677         break;
2678       }
2679   }
2680   SDValue Sub = RangeSub;
2681   if (UsePtrType) {
2682     VT = TLI.getPointerTy(DAG.getDataLayout());
2683     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2684   }
2685 
2686   B.RegVT = VT.getSimpleVT();
2687   B.Reg = FuncInfo.CreateReg(B.RegVT);
2688   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2689 
2690   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2691 
2692   if (!B.OmitRangeCheck)
2693     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2694   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2695   SwitchBB->normalizeSuccProbs();
2696 
2697   SDValue Root = CopyTo;
2698   if (!B.OmitRangeCheck) {
2699     // Conditional branch to the default block.
2700     SDValue RangeCmp = DAG.getSetCC(dl,
2701         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2702                                RangeSub.getValueType()),
2703         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2704         ISD::SETUGT);
2705 
2706     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2707                        DAG.getBasicBlock(B.Default));
2708   }
2709 
2710   // Avoid emitting unnecessary branches to the next block.
2711   if (MBB != NextBlock(SwitchBB))
2712     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2713 
2714   DAG.setRoot(Root);
2715 }
2716 
2717 /// visitBitTestCase - this function produces one "bit test"
2718 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2719                                            MachineBasicBlock* NextMBB,
2720                                            BranchProbability BranchProbToNext,
2721                                            unsigned Reg,
2722                                            BitTestCase &B,
2723                                            MachineBasicBlock *SwitchBB) {
2724   SDLoc dl = getCurSDLoc();
2725   MVT VT = BB.RegVT;
2726   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2727   SDValue Cmp;
2728   unsigned PopCount = countPopulation(B.Mask);
2729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2730   if (PopCount == 1) {
2731     // Testing for a single bit; just compare the shift count with what it
2732     // would need to be to shift a 1 bit in that position.
2733     Cmp = DAG.getSetCC(
2734         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2735         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2736         ISD::SETEQ);
2737   } else if (PopCount == BB.Range) {
2738     // There is only one zero bit in the range, test for it directly.
2739     Cmp = DAG.getSetCC(
2740         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2741         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2742         ISD::SETNE);
2743   } else {
2744     // Make desired shift
2745     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2746                                     DAG.getConstant(1, dl, VT), ShiftOp);
2747 
2748     // Emit bit tests and jumps
2749     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2750                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2751     Cmp = DAG.getSetCC(
2752         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2753         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2754   }
2755 
2756   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2757   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2758   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2759   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2760   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2761   // one as they are relative probabilities (and thus work more like weights),
2762   // and hence we need to normalize them to let the sum of them become one.
2763   SwitchBB->normalizeSuccProbs();
2764 
2765   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2766                               MVT::Other, getControlRoot(),
2767                               Cmp, DAG.getBasicBlock(B.TargetBB));
2768 
2769   // Avoid emitting unnecessary branches to the next block.
2770   if (NextMBB != NextBlock(SwitchBB))
2771     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2772                         DAG.getBasicBlock(NextMBB));
2773 
2774   DAG.setRoot(BrAnd);
2775 }
2776 
2777 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2778   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2779 
2780   // Retrieve successors. Look through artificial IR level blocks like
2781   // catchswitch for successors.
2782   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2783   const BasicBlock *EHPadBB = I.getSuccessor(1);
2784 
2785   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2786   // have to do anything here to lower funclet bundles.
2787   assert(!I.hasOperandBundlesOtherThan(
2788              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2789               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2790               LLVMContext::OB_cfguardtarget,
2791               LLVMContext::OB_clang_arc_attachedcall}) &&
2792          "Cannot lower invokes with arbitrary operand bundles yet!");
2793 
2794   const Value *Callee(I.getCalledOperand());
2795   const Function *Fn = dyn_cast<Function>(Callee);
2796   if (isa<InlineAsm>(Callee))
2797     visitInlineAsm(I);
2798   else if (Fn && Fn->isIntrinsic()) {
2799     switch (Fn->getIntrinsicID()) {
2800     default:
2801       llvm_unreachable("Cannot invoke this intrinsic");
2802     case Intrinsic::donothing:
2803       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2804       break;
2805     case Intrinsic::experimental_patchpoint_void:
2806     case Intrinsic::experimental_patchpoint_i64:
2807       visitPatchpoint(I, EHPadBB);
2808       break;
2809     case Intrinsic::experimental_gc_statepoint:
2810       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2811       break;
2812     case Intrinsic::wasm_rethrow: {
2813       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2814       // special because it can be invoked, so we manually lower it to a DAG
2815       // node here.
2816       SmallVector<SDValue, 8> Ops;
2817       Ops.push_back(getRoot()); // inchain
2818       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2819       Ops.push_back(
2820           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2821                                 TLI.getPointerTy(DAG.getDataLayout())));
2822       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2823       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2824       break;
2825     }
2826     }
2827   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2828     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2829     // Eventually we will support lowering the @llvm.experimental.deoptimize
2830     // intrinsic, and right now there are no plans to support other intrinsics
2831     // with deopt state.
2832     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2833   } else {
2834     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2835   }
2836 
2837   // If the value of the invoke is used outside of its defining block, make it
2838   // available as a virtual register.
2839   // We already took care of the exported value for the statepoint instruction
2840   // during call to the LowerStatepoint.
2841   if (!isa<GCStatepointInst>(I)) {
2842     CopyToExportRegsIfNeeded(&I);
2843   }
2844 
2845   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2846   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2847   BranchProbability EHPadBBProb =
2848       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2849           : BranchProbability::getZero();
2850   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2851 
2852   // Update successor info.
2853   addSuccessorWithProb(InvokeMBB, Return);
2854   for (auto &UnwindDest : UnwindDests) {
2855     UnwindDest.first->setIsEHPad();
2856     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2857   }
2858   InvokeMBB->normalizeSuccProbs();
2859 
2860   // Drop into normal successor.
2861   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2862                           DAG.getBasicBlock(Return)));
2863 }
2864 
2865 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2866   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2867 
2868   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2869   // have to do anything here to lower funclet bundles.
2870   assert(!I.hasOperandBundlesOtherThan(
2871              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2872          "Cannot lower callbrs with arbitrary operand bundles yet!");
2873 
2874   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2875   visitInlineAsm(I);
2876   CopyToExportRegsIfNeeded(&I);
2877 
2878   // Retrieve successors.
2879   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2880 
2881   // Update successor info.
2882   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2883   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2884     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2885     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2886     Target->setIsInlineAsmBrIndirectTarget();
2887   }
2888   CallBrMBB->normalizeSuccProbs();
2889 
2890   // Drop into default successor.
2891   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2892                           MVT::Other, getControlRoot(),
2893                           DAG.getBasicBlock(Return)));
2894 }
2895 
2896 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2897   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2898 }
2899 
2900 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2901   assert(FuncInfo.MBB->isEHPad() &&
2902          "Call to landingpad not in landing pad!");
2903 
2904   // If there aren't registers to copy the values into (e.g., during SjLj
2905   // exceptions), then don't bother to create these DAG nodes.
2906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2907   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2908   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2909       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2910     return;
2911 
2912   // If landingpad's return type is token type, we don't create DAG nodes
2913   // for its exception pointer and selector value. The extraction of exception
2914   // pointer or selector value from token type landingpads is not currently
2915   // supported.
2916   if (LP.getType()->isTokenTy())
2917     return;
2918 
2919   SmallVector<EVT, 2> ValueVTs;
2920   SDLoc dl = getCurSDLoc();
2921   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2922   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2923 
2924   // Get the two live-in registers as SDValues. The physregs have already been
2925   // copied into virtual registers.
2926   SDValue Ops[2];
2927   if (FuncInfo.ExceptionPointerVirtReg) {
2928     Ops[0] = DAG.getZExtOrTrunc(
2929         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2930                            FuncInfo.ExceptionPointerVirtReg,
2931                            TLI.getPointerTy(DAG.getDataLayout())),
2932         dl, ValueVTs[0]);
2933   } else {
2934     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2935   }
2936   Ops[1] = DAG.getZExtOrTrunc(
2937       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2938                          FuncInfo.ExceptionSelectorVirtReg,
2939                          TLI.getPointerTy(DAG.getDataLayout())),
2940       dl, ValueVTs[1]);
2941 
2942   // Merge into one.
2943   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2944                             DAG.getVTList(ValueVTs), Ops);
2945   setValue(&LP, Res);
2946 }
2947 
2948 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2949                                            MachineBasicBlock *Last) {
2950   // Update JTCases.
2951   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2952     if (SL->JTCases[i].first.HeaderBB == First)
2953       SL->JTCases[i].first.HeaderBB = Last;
2954 
2955   // Update BitTestCases.
2956   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2957     if (SL->BitTestCases[i].Parent == First)
2958       SL->BitTestCases[i].Parent = Last;
2959 }
2960 
2961 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2962   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2963 
2964   // Update machine-CFG edges with unique successors.
2965   SmallSet<BasicBlock*, 32> Done;
2966   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2967     BasicBlock *BB = I.getSuccessor(i);
2968     bool Inserted = Done.insert(BB).second;
2969     if (!Inserted)
2970         continue;
2971 
2972     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2973     addSuccessorWithProb(IndirectBrMBB, Succ);
2974   }
2975   IndirectBrMBB->normalizeSuccProbs();
2976 
2977   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2978                           MVT::Other, getControlRoot(),
2979                           getValue(I.getAddress())));
2980 }
2981 
2982 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2983   if (!DAG.getTarget().Options.TrapUnreachable)
2984     return;
2985 
2986   // We may be able to ignore unreachable behind a noreturn call.
2987   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2988     const BasicBlock &BB = *I.getParent();
2989     if (&I != &BB.front()) {
2990       BasicBlock::const_iterator PredI =
2991         std::prev(BasicBlock::const_iterator(&I));
2992       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2993         if (Call->doesNotReturn())
2994           return;
2995       }
2996     }
2997   }
2998 
2999   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3000 }
3001 
3002 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3003   SDNodeFlags Flags;
3004 
3005   SDValue Op = getValue(I.getOperand(0));
3006   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3007                                     Op, Flags);
3008   setValue(&I, UnNodeValue);
3009 }
3010 
3011 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3012   SDNodeFlags Flags;
3013   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3014     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3015     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3016   }
3017   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3018     Flags.setExact(ExactOp->isExact());
3019   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3020     Flags.copyFMF(*FPOp);
3021 
3022   SDValue Op1 = getValue(I.getOperand(0));
3023   SDValue Op2 = getValue(I.getOperand(1));
3024   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3025                                      Op1, Op2, Flags);
3026   setValue(&I, BinNodeValue);
3027 }
3028 
3029 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3030   SDValue Op1 = getValue(I.getOperand(0));
3031   SDValue Op2 = getValue(I.getOperand(1));
3032 
3033   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3034       Op1.getValueType(), DAG.getDataLayout());
3035 
3036   // Coerce the shift amount to the right type if we can.
3037   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3038     unsigned ShiftSize = ShiftTy.getSizeInBits();
3039     unsigned Op2Size = Op2.getValueSizeInBits();
3040     SDLoc DL = getCurSDLoc();
3041 
3042     // If the operand is smaller than the shift count type, promote it.
3043     if (ShiftSize > Op2Size)
3044       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3045 
3046     // If the operand is larger than the shift count type but the shift
3047     // count type has enough bits to represent any shift value, truncate
3048     // it now. This is a common case and it exposes the truncate to
3049     // optimization early.
3050     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3051       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3052     // Otherwise we'll need to temporarily settle for some other convenient
3053     // type.  Type legalization will make adjustments once the shiftee is split.
3054     else
3055       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3056   }
3057 
3058   bool nuw = false;
3059   bool nsw = false;
3060   bool exact = false;
3061 
3062   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3063 
3064     if (const OverflowingBinaryOperator *OFBinOp =
3065             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3066       nuw = OFBinOp->hasNoUnsignedWrap();
3067       nsw = OFBinOp->hasNoSignedWrap();
3068     }
3069     if (const PossiblyExactOperator *ExactOp =
3070             dyn_cast<const PossiblyExactOperator>(&I))
3071       exact = ExactOp->isExact();
3072   }
3073   SDNodeFlags Flags;
3074   Flags.setExact(exact);
3075   Flags.setNoSignedWrap(nsw);
3076   Flags.setNoUnsignedWrap(nuw);
3077   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3078                             Flags);
3079   setValue(&I, Res);
3080 }
3081 
3082 void SelectionDAGBuilder::visitSDiv(const User &I) {
3083   SDValue Op1 = getValue(I.getOperand(0));
3084   SDValue Op2 = getValue(I.getOperand(1));
3085 
3086   SDNodeFlags Flags;
3087   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3088                  cast<PossiblyExactOperator>(&I)->isExact());
3089   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3090                            Op2, Flags));
3091 }
3092 
3093 void SelectionDAGBuilder::visitICmp(const User &I) {
3094   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3095   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3096     predicate = IC->getPredicate();
3097   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3098     predicate = ICmpInst::Predicate(IC->getPredicate());
3099   SDValue Op1 = getValue(I.getOperand(0));
3100   SDValue Op2 = getValue(I.getOperand(1));
3101   ISD::CondCode Opcode = getICmpCondCode(predicate);
3102 
3103   auto &TLI = DAG.getTargetLoweringInfo();
3104   EVT MemVT =
3105       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3106 
3107   // If a pointer's DAG type is larger than its memory type then the DAG values
3108   // are zero-extended. This breaks signed comparisons so truncate back to the
3109   // underlying type before doing the compare.
3110   if (Op1.getValueType() != MemVT) {
3111     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3112     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3113   }
3114 
3115   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3116                                                         I.getType());
3117   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3118 }
3119 
3120 void SelectionDAGBuilder::visitFCmp(const User &I) {
3121   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3122   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3123     predicate = FC->getPredicate();
3124   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3125     predicate = FCmpInst::Predicate(FC->getPredicate());
3126   SDValue Op1 = getValue(I.getOperand(0));
3127   SDValue Op2 = getValue(I.getOperand(1));
3128 
3129   ISD::CondCode Condition = getFCmpCondCode(predicate);
3130   auto *FPMO = cast<FPMathOperator>(&I);
3131   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3132     Condition = getFCmpCodeWithoutNaN(Condition);
3133 
3134   SDNodeFlags Flags;
3135   Flags.copyFMF(*FPMO);
3136   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3137 
3138   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3139                                                         I.getType());
3140   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3141 }
3142 
3143 // Check if the condition of the select has one use or two users that are both
3144 // selects with the same condition.
3145 static bool hasOnlySelectUsers(const Value *Cond) {
3146   return llvm::all_of(Cond->users(), [](const Value *V) {
3147     return isa<SelectInst>(V);
3148   });
3149 }
3150 
3151 void SelectionDAGBuilder::visitSelect(const User &I) {
3152   SmallVector<EVT, 4> ValueVTs;
3153   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3154                   ValueVTs);
3155   unsigned NumValues = ValueVTs.size();
3156   if (NumValues == 0) return;
3157 
3158   SmallVector<SDValue, 4> Values(NumValues);
3159   SDValue Cond     = getValue(I.getOperand(0));
3160   SDValue LHSVal   = getValue(I.getOperand(1));
3161   SDValue RHSVal   = getValue(I.getOperand(2));
3162   SmallVector<SDValue, 1> BaseOps(1, Cond);
3163   ISD::NodeType OpCode =
3164       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3165 
3166   bool IsUnaryAbs = false;
3167   bool Negate = false;
3168 
3169   SDNodeFlags Flags;
3170   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3171     Flags.copyFMF(*FPOp);
3172 
3173   // Min/max matching is only viable if all output VTs are the same.
3174   if (is_splat(ValueVTs)) {
3175     EVT VT = ValueVTs[0];
3176     LLVMContext &Ctx = *DAG.getContext();
3177     auto &TLI = DAG.getTargetLoweringInfo();
3178 
3179     // We care about the legality of the operation after it has been type
3180     // legalized.
3181     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3182       VT = TLI.getTypeToTransformTo(Ctx, VT);
3183 
3184     // If the vselect is legal, assume we want to leave this as a vector setcc +
3185     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3186     // min/max is legal on the scalar type.
3187     bool UseScalarMinMax = VT.isVector() &&
3188       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3189 
3190     Value *LHS, *RHS;
3191     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3192     ISD::NodeType Opc = ISD::DELETED_NODE;
3193     switch (SPR.Flavor) {
3194     case SPF_UMAX:    Opc = ISD::UMAX; break;
3195     case SPF_UMIN:    Opc = ISD::UMIN; break;
3196     case SPF_SMAX:    Opc = ISD::SMAX; break;
3197     case SPF_SMIN:    Opc = ISD::SMIN; break;
3198     case SPF_FMINNUM:
3199       switch (SPR.NaNBehavior) {
3200       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3201       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3202       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3203       case SPNB_RETURNS_ANY: {
3204         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3205           Opc = ISD::FMINNUM;
3206         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3207           Opc = ISD::FMINIMUM;
3208         else if (UseScalarMinMax)
3209           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3210             ISD::FMINNUM : ISD::FMINIMUM;
3211         break;
3212       }
3213       }
3214       break;
3215     case SPF_FMAXNUM:
3216       switch (SPR.NaNBehavior) {
3217       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3218       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3219       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3220       case SPNB_RETURNS_ANY:
3221 
3222         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3223           Opc = ISD::FMAXNUM;
3224         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3225           Opc = ISD::FMAXIMUM;
3226         else if (UseScalarMinMax)
3227           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3228             ISD::FMAXNUM : ISD::FMAXIMUM;
3229         break;
3230       }
3231       break;
3232     case SPF_NABS:
3233       Negate = true;
3234       LLVM_FALLTHROUGH;
3235     case SPF_ABS:
3236       IsUnaryAbs = true;
3237       Opc = ISD::ABS;
3238       break;
3239     default: break;
3240     }
3241 
3242     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3243         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3244          (UseScalarMinMax &&
3245           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3246         // If the underlying comparison instruction is used by any other
3247         // instruction, the consumed instructions won't be destroyed, so it is
3248         // not profitable to convert to a min/max.
3249         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3250       OpCode = Opc;
3251       LHSVal = getValue(LHS);
3252       RHSVal = getValue(RHS);
3253       BaseOps.clear();
3254     }
3255 
3256     if (IsUnaryAbs) {
3257       OpCode = Opc;
3258       LHSVal = getValue(LHS);
3259       BaseOps.clear();
3260     }
3261   }
3262 
3263   if (IsUnaryAbs) {
3264     for (unsigned i = 0; i != NumValues; ++i) {
3265       SDLoc dl = getCurSDLoc();
3266       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3267       Values[i] =
3268           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3269       if (Negate)
3270         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3271                                 Values[i]);
3272     }
3273   } else {
3274     for (unsigned i = 0; i != NumValues; ++i) {
3275       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3276       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3277       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3278       Values[i] = DAG.getNode(
3279           OpCode, getCurSDLoc(),
3280           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3281     }
3282   }
3283 
3284   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3285                            DAG.getVTList(ValueVTs), Values));
3286 }
3287 
3288 void SelectionDAGBuilder::visitTrunc(const User &I) {
3289   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3290   SDValue N = getValue(I.getOperand(0));
3291   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3292                                                         I.getType());
3293   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3294 }
3295 
3296 void SelectionDAGBuilder::visitZExt(const User &I) {
3297   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3298   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3299   SDValue N = getValue(I.getOperand(0));
3300   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3301                                                         I.getType());
3302   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3303 }
3304 
3305 void SelectionDAGBuilder::visitSExt(const User &I) {
3306   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3307   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3308   SDValue N = getValue(I.getOperand(0));
3309   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3310                                                         I.getType());
3311   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3312 }
3313 
3314 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3315   // FPTrunc is never a no-op cast, no need to check
3316   SDValue N = getValue(I.getOperand(0));
3317   SDLoc dl = getCurSDLoc();
3318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3319   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3320   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3321                            DAG.getTargetConstant(
3322                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3323 }
3324 
3325 void SelectionDAGBuilder::visitFPExt(const User &I) {
3326   // FPExt is never a no-op cast, no need to check
3327   SDValue N = getValue(I.getOperand(0));
3328   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3329                                                         I.getType());
3330   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3331 }
3332 
3333 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3334   // FPToUI is never a no-op cast, no need to check
3335   SDValue N = getValue(I.getOperand(0));
3336   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3337                                                         I.getType());
3338   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3339 }
3340 
3341 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3342   // FPToSI is never a no-op cast, no need to check
3343   SDValue N = getValue(I.getOperand(0));
3344   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3345                                                         I.getType());
3346   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3347 }
3348 
3349 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3350   // UIToFP is never a no-op cast, no need to check
3351   SDValue N = getValue(I.getOperand(0));
3352   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3353                                                         I.getType());
3354   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3355 }
3356 
3357 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3358   // SIToFP is never a no-op cast, no need to check
3359   SDValue N = getValue(I.getOperand(0));
3360   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3361                                                         I.getType());
3362   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3363 }
3364 
3365 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3366   // What to do depends on the size of the integer and the size of the pointer.
3367   // We can either truncate, zero extend, or no-op, accordingly.
3368   SDValue N = getValue(I.getOperand(0));
3369   auto &TLI = DAG.getTargetLoweringInfo();
3370   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3371                                                         I.getType());
3372   EVT PtrMemVT =
3373       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3374   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3375   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3376   setValue(&I, N);
3377 }
3378 
3379 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3380   // What to do depends on the size of the integer and the size of the pointer.
3381   // We can either truncate, zero extend, or no-op, accordingly.
3382   SDValue N = getValue(I.getOperand(0));
3383   auto &TLI = DAG.getTargetLoweringInfo();
3384   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3385   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3386   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3387   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3388   setValue(&I, N);
3389 }
3390 
3391 void SelectionDAGBuilder::visitBitCast(const User &I) {
3392   SDValue N = getValue(I.getOperand(0));
3393   SDLoc dl = getCurSDLoc();
3394   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3395                                                         I.getType());
3396 
3397   // BitCast assures us that source and destination are the same size so this is
3398   // either a BITCAST or a no-op.
3399   if (DestVT != N.getValueType())
3400     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3401                              DestVT, N)); // convert types.
3402   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3403   // might fold any kind of constant expression to an integer constant and that
3404   // is not what we are looking for. Only recognize a bitcast of a genuine
3405   // constant integer as an opaque constant.
3406   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3407     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3408                                  /*isOpaque*/true));
3409   else
3410     setValue(&I, N);            // noop cast.
3411 }
3412 
3413 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3415   const Value *SV = I.getOperand(0);
3416   SDValue N = getValue(SV);
3417   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3418 
3419   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3420   unsigned DestAS = I.getType()->getPointerAddressSpace();
3421 
3422   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3423     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3424 
3425   setValue(&I, N);
3426 }
3427 
3428 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3430   SDValue InVec = getValue(I.getOperand(0));
3431   SDValue InVal = getValue(I.getOperand(1));
3432   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3433                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3434   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3435                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3436                            InVec, InVal, InIdx));
3437 }
3438 
3439 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3441   SDValue InVec = getValue(I.getOperand(0));
3442   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3443                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3444   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3445                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3446                            InVec, InIdx));
3447 }
3448 
3449 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3450   SDValue Src1 = getValue(I.getOperand(0));
3451   SDValue Src2 = getValue(I.getOperand(1));
3452   ArrayRef<int> Mask;
3453   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3454     Mask = SVI->getShuffleMask();
3455   else
3456     Mask = cast<ConstantExpr>(I).getShuffleMask();
3457   SDLoc DL = getCurSDLoc();
3458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3459   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3460   EVT SrcVT = Src1.getValueType();
3461 
3462   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3463       VT.isScalableVector()) {
3464     // Canonical splat form of first element of first input vector.
3465     SDValue FirstElt =
3466         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3467                     DAG.getVectorIdxConstant(0, DL));
3468     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3469     return;
3470   }
3471 
3472   // For now, we only handle splats for scalable vectors.
3473   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3474   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3475   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3476 
3477   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3478   unsigned MaskNumElts = Mask.size();
3479 
3480   if (SrcNumElts == MaskNumElts) {
3481     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3482     return;
3483   }
3484 
3485   // Normalize the shuffle vector since mask and vector length don't match.
3486   if (SrcNumElts < MaskNumElts) {
3487     // Mask is longer than the source vectors. We can use concatenate vector to
3488     // make the mask and vectors lengths match.
3489 
3490     if (MaskNumElts % SrcNumElts == 0) {
3491       // Mask length is a multiple of the source vector length.
3492       // Check if the shuffle is some kind of concatenation of the input
3493       // vectors.
3494       unsigned NumConcat = MaskNumElts / SrcNumElts;
3495       bool IsConcat = true;
3496       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3497       for (unsigned i = 0; i != MaskNumElts; ++i) {
3498         int Idx = Mask[i];
3499         if (Idx < 0)
3500           continue;
3501         // Ensure the indices in each SrcVT sized piece are sequential and that
3502         // the same source is used for the whole piece.
3503         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3504             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3505              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3506           IsConcat = false;
3507           break;
3508         }
3509         // Remember which source this index came from.
3510         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3511       }
3512 
3513       // The shuffle is concatenating multiple vectors together. Just emit
3514       // a CONCAT_VECTORS operation.
3515       if (IsConcat) {
3516         SmallVector<SDValue, 8> ConcatOps;
3517         for (auto Src : ConcatSrcs) {
3518           if (Src < 0)
3519             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3520           else if (Src == 0)
3521             ConcatOps.push_back(Src1);
3522           else
3523             ConcatOps.push_back(Src2);
3524         }
3525         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3526         return;
3527       }
3528     }
3529 
3530     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3531     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3532     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3533                                     PaddedMaskNumElts);
3534 
3535     // Pad both vectors with undefs to make them the same length as the mask.
3536     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3537 
3538     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3539     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3540     MOps1[0] = Src1;
3541     MOps2[0] = Src2;
3542 
3543     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3544     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3545 
3546     // Readjust mask for new input vector length.
3547     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3548     for (unsigned i = 0; i != MaskNumElts; ++i) {
3549       int Idx = Mask[i];
3550       if (Idx >= (int)SrcNumElts)
3551         Idx -= SrcNumElts - PaddedMaskNumElts;
3552       MappedOps[i] = Idx;
3553     }
3554 
3555     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3556 
3557     // If the concatenated vector was padded, extract a subvector with the
3558     // correct number of elements.
3559     if (MaskNumElts != PaddedMaskNumElts)
3560       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3561                            DAG.getVectorIdxConstant(0, DL));
3562 
3563     setValue(&I, Result);
3564     return;
3565   }
3566 
3567   if (SrcNumElts > MaskNumElts) {
3568     // Analyze the access pattern of the vector to see if we can extract
3569     // two subvectors and do the shuffle.
3570     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3571     bool CanExtract = true;
3572     for (int Idx : Mask) {
3573       unsigned Input = 0;
3574       if (Idx < 0)
3575         continue;
3576 
3577       if (Idx >= (int)SrcNumElts) {
3578         Input = 1;
3579         Idx -= SrcNumElts;
3580       }
3581 
3582       // If all the indices come from the same MaskNumElts sized portion of
3583       // the sources we can use extract. Also make sure the extract wouldn't
3584       // extract past the end of the source.
3585       int NewStartIdx = alignDown(Idx, MaskNumElts);
3586       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3587           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3588         CanExtract = false;
3589       // Make sure we always update StartIdx as we use it to track if all
3590       // elements are undef.
3591       StartIdx[Input] = NewStartIdx;
3592     }
3593 
3594     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3595       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3596       return;
3597     }
3598     if (CanExtract) {
3599       // Extract appropriate subvector and generate a vector shuffle
3600       for (unsigned Input = 0; Input < 2; ++Input) {
3601         SDValue &Src = Input == 0 ? Src1 : Src2;
3602         if (StartIdx[Input] < 0)
3603           Src = DAG.getUNDEF(VT);
3604         else {
3605           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3606                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3607         }
3608       }
3609 
3610       // Calculate new mask.
3611       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3612       for (int &Idx : MappedOps) {
3613         if (Idx >= (int)SrcNumElts)
3614           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3615         else if (Idx >= 0)
3616           Idx -= StartIdx[0];
3617       }
3618 
3619       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3620       return;
3621     }
3622   }
3623 
3624   // We can't use either concat vectors or extract subvectors so fall back to
3625   // replacing the shuffle with extract and build vector.
3626   // to insert and build vector.
3627   EVT EltVT = VT.getVectorElementType();
3628   SmallVector<SDValue,8> Ops;
3629   for (int Idx : Mask) {
3630     SDValue Res;
3631 
3632     if (Idx < 0) {
3633       Res = DAG.getUNDEF(EltVT);
3634     } else {
3635       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3636       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3637 
3638       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3639                         DAG.getVectorIdxConstant(Idx, DL));
3640     }
3641 
3642     Ops.push_back(Res);
3643   }
3644 
3645   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3646 }
3647 
3648 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3649   ArrayRef<unsigned> Indices;
3650   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3651     Indices = IV->getIndices();
3652   else
3653     Indices = cast<ConstantExpr>(&I)->getIndices();
3654 
3655   const Value *Op0 = I.getOperand(0);
3656   const Value *Op1 = I.getOperand(1);
3657   Type *AggTy = I.getType();
3658   Type *ValTy = Op1->getType();
3659   bool IntoUndef = isa<UndefValue>(Op0);
3660   bool FromUndef = isa<UndefValue>(Op1);
3661 
3662   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3663 
3664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3665   SmallVector<EVT, 4> AggValueVTs;
3666   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3667   SmallVector<EVT, 4> ValValueVTs;
3668   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3669 
3670   unsigned NumAggValues = AggValueVTs.size();
3671   unsigned NumValValues = ValValueVTs.size();
3672   SmallVector<SDValue, 4> Values(NumAggValues);
3673 
3674   // Ignore an insertvalue that produces an empty object
3675   if (!NumAggValues) {
3676     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3677     return;
3678   }
3679 
3680   SDValue Agg = getValue(Op0);
3681   unsigned i = 0;
3682   // Copy the beginning value(s) from the original aggregate.
3683   for (; i != LinearIndex; ++i)
3684     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3685                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3686   // Copy values from the inserted value(s).
3687   if (NumValValues) {
3688     SDValue Val = getValue(Op1);
3689     for (; i != LinearIndex + NumValValues; ++i)
3690       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3691                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3692   }
3693   // Copy remaining value(s) from the original aggregate.
3694   for (; i != NumAggValues; ++i)
3695     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3696                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3697 
3698   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3699                            DAG.getVTList(AggValueVTs), Values));
3700 }
3701 
3702 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3703   ArrayRef<unsigned> Indices;
3704   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3705     Indices = EV->getIndices();
3706   else
3707     Indices = cast<ConstantExpr>(&I)->getIndices();
3708 
3709   const Value *Op0 = I.getOperand(0);
3710   Type *AggTy = Op0->getType();
3711   Type *ValTy = I.getType();
3712   bool OutOfUndef = isa<UndefValue>(Op0);
3713 
3714   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3715 
3716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3717   SmallVector<EVT, 4> ValValueVTs;
3718   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3719 
3720   unsigned NumValValues = ValValueVTs.size();
3721 
3722   // Ignore a extractvalue that produces an empty object
3723   if (!NumValValues) {
3724     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3725     return;
3726   }
3727 
3728   SmallVector<SDValue, 4> Values(NumValValues);
3729 
3730   SDValue Agg = getValue(Op0);
3731   // Copy out the selected value(s).
3732   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3733     Values[i - LinearIndex] =
3734       OutOfUndef ?
3735         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3736         SDValue(Agg.getNode(), Agg.getResNo() + i);
3737 
3738   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3739                            DAG.getVTList(ValValueVTs), Values));
3740 }
3741 
3742 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3743   Value *Op0 = I.getOperand(0);
3744   // Note that the pointer operand may be a vector of pointers. Take the scalar
3745   // element which holds a pointer.
3746   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3747   SDValue N = getValue(Op0);
3748   SDLoc dl = getCurSDLoc();
3749   auto &TLI = DAG.getTargetLoweringInfo();
3750 
3751   // Normalize Vector GEP - all scalar operands should be converted to the
3752   // splat vector.
3753   bool IsVectorGEP = I.getType()->isVectorTy();
3754   ElementCount VectorElementCount =
3755       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3756                   : ElementCount::getFixed(0);
3757 
3758   if (IsVectorGEP && !N.getValueType().isVector()) {
3759     LLVMContext &Context = *DAG.getContext();
3760     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3761     if (VectorElementCount.isScalable())
3762       N = DAG.getSplatVector(VT, dl, N);
3763     else
3764       N = DAG.getSplatBuildVector(VT, dl, N);
3765   }
3766 
3767   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3768        GTI != E; ++GTI) {
3769     const Value *Idx = GTI.getOperand();
3770     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3771       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3772       if (Field) {
3773         // N = N + Offset
3774         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3775 
3776         // In an inbounds GEP with an offset that is nonnegative even when
3777         // interpreted as signed, assume there is no unsigned overflow.
3778         SDNodeFlags Flags;
3779         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3780           Flags.setNoUnsignedWrap(true);
3781 
3782         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3783                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3784       }
3785     } else {
3786       // IdxSize is the width of the arithmetic according to IR semantics.
3787       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3788       // (and fix up the result later).
3789       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3790       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3791       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3792       // We intentionally mask away the high bits here; ElementSize may not
3793       // fit in IdxTy.
3794       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3795       bool ElementScalable = ElementSize.isScalable();
3796 
3797       // If this is a scalar constant or a splat vector of constants,
3798       // handle it quickly.
3799       const auto *C = dyn_cast<Constant>(Idx);
3800       if (C && isa<VectorType>(C->getType()))
3801         C = C->getSplatValue();
3802 
3803       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3804       if (CI && CI->isZero())
3805         continue;
3806       if (CI && !ElementScalable) {
3807         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3808         LLVMContext &Context = *DAG.getContext();
3809         SDValue OffsVal;
3810         if (IsVectorGEP)
3811           OffsVal = DAG.getConstant(
3812               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3813         else
3814           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3815 
3816         // In an inbounds GEP with an offset that is nonnegative even when
3817         // interpreted as signed, assume there is no unsigned overflow.
3818         SDNodeFlags Flags;
3819         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3820           Flags.setNoUnsignedWrap(true);
3821 
3822         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3823 
3824         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3825         continue;
3826       }
3827 
3828       // N = N + Idx * ElementMul;
3829       SDValue IdxN = getValue(Idx);
3830 
3831       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3832         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3833                                   VectorElementCount);
3834         if (VectorElementCount.isScalable())
3835           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3836         else
3837           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3838       }
3839 
3840       // If the index is smaller or larger than intptr_t, truncate or extend
3841       // it.
3842       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3843 
3844       if (ElementScalable) {
3845         EVT VScaleTy = N.getValueType().getScalarType();
3846         SDValue VScale = DAG.getNode(
3847             ISD::VSCALE, dl, VScaleTy,
3848             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3849         if (IsVectorGEP)
3850           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3851         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3852       } else {
3853         // If this is a multiply by a power of two, turn it into a shl
3854         // immediately.  This is a very common case.
3855         if (ElementMul != 1) {
3856           if (ElementMul.isPowerOf2()) {
3857             unsigned Amt = ElementMul.logBase2();
3858             IdxN = DAG.getNode(ISD::SHL, dl,
3859                                N.getValueType(), IdxN,
3860                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3861           } else {
3862             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3863                                             IdxN.getValueType());
3864             IdxN = DAG.getNode(ISD::MUL, dl,
3865                                N.getValueType(), IdxN, Scale);
3866           }
3867         }
3868       }
3869 
3870       N = DAG.getNode(ISD::ADD, dl,
3871                       N.getValueType(), N, IdxN);
3872     }
3873   }
3874 
3875   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3876   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3877   if (IsVectorGEP) {
3878     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3879     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3880   }
3881 
3882   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3883     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3884 
3885   setValue(&I, N);
3886 }
3887 
3888 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3889   // If this is a fixed sized alloca in the entry block of the function,
3890   // allocate it statically on the stack.
3891   if (FuncInfo.StaticAllocaMap.count(&I))
3892     return;   // getValue will auto-populate this.
3893 
3894   SDLoc dl = getCurSDLoc();
3895   Type *Ty = I.getAllocatedType();
3896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3897   auto &DL = DAG.getDataLayout();
3898   uint64_t TySize = DL.getTypeAllocSize(Ty);
3899   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3900 
3901   SDValue AllocSize = getValue(I.getArraySize());
3902 
3903   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3904   if (AllocSize.getValueType() != IntPtr)
3905     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3906 
3907   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3908                           AllocSize,
3909                           DAG.getConstant(TySize, dl, IntPtr));
3910 
3911   // Handle alignment.  If the requested alignment is less than or equal to
3912   // the stack alignment, ignore it.  If the size is greater than or equal to
3913   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3914   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3915   if (*Alignment <= StackAlign)
3916     Alignment = None;
3917 
3918   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3919   // Round the size of the allocation up to the stack alignment size
3920   // by add SA-1 to the size. This doesn't overflow because we're computing
3921   // an address inside an alloca.
3922   SDNodeFlags Flags;
3923   Flags.setNoUnsignedWrap(true);
3924   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3925                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3926 
3927   // Mask out the low bits for alignment purposes.
3928   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3929                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3930 
3931   SDValue Ops[] = {
3932       getRoot(), AllocSize,
3933       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3934   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3935   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3936   setValue(&I, DSA);
3937   DAG.setRoot(DSA.getValue(1));
3938 
3939   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3940 }
3941 
3942 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3943   if (I.isAtomic())
3944     return visitAtomicLoad(I);
3945 
3946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3947   const Value *SV = I.getOperand(0);
3948   if (TLI.supportSwiftError()) {
3949     // Swifterror values can come from either a function parameter with
3950     // swifterror attribute or an alloca with swifterror attribute.
3951     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3952       if (Arg->hasSwiftErrorAttr())
3953         return visitLoadFromSwiftError(I);
3954     }
3955 
3956     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3957       if (Alloca->isSwiftError())
3958         return visitLoadFromSwiftError(I);
3959     }
3960   }
3961 
3962   SDValue Ptr = getValue(SV);
3963 
3964   Type *Ty = I.getType();
3965   Align Alignment = I.getAlign();
3966 
3967   AAMDNodes AAInfo;
3968   I.getAAMetadata(AAInfo);
3969   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3970 
3971   SmallVector<EVT, 4> ValueVTs, MemVTs;
3972   SmallVector<uint64_t, 4> Offsets;
3973   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3974   unsigned NumValues = ValueVTs.size();
3975   if (NumValues == 0)
3976     return;
3977 
3978   bool isVolatile = I.isVolatile();
3979 
3980   SDValue Root;
3981   bool ConstantMemory = false;
3982   if (isVolatile)
3983     // Serialize volatile loads with other side effects.
3984     Root = getRoot();
3985   else if (NumValues > MaxParallelChains)
3986     Root = getMemoryRoot();
3987   else if (AA &&
3988            AA->pointsToConstantMemory(MemoryLocation(
3989                SV,
3990                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3991                AAInfo))) {
3992     // Do not serialize (non-volatile) loads of constant memory with anything.
3993     Root = DAG.getEntryNode();
3994     ConstantMemory = true;
3995   } else {
3996     // Do not serialize non-volatile loads against each other.
3997     Root = DAG.getRoot();
3998   }
3999 
4000   SDLoc dl = getCurSDLoc();
4001 
4002   if (isVolatile)
4003     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4004 
4005   // An aggregate load cannot wrap around the address space, so offsets to its
4006   // parts don't wrap either.
4007   SDNodeFlags Flags;
4008   Flags.setNoUnsignedWrap(true);
4009 
4010   SmallVector<SDValue, 4> Values(NumValues);
4011   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4012   EVT PtrVT = Ptr.getValueType();
4013 
4014   MachineMemOperand::Flags MMOFlags
4015     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4016 
4017   unsigned ChainI = 0;
4018   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4019     // Serializing loads here may result in excessive register pressure, and
4020     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4021     // could recover a bit by hoisting nodes upward in the chain by recognizing
4022     // they are side-effect free or do not alias. The optimizer should really
4023     // avoid this case by converting large object/array copies to llvm.memcpy
4024     // (MaxParallelChains should always remain as failsafe).
4025     if (ChainI == MaxParallelChains) {
4026       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4027       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4028                                   makeArrayRef(Chains.data(), ChainI));
4029       Root = Chain;
4030       ChainI = 0;
4031     }
4032     SDValue A = DAG.getNode(ISD::ADD, dl,
4033                             PtrVT, Ptr,
4034                             DAG.getConstant(Offsets[i], dl, PtrVT),
4035                             Flags);
4036 
4037     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4038                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4039                             MMOFlags, AAInfo, Ranges);
4040     Chains[ChainI] = L.getValue(1);
4041 
4042     if (MemVTs[i] != ValueVTs[i])
4043       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4044 
4045     Values[i] = L;
4046   }
4047 
4048   if (!ConstantMemory) {
4049     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4050                                 makeArrayRef(Chains.data(), ChainI));
4051     if (isVolatile)
4052       DAG.setRoot(Chain);
4053     else
4054       PendingLoads.push_back(Chain);
4055   }
4056 
4057   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4058                            DAG.getVTList(ValueVTs), Values));
4059 }
4060 
4061 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4062   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4063          "call visitStoreToSwiftError when backend supports swifterror");
4064 
4065   SmallVector<EVT, 4> ValueVTs;
4066   SmallVector<uint64_t, 4> Offsets;
4067   const Value *SrcV = I.getOperand(0);
4068   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4069                   SrcV->getType(), ValueVTs, &Offsets);
4070   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4071          "expect a single EVT for swifterror");
4072 
4073   SDValue Src = getValue(SrcV);
4074   // Create a virtual register, then update the virtual register.
4075   Register VReg =
4076       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4077   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4078   // Chain can be getRoot or getControlRoot.
4079   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4080                                       SDValue(Src.getNode(), Src.getResNo()));
4081   DAG.setRoot(CopyNode);
4082 }
4083 
4084 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4085   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4086          "call visitLoadFromSwiftError when backend supports swifterror");
4087 
4088   assert(!I.isVolatile() &&
4089          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4090          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4091          "Support volatile, non temporal, invariant for load_from_swift_error");
4092 
4093   const Value *SV = I.getOperand(0);
4094   Type *Ty = I.getType();
4095   AAMDNodes AAInfo;
4096   I.getAAMetadata(AAInfo);
4097   assert(
4098       (!AA ||
4099        !AA->pointsToConstantMemory(MemoryLocation(
4100            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4101            AAInfo))) &&
4102       "load_from_swift_error should not be constant memory");
4103 
4104   SmallVector<EVT, 4> ValueVTs;
4105   SmallVector<uint64_t, 4> Offsets;
4106   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4107                   ValueVTs, &Offsets);
4108   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4109          "expect a single EVT for swifterror");
4110 
4111   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4112   SDValue L = DAG.getCopyFromReg(
4113       getRoot(), getCurSDLoc(),
4114       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4115 
4116   setValue(&I, L);
4117 }
4118 
4119 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4120   if (I.isAtomic())
4121     return visitAtomicStore(I);
4122 
4123   const Value *SrcV = I.getOperand(0);
4124   const Value *PtrV = I.getOperand(1);
4125 
4126   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4127   if (TLI.supportSwiftError()) {
4128     // Swifterror values can come from either a function parameter with
4129     // swifterror attribute or an alloca with swifterror attribute.
4130     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4131       if (Arg->hasSwiftErrorAttr())
4132         return visitStoreToSwiftError(I);
4133     }
4134 
4135     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4136       if (Alloca->isSwiftError())
4137         return visitStoreToSwiftError(I);
4138     }
4139   }
4140 
4141   SmallVector<EVT, 4> ValueVTs, MemVTs;
4142   SmallVector<uint64_t, 4> Offsets;
4143   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4144                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4145   unsigned NumValues = ValueVTs.size();
4146   if (NumValues == 0)
4147     return;
4148 
4149   // Get the lowered operands. Note that we do this after
4150   // checking if NumResults is zero, because with zero results
4151   // the operands won't have values in the map.
4152   SDValue Src = getValue(SrcV);
4153   SDValue Ptr = getValue(PtrV);
4154 
4155   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4156   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4157   SDLoc dl = getCurSDLoc();
4158   Align Alignment = I.getAlign();
4159   AAMDNodes AAInfo;
4160   I.getAAMetadata(AAInfo);
4161 
4162   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4163 
4164   // An aggregate load cannot wrap around the address space, so offsets to its
4165   // parts don't wrap either.
4166   SDNodeFlags Flags;
4167   Flags.setNoUnsignedWrap(true);
4168 
4169   unsigned ChainI = 0;
4170   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4171     // See visitLoad comments.
4172     if (ChainI == MaxParallelChains) {
4173       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4174                                   makeArrayRef(Chains.data(), ChainI));
4175       Root = Chain;
4176       ChainI = 0;
4177     }
4178     SDValue Add =
4179         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4180     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4181     if (MemVTs[i] != ValueVTs[i])
4182       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4183     SDValue St =
4184         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4185                      Alignment, MMOFlags, AAInfo);
4186     Chains[ChainI] = St;
4187   }
4188 
4189   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4190                                   makeArrayRef(Chains.data(), ChainI));
4191   DAG.setRoot(StoreNode);
4192 }
4193 
4194 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4195                                            bool IsCompressing) {
4196   SDLoc sdl = getCurSDLoc();
4197 
4198   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4199                                MaybeAlign &Alignment) {
4200     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4201     Src0 = I.getArgOperand(0);
4202     Ptr = I.getArgOperand(1);
4203     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4204     Mask = I.getArgOperand(3);
4205   };
4206   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4207                                     MaybeAlign &Alignment) {
4208     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4209     Src0 = I.getArgOperand(0);
4210     Ptr = I.getArgOperand(1);
4211     Mask = I.getArgOperand(2);
4212     Alignment = None;
4213   };
4214 
4215   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4216   MaybeAlign Alignment;
4217   if (IsCompressing)
4218     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4219   else
4220     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4221 
4222   SDValue Ptr = getValue(PtrOperand);
4223   SDValue Src0 = getValue(Src0Operand);
4224   SDValue Mask = getValue(MaskOperand);
4225   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4226 
4227   EVT VT = Src0.getValueType();
4228   if (!Alignment)
4229     Alignment = DAG.getEVTAlign(VT);
4230 
4231   AAMDNodes AAInfo;
4232   I.getAAMetadata(AAInfo);
4233 
4234   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4235       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4236       // TODO: Make MachineMemOperands aware of scalable
4237       // vectors.
4238       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4239   SDValue StoreNode =
4240       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4241                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4242   DAG.setRoot(StoreNode);
4243   setValue(&I, StoreNode);
4244 }
4245 
4246 // Get a uniform base for the Gather/Scatter intrinsic.
4247 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4248 // We try to represent it as a base pointer + vector of indices.
4249 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4250 // The first operand of the GEP may be a single pointer or a vector of pointers
4251 // Example:
4252 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4253 //  or
4254 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4255 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4256 //
4257 // When the first GEP operand is a single pointer - it is the uniform base we
4258 // are looking for. If first operand of the GEP is a splat vector - we
4259 // extract the splat value and use it as a uniform base.
4260 // In all other cases the function returns 'false'.
4261 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4262                            ISD::MemIndexType &IndexType, SDValue &Scale,
4263                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4264   SelectionDAG& DAG = SDB->DAG;
4265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4266   const DataLayout &DL = DAG.getDataLayout();
4267 
4268   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4269 
4270   // Handle splat constant pointer.
4271   if (auto *C = dyn_cast<Constant>(Ptr)) {
4272     C = C->getSplatValue();
4273     if (!C)
4274       return false;
4275 
4276     Base = SDB->getValue(C);
4277 
4278     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4279     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4280     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4281     IndexType = ISD::SIGNED_SCALED;
4282     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4283     return true;
4284   }
4285 
4286   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4287   if (!GEP || GEP->getParent() != CurBB)
4288     return false;
4289 
4290   if (GEP->getNumOperands() != 2)
4291     return false;
4292 
4293   const Value *BasePtr = GEP->getPointerOperand();
4294   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4295 
4296   // Make sure the base is scalar and the index is a vector.
4297   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4298     return false;
4299 
4300   Base = SDB->getValue(BasePtr);
4301   Index = SDB->getValue(IndexVal);
4302   IndexType = ISD::SIGNED_SCALED;
4303   Scale = DAG.getTargetConstant(
4304               DL.getTypeAllocSize(GEP->getResultElementType()),
4305               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4306   return true;
4307 }
4308 
4309 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4310   SDLoc sdl = getCurSDLoc();
4311 
4312   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4313   const Value *Ptr = I.getArgOperand(1);
4314   SDValue Src0 = getValue(I.getArgOperand(0));
4315   SDValue Mask = getValue(I.getArgOperand(3));
4316   EVT VT = Src0.getValueType();
4317   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4318                         ->getMaybeAlignValue()
4319                         .getValueOr(DAG.getEVTAlign(VT));
4320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4321 
4322   AAMDNodes AAInfo;
4323   I.getAAMetadata(AAInfo);
4324 
4325   SDValue Base;
4326   SDValue Index;
4327   ISD::MemIndexType IndexType;
4328   SDValue Scale;
4329   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4330                                     I.getParent());
4331 
4332   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4333   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4334       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4335       // TODO: Make MachineMemOperands aware of scalable
4336       // vectors.
4337       MemoryLocation::UnknownSize, Alignment, AAInfo);
4338   if (!UniformBase) {
4339     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4340     Index = getValue(Ptr);
4341     IndexType = ISD::SIGNED_UNSCALED;
4342     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4343   }
4344 
4345   EVT IdxVT = Index.getValueType();
4346   EVT EltTy = IdxVT.getVectorElementType();
4347   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4348     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4349     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4350   }
4351 
4352   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4353   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4354                                          Ops, MMO, IndexType, false);
4355   DAG.setRoot(Scatter);
4356   setValue(&I, Scatter);
4357 }
4358 
4359 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4360   SDLoc sdl = getCurSDLoc();
4361 
4362   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4363                               MaybeAlign &Alignment) {
4364     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4365     Ptr = I.getArgOperand(0);
4366     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4367     Mask = I.getArgOperand(2);
4368     Src0 = I.getArgOperand(3);
4369   };
4370   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4371                                  MaybeAlign &Alignment) {
4372     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4373     Ptr = I.getArgOperand(0);
4374     Alignment = None;
4375     Mask = I.getArgOperand(1);
4376     Src0 = I.getArgOperand(2);
4377   };
4378 
4379   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4380   MaybeAlign Alignment;
4381   if (IsExpanding)
4382     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4383   else
4384     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4385 
4386   SDValue Ptr = getValue(PtrOperand);
4387   SDValue Src0 = getValue(Src0Operand);
4388   SDValue Mask = getValue(MaskOperand);
4389   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4390 
4391   EVT VT = Src0.getValueType();
4392   if (!Alignment)
4393     Alignment = DAG.getEVTAlign(VT);
4394 
4395   AAMDNodes AAInfo;
4396   I.getAAMetadata(AAInfo);
4397   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4398 
4399   // Do not serialize masked loads of constant memory with anything.
4400   MemoryLocation ML;
4401   if (VT.isScalableVector())
4402     ML = MemoryLocation::getAfter(PtrOperand);
4403   else
4404     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4405                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4406                            AAInfo);
4407   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4408 
4409   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4410 
4411   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4412       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4413       // TODO: Make MachineMemOperands aware of scalable
4414       // vectors.
4415       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4416 
4417   SDValue Load =
4418       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4419                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4420   if (AddToChain)
4421     PendingLoads.push_back(Load.getValue(1));
4422   setValue(&I, Load);
4423 }
4424 
4425 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4426   SDLoc sdl = getCurSDLoc();
4427 
4428   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4429   const Value *Ptr = I.getArgOperand(0);
4430   SDValue Src0 = getValue(I.getArgOperand(3));
4431   SDValue Mask = getValue(I.getArgOperand(2));
4432 
4433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4434   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4435   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4436                         ->getMaybeAlignValue()
4437                         .getValueOr(DAG.getEVTAlign(VT));
4438 
4439   AAMDNodes AAInfo;
4440   I.getAAMetadata(AAInfo);
4441   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4442 
4443   SDValue Root = DAG.getRoot();
4444   SDValue Base;
4445   SDValue Index;
4446   ISD::MemIndexType IndexType;
4447   SDValue Scale;
4448   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4449                                     I.getParent());
4450   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4451   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4452       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4453       // TODO: Make MachineMemOperands aware of scalable
4454       // vectors.
4455       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4456 
4457   if (!UniformBase) {
4458     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4459     Index = getValue(Ptr);
4460     IndexType = ISD::SIGNED_UNSCALED;
4461     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4462   }
4463 
4464   EVT IdxVT = Index.getValueType();
4465   EVT EltTy = IdxVT.getVectorElementType();
4466   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4467     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4468     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4469   }
4470 
4471   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4472   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4473                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4474 
4475   PendingLoads.push_back(Gather.getValue(1));
4476   setValue(&I, Gather);
4477 }
4478 
4479 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4480   SDLoc dl = getCurSDLoc();
4481   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4482   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4483   SyncScope::ID SSID = I.getSyncScopeID();
4484 
4485   SDValue InChain = getRoot();
4486 
4487   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4488   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4489 
4490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4491   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4492 
4493   MachineFunction &MF = DAG.getMachineFunction();
4494   MachineMemOperand *MMO = MF.getMachineMemOperand(
4495       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4496       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4497       FailureOrdering);
4498 
4499   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4500                                    dl, MemVT, VTs, InChain,
4501                                    getValue(I.getPointerOperand()),
4502                                    getValue(I.getCompareOperand()),
4503                                    getValue(I.getNewValOperand()), MMO);
4504 
4505   SDValue OutChain = L.getValue(2);
4506 
4507   setValue(&I, L);
4508   DAG.setRoot(OutChain);
4509 }
4510 
4511 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4512   SDLoc dl = getCurSDLoc();
4513   ISD::NodeType NT;
4514   switch (I.getOperation()) {
4515   default: llvm_unreachable("Unknown atomicrmw operation");
4516   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4517   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4518   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4519   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4520   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4521   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4522   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4523   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4524   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4525   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4526   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4527   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4528   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4529   }
4530   AtomicOrdering Ordering = I.getOrdering();
4531   SyncScope::ID SSID = I.getSyncScopeID();
4532 
4533   SDValue InChain = getRoot();
4534 
4535   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4537   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4538 
4539   MachineFunction &MF = DAG.getMachineFunction();
4540   MachineMemOperand *MMO = MF.getMachineMemOperand(
4541       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4542       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4543 
4544   SDValue L =
4545     DAG.getAtomic(NT, dl, MemVT, InChain,
4546                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4547                   MMO);
4548 
4549   SDValue OutChain = L.getValue(1);
4550 
4551   setValue(&I, L);
4552   DAG.setRoot(OutChain);
4553 }
4554 
4555 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4556   SDLoc dl = getCurSDLoc();
4557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4558   SDValue Ops[3];
4559   Ops[0] = getRoot();
4560   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4561                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4562   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4563                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4564   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4565 }
4566 
4567 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4568   SDLoc dl = getCurSDLoc();
4569   AtomicOrdering Order = I.getOrdering();
4570   SyncScope::ID SSID = I.getSyncScopeID();
4571 
4572   SDValue InChain = getRoot();
4573 
4574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4575   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4576   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4577 
4578   if (!TLI.supportsUnalignedAtomics() &&
4579       I.getAlignment() < MemVT.getSizeInBits() / 8)
4580     report_fatal_error("Cannot generate unaligned atomic load");
4581 
4582   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4583 
4584   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4585       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4586       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4587 
4588   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4589 
4590   SDValue Ptr = getValue(I.getPointerOperand());
4591 
4592   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4593     // TODO: Once this is better exercised by tests, it should be merged with
4594     // the normal path for loads to prevent future divergence.
4595     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4596     if (MemVT != VT)
4597       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4598 
4599     setValue(&I, L);
4600     SDValue OutChain = L.getValue(1);
4601     if (!I.isUnordered())
4602       DAG.setRoot(OutChain);
4603     else
4604       PendingLoads.push_back(OutChain);
4605     return;
4606   }
4607 
4608   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4609                             Ptr, MMO);
4610 
4611   SDValue OutChain = L.getValue(1);
4612   if (MemVT != VT)
4613     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4614 
4615   setValue(&I, L);
4616   DAG.setRoot(OutChain);
4617 }
4618 
4619 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4620   SDLoc dl = getCurSDLoc();
4621 
4622   AtomicOrdering Ordering = I.getOrdering();
4623   SyncScope::ID SSID = I.getSyncScopeID();
4624 
4625   SDValue InChain = getRoot();
4626 
4627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4628   EVT MemVT =
4629       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4630 
4631   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4632     report_fatal_error("Cannot generate unaligned atomic store");
4633 
4634   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4635 
4636   MachineFunction &MF = DAG.getMachineFunction();
4637   MachineMemOperand *MMO = MF.getMachineMemOperand(
4638       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4639       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4640 
4641   SDValue Val = getValue(I.getValueOperand());
4642   if (Val.getValueType() != MemVT)
4643     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4644   SDValue Ptr = getValue(I.getPointerOperand());
4645 
4646   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4647     // TODO: Once this is better exercised by tests, it should be merged with
4648     // the normal path for stores to prevent future divergence.
4649     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4650     DAG.setRoot(S);
4651     return;
4652   }
4653   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4654                                    Ptr, Val, MMO);
4655 
4656 
4657   DAG.setRoot(OutChain);
4658 }
4659 
4660 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4661 /// node.
4662 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4663                                                unsigned Intrinsic) {
4664   // Ignore the callsite's attributes. A specific call site may be marked with
4665   // readnone, but the lowering code will expect the chain based on the
4666   // definition.
4667   const Function *F = I.getCalledFunction();
4668   bool HasChain = !F->doesNotAccessMemory();
4669   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4670 
4671   // Build the operand list.
4672   SmallVector<SDValue, 8> Ops;
4673   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4674     if (OnlyLoad) {
4675       // We don't need to serialize loads against other loads.
4676       Ops.push_back(DAG.getRoot());
4677     } else {
4678       Ops.push_back(getRoot());
4679     }
4680   }
4681 
4682   // Info is set by getTgtMemInstrinsic
4683   TargetLowering::IntrinsicInfo Info;
4684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4685   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4686                                                DAG.getMachineFunction(),
4687                                                Intrinsic);
4688 
4689   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4690   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4691       Info.opc == ISD::INTRINSIC_W_CHAIN)
4692     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4693                                         TLI.getPointerTy(DAG.getDataLayout())));
4694 
4695   // Add all operands of the call to the operand list.
4696   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4697     const Value *Arg = I.getArgOperand(i);
4698     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4699       Ops.push_back(getValue(Arg));
4700       continue;
4701     }
4702 
4703     // Use TargetConstant instead of a regular constant for immarg.
4704     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4705     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4706       assert(CI->getBitWidth() <= 64 &&
4707              "large intrinsic immediates not handled");
4708       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4709     } else {
4710       Ops.push_back(
4711           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4712     }
4713   }
4714 
4715   SmallVector<EVT, 4> ValueVTs;
4716   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4717 
4718   if (HasChain)
4719     ValueVTs.push_back(MVT::Other);
4720 
4721   SDVTList VTs = DAG.getVTList(ValueVTs);
4722 
4723   // Create the node.
4724   SDValue Result;
4725   if (IsTgtIntrinsic) {
4726     // This is target intrinsic that touches memory
4727     AAMDNodes AAInfo;
4728     I.getAAMetadata(AAInfo);
4729     Result =
4730         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4731                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4732                                 Info.align, Info.flags, Info.size, AAInfo);
4733   } else if (!HasChain) {
4734     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4735   } else if (!I.getType()->isVoidTy()) {
4736     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4737   } else {
4738     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4739   }
4740 
4741   if (HasChain) {
4742     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4743     if (OnlyLoad)
4744       PendingLoads.push_back(Chain);
4745     else
4746       DAG.setRoot(Chain);
4747   }
4748 
4749   if (!I.getType()->isVoidTy()) {
4750     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4751       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4752       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4753     } else
4754       Result = lowerRangeToAssertZExt(DAG, I, Result);
4755 
4756     MaybeAlign Alignment = I.getRetAlign();
4757     if (!Alignment)
4758       Alignment = F->getAttributes().getRetAlignment();
4759     // Insert `assertalign` node if there's an alignment.
4760     if (InsertAssertAlign && Alignment) {
4761       Result =
4762           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4763     }
4764 
4765     setValue(&I, Result);
4766   }
4767 }
4768 
4769 /// GetSignificand - Get the significand and build it into a floating-point
4770 /// number with exponent of 1:
4771 ///
4772 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4773 ///
4774 /// where Op is the hexadecimal representation of floating point value.
4775 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4776   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4777                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4778   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4779                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4780   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4781 }
4782 
4783 /// GetExponent - Get the exponent:
4784 ///
4785 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4786 ///
4787 /// where Op is the hexadecimal representation of floating point value.
4788 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4789                            const TargetLowering &TLI, const SDLoc &dl) {
4790   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4791                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4792   SDValue t1 = DAG.getNode(
4793       ISD::SRL, dl, MVT::i32, t0,
4794       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4795   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4796                            DAG.getConstant(127, dl, MVT::i32));
4797   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4798 }
4799 
4800 /// getF32Constant - Get 32-bit floating point constant.
4801 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4802                               const SDLoc &dl) {
4803   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4804                            MVT::f32);
4805 }
4806 
4807 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4808                                        SelectionDAG &DAG) {
4809   // TODO: What fast-math-flags should be set on the floating-point nodes?
4810 
4811   //   IntegerPartOfX = ((int32_t)(t0);
4812   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4813 
4814   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4815   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4816   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4817 
4818   //   IntegerPartOfX <<= 23;
4819   IntegerPartOfX = DAG.getNode(
4820       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4821       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4822                                   DAG.getDataLayout())));
4823 
4824   SDValue TwoToFractionalPartOfX;
4825   if (LimitFloatPrecision <= 6) {
4826     // For floating-point precision of 6:
4827     //
4828     //   TwoToFractionalPartOfX =
4829     //     0.997535578f +
4830     //       (0.735607626f + 0.252464424f * x) * x;
4831     //
4832     // error 0.0144103317, which is 6 bits
4833     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4834                              getF32Constant(DAG, 0x3e814304, dl));
4835     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4836                              getF32Constant(DAG, 0x3f3c50c8, dl));
4837     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4838     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4839                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4840   } else if (LimitFloatPrecision <= 12) {
4841     // For floating-point precision of 12:
4842     //
4843     //   TwoToFractionalPartOfX =
4844     //     0.999892986f +
4845     //       (0.696457318f +
4846     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4847     //
4848     // error 0.000107046256, which is 13 to 14 bits
4849     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4850                              getF32Constant(DAG, 0x3da235e3, dl));
4851     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4852                              getF32Constant(DAG, 0x3e65b8f3, dl));
4853     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4854     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4855                              getF32Constant(DAG, 0x3f324b07, dl));
4856     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4857     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4858                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4859   } else { // LimitFloatPrecision <= 18
4860     // For floating-point precision of 18:
4861     //
4862     //   TwoToFractionalPartOfX =
4863     //     0.999999982f +
4864     //       (0.693148872f +
4865     //         (0.240227044f +
4866     //           (0.554906021e-1f +
4867     //             (0.961591928e-2f +
4868     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4869     // error 2.47208000*10^(-7), which is better than 18 bits
4870     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4871                              getF32Constant(DAG, 0x3924b03e, dl));
4872     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4873                              getF32Constant(DAG, 0x3ab24b87, dl));
4874     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4875     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4876                              getF32Constant(DAG, 0x3c1d8c17, dl));
4877     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4878     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4879                              getF32Constant(DAG, 0x3d634a1d, dl));
4880     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4881     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4882                              getF32Constant(DAG, 0x3e75fe14, dl));
4883     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4884     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4885                               getF32Constant(DAG, 0x3f317234, dl));
4886     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4887     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4888                                          getF32Constant(DAG, 0x3f800000, dl));
4889   }
4890 
4891   // Add the exponent into the result in integer domain.
4892   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4893   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4894                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4895 }
4896 
4897 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4898 /// limited-precision mode.
4899 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4900                          const TargetLowering &TLI, SDNodeFlags Flags) {
4901   if (Op.getValueType() == MVT::f32 &&
4902       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4903 
4904     // Put the exponent in the right bit position for later addition to the
4905     // final result:
4906     //
4907     // t0 = Op * log2(e)
4908 
4909     // TODO: What fast-math-flags should be set here?
4910     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4911                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4912     return getLimitedPrecisionExp2(t0, dl, DAG);
4913   }
4914 
4915   // No special expansion.
4916   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4917 }
4918 
4919 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4920 /// limited-precision mode.
4921 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4922                          const TargetLowering &TLI, SDNodeFlags Flags) {
4923   // TODO: What fast-math-flags should be set on the floating-point nodes?
4924 
4925   if (Op.getValueType() == MVT::f32 &&
4926       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4927     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4928 
4929     // Scale the exponent by log(2).
4930     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4931     SDValue LogOfExponent =
4932         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4933                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4934 
4935     // Get the significand and build it into a floating-point number with
4936     // exponent of 1.
4937     SDValue X = GetSignificand(DAG, Op1, dl);
4938 
4939     SDValue LogOfMantissa;
4940     if (LimitFloatPrecision <= 6) {
4941       // For floating-point precision of 6:
4942       //
4943       //   LogofMantissa =
4944       //     -1.1609546f +
4945       //       (1.4034025f - 0.23903021f * x) * x;
4946       //
4947       // error 0.0034276066, which is better than 8 bits
4948       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4949                                getF32Constant(DAG, 0xbe74c456, dl));
4950       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4951                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4952       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4953       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4954                                   getF32Constant(DAG, 0x3f949a29, dl));
4955     } else if (LimitFloatPrecision <= 12) {
4956       // For floating-point precision of 12:
4957       //
4958       //   LogOfMantissa =
4959       //     -1.7417939f +
4960       //       (2.8212026f +
4961       //         (-1.4699568f +
4962       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4963       //
4964       // error 0.000061011436, which is 14 bits
4965       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4966                                getF32Constant(DAG, 0xbd67b6d6, dl));
4967       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4968                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4969       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4970       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4971                                getF32Constant(DAG, 0x3fbc278b, dl));
4972       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4973       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4974                                getF32Constant(DAG, 0x40348e95, dl));
4975       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4976       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4977                                   getF32Constant(DAG, 0x3fdef31a, dl));
4978     } else { // LimitFloatPrecision <= 18
4979       // For floating-point precision of 18:
4980       //
4981       //   LogOfMantissa =
4982       //     -2.1072184f +
4983       //       (4.2372794f +
4984       //         (-3.7029485f +
4985       //           (2.2781945f +
4986       //             (-0.87823314f +
4987       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4988       //
4989       // error 0.0000023660568, which is better than 18 bits
4990       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4991                                getF32Constant(DAG, 0xbc91e5ac, dl));
4992       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4993                                getF32Constant(DAG, 0x3e4350aa, dl));
4994       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4995       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4996                                getF32Constant(DAG, 0x3f60d3e3, dl));
4997       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4998       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4999                                getF32Constant(DAG, 0x4011cdf0, dl));
5000       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5001       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5002                                getF32Constant(DAG, 0x406cfd1c, dl));
5003       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5004       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5005                                getF32Constant(DAG, 0x408797cb, dl));
5006       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5007       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5008                                   getF32Constant(DAG, 0x4006dcab, dl));
5009     }
5010 
5011     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5012   }
5013 
5014   // No special expansion.
5015   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5016 }
5017 
5018 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5019 /// limited-precision mode.
5020 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5021                           const TargetLowering &TLI, SDNodeFlags Flags) {
5022   // TODO: What fast-math-flags should be set on the floating-point nodes?
5023 
5024   if (Op.getValueType() == MVT::f32 &&
5025       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5026     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5027 
5028     // Get the exponent.
5029     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5030 
5031     // Get the significand and build it into a floating-point number with
5032     // exponent of 1.
5033     SDValue X = GetSignificand(DAG, Op1, dl);
5034 
5035     // Different possible minimax approximations of significand in
5036     // floating-point for various degrees of accuracy over [1,2].
5037     SDValue Log2ofMantissa;
5038     if (LimitFloatPrecision <= 6) {
5039       // For floating-point precision of 6:
5040       //
5041       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5042       //
5043       // error 0.0049451742, which is more than 7 bits
5044       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5045                                getF32Constant(DAG, 0xbeb08fe0, dl));
5046       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5047                                getF32Constant(DAG, 0x40019463, dl));
5048       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5049       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5050                                    getF32Constant(DAG, 0x3fd6633d, dl));
5051     } else if (LimitFloatPrecision <= 12) {
5052       // For floating-point precision of 12:
5053       //
5054       //   Log2ofMantissa =
5055       //     -2.51285454f +
5056       //       (4.07009056f +
5057       //         (-2.12067489f +
5058       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5059       //
5060       // error 0.0000876136000, which is better than 13 bits
5061       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5062                                getF32Constant(DAG, 0xbda7262e, dl));
5063       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5064                                getF32Constant(DAG, 0x3f25280b, dl));
5065       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5066       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5067                                getF32Constant(DAG, 0x4007b923, dl));
5068       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5069       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5070                                getF32Constant(DAG, 0x40823e2f, dl));
5071       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5072       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5073                                    getF32Constant(DAG, 0x4020d29c, dl));
5074     } else { // LimitFloatPrecision <= 18
5075       // For floating-point precision of 18:
5076       //
5077       //   Log2ofMantissa =
5078       //     -3.0400495f +
5079       //       (6.1129976f +
5080       //         (-5.3420409f +
5081       //           (3.2865683f +
5082       //             (-1.2669343f +
5083       //               (0.27515199f -
5084       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5085       //
5086       // error 0.0000018516, which is better than 18 bits
5087       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5088                                getF32Constant(DAG, 0xbcd2769e, dl));
5089       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5090                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5091       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5092       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5093                                getF32Constant(DAG, 0x3fa22ae7, dl));
5094       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5095       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5096                                getF32Constant(DAG, 0x40525723, dl));
5097       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5098       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5099                                getF32Constant(DAG, 0x40aaf200, dl));
5100       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5101       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5102                                getF32Constant(DAG, 0x40c39dad, dl));
5103       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5104       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5105                                    getF32Constant(DAG, 0x4042902c, dl));
5106     }
5107 
5108     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5109   }
5110 
5111   // No special expansion.
5112   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5113 }
5114 
5115 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5116 /// limited-precision mode.
5117 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5118                            const TargetLowering &TLI, SDNodeFlags Flags) {
5119   // TODO: What fast-math-flags should be set on the floating-point nodes?
5120 
5121   if (Op.getValueType() == MVT::f32 &&
5122       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5123     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5124 
5125     // Scale the exponent by log10(2) [0.30102999f].
5126     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5127     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5128                                         getF32Constant(DAG, 0x3e9a209a, dl));
5129 
5130     // Get the significand and build it into a floating-point number with
5131     // exponent of 1.
5132     SDValue X = GetSignificand(DAG, Op1, dl);
5133 
5134     SDValue Log10ofMantissa;
5135     if (LimitFloatPrecision <= 6) {
5136       // For floating-point precision of 6:
5137       //
5138       //   Log10ofMantissa =
5139       //     -0.50419619f +
5140       //       (0.60948995f - 0.10380950f * x) * x;
5141       //
5142       // error 0.0014886165, which is 6 bits
5143       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5144                                getF32Constant(DAG, 0xbdd49a13, dl));
5145       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5146                                getF32Constant(DAG, 0x3f1c0789, dl));
5147       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5148       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5149                                     getF32Constant(DAG, 0x3f011300, dl));
5150     } else if (LimitFloatPrecision <= 12) {
5151       // For floating-point precision of 12:
5152       //
5153       //   Log10ofMantissa =
5154       //     -0.64831180f +
5155       //       (0.91751397f +
5156       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5157       //
5158       // error 0.00019228036, which is better than 12 bits
5159       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5160                                getF32Constant(DAG, 0x3d431f31, dl));
5161       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5162                                getF32Constant(DAG, 0x3ea21fb2, dl));
5163       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5164       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5165                                getF32Constant(DAG, 0x3f6ae232, dl));
5166       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5167       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5168                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5169     } else { // LimitFloatPrecision <= 18
5170       // For floating-point precision of 18:
5171       //
5172       //   Log10ofMantissa =
5173       //     -0.84299375f +
5174       //       (1.5327582f +
5175       //         (-1.0688956f +
5176       //           (0.49102474f +
5177       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5178       //
5179       // error 0.0000037995730, which is better than 18 bits
5180       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5181                                getF32Constant(DAG, 0x3c5d51ce, dl));
5182       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5183                                getF32Constant(DAG, 0x3e00685a, dl));
5184       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5185       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5186                                getF32Constant(DAG, 0x3efb6798, dl));
5187       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5188       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5189                                getF32Constant(DAG, 0x3f88d192, dl));
5190       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5191       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5192                                getF32Constant(DAG, 0x3fc4316c, dl));
5193       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5194       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5195                                     getF32Constant(DAG, 0x3f57ce70, dl));
5196     }
5197 
5198     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5199   }
5200 
5201   // No special expansion.
5202   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5203 }
5204 
5205 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5206 /// limited-precision mode.
5207 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5208                           const TargetLowering &TLI, SDNodeFlags Flags) {
5209   if (Op.getValueType() == MVT::f32 &&
5210       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5211     return getLimitedPrecisionExp2(Op, dl, DAG);
5212 
5213   // No special expansion.
5214   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5215 }
5216 
5217 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5218 /// limited-precision mode with x == 10.0f.
5219 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5220                          SelectionDAG &DAG, const TargetLowering &TLI,
5221                          SDNodeFlags Flags) {
5222   bool IsExp10 = false;
5223   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5224       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5225     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5226       APFloat Ten(10.0f);
5227       IsExp10 = LHSC->isExactlyValue(Ten);
5228     }
5229   }
5230 
5231   // TODO: What fast-math-flags should be set on the FMUL node?
5232   if (IsExp10) {
5233     // Put the exponent in the right bit position for later addition to the
5234     // final result:
5235     //
5236     //   #define LOG2OF10 3.3219281f
5237     //   t0 = Op * LOG2OF10;
5238     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5239                              getF32Constant(DAG, 0x40549a78, dl));
5240     return getLimitedPrecisionExp2(t0, dl, DAG);
5241   }
5242 
5243   // No special expansion.
5244   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5245 }
5246 
5247 /// ExpandPowI - Expand a llvm.powi intrinsic.
5248 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5249                           SelectionDAG &DAG) {
5250   // If RHS is a constant, we can expand this out to a multiplication tree,
5251   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5252   // optimizing for size, we only want to do this if the expansion would produce
5253   // a small number of multiplies, otherwise we do the full expansion.
5254   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5255     // Get the exponent as a positive value.
5256     unsigned Val = RHSC->getSExtValue();
5257     if ((int)Val < 0) Val = -Val;
5258 
5259     // powi(x, 0) -> 1.0
5260     if (Val == 0)
5261       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5262 
5263     bool OptForSize = DAG.shouldOptForSize();
5264     if (!OptForSize ||
5265         // If optimizing for size, don't insert too many multiplies.
5266         // This inserts up to 5 multiplies.
5267         countPopulation(Val) + Log2_32(Val) < 7) {
5268       // We use the simple binary decomposition method to generate the multiply
5269       // sequence.  There are more optimal ways to do this (for example,
5270       // powi(x,15) generates one more multiply than it should), but this has
5271       // the benefit of being both really simple and much better than a libcall.
5272       SDValue Res;  // Logically starts equal to 1.0
5273       SDValue CurSquare = LHS;
5274       // TODO: Intrinsics should have fast-math-flags that propagate to these
5275       // nodes.
5276       while (Val) {
5277         if (Val & 1) {
5278           if (Res.getNode())
5279             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5280           else
5281             Res = CurSquare;  // 1.0*CurSquare.
5282         }
5283 
5284         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5285                                 CurSquare, CurSquare);
5286         Val >>= 1;
5287       }
5288 
5289       // If the original was negative, invert the result, producing 1/(x*x*x).
5290       if (RHSC->getSExtValue() < 0)
5291         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5292                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5293       return Res;
5294     }
5295   }
5296 
5297   // Otherwise, expand to a libcall.
5298   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5299 }
5300 
5301 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5302                             SDValue LHS, SDValue RHS, SDValue Scale,
5303                             SelectionDAG &DAG, const TargetLowering &TLI) {
5304   EVT VT = LHS.getValueType();
5305   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5306   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5307   LLVMContext &Ctx = *DAG.getContext();
5308 
5309   // If the type is legal but the operation isn't, this node might survive all
5310   // the way to operation legalization. If we end up there and we do not have
5311   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5312   // node.
5313 
5314   // Coax the legalizer into expanding the node during type legalization instead
5315   // by bumping the size by one bit. This will force it to Promote, enabling the
5316   // early expansion and avoiding the need to expand later.
5317 
5318   // We don't have to do this if Scale is 0; that can always be expanded, unless
5319   // it's a saturating signed operation. Those can experience true integer
5320   // division overflow, a case which we must avoid.
5321 
5322   // FIXME: We wouldn't have to do this (or any of the early
5323   // expansion/promotion) if it was possible to expand a libcall of an
5324   // illegal type during operation legalization. But it's not, so things
5325   // get a bit hacky.
5326   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5327   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5328       (TLI.isTypeLegal(VT) ||
5329        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5330     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5331         Opcode, VT, ScaleInt);
5332     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5333       EVT PromVT;
5334       if (VT.isScalarInteger())
5335         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5336       else if (VT.isVector()) {
5337         PromVT = VT.getVectorElementType();
5338         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5339         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5340       } else
5341         llvm_unreachable("Wrong VT for DIVFIX?");
5342       if (Signed) {
5343         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5344         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5345       } else {
5346         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5347         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5348       }
5349       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5350       // For saturating operations, we need to shift up the LHS to get the
5351       // proper saturation width, and then shift down again afterwards.
5352       if (Saturating)
5353         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5354                           DAG.getConstant(1, DL, ShiftTy));
5355       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5356       if (Saturating)
5357         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5358                           DAG.getConstant(1, DL, ShiftTy));
5359       return DAG.getZExtOrTrunc(Res, DL, VT);
5360     }
5361   }
5362 
5363   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5364 }
5365 
5366 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5367 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5368 static void
5369 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5370                      const SDValue &N) {
5371   switch (N.getOpcode()) {
5372   case ISD::CopyFromReg: {
5373     SDValue Op = N.getOperand(1);
5374     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5375                       Op.getValueType().getSizeInBits());
5376     return;
5377   }
5378   case ISD::BITCAST:
5379   case ISD::AssertZext:
5380   case ISD::AssertSext:
5381   case ISD::TRUNCATE:
5382     getUnderlyingArgRegs(Regs, N.getOperand(0));
5383     return;
5384   case ISD::BUILD_PAIR:
5385   case ISD::BUILD_VECTOR:
5386   case ISD::CONCAT_VECTORS:
5387     for (SDValue Op : N->op_values())
5388       getUnderlyingArgRegs(Regs, Op);
5389     return;
5390   default:
5391     return;
5392   }
5393 }
5394 
5395 /// If the DbgValueInst is a dbg_value of a function argument, create the
5396 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5397 /// instruction selection, they will be inserted to the entry BB.
5398 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5399     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5400     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5401   const Argument *Arg = dyn_cast<Argument>(V);
5402   if (!Arg)
5403     return false;
5404 
5405   if (!IsDbgDeclare) {
5406     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5407     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5408     // the entry block.
5409     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5410     if (!IsInEntryBlock)
5411       return false;
5412 
5413     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5414     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5415     // variable that also is a param.
5416     //
5417     // Although, if we are at the top of the entry block already, we can still
5418     // emit using ArgDbgValue. This might catch some situations when the
5419     // dbg.value refers to an argument that isn't used in the entry block, so
5420     // any CopyToReg node would be optimized out and the only way to express
5421     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5422     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5423     // we should only emit as ArgDbgValue if the Variable is an argument to the
5424     // current function, and the dbg.value intrinsic is found in the entry
5425     // block.
5426     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5427         !DL->getInlinedAt();
5428     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5429     if (!IsInPrologue && !VariableIsFunctionInputArg)
5430       return false;
5431 
5432     // Here we assume that a function argument on IR level only can be used to
5433     // describe one input parameter on source level. If we for example have
5434     // source code like this
5435     //
5436     //    struct A { long x, y; };
5437     //    void foo(struct A a, long b) {
5438     //      ...
5439     //      b = a.x;
5440     //      ...
5441     //    }
5442     //
5443     // and IR like this
5444     //
5445     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5446     //  entry:
5447     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5448     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5449     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5450     //    ...
5451     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5452     //    ...
5453     //
5454     // then the last dbg.value is describing a parameter "b" using a value that
5455     // is an argument. But since we already has used %a1 to describe a parameter
5456     // we should not handle that last dbg.value here (that would result in an
5457     // incorrect hoisting of the DBG_VALUE to the function entry).
5458     // Notice that we allow one dbg.value per IR level argument, to accommodate
5459     // for the situation with fragments above.
5460     if (VariableIsFunctionInputArg) {
5461       unsigned ArgNo = Arg->getArgNo();
5462       if (ArgNo >= FuncInfo.DescribedArgs.size())
5463         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5464       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5465         return false;
5466       FuncInfo.DescribedArgs.set(ArgNo);
5467     }
5468   }
5469 
5470   MachineFunction &MF = DAG.getMachineFunction();
5471   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5472 
5473   bool IsIndirect = false;
5474   Optional<MachineOperand> Op;
5475   // Some arguments' frame index is recorded during argument lowering.
5476   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5477   if (FI != std::numeric_limits<int>::max())
5478     Op = MachineOperand::CreateFI(FI);
5479 
5480   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5481   if (!Op && N.getNode()) {
5482     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5483     Register Reg;
5484     if (ArgRegsAndSizes.size() == 1)
5485       Reg = ArgRegsAndSizes.front().first;
5486 
5487     if (Reg && Reg.isVirtual()) {
5488       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5489       Register PR = RegInfo.getLiveInPhysReg(Reg);
5490       if (PR)
5491         Reg = PR;
5492     }
5493     if (Reg) {
5494       Op = MachineOperand::CreateReg(Reg, false);
5495       IsIndirect = IsDbgDeclare;
5496     }
5497   }
5498 
5499   if (!Op && N.getNode()) {
5500     // Check if frame index is available.
5501     SDValue LCandidate = peekThroughBitcasts(N);
5502     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5503       if (FrameIndexSDNode *FINode =
5504           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5505         Op = MachineOperand::CreateFI(FINode->getIndex());
5506   }
5507 
5508   if (!Op) {
5509     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5510     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5511                                          SplitRegs) {
5512       unsigned Offset = 0;
5513       for (auto RegAndSize : SplitRegs) {
5514         // If the expression is already a fragment, the current register
5515         // offset+size might extend beyond the fragment. In this case, only
5516         // the register bits that are inside the fragment are relevant.
5517         int RegFragmentSizeInBits = RegAndSize.second;
5518         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5519           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5520           // The register is entirely outside the expression fragment,
5521           // so is irrelevant for debug info.
5522           if (Offset >= ExprFragmentSizeInBits)
5523             break;
5524           // The register is partially outside the expression fragment, only
5525           // the low bits within the fragment are relevant for debug info.
5526           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5527             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5528           }
5529         }
5530 
5531         auto FragmentExpr = DIExpression::createFragmentExpression(
5532             Expr, Offset, RegFragmentSizeInBits);
5533         Offset += RegAndSize.second;
5534         // If a valid fragment expression cannot be created, the variable's
5535         // correct value cannot be determined and so it is set as Undef.
5536         if (!FragmentExpr) {
5537           SDDbgValue *SDV = DAG.getConstantDbgValue(
5538               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5539           DAG.AddDbgValue(SDV, nullptr, false);
5540           continue;
5541         }
5542         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5543         FuncInfo.ArgDbgValues.push_back(
5544           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5545                   RegAndSize.first, Variable, *FragmentExpr));
5546       }
5547     };
5548 
5549     // Check if ValueMap has reg number.
5550     DenseMap<const Value *, Register>::const_iterator
5551       VMI = FuncInfo.ValueMap.find(V);
5552     if (VMI != FuncInfo.ValueMap.end()) {
5553       const auto &TLI = DAG.getTargetLoweringInfo();
5554       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5555                        V->getType(), None);
5556       if (RFV.occupiesMultipleRegs()) {
5557         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5558         return true;
5559       }
5560 
5561       Op = MachineOperand::CreateReg(VMI->second, false);
5562       IsIndirect = IsDbgDeclare;
5563     } else if (ArgRegsAndSizes.size() > 1) {
5564       // This was split due to the calling convention, and no virtual register
5565       // mapping exists for the value.
5566       splitMultiRegDbgValue(ArgRegsAndSizes);
5567       return true;
5568     }
5569   }
5570 
5571   if (!Op)
5572     return false;
5573 
5574   assert(Variable->isValidLocationForIntrinsic(DL) &&
5575          "Expected inlined-at fields to agree");
5576   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5577   FuncInfo.ArgDbgValues.push_back(
5578       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5579               *Op, Variable, Expr));
5580 
5581   return true;
5582 }
5583 
5584 /// Return the appropriate SDDbgValue based on N.
5585 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5586                                              DILocalVariable *Variable,
5587                                              DIExpression *Expr,
5588                                              const DebugLoc &dl,
5589                                              unsigned DbgSDNodeOrder) {
5590   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5591     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5592     // stack slot locations.
5593     //
5594     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5595     // debug values here after optimization:
5596     //
5597     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5598     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5599     //
5600     // Both describe the direct values of their associated variables.
5601     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5602                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5603   }
5604   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5605                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5606 }
5607 
5608 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5609   switch (Intrinsic) {
5610   case Intrinsic::smul_fix:
5611     return ISD::SMULFIX;
5612   case Intrinsic::umul_fix:
5613     return ISD::UMULFIX;
5614   case Intrinsic::smul_fix_sat:
5615     return ISD::SMULFIXSAT;
5616   case Intrinsic::umul_fix_sat:
5617     return ISD::UMULFIXSAT;
5618   case Intrinsic::sdiv_fix:
5619     return ISD::SDIVFIX;
5620   case Intrinsic::udiv_fix:
5621     return ISD::UDIVFIX;
5622   case Intrinsic::sdiv_fix_sat:
5623     return ISD::SDIVFIXSAT;
5624   case Intrinsic::udiv_fix_sat:
5625     return ISD::UDIVFIXSAT;
5626   default:
5627     llvm_unreachable("Unhandled fixed point intrinsic");
5628   }
5629 }
5630 
5631 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5632                                            const char *FunctionName) {
5633   assert(FunctionName && "FunctionName must not be nullptr");
5634   SDValue Callee = DAG.getExternalSymbol(
5635       FunctionName,
5636       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5637   LowerCallTo(I, Callee, I.isTailCall());
5638 }
5639 
5640 /// Given a @llvm.call.preallocated.setup, return the corresponding
5641 /// preallocated call.
5642 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5643   assert(cast<CallBase>(PreallocatedSetup)
5644                  ->getCalledFunction()
5645                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5646          "expected call_preallocated_setup Value");
5647   for (auto *U : PreallocatedSetup->users()) {
5648     auto *UseCall = cast<CallBase>(U);
5649     const Function *Fn = UseCall->getCalledFunction();
5650     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5651       return UseCall;
5652     }
5653   }
5654   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5655 }
5656 
5657 /// Lower the call to the specified intrinsic function.
5658 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5659                                              unsigned Intrinsic) {
5660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5661   SDLoc sdl = getCurSDLoc();
5662   DebugLoc dl = getCurDebugLoc();
5663   SDValue Res;
5664 
5665   SDNodeFlags Flags;
5666   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5667     Flags.copyFMF(*FPOp);
5668 
5669   switch (Intrinsic) {
5670   default:
5671     // By default, turn this into a target intrinsic node.
5672     visitTargetIntrinsic(I, Intrinsic);
5673     return;
5674   case Intrinsic::vscale: {
5675     match(&I, m_VScale(DAG.getDataLayout()));
5676     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5677     setValue(&I,
5678              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5679     return;
5680   }
5681   case Intrinsic::vastart:  visitVAStart(I); return;
5682   case Intrinsic::vaend:    visitVAEnd(I); return;
5683   case Intrinsic::vacopy:   visitVACopy(I); return;
5684   case Intrinsic::returnaddress:
5685     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5686                              TLI.getPointerTy(DAG.getDataLayout()),
5687                              getValue(I.getArgOperand(0))));
5688     return;
5689   case Intrinsic::addressofreturnaddress:
5690     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5691                              TLI.getPointerTy(DAG.getDataLayout())));
5692     return;
5693   case Intrinsic::sponentry:
5694     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5695                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5696     return;
5697   case Intrinsic::frameaddress:
5698     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5699                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5700                              getValue(I.getArgOperand(0))));
5701     return;
5702   case Intrinsic::read_volatile_register:
5703   case Intrinsic::read_register: {
5704     Value *Reg = I.getArgOperand(0);
5705     SDValue Chain = getRoot();
5706     SDValue RegName =
5707         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5708     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5709     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5710       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5711     setValue(&I, Res);
5712     DAG.setRoot(Res.getValue(1));
5713     return;
5714   }
5715   case Intrinsic::write_register: {
5716     Value *Reg = I.getArgOperand(0);
5717     Value *RegValue = I.getArgOperand(1);
5718     SDValue Chain = getRoot();
5719     SDValue RegName =
5720         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5721     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5722                             RegName, getValue(RegValue)));
5723     return;
5724   }
5725   case Intrinsic::memcpy: {
5726     const auto &MCI = cast<MemCpyInst>(I);
5727     SDValue Op1 = getValue(I.getArgOperand(0));
5728     SDValue Op2 = getValue(I.getArgOperand(1));
5729     SDValue Op3 = getValue(I.getArgOperand(2));
5730     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5731     Align DstAlign = MCI.getDestAlign().valueOrOne();
5732     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5733     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5734     bool isVol = MCI.isVolatile();
5735     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5736     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5737     // node.
5738     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5739     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5740                                /* AlwaysInline */ false, isTC,
5741                                MachinePointerInfo(I.getArgOperand(0)),
5742                                MachinePointerInfo(I.getArgOperand(1)));
5743     updateDAGForMaybeTailCall(MC);
5744     return;
5745   }
5746   case Intrinsic::memcpy_inline: {
5747     const auto &MCI = cast<MemCpyInlineInst>(I);
5748     SDValue Dst = getValue(I.getArgOperand(0));
5749     SDValue Src = getValue(I.getArgOperand(1));
5750     SDValue Size = getValue(I.getArgOperand(2));
5751     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5752     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5753     Align DstAlign = MCI.getDestAlign().valueOrOne();
5754     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5755     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5756     bool isVol = MCI.isVolatile();
5757     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5758     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5759     // node.
5760     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5761                                /* AlwaysInline */ true, isTC,
5762                                MachinePointerInfo(I.getArgOperand(0)),
5763                                MachinePointerInfo(I.getArgOperand(1)));
5764     updateDAGForMaybeTailCall(MC);
5765     return;
5766   }
5767   case Intrinsic::memset: {
5768     const auto &MSI = cast<MemSetInst>(I);
5769     SDValue Op1 = getValue(I.getArgOperand(0));
5770     SDValue Op2 = getValue(I.getArgOperand(1));
5771     SDValue Op3 = getValue(I.getArgOperand(2));
5772     // @llvm.memset defines 0 and 1 to both mean no alignment.
5773     Align Alignment = MSI.getDestAlign().valueOrOne();
5774     bool isVol = MSI.isVolatile();
5775     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5776     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5777     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5778                                MachinePointerInfo(I.getArgOperand(0)));
5779     updateDAGForMaybeTailCall(MS);
5780     return;
5781   }
5782   case Intrinsic::memmove: {
5783     const auto &MMI = cast<MemMoveInst>(I);
5784     SDValue Op1 = getValue(I.getArgOperand(0));
5785     SDValue Op2 = getValue(I.getArgOperand(1));
5786     SDValue Op3 = getValue(I.getArgOperand(2));
5787     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5788     Align DstAlign = MMI.getDestAlign().valueOrOne();
5789     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5790     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5791     bool isVol = MMI.isVolatile();
5792     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5793     // FIXME: Support passing different dest/src alignments to the memmove DAG
5794     // node.
5795     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5796     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5797                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5798                                 MachinePointerInfo(I.getArgOperand(1)));
5799     updateDAGForMaybeTailCall(MM);
5800     return;
5801   }
5802   case Intrinsic::memcpy_element_unordered_atomic: {
5803     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5804     SDValue Dst = getValue(MI.getRawDest());
5805     SDValue Src = getValue(MI.getRawSource());
5806     SDValue Length = getValue(MI.getLength());
5807 
5808     unsigned DstAlign = MI.getDestAlignment();
5809     unsigned SrcAlign = MI.getSourceAlignment();
5810     Type *LengthTy = MI.getLength()->getType();
5811     unsigned ElemSz = MI.getElementSizeInBytes();
5812     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5813     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5814                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5815                                      MachinePointerInfo(MI.getRawDest()),
5816                                      MachinePointerInfo(MI.getRawSource()));
5817     updateDAGForMaybeTailCall(MC);
5818     return;
5819   }
5820   case Intrinsic::memmove_element_unordered_atomic: {
5821     auto &MI = cast<AtomicMemMoveInst>(I);
5822     SDValue Dst = getValue(MI.getRawDest());
5823     SDValue Src = getValue(MI.getRawSource());
5824     SDValue Length = getValue(MI.getLength());
5825 
5826     unsigned DstAlign = MI.getDestAlignment();
5827     unsigned SrcAlign = MI.getSourceAlignment();
5828     Type *LengthTy = MI.getLength()->getType();
5829     unsigned ElemSz = MI.getElementSizeInBytes();
5830     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5831     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5832                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5833                                       MachinePointerInfo(MI.getRawDest()),
5834                                       MachinePointerInfo(MI.getRawSource()));
5835     updateDAGForMaybeTailCall(MC);
5836     return;
5837   }
5838   case Intrinsic::memset_element_unordered_atomic: {
5839     auto &MI = cast<AtomicMemSetInst>(I);
5840     SDValue Dst = getValue(MI.getRawDest());
5841     SDValue Val = getValue(MI.getValue());
5842     SDValue Length = getValue(MI.getLength());
5843 
5844     unsigned DstAlign = MI.getDestAlignment();
5845     Type *LengthTy = MI.getLength()->getType();
5846     unsigned ElemSz = MI.getElementSizeInBytes();
5847     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5848     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5849                                      LengthTy, ElemSz, isTC,
5850                                      MachinePointerInfo(MI.getRawDest()));
5851     updateDAGForMaybeTailCall(MC);
5852     return;
5853   }
5854   case Intrinsic::call_preallocated_setup: {
5855     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5856     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5857     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5858                               getRoot(), SrcValue);
5859     setValue(&I, Res);
5860     DAG.setRoot(Res);
5861     return;
5862   }
5863   case Intrinsic::call_preallocated_arg: {
5864     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5865     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5866     SDValue Ops[3];
5867     Ops[0] = getRoot();
5868     Ops[1] = SrcValue;
5869     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5870                                    MVT::i32); // arg index
5871     SDValue Res = DAG.getNode(
5872         ISD::PREALLOCATED_ARG, sdl,
5873         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5874     setValue(&I, Res);
5875     DAG.setRoot(Res.getValue(1));
5876     return;
5877   }
5878   case Intrinsic::dbg_addr:
5879   case Intrinsic::dbg_declare: {
5880     const auto &DI = cast<DbgVariableIntrinsic>(I);
5881     DILocalVariable *Variable = DI.getVariable();
5882     DIExpression *Expression = DI.getExpression();
5883     dropDanglingDebugInfo(Variable, Expression);
5884     assert(Variable && "Missing variable");
5885     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5886                       << "\n");
5887     // Check if address has undef value.
5888     const Value *Address = DI.getVariableLocation();
5889     if (!Address || isa<UndefValue>(Address) ||
5890         (Address->use_empty() && !isa<Argument>(Address))) {
5891       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5892                         << " (bad/undef/unused-arg address)\n");
5893       return;
5894     }
5895 
5896     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5897 
5898     // Check if this variable can be described by a frame index, typically
5899     // either as a static alloca or a byval parameter.
5900     int FI = std::numeric_limits<int>::max();
5901     if (const auto *AI =
5902             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5903       if (AI->isStaticAlloca()) {
5904         auto I = FuncInfo.StaticAllocaMap.find(AI);
5905         if (I != FuncInfo.StaticAllocaMap.end())
5906           FI = I->second;
5907       }
5908     } else if (const auto *Arg = dyn_cast<Argument>(
5909                    Address->stripInBoundsConstantOffsets())) {
5910       FI = FuncInfo.getArgumentFrameIndex(Arg);
5911     }
5912 
5913     // llvm.dbg.addr is control dependent and always generates indirect
5914     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5915     // the MachineFunction variable table.
5916     if (FI != std::numeric_limits<int>::max()) {
5917       if (Intrinsic == Intrinsic::dbg_addr) {
5918         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5919             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5920         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5921       } else {
5922         LLVM_DEBUG(dbgs() << "Skipping " << DI
5923                           << " (variable info stashed in MF side table)\n");
5924       }
5925       return;
5926     }
5927 
5928     SDValue &N = NodeMap[Address];
5929     if (!N.getNode() && isa<Argument>(Address))
5930       // Check unused arguments map.
5931       N = UnusedArgNodeMap[Address];
5932     SDDbgValue *SDV;
5933     if (N.getNode()) {
5934       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5935         Address = BCI->getOperand(0);
5936       // Parameters are handled specially.
5937       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5938       if (isParameter && FINode) {
5939         // Byval parameter. We have a frame index at this point.
5940         SDV =
5941             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5942                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5943       } else if (isa<Argument>(Address)) {
5944         // Address is an argument, so try to emit its dbg value using
5945         // virtual register info from the FuncInfo.ValueMap.
5946         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5947         return;
5948       } else {
5949         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5950                               true, dl, SDNodeOrder);
5951       }
5952       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5953     } else {
5954       // If Address is an argument then try to emit its dbg value using
5955       // virtual register info from the FuncInfo.ValueMap.
5956       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5957                                     N)) {
5958         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5959                           << " (could not emit func-arg dbg_value)\n");
5960       }
5961     }
5962     return;
5963   }
5964   case Intrinsic::dbg_label: {
5965     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5966     DILabel *Label = DI.getLabel();
5967     assert(Label && "Missing label");
5968 
5969     SDDbgLabel *SDV;
5970     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5971     DAG.AddDbgLabel(SDV);
5972     return;
5973   }
5974   case Intrinsic::dbg_value: {
5975     const DbgValueInst &DI = cast<DbgValueInst>(I);
5976     assert(DI.getVariable() && "Missing variable");
5977 
5978     DILocalVariable *Variable = DI.getVariable();
5979     DIExpression *Expression = DI.getExpression();
5980     dropDanglingDebugInfo(Variable, Expression);
5981     const Value *V = DI.getValue();
5982     if (!V)
5983       return;
5984 
5985     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5986         SDNodeOrder))
5987       return;
5988 
5989     // TODO: Dangling debug info will eventually either be resolved or produce
5990     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5991     // between the original dbg.value location and its resolved DBG_VALUE, which
5992     // we should ideally fill with an extra Undef DBG_VALUE.
5993 
5994     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5995     return;
5996   }
5997 
5998   case Intrinsic::eh_typeid_for: {
5999     // Find the type id for the given typeinfo.
6000     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6001     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6002     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6003     setValue(&I, Res);
6004     return;
6005   }
6006 
6007   case Intrinsic::eh_return_i32:
6008   case Intrinsic::eh_return_i64:
6009     DAG.getMachineFunction().setCallsEHReturn(true);
6010     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6011                             MVT::Other,
6012                             getControlRoot(),
6013                             getValue(I.getArgOperand(0)),
6014                             getValue(I.getArgOperand(1))));
6015     return;
6016   case Intrinsic::eh_unwind_init:
6017     DAG.getMachineFunction().setCallsUnwindInit(true);
6018     return;
6019   case Intrinsic::eh_dwarf_cfa:
6020     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6021                              TLI.getPointerTy(DAG.getDataLayout()),
6022                              getValue(I.getArgOperand(0))));
6023     return;
6024   case Intrinsic::eh_sjlj_callsite: {
6025     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6026     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6027     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6028     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6029 
6030     MMI.setCurrentCallSite(CI->getZExtValue());
6031     return;
6032   }
6033   case Intrinsic::eh_sjlj_functioncontext: {
6034     // Get and store the index of the function context.
6035     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6036     AllocaInst *FnCtx =
6037       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6038     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6039     MFI.setFunctionContextIndex(FI);
6040     return;
6041   }
6042   case Intrinsic::eh_sjlj_setjmp: {
6043     SDValue Ops[2];
6044     Ops[0] = getRoot();
6045     Ops[1] = getValue(I.getArgOperand(0));
6046     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6047                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6048     setValue(&I, Op.getValue(0));
6049     DAG.setRoot(Op.getValue(1));
6050     return;
6051   }
6052   case Intrinsic::eh_sjlj_longjmp:
6053     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6054                             getRoot(), getValue(I.getArgOperand(0))));
6055     return;
6056   case Intrinsic::eh_sjlj_setup_dispatch:
6057     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6058                             getRoot()));
6059     return;
6060   case Intrinsic::masked_gather:
6061     visitMaskedGather(I);
6062     return;
6063   case Intrinsic::masked_load:
6064     visitMaskedLoad(I);
6065     return;
6066   case Intrinsic::masked_scatter:
6067     visitMaskedScatter(I);
6068     return;
6069   case Intrinsic::masked_store:
6070     visitMaskedStore(I);
6071     return;
6072   case Intrinsic::masked_expandload:
6073     visitMaskedLoad(I, true /* IsExpanding */);
6074     return;
6075   case Intrinsic::masked_compressstore:
6076     visitMaskedStore(I, true /* IsCompressing */);
6077     return;
6078   case Intrinsic::powi:
6079     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6080                             getValue(I.getArgOperand(1)), DAG));
6081     return;
6082   case Intrinsic::log:
6083     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6084     return;
6085   case Intrinsic::log2:
6086     setValue(&I,
6087              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6088     return;
6089   case Intrinsic::log10:
6090     setValue(&I,
6091              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6092     return;
6093   case Intrinsic::exp:
6094     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6095     return;
6096   case Intrinsic::exp2:
6097     setValue(&I,
6098              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6099     return;
6100   case Intrinsic::pow:
6101     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6102                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6103     return;
6104   case Intrinsic::sqrt:
6105   case Intrinsic::fabs:
6106   case Intrinsic::sin:
6107   case Intrinsic::cos:
6108   case Intrinsic::floor:
6109   case Intrinsic::ceil:
6110   case Intrinsic::trunc:
6111   case Intrinsic::rint:
6112   case Intrinsic::nearbyint:
6113   case Intrinsic::round:
6114   case Intrinsic::roundeven:
6115   case Intrinsic::canonicalize: {
6116     unsigned Opcode;
6117     switch (Intrinsic) {
6118     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6119     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6120     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6121     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6122     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6123     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6124     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6125     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6126     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6127     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6128     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6129     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6130     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6131     }
6132 
6133     setValue(&I, DAG.getNode(Opcode, sdl,
6134                              getValue(I.getArgOperand(0)).getValueType(),
6135                              getValue(I.getArgOperand(0)), Flags));
6136     return;
6137   }
6138   case Intrinsic::lround:
6139   case Intrinsic::llround:
6140   case Intrinsic::lrint:
6141   case Intrinsic::llrint: {
6142     unsigned Opcode;
6143     switch (Intrinsic) {
6144     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6145     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6146     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6147     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6148     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6149     }
6150 
6151     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6152     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6153                              getValue(I.getArgOperand(0))));
6154     return;
6155   }
6156   case Intrinsic::minnum:
6157     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6158                              getValue(I.getArgOperand(0)).getValueType(),
6159                              getValue(I.getArgOperand(0)),
6160                              getValue(I.getArgOperand(1)), Flags));
6161     return;
6162   case Intrinsic::maxnum:
6163     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6164                              getValue(I.getArgOperand(0)).getValueType(),
6165                              getValue(I.getArgOperand(0)),
6166                              getValue(I.getArgOperand(1)), Flags));
6167     return;
6168   case Intrinsic::minimum:
6169     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6170                              getValue(I.getArgOperand(0)).getValueType(),
6171                              getValue(I.getArgOperand(0)),
6172                              getValue(I.getArgOperand(1)), Flags));
6173     return;
6174   case Intrinsic::maximum:
6175     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6176                              getValue(I.getArgOperand(0)).getValueType(),
6177                              getValue(I.getArgOperand(0)),
6178                              getValue(I.getArgOperand(1)), Flags));
6179     return;
6180   case Intrinsic::copysign:
6181     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6182                              getValue(I.getArgOperand(0)).getValueType(),
6183                              getValue(I.getArgOperand(0)),
6184                              getValue(I.getArgOperand(1)), Flags));
6185     return;
6186   case Intrinsic::fma:
6187     setValue(&I, DAG.getNode(
6188                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6189                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6190                      getValue(I.getArgOperand(2)), Flags));
6191     return;
6192 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6193   case Intrinsic::INTRINSIC:
6194 #include "llvm/IR/ConstrainedOps.def"
6195     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6196     return;
6197 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6198 #include "llvm/IR/VPIntrinsics.def"
6199     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6200     return;
6201   case Intrinsic::fmuladd: {
6202     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6203     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6204         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6205       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6206                                getValue(I.getArgOperand(0)).getValueType(),
6207                                getValue(I.getArgOperand(0)),
6208                                getValue(I.getArgOperand(1)),
6209                                getValue(I.getArgOperand(2)), Flags));
6210     } else {
6211       // TODO: Intrinsic calls should have fast-math-flags.
6212       SDValue Mul = DAG.getNode(
6213           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6214           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6215       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6216                                 getValue(I.getArgOperand(0)).getValueType(),
6217                                 Mul, getValue(I.getArgOperand(2)), Flags);
6218       setValue(&I, Add);
6219     }
6220     return;
6221   }
6222   case Intrinsic::convert_to_fp16:
6223     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6224                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6225                                          getValue(I.getArgOperand(0)),
6226                                          DAG.getTargetConstant(0, sdl,
6227                                                                MVT::i32))));
6228     return;
6229   case Intrinsic::convert_from_fp16:
6230     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6231                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6232                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6233                                          getValue(I.getArgOperand(0)))));
6234     return;
6235   case Intrinsic::fptosi_sat: {
6236     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6237     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6238     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type,
6239                              getValue(I.getArgOperand(0)), SatW));
6240     return;
6241   }
6242   case Intrinsic::fptoui_sat: {
6243     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6244     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6245     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type,
6246                              getValue(I.getArgOperand(0)), SatW));
6247     return;
6248   }
6249   case Intrinsic::set_rounding:
6250     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6251                       {getRoot(), getValue(I.getArgOperand(0))});
6252     setValue(&I, Res);
6253     DAG.setRoot(Res.getValue(0));
6254     return;
6255   case Intrinsic::pcmarker: {
6256     SDValue Tmp = getValue(I.getArgOperand(0));
6257     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6258     return;
6259   }
6260   case Intrinsic::readcyclecounter: {
6261     SDValue Op = getRoot();
6262     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6263                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6264     setValue(&I, Res);
6265     DAG.setRoot(Res.getValue(1));
6266     return;
6267   }
6268   case Intrinsic::bitreverse:
6269     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6270                              getValue(I.getArgOperand(0)).getValueType(),
6271                              getValue(I.getArgOperand(0))));
6272     return;
6273   case Intrinsic::bswap:
6274     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6275                              getValue(I.getArgOperand(0)).getValueType(),
6276                              getValue(I.getArgOperand(0))));
6277     return;
6278   case Intrinsic::cttz: {
6279     SDValue Arg = getValue(I.getArgOperand(0));
6280     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6281     EVT Ty = Arg.getValueType();
6282     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6283                              sdl, Ty, Arg));
6284     return;
6285   }
6286   case Intrinsic::ctlz: {
6287     SDValue Arg = getValue(I.getArgOperand(0));
6288     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6289     EVT Ty = Arg.getValueType();
6290     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6291                              sdl, Ty, Arg));
6292     return;
6293   }
6294   case Intrinsic::ctpop: {
6295     SDValue Arg = getValue(I.getArgOperand(0));
6296     EVT Ty = Arg.getValueType();
6297     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6298     return;
6299   }
6300   case Intrinsic::fshl:
6301   case Intrinsic::fshr: {
6302     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6303     SDValue X = getValue(I.getArgOperand(0));
6304     SDValue Y = getValue(I.getArgOperand(1));
6305     SDValue Z = getValue(I.getArgOperand(2));
6306     EVT VT = X.getValueType();
6307 
6308     if (X == Y) {
6309       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6310       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6311     } else {
6312       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6313       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6314     }
6315     return;
6316   }
6317   case Intrinsic::sadd_sat: {
6318     SDValue Op1 = getValue(I.getArgOperand(0));
6319     SDValue Op2 = getValue(I.getArgOperand(1));
6320     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6321     return;
6322   }
6323   case Intrinsic::uadd_sat: {
6324     SDValue Op1 = getValue(I.getArgOperand(0));
6325     SDValue Op2 = getValue(I.getArgOperand(1));
6326     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6327     return;
6328   }
6329   case Intrinsic::ssub_sat: {
6330     SDValue Op1 = getValue(I.getArgOperand(0));
6331     SDValue Op2 = getValue(I.getArgOperand(1));
6332     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6333     return;
6334   }
6335   case Intrinsic::usub_sat: {
6336     SDValue Op1 = getValue(I.getArgOperand(0));
6337     SDValue Op2 = getValue(I.getArgOperand(1));
6338     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6339     return;
6340   }
6341   case Intrinsic::sshl_sat: {
6342     SDValue Op1 = getValue(I.getArgOperand(0));
6343     SDValue Op2 = getValue(I.getArgOperand(1));
6344     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6345     return;
6346   }
6347   case Intrinsic::ushl_sat: {
6348     SDValue Op1 = getValue(I.getArgOperand(0));
6349     SDValue Op2 = getValue(I.getArgOperand(1));
6350     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6351     return;
6352   }
6353   case Intrinsic::smul_fix:
6354   case Intrinsic::umul_fix:
6355   case Intrinsic::smul_fix_sat:
6356   case Intrinsic::umul_fix_sat: {
6357     SDValue Op1 = getValue(I.getArgOperand(0));
6358     SDValue Op2 = getValue(I.getArgOperand(1));
6359     SDValue Op3 = getValue(I.getArgOperand(2));
6360     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6361                              Op1.getValueType(), Op1, Op2, Op3));
6362     return;
6363   }
6364   case Intrinsic::sdiv_fix:
6365   case Intrinsic::udiv_fix:
6366   case Intrinsic::sdiv_fix_sat:
6367   case Intrinsic::udiv_fix_sat: {
6368     SDValue Op1 = getValue(I.getArgOperand(0));
6369     SDValue Op2 = getValue(I.getArgOperand(1));
6370     SDValue Op3 = getValue(I.getArgOperand(2));
6371     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6372                               Op1, Op2, Op3, DAG, TLI));
6373     return;
6374   }
6375   case Intrinsic::smax: {
6376     SDValue Op1 = getValue(I.getArgOperand(0));
6377     SDValue Op2 = getValue(I.getArgOperand(1));
6378     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6379     return;
6380   }
6381   case Intrinsic::smin: {
6382     SDValue Op1 = getValue(I.getArgOperand(0));
6383     SDValue Op2 = getValue(I.getArgOperand(1));
6384     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6385     return;
6386   }
6387   case Intrinsic::umax: {
6388     SDValue Op1 = getValue(I.getArgOperand(0));
6389     SDValue Op2 = getValue(I.getArgOperand(1));
6390     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6391     return;
6392   }
6393   case Intrinsic::umin: {
6394     SDValue Op1 = getValue(I.getArgOperand(0));
6395     SDValue Op2 = getValue(I.getArgOperand(1));
6396     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6397     return;
6398   }
6399   case Intrinsic::abs: {
6400     // TODO: Preserve "int min is poison" arg in SDAG?
6401     SDValue Op1 = getValue(I.getArgOperand(0));
6402     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6403     return;
6404   }
6405   case Intrinsic::stacksave: {
6406     SDValue Op = getRoot();
6407     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6408     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6409     setValue(&I, Res);
6410     DAG.setRoot(Res.getValue(1));
6411     return;
6412   }
6413   case Intrinsic::stackrestore:
6414     Res = getValue(I.getArgOperand(0));
6415     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6416     return;
6417   case Intrinsic::get_dynamic_area_offset: {
6418     SDValue Op = getRoot();
6419     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6420     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6421     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6422     // target.
6423     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6424       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6425                          " intrinsic!");
6426     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6427                       Op);
6428     DAG.setRoot(Op);
6429     setValue(&I, Res);
6430     return;
6431   }
6432   case Intrinsic::stackguard: {
6433     MachineFunction &MF = DAG.getMachineFunction();
6434     const Module &M = *MF.getFunction().getParent();
6435     SDValue Chain = getRoot();
6436     if (TLI.useLoadStackGuardNode()) {
6437       Res = getLoadStackGuard(DAG, sdl, Chain);
6438     } else {
6439       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6440       const Value *Global = TLI.getSDagStackGuard(M);
6441       Align Align = DL->getPrefTypeAlign(Global->getType());
6442       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6443                         MachinePointerInfo(Global, 0), Align,
6444                         MachineMemOperand::MOVolatile);
6445     }
6446     if (TLI.useStackGuardXorFP())
6447       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6448     DAG.setRoot(Chain);
6449     setValue(&I, Res);
6450     return;
6451   }
6452   case Intrinsic::stackprotector: {
6453     // Emit code into the DAG to store the stack guard onto the stack.
6454     MachineFunction &MF = DAG.getMachineFunction();
6455     MachineFrameInfo &MFI = MF.getFrameInfo();
6456     SDValue Src, Chain = getRoot();
6457 
6458     if (TLI.useLoadStackGuardNode())
6459       Src = getLoadStackGuard(DAG, sdl, Chain);
6460     else
6461       Src = getValue(I.getArgOperand(0));   // The guard's value.
6462 
6463     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6464 
6465     int FI = FuncInfo.StaticAllocaMap[Slot];
6466     MFI.setStackProtectorIndex(FI);
6467     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6468 
6469     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6470 
6471     // Store the stack protector onto the stack.
6472     Res = DAG.getStore(
6473         Chain, sdl, Src, FIN,
6474         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6475         MaybeAlign(), MachineMemOperand::MOVolatile);
6476     setValue(&I, Res);
6477     DAG.setRoot(Res);
6478     return;
6479   }
6480   case Intrinsic::objectsize:
6481     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6482 
6483   case Intrinsic::is_constant:
6484     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6485 
6486   case Intrinsic::annotation:
6487   case Intrinsic::ptr_annotation:
6488   case Intrinsic::launder_invariant_group:
6489   case Intrinsic::strip_invariant_group:
6490     // Drop the intrinsic, but forward the value
6491     setValue(&I, getValue(I.getOperand(0)));
6492     return;
6493 
6494   case Intrinsic::assume:
6495   case Intrinsic::experimental_noalias_scope_decl:
6496   case Intrinsic::var_annotation:
6497   case Intrinsic::sideeffect:
6498     // Discard annotate attributes, noalias scope declarations, assumptions, and
6499     // artificial side-effects.
6500     return;
6501 
6502   case Intrinsic::codeview_annotation: {
6503     // Emit a label associated with this metadata.
6504     MachineFunction &MF = DAG.getMachineFunction();
6505     MCSymbol *Label =
6506         MF.getMMI().getContext().createTempSymbol("annotation", true);
6507     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6508     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6509     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6510     DAG.setRoot(Res);
6511     return;
6512   }
6513 
6514   case Intrinsic::init_trampoline: {
6515     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6516 
6517     SDValue Ops[6];
6518     Ops[0] = getRoot();
6519     Ops[1] = getValue(I.getArgOperand(0));
6520     Ops[2] = getValue(I.getArgOperand(1));
6521     Ops[3] = getValue(I.getArgOperand(2));
6522     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6523     Ops[5] = DAG.getSrcValue(F);
6524 
6525     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6526 
6527     DAG.setRoot(Res);
6528     return;
6529   }
6530   case Intrinsic::adjust_trampoline:
6531     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6532                              TLI.getPointerTy(DAG.getDataLayout()),
6533                              getValue(I.getArgOperand(0))));
6534     return;
6535   case Intrinsic::gcroot: {
6536     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6537            "only valid in functions with gc specified, enforced by Verifier");
6538     assert(GFI && "implied by previous");
6539     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6540     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6541 
6542     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6543     GFI->addStackRoot(FI->getIndex(), TypeMap);
6544     return;
6545   }
6546   case Intrinsic::gcread:
6547   case Intrinsic::gcwrite:
6548     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6549   case Intrinsic::flt_rounds:
6550     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6551     setValue(&I, Res);
6552     DAG.setRoot(Res.getValue(1));
6553     return;
6554 
6555   case Intrinsic::expect:
6556     // Just replace __builtin_expect(exp, c) with EXP.
6557     setValue(&I, getValue(I.getArgOperand(0)));
6558     return;
6559 
6560   case Intrinsic::ubsantrap:
6561   case Intrinsic::debugtrap:
6562   case Intrinsic::trap: {
6563     StringRef TrapFuncName =
6564         I.getAttributes()
6565             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6566             .getValueAsString();
6567     if (TrapFuncName.empty()) {
6568       switch (Intrinsic) {
6569       case Intrinsic::trap:
6570         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6571         break;
6572       case Intrinsic::debugtrap:
6573         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6574         break;
6575       case Intrinsic::ubsantrap:
6576         DAG.setRoot(DAG.getNode(
6577             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6578             DAG.getTargetConstant(
6579                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6580                 MVT::i32)));
6581         break;
6582       default: llvm_unreachable("unknown trap intrinsic");
6583       }
6584       return;
6585     }
6586     TargetLowering::ArgListTy Args;
6587     if (Intrinsic == Intrinsic::ubsantrap) {
6588       Args.push_back(TargetLoweringBase::ArgListEntry());
6589       Args[0].Val = I.getArgOperand(0);
6590       Args[0].Node = getValue(Args[0].Val);
6591       Args[0].Ty = Args[0].Val->getType();
6592     }
6593 
6594     TargetLowering::CallLoweringInfo CLI(DAG);
6595     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6596         CallingConv::C, I.getType(),
6597         DAG.getExternalSymbol(TrapFuncName.data(),
6598                               TLI.getPointerTy(DAG.getDataLayout())),
6599         std::move(Args));
6600 
6601     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6602     DAG.setRoot(Result.second);
6603     return;
6604   }
6605 
6606   case Intrinsic::uadd_with_overflow:
6607   case Intrinsic::sadd_with_overflow:
6608   case Intrinsic::usub_with_overflow:
6609   case Intrinsic::ssub_with_overflow:
6610   case Intrinsic::umul_with_overflow:
6611   case Intrinsic::smul_with_overflow: {
6612     ISD::NodeType Op;
6613     switch (Intrinsic) {
6614     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6615     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6616     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6617     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6618     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6619     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6620     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6621     }
6622     SDValue Op1 = getValue(I.getArgOperand(0));
6623     SDValue Op2 = getValue(I.getArgOperand(1));
6624 
6625     EVT ResultVT = Op1.getValueType();
6626     EVT OverflowVT = MVT::i1;
6627     if (ResultVT.isVector())
6628       OverflowVT = EVT::getVectorVT(
6629           *Context, OverflowVT, ResultVT.getVectorElementCount());
6630 
6631     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6632     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6633     return;
6634   }
6635   case Intrinsic::prefetch: {
6636     SDValue Ops[5];
6637     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6638     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6639     Ops[0] = DAG.getRoot();
6640     Ops[1] = getValue(I.getArgOperand(0));
6641     Ops[2] = getValue(I.getArgOperand(1));
6642     Ops[3] = getValue(I.getArgOperand(2));
6643     Ops[4] = getValue(I.getArgOperand(3));
6644     SDValue Result = DAG.getMemIntrinsicNode(
6645         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6646         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6647         /* align */ None, Flags);
6648 
6649     // Chain the prefetch in parallell with any pending loads, to stay out of
6650     // the way of later optimizations.
6651     PendingLoads.push_back(Result);
6652     Result = getRoot();
6653     DAG.setRoot(Result);
6654     return;
6655   }
6656   case Intrinsic::lifetime_start:
6657   case Intrinsic::lifetime_end: {
6658     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6659     // Stack coloring is not enabled in O0, discard region information.
6660     if (TM.getOptLevel() == CodeGenOpt::None)
6661       return;
6662 
6663     const int64_t ObjectSize =
6664         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6665     Value *const ObjectPtr = I.getArgOperand(1);
6666     SmallVector<const Value *, 4> Allocas;
6667     getUnderlyingObjects(ObjectPtr, Allocas);
6668 
6669     for (const Value *Alloca : Allocas) {
6670       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6671 
6672       // Could not find an Alloca.
6673       if (!LifetimeObject)
6674         continue;
6675 
6676       // First check that the Alloca is static, otherwise it won't have a
6677       // valid frame index.
6678       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6679       if (SI == FuncInfo.StaticAllocaMap.end())
6680         return;
6681 
6682       const int FrameIndex = SI->second;
6683       int64_t Offset;
6684       if (GetPointerBaseWithConstantOffset(
6685               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6686         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6687       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6688                                 Offset);
6689       DAG.setRoot(Res);
6690     }
6691     return;
6692   }
6693   case Intrinsic::pseudoprobe: {
6694     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6695     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6696     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6697     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6698     DAG.setRoot(Res);
6699     return;
6700   }
6701   case Intrinsic::invariant_start:
6702     // Discard region information.
6703     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6704     return;
6705   case Intrinsic::invariant_end:
6706     // Discard region information.
6707     return;
6708   case Intrinsic::clear_cache:
6709     /// FunctionName may be null.
6710     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6711       lowerCallToExternalSymbol(I, FunctionName);
6712     return;
6713   case Intrinsic::donothing:
6714     // ignore
6715     return;
6716   case Intrinsic::experimental_stackmap:
6717     visitStackmap(I);
6718     return;
6719   case Intrinsic::experimental_patchpoint_void:
6720   case Intrinsic::experimental_patchpoint_i64:
6721     visitPatchpoint(I);
6722     return;
6723   case Intrinsic::experimental_gc_statepoint:
6724     LowerStatepoint(cast<GCStatepointInst>(I));
6725     return;
6726   case Intrinsic::experimental_gc_result:
6727     visitGCResult(cast<GCResultInst>(I));
6728     return;
6729   case Intrinsic::experimental_gc_relocate:
6730     visitGCRelocate(cast<GCRelocateInst>(I));
6731     return;
6732   case Intrinsic::instrprof_increment:
6733     llvm_unreachable("instrprof failed to lower an increment");
6734   case Intrinsic::instrprof_value_profile:
6735     llvm_unreachable("instrprof failed to lower a value profiling call");
6736   case Intrinsic::localescape: {
6737     MachineFunction &MF = DAG.getMachineFunction();
6738     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6739 
6740     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6741     // is the same on all targets.
6742     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6743       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6744       if (isa<ConstantPointerNull>(Arg))
6745         continue; // Skip null pointers. They represent a hole in index space.
6746       AllocaInst *Slot = cast<AllocaInst>(Arg);
6747       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6748              "can only escape static allocas");
6749       int FI = FuncInfo.StaticAllocaMap[Slot];
6750       MCSymbol *FrameAllocSym =
6751           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6752               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6753       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6754               TII->get(TargetOpcode::LOCAL_ESCAPE))
6755           .addSym(FrameAllocSym)
6756           .addFrameIndex(FI);
6757     }
6758 
6759     return;
6760   }
6761 
6762   case Intrinsic::localrecover: {
6763     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6764     MachineFunction &MF = DAG.getMachineFunction();
6765 
6766     // Get the symbol that defines the frame offset.
6767     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6768     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6769     unsigned IdxVal =
6770         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6771     MCSymbol *FrameAllocSym =
6772         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6773             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6774 
6775     Value *FP = I.getArgOperand(1);
6776     SDValue FPVal = getValue(FP);
6777     EVT PtrVT = FPVal.getValueType();
6778 
6779     // Create a MCSymbol for the label to avoid any target lowering
6780     // that would make this PC relative.
6781     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6782     SDValue OffsetVal =
6783         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6784 
6785     // Add the offset to the FP.
6786     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6787     setValue(&I, Add);
6788 
6789     return;
6790   }
6791 
6792   case Intrinsic::eh_exceptionpointer:
6793   case Intrinsic::eh_exceptioncode: {
6794     // Get the exception pointer vreg, copy from it, and resize it to fit.
6795     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6796     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6797     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6798     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6799     SDValue N =
6800         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6801     if (Intrinsic == Intrinsic::eh_exceptioncode)
6802       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6803     setValue(&I, N);
6804     return;
6805   }
6806   case Intrinsic::xray_customevent: {
6807     // Here we want to make sure that the intrinsic behaves as if it has a
6808     // specific calling convention, and only for x86_64.
6809     // FIXME: Support other platforms later.
6810     const auto &Triple = DAG.getTarget().getTargetTriple();
6811     if (Triple.getArch() != Triple::x86_64)
6812       return;
6813 
6814     SDLoc DL = getCurSDLoc();
6815     SmallVector<SDValue, 8> Ops;
6816 
6817     // We want to say that we always want the arguments in registers.
6818     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6819     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6820     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6821     SDValue Chain = getRoot();
6822     Ops.push_back(LogEntryVal);
6823     Ops.push_back(StrSizeVal);
6824     Ops.push_back(Chain);
6825 
6826     // We need to enforce the calling convention for the callsite, so that
6827     // argument ordering is enforced correctly, and that register allocation can
6828     // see that some registers may be assumed clobbered and have to preserve
6829     // them across calls to the intrinsic.
6830     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6831                                            DL, NodeTys, Ops);
6832     SDValue patchableNode = SDValue(MN, 0);
6833     DAG.setRoot(patchableNode);
6834     setValue(&I, patchableNode);
6835     return;
6836   }
6837   case Intrinsic::xray_typedevent: {
6838     // Here we want to make sure that the intrinsic behaves as if it has a
6839     // specific calling convention, and only for x86_64.
6840     // FIXME: Support other platforms later.
6841     const auto &Triple = DAG.getTarget().getTargetTriple();
6842     if (Triple.getArch() != Triple::x86_64)
6843       return;
6844 
6845     SDLoc DL = getCurSDLoc();
6846     SmallVector<SDValue, 8> Ops;
6847 
6848     // We want to say that we always want the arguments in registers.
6849     // It's unclear to me how manipulating the selection DAG here forces callers
6850     // to provide arguments in registers instead of on the stack.
6851     SDValue LogTypeId = getValue(I.getArgOperand(0));
6852     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6853     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6854     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6855     SDValue Chain = getRoot();
6856     Ops.push_back(LogTypeId);
6857     Ops.push_back(LogEntryVal);
6858     Ops.push_back(StrSizeVal);
6859     Ops.push_back(Chain);
6860 
6861     // We need to enforce the calling convention for the callsite, so that
6862     // argument ordering is enforced correctly, and that register allocation can
6863     // see that some registers may be assumed clobbered and have to preserve
6864     // them across calls to the intrinsic.
6865     MachineSDNode *MN = DAG.getMachineNode(
6866         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6867     SDValue patchableNode = SDValue(MN, 0);
6868     DAG.setRoot(patchableNode);
6869     setValue(&I, patchableNode);
6870     return;
6871   }
6872   case Intrinsic::experimental_deoptimize:
6873     LowerDeoptimizeCall(&I);
6874     return;
6875 
6876   case Intrinsic::vector_reduce_fadd:
6877   case Intrinsic::vector_reduce_fmul:
6878   case Intrinsic::vector_reduce_add:
6879   case Intrinsic::vector_reduce_mul:
6880   case Intrinsic::vector_reduce_and:
6881   case Intrinsic::vector_reduce_or:
6882   case Intrinsic::vector_reduce_xor:
6883   case Intrinsic::vector_reduce_smax:
6884   case Intrinsic::vector_reduce_smin:
6885   case Intrinsic::vector_reduce_umax:
6886   case Intrinsic::vector_reduce_umin:
6887   case Intrinsic::vector_reduce_fmax:
6888   case Intrinsic::vector_reduce_fmin:
6889     visitVectorReduce(I, Intrinsic);
6890     return;
6891 
6892   case Intrinsic::icall_branch_funnel: {
6893     SmallVector<SDValue, 16> Ops;
6894     Ops.push_back(getValue(I.getArgOperand(0)));
6895 
6896     int64_t Offset;
6897     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6898         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6899     if (!Base)
6900       report_fatal_error(
6901           "llvm.icall.branch.funnel operand must be a GlobalValue");
6902     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6903 
6904     struct BranchFunnelTarget {
6905       int64_t Offset;
6906       SDValue Target;
6907     };
6908     SmallVector<BranchFunnelTarget, 8> Targets;
6909 
6910     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6911       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6912           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6913       if (ElemBase != Base)
6914         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6915                            "to the same GlobalValue");
6916 
6917       SDValue Val = getValue(I.getArgOperand(Op + 1));
6918       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6919       if (!GA)
6920         report_fatal_error(
6921             "llvm.icall.branch.funnel operand must be a GlobalValue");
6922       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6923                                      GA->getGlobal(), getCurSDLoc(),
6924                                      Val.getValueType(), GA->getOffset())});
6925     }
6926     llvm::sort(Targets,
6927                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6928                  return T1.Offset < T2.Offset;
6929                });
6930 
6931     for (auto &T : Targets) {
6932       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6933       Ops.push_back(T.Target);
6934     }
6935 
6936     Ops.push_back(DAG.getRoot()); // Chain
6937     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6938                                  getCurSDLoc(), MVT::Other, Ops),
6939               0);
6940     DAG.setRoot(N);
6941     setValue(&I, N);
6942     HasTailCall = true;
6943     return;
6944   }
6945 
6946   case Intrinsic::wasm_landingpad_index:
6947     // Information this intrinsic contained has been transferred to
6948     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6949     // delete it now.
6950     return;
6951 
6952   case Intrinsic::aarch64_settag:
6953   case Intrinsic::aarch64_settag_zero: {
6954     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6955     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6956     SDValue Val = TSI.EmitTargetCodeForSetTag(
6957         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6958         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6959         ZeroMemory);
6960     DAG.setRoot(Val);
6961     setValue(&I, Val);
6962     return;
6963   }
6964   case Intrinsic::ptrmask: {
6965     SDValue Ptr = getValue(I.getOperand(0));
6966     SDValue Const = getValue(I.getOperand(1));
6967 
6968     EVT PtrVT = Ptr.getValueType();
6969     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6970                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6971     return;
6972   }
6973   case Intrinsic::get_active_lane_mask: {
6974     auto DL = getCurSDLoc();
6975     SDValue Index = getValue(I.getOperand(0));
6976     SDValue TripCount = getValue(I.getOperand(1));
6977     Type *ElementTy = I.getOperand(0)->getType();
6978     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6979     unsigned VecWidth = VT.getVectorNumElements();
6980 
6981     SmallVector<SDValue, 16> OpsTripCount;
6982     SmallVector<SDValue, 16> OpsIndex;
6983     SmallVector<SDValue, 16> OpsStepConstants;
6984     for (unsigned i = 0; i < VecWidth; i++) {
6985       OpsTripCount.push_back(TripCount);
6986       OpsIndex.push_back(Index);
6987       OpsStepConstants.push_back(
6988           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
6989     }
6990 
6991     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
6992 
6993     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
6994     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6995     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6996     SDValue VectorInduction = DAG.getNode(
6997        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6998     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
6999     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7000                                  VectorTripCount, ISD::CondCode::SETULT);
7001     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7002                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7003                              SetCC));
7004     return;
7005   }
7006   case Intrinsic::experimental_vector_insert: {
7007     auto DL = getCurSDLoc();
7008 
7009     SDValue Vec = getValue(I.getOperand(0));
7010     SDValue SubVec = getValue(I.getOperand(1));
7011     SDValue Index = getValue(I.getOperand(2));
7012 
7013     // The intrinsic's index type is i64, but the SDNode requires an index type
7014     // suitable for the target. Convert the index as required.
7015     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7016     if (Index.getValueType() != VectorIdxTy)
7017       Index = DAG.getVectorIdxConstant(
7018           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7019 
7020     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7021     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7022                              Index));
7023     return;
7024   }
7025   case Intrinsic::experimental_vector_extract: {
7026     auto DL = getCurSDLoc();
7027 
7028     SDValue Vec = getValue(I.getOperand(0));
7029     SDValue Index = getValue(I.getOperand(1));
7030     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7031 
7032     // The intrinsic's index type is i64, but the SDNode requires an index type
7033     // suitable for the target. Convert the index as required.
7034     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7035     if (Index.getValueType() != VectorIdxTy)
7036       Index = DAG.getVectorIdxConstant(
7037           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7038 
7039     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7040     return;
7041   }
7042   case Intrinsic::experimental_vector_reverse:
7043     visitVectorReverse(I);
7044     return;
7045   }
7046 }
7047 
7048 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7049     const ConstrainedFPIntrinsic &FPI) {
7050   SDLoc sdl = getCurSDLoc();
7051 
7052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7053   SmallVector<EVT, 4> ValueVTs;
7054   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7055   ValueVTs.push_back(MVT::Other); // Out chain
7056 
7057   // We do not need to serialize constrained FP intrinsics against
7058   // each other or against (nonvolatile) loads, so they can be
7059   // chained like loads.
7060   SDValue Chain = DAG.getRoot();
7061   SmallVector<SDValue, 4> Opers;
7062   Opers.push_back(Chain);
7063   if (FPI.isUnaryOp()) {
7064     Opers.push_back(getValue(FPI.getArgOperand(0)));
7065   } else if (FPI.isTernaryOp()) {
7066     Opers.push_back(getValue(FPI.getArgOperand(0)));
7067     Opers.push_back(getValue(FPI.getArgOperand(1)));
7068     Opers.push_back(getValue(FPI.getArgOperand(2)));
7069   } else {
7070     Opers.push_back(getValue(FPI.getArgOperand(0)));
7071     Opers.push_back(getValue(FPI.getArgOperand(1)));
7072   }
7073 
7074   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7075     assert(Result.getNode()->getNumValues() == 2);
7076 
7077     // Push node to the appropriate list so that future instructions can be
7078     // chained up correctly.
7079     SDValue OutChain = Result.getValue(1);
7080     switch (EB) {
7081     case fp::ExceptionBehavior::ebIgnore:
7082       // The only reason why ebIgnore nodes still need to be chained is that
7083       // they might depend on the current rounding mode, and therefore must
7084       // not be moved across instruction that may change that mode.
7085       LLVM_FALLTHROUGH;
7086     case fp::ExceptionBehavior::ebMayTrap:
7087       // These must not be moved across calls or instructions that may change
7088       // floating-point exception masks.
7089       PendingConstrainedFP.push_back(OutChain);
7090       break;
7091     case fp::ExceptionBehavior::ebStrict:
7092       // These must not be moved across calls or instructions that may change
7093       // floating-point exception masks or read floating-point exception flags.
7094       // In addition, they cannot be optimized out even if unused.
7095       PendingConstrainedFPStrict.push_back(OutChain);
7096       break;
7097     }
7098   };
7099 
7100   SDVTList VTs = DAG.getVTList(ValueVTs);
7101   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7102 
7103   SDNodeFlags Flags;
7104   if (EB == fp::ExceptionBehavior::ebIgnore)
7105     Flags.setNoFPExcept(true);
7106 
7107   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7108     Flags.copyFMF(*FPOp);
7109 
7110   unsigned Opcode;
7111   switch (FPI.getIntrinsicID()) {
7112   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7113 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7114   case Intrinsic::INTRINSIC:                                                   \
7115     Opcode = ISD::STRICT_##DAGN;                                               \
7116     break;
7117 #include "llvm/IR/ConstrainedOps.def"
7118   case Intrinsic::experimental_constrained_fmuladd: {
7119     Opcode = ISD::STRICT_FMA;
7120     // Break fmuladd into fmul and fadd.
7121     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7122         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7123                                         ValueVTs[0])) {
7124       Opers.pop_back();
7125       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7126       pushOutChain(Mul, EB);
7127       Opcode = ISD::STRICT_FADD;
7128       Opers.clear();
7129       Opers.push_back(Mul.getValue(1));
7130       Opers.push_back(Mul.getValue(0));
7131       Opers.push_back(getValue(FPI.getArgOperand(2)));
7132     }
7133     break;
7134   }
7135   }
7136 
7137   // A few strict DAG nodes carry additional operands that are not
7138   // set up by the default code above.
7139   switch (Opcode) {
7140   default: break;
7141   case ISD::STRICT_FP_ROUND:
7142     Opers.push_back(
7143         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7144     break;
7145   case ISD::STRICT_FSETCC:
7146   case ISD::STRICT_FSETCCS: {
7147     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7148     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7149     if (TM.Options.NoNaNsFPMath)
7150       Condition = getFCmpCodeWithoutNaN(Condition);
7151     Opers.push_back(DAG.getCondCode(Condition));
7152     break;
7153   }
7154   }
7155 
7156   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7157   pushOutChain(Result, EB);
7158 
7159   SDValue FPResult = Result.getValue(0);
7160   setValue(&FPI, FPResult);
7161 }
7162 
7163 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7164   Optional<unsigned> ResOPC;
7165   switch (VPIntrin.getIntrinsicID()) {
7166 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7167 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7168 #define END_REGISTER_VP_INTRINSIC(...) break;
7169 #include "llvm/IR/VPIntrinsics.def"
7170   }
7171 
7172   if (!ResOPC.hasValue())
7173     llvm_unreachable(
7174         "Inconsistency: no SDNode available for this VPIntrinsic!");
7175 
7176   return ResOPC.getValue();
7177 }
7178 
7179 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7180     const VPIntrinsic &VPIntrin) {
7181   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7182 
7183   SmallVector<EVT, 4> ValueVTs;
7184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7185   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7186   SDVTList VTs = DAG.getVTList(ValueVTs);
7187 
7188   // Request operands.
7189   SmallVector<SDValue, 7> OpValues;
7190   for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
7191     OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
7192 
7193   SDLoc DL = getCurSDLoc();
7194   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7195   setValue(&VPIntrin, Result);
7196 }
7197 
7198 std::pair<SDValue, SDValue>
7199 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7200                                     const BasicBlock *EHPadBB) {
7201   MachineFunction &MF = DAG.getMachineFunction();
7202   MachineModuleInfo &MMI = MF.getMMI();
7203   MCSymbol *BeginLabel = nullptr;
7204 
7205   if (EHPadBB) {
7206     // Insert a label before the invoke call to mark the try range.  This can be
7207     // used to detect deletion of the invoke via the MachineModuleInfo.
7208     BeginLabel = MMI.getContext().createTempSymbol();
7209 
7210     // For SjLj, keep track of which landing pads go with which invokes
7211     // so as to maintain the ordering of pads in the LSDA.
7212     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7213     if (CallSiteIndex) {
7214       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7215       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7216 
7217       // Now that the call site is handled, stop tracking it.
7218       MMI.setCurrentCallSite(0);
7219     }
7220 
7221     // Both PendingLoads and PendingExports must be flushed here;
7222     // this call might not return.
7223     (void)getRoot();
7224     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7225 
7226     CLI.setChain(getRoot());
7227   }
7228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7229   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7230 
7231   assert((CLI.IsTailCall || Result.second.getNode()) &&
7232          "Non-null chain expected with non-tail call!");
7233   assert((Result.second.getNode() || !Result.first.getNode()) &&
7234          "Null value expected with tail call!");
7235 
7236   if (!Result.second.getNode()) {
7237     // As a special case, a null chain means that a tail call has been emitted
7238     // and the DAG root is already updated.
7239     HasTailCall = true;
7240 
7241     // Since there's no actual continuation from this block, nothing can be
7242     // relying on us setting vregs for them.
7243     PendingExports.clear();
7244   } else {
7245     DAG.setRoot(Result.second);
7246   }
7247 
7248   if (EHPadBB) {
7249     // Insert a label at the end of the invoke call to mark the try range.  This
7250     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7251     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7252     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7253 
7254     // Inform MachineModuleInfo of range.
7255     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7256     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7257     // actually use outlined funclets and their LSDA info style.
7258     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7259       assert(CLI.CB);
7260       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7261       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7262     } else if (!isScopedEHPersonality(Pers)) {
7263       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7264     }
7265   }
7266 
7267   return Result;
7268 }
7269 
7270 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7271                                       bool isTailCall,
7272                                       const BasicBlock *EHPadBB) {
7273   auto &DL = DAG.getDataLayout();
7274   FunctionType *FTy = CB.getFunctionType();
7275   Type *RetTy = CB.getType();
7276 
7277   TargetLowering::ArgListTy Args;
7278   Args.reserve(CB.arg_size());
7279 
7280   const Value *SwiftErrorVal = nullptr;
7281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7282 
7283   if (isTailCall) {
7284     // Avoid emitting tail calls in functions with the disable-tail-calls
7285     // attribute.
7286     auto *Caller = CB.getParent()->getParent();
7287     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7288         "true")
7289       isTailCall = false;
7290 
7291     // We can't tail call inside a function with a swifterror argument. Lowering
7292     // does not support this yet. It would have to move into the swifterror
7293     // register before the call.
7294     if (TLI.supportSwiftError() &&
7295         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7296       isTailCall = false;
7297   }
7298 
7299   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7300     TargetLowering::ArgListEntry Entry;
7301     const Value *V = *I;
7302 
7303     // Skip empty types
7304     if (V->getType()->isEmptyTy())
7305       continue;
7306 
7307     SDValue ArgNode = getValue(V);
7308     Entry.Node = ArgNode; Entry.Ty = V->getType();
7309 
7310     Entry.setAttributes(&CB, I - CB.arg_begin());
7311 
7312     // Use swifterror virtual register as input to the call.
7313     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7314       SwiftErrorVal = V;
7315       // We find the virtual register for the actual swifterror argument.
7316       // Instead of using the Value, we use the virtual register instead.
7317       Entry.Node =
7318           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7319                           EVT(TLI.getPointerTy(DL)));
7320     }
7321 
7322     Args.push_back(Entry);
7323 
7324     // If we have an explicit sret argument that is an Instruction, (i.e., it
7325     // might point to function-local memory), we can't meaningfully tail-call.
7326     if (Entry.IsSRet && isa<Instruction>(V))
7327       isTailCall = false;
7328   }
7329 
7330   // If call site has a cfguardtarget operand bundle, create and add an
7331   // additional ArgListEntry.
7332   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7333     TargetLowering::ArgListEntry Entry;
7334     Value *V = Bundle->Inputs[0];
7335     SDValue ArgNode = getValue(V);
7336     Entry.Node = ArgNode;
7337     Entry.Ty = V->getType();
7338     Entry.IsCFGuardTarget = true;
7339     Args.push_back(Entry);
7340   }
7341 
7342   // Check if target-independent constraints permit a tail call here.
7343   // Target-dependent constraints are checked within TLI->LowerCallTo.
7344   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7345     isTailCall = false;
7346 
7347   // Disable tail calls if there is an swifterror argument. Targets have not
7348   // been updated to support tail calls.
7349   if (TLI.supportSwiftError() && SwiftErrorVal)
7350     isTailCall = false;
7351 
7352   TargetLowering::CallLoweringInfo CLI(DAG);
7353   CLI.setDebugLoc(getCurSDLoc())
7354       .setChain(getRoot())
7355       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7356       .setTailCall(isTailCall)
7357       .setConvergent(CB.isConvergent())
7358       .setIsPreallocated(
7359           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7360   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7361 
7362   if (Result.first.getNode()) {
7363     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7364     setValue(&CB, Result.first);
7365   }
7366 
7367   // The last element of CLI.InVals has the SDValue for swifterror return.
7368   // Here we copy it to a virtual register and update SwiftErrorMap for
7369   // book-keeping.
7370   if (SwiftErrorVal && TLI.supportSwiftError()) {
7371     // Get the last element of InVals.
7372     SDValue Src = CLI.InVals.back();
7373     Register VReg =
7374         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7375     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7376     DAG.setRoot(CopyNode);
7377   }
7378 }
7379 
7380 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7381                              SelectionDAGBuilder &Builder) {
7382   // Check to see if this load can be trivially constant folded, e.g. if the
7383   // input is from a string literal.
7384   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7385     // Cast pointer to the type we really want to load.
7386     Type *LoadTy =
7387         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7388     if (LoadVT.isVector())
7389       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7390 
7391     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7392                                          PointerType::getUnqual(LoadTy));
7393 
7394     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7395             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7396       return Builder.getValue(LoadCst);
7397   }
7398 
7399   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7400   // still constant memory, the input chain can be the entry node.
7401   SDValue Root;
7402   bool ConstantMemory = false;
7403 
7404   // Do not serialize (non-volatile) loads of constant memory with anything.
7405   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7406     Root = Builder.DAG.getEntryNode();
7407     ConstantMemory = true;
7408   } else {
7409     // Do not serialize non-volatile loads against each other.
7410     Root = Builder.DAG.getRoot();
7411   }
7412 
7413   SDValue Ptr = Builder.getValue(PtrVal);
7414   SDValue LoadVal =
7415       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7416                           MachinePointerInfo(PtrVal), Align(1));
7417 
7418   if (!ConstantMemory)
7419     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7420   return LoadVal;
7421 }
7422 
7423 /// Record the value for an instruction that produces an integer result,
7424 /// converting the type where necessary.
7425 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7426                                                   SDValue Value,
7427                                                   bool IsSigned) {
7428   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7429                                                     I.getType(), true);
7430   if (IsSigned)
7431     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7432   else
7433     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7434   setValue(&I, Value);
7435 }
7436 
7437 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7438 /// true and lower it. Otherwise return false, and it will be lowered like a
7439 /// normal call.
7440 /// The caller already checked that \p I calls the appropriate LibFunc with a
7441 /// correct prototype.
7442 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7443   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7444   const Value *Size = I.getArgOperand(2);
7445   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7446   if (CSize && CSize->getZExtValue() == 0) {
7447     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7448                                                           I.getType(), true);
7449     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7450     return true;
7451   }
7452 
7453   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7454   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7455       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7456       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7457   if (Res.first.getNode()) {
7458     processIntegerCallValue(I, Res.first, true);
7459     PendingLoads.push_back(Res.second);
7460     return true;
7461   }
7462 
7463   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7464   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7465   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7466     return false;
7467 
7468   // If the target has a fast compare for the given size, it will return a
7469   // preferred load type for that size. Require that the load VT is legal and
7470   // that the target supports unaligned loads of that type. Otherwise, return
7471   // INVALID.
7472   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7473     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7474     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7475     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7476       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7477       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7478       // TODO: Check alignment of src and dest ptrs.
7479       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7480       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7481       if (!TLI.isTypeLegal(LVT) ||
7482           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7483           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7484         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7485     }
7486 
7487     return LVT;
7488   };
7489 
7490   // This turns into unaligned loads. We only do this if the target natively
7491   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7492   // we'll only produce a small number of byte loads.
7493   MVT LoadVT;
7494   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7495   switch (NumBitsToCompare) {
7496   default:
7497     return false;
7498   case 16:
7499     LoadVT = MVT::i16;
7500     break;
7501   case 32:
7502     LoadVT = MVT::i32;
7503     break;
7504   case 64:
7505   case 128:
7506   case 256:
7507     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7508     break;
7509   }
7510 
7511   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7512     return false;
7513 
7514   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7515   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7516 
7517   // Bitcast to a wide integer type if the loads are vectors.
7518   if (LoadVT.isVector()) {
7519     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7520     LoadL = DAG.getBitcast(CmpVT, LoadL);
7521     LoadR = DAG.getBitcast(CmpVT, LoadR);
7522   }
7523 
7524   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7525   processIntegerCallValue(I, Cmp, false);
7526   return true;
7527 }
7528 
7529 /// See if we can lower a memchr call into an optimized form. If so, return
7530 /// true and lower it. Otherwise return false, and it will be lowered like a
7531 /// normal call.
7532 /// The caller already checked that \p I calls the appropriate LibFunc with a
7533 /// correct prototype.
7534 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7535   const Value *Src = I.getArgOperand(0);
7536   const Value *Char = I.getArgOperand(1);
7537   const Value *Length = I.getArgOperand(2);
7538 
7539   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7540   std::pair<SDValue, SDValue> Res =
7541     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7542                                 getValue(Src), getValue(Char), getValue(Length),
7543                                 MachinePointerInfo(Src));
7544   if (Res.first.getNode()) {
7545     setValue(&I, Res.first);
7546     PendingLoads.push_back(Res.second);
7547     return true;
7548   }
7549 
7550   return false;
7551 }
7552 
7553 /// See if we can lower a mempcpy call into an optimized form. If so, return
7554 /// true and lower it. Otherwise return false, and it will be lowered like a
7555 /// normal call.
7556 /// The caller already checked that \p I calls the appropriate LibFunc with a
7557 /// correct prototype.
7558 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7559   SDValue Dst = getValue(I.getArgOperand(0));
7560   SDValue Src = getValue(I.getArgOperand(1));
7561   SDValue Size = getValue(I.getArgOperand(2));
7562 
7563   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7564   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7565   // DAG::getMemcpy needs Alignment to be defined.
7566   Align Alignment = std::min(DstAlign, SrcAlign);
7567 
7568   bool isVol = false;
7569   SDLoc sdl = getCurSDLoc();
7570 
7571   // In the mempcpy context we need to pass in a false value for isTailCall
7572   // because the return pointer needs to be adjusted by the size of
7573   // the copied memory.
7574   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7575   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7576                              /*isTailCall=*/false,
7577                              MachinePointerInfo(I.getArgOperand(0)),
7578                              MachinePointerInfo(I.getArgOperand(1)));
7579   assert(MC.getNode() != nullptr &&
7580          "** memcpy should not be lowered as TailCall in mempcpy context **");
7581   DAG.setRoot(MC);
7582 
7583   // Check if Size needs to be truncated or extended.
7584   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7585 
7586   // Adjust return pointer to point just past the last dst byte.
7587   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7588                                     Dst, Size);
7589   setValue(&I, DstPlusSize);
7590   return true;
7591 }
7592 
7593 /// See if we can lower a strcpy call into an optimized form.  If so, return
7594 /// true and lower it, otherwise return false and it will be lowered like a
7595 /// normal call.
7596 /// The caller already checked that \p I calls the appropriate LibFunc with a
7597 /// correct prototype.
7598 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7599   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7600 
7601   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7602   std::pair<SDValue, SDValue> Res =
7603     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7604                                 getValue(Arg0), getValue(Arg1),
7605                                 MachinePointerInfo(Arg0),
7606                                 MachinePointerInfo(Arg1), isStpcpy);
7607   if (Res.first.getNode()) {
7608     setValue(&I, Res.first);
7609     DAG.setRoot(Res.second);
7610     return true;
7611   }
7612 
7613   return false;
7614 }
7615 
7616 /// See if we can lower a strcmp call into an optimized form.  If so, return
7617 /// true and lower it, otherwise return false and it will be lowered like a
7618 /// normal call.
7619 /// The caller already checked that \p I calls the appropriate LibFunc with a
7620 /// correct prototype.
7621 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7622   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7623 
7624   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7625   std::pair<SDValue, SDValue> Res =
7626     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7627                                 getValue(Arg0), getValue(Arg1),
7628                                 MachinePointerInfo(Arg0),
7629                                 MachinePointerInfo(Arg1));
7630   if (Res.first.getNode()) {
7631     processIntegerCallValue(I, Res.first, true);
7632     PendingLoads.push_back(Res.second);
7633     return true;
7634   }
7635 
7636   return false;
7637 }
7638 
7639 /// See if we can lower a strlen call into an optimized form.  If so, return
7640 /// true and lower it, otherwise return false and it will be lowered like a
7641 /// normal call.
7642 /// The caller already checked that \p I calls the appropriate LibFunc with a
7643 /// correct prototype.
7644 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7645   const Value *Arg0 = I.getArgOperand(0);
7646 
7647   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7648   std::pair<SDValue, SDValue> Res =
7649     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7650                                 getValue(Arg0), MachinePointerInfo(Arg0));
7651   if (Res.first.getNode()) {
7652     processIntegerCallValue(I, Res.first, false);
7653     PendingLoads.push_back(Res.second);
7654     return true;
7655   }
7656 
7657   return false;
7658 }
7659 
7660 /// See if we can lower a strnlen call into an optimized form.  If so, return
7661 /// true and lower it, otherwise return false and it will be lowered like a
7662 /// normal call.
7663 /// The caller already checked that \p I calls the appropriate LibFunc with a
7664 /// correct prototype.
7665 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7666   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7667 
7668   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7669   std::pair<SDValue, SDValue> Res =
7670     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7671                                  getValue(Arg0), getValue(Arg1),
7672                                  MachinePointerInfo(Arg0));
7673   if (Res.first.getNode()) {
7674     processIntegerCallValue(I, Res.first, false);
7675     PendingLoads.push_back(Res.second);
7676     return true;
7677   }
7678 
7679   return false;
7680 }
7681 
7682 /// See if we can lower a unary floating-point operation into an SDNode with
7683 /// the specified Opcode.  If so, return true and lower it, otherwise return
7684 /// false and it will be lowered like a normal call.
7685 /// The caller already checked that \p I calls the appropriate LibFunc with a
7686 /// correct prototype.
7687 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7688                                               unsigned Opcode) {
7689   // We already checked this call's prototype; verify it doesn't modify errno.
7690   if (!I.onlyReadsMemory())
7691     return false;
7692 
7693   SDNodeFlags Flags;
7694   Flags.copyFMF(cast<FPMathOperator>(I));
7695 
7696   SDValue Tmp = getValue(I.getArgOperand(0));
7697   setValue(&I,
7698            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7699   return true;
7700 }
7701 
7702 /// See if we can lower a binary floating-point operation into an SDNode with
7703 /// the specified Opcode. If so, return true and lower it. Otherwise return
7704 /// false, and it will be lowered like a normal call.
7705 /// The caller already checked that \p I calls the appropriate LibFunc with a
7706 /// correct prototype.
7707 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7708                                                unsigned Opcode) {
7709   // We already checked this call's prototype; verify it doesn't modify errno.
7710   if (!I.onlyReadsMemory())
7711     return false;
7712 
7713   SDNodeFlags Flags;
7714   Flags.copyFMF(cast<FPMathOperator>(I));
7715 
7716   SDValue Tmp0 = getValue(I.getArgOperand(0));
7717   SDValue Tmp1 = getValue(I.getArgOperand(1));
7718   EVT VT = Tmp0.getValueType();
7719   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7720   return true;
7721 }
7722 
7723 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7724   // Handle inline assembly differently.
7725   if (I.isInlineAsm()) {
7726     visitInlineAsm(I);
7727     return;
7728   }
7729 
7730   if (Function *F = I.getCalledFunction()) {
7731     if (F->isDeclaration()) {
7732       // Is this an LLVM intrinsic or a target-specific intrinsic?
7733       unsigned IID = F->getIntrinsicID();
7734       if (!IID)
7735         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7736           IID = II->getIntrinsicID(F);
7737 
7738       if (IID) {
7739         visitIntrinsicCall(I, IID);
7740         return;
7741       }
7742     }
7743 
7744     // Check for well-known libc/libm calls.  If the function is internal, it
7745     // can't be a library call.  Don't do the check if marked as nobuiltin for
7746     // some reason or the call site requires strict floating point semantics.
7747     LibFunc Func;
7748     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7749         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7750         LibInfo->hasOptimizedCodeGen(Func)) {
7751       switch (Func) {
7752       default: break;
7753       case LibFunc_bcmp:
7754         if (visitMemCmpBCmpCall(I))
7755           return;
7756         break;
7757       case LibFunc_copysign:
7758       case LibFunc_copysignf:
7759       case LibFunc_copysignl:
7760         // We already checked this call's prototype; verify it doesn't modify
7761         // errno.
7762         if (I.onlyReadsMemory()) {
7763           SDValue LHS = getValue(I.getArgOperand(0));
7764           SDValue RHS = getValue(I.getArgOperand(1));
7765           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7766                                    LHS.getValueType(), LHS, RHS));
7767           return;
7768         }
7769         break;
7770       case LibFunc_fabs:
7771       case LibFunc_fabsf:
7772       case LibFunc_fabsl:
7773         if (visitUnaryFloatCall(I, ISD::FABS))
7774           return;
7775         break;
7776       case LibFunc_fmin:
7777       case LibFunc_fminf:
7778       case LibFunc_fminl:
7779         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7780           return;
7781         break;
7782       case LibFunc_fmax:
7783       case LibFunc_fmaxf:
7784       case LibFunc_fmaxl:
7785         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7786           return;
7787         break;
7788       case LibFunc_sin:
7789       case LibFunc_sinf:
7790       case LibFunc_sinl:
7791         if (visitUnaryFloatCall(I, ISD::FSIN))
7792           return;
7793         break;
7794       case LibFunc_cos:
7795       case LibFunc_cosf:
7796       case LibFunc_cosl:
7797         if (visitUnaryFloatCall(I, ISD::FCOS))
7798           return;
7799         break;
7800       case LibFunc_sqrt:
7801       case LibFunc_sqrtf:
7802       case LibFunc_sqrtl:
7803       case LibFunc_sqrt_finite:
7804       case LibFunc_sqrtf_finite:
7805       case LibFunc_sqrtl_finite:
7806         if (visitUnaryFloatCall(I, ISD::FSQRT))
7807           return;
7808         break;
7809       case LibFunc_floor:
7810       case LibFunc_floorf:
7811       case LibFunc_floorl:
7812         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7813           return;
7814         break;
7815       case LibFunc_nearbyint:
7816       case LibFunc_nearbyintf:
7817       case LibFunc_nearbyintl:
7818         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7819           return;
7820         break;
7821       case LibFunc_ceil:
7822       case LibFunc_ceilf:
7823       case LibFunc_ceill:
7824         if (visitUnaryFloatCall(I, ISD::FCEIL))
7825           return;
7826         break;
7827       case LibFunc_rint:
7828       case LibFunc_rintf:
7829       case LibFunc_rintl:
7830         if (visitUnaryFloatCall(I, ISD::FRINT))
7831           return;
7832         break;
7833       case LibFunc_round:
7834       case LibFunc_roundf:
7835       case LibFunc_roundl:
7836         if (visitUnaryFloatCall(I, ISD::FROUND))
7837           return;
7838         break;
7839       case LibFunc_trunc:
7840       case LibFunc_truncf:
7841       case LibFunc_truncl:
7842         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7843           return;
7844         break;
7845       case LibFunc_log2:
7846       case LibFunc_log2f:
7847       case LibFunc_log2l:
7848         if (visitUnaryFloatCall(I, ISD::FLOG2))
7849           return;
7850         break;
7851       case LibFunc_exp2:
7852       case LibFunc_exp2f:
7853       case LibFunc_exp2l:
7854         if (visitUnaryFloatCall(I, ISD::FEXP2))
7855           return;
7856         break;
7857       case LibFunc_memcmp:
7858         if (visitMemCmpBCmpCall(I))
7859           return;
7860         break;
7861       case LibFunc_mempcpy:
7862         if (visitMemPCpyCall(I))
7863           return;
7864         break;
7865       case LibFunc_memchr:
7866         if (visitMemChrCall(I))
7867           return;
7868         break;
7869       case LibFunc_strcpy:
7870         if (visitStrCpyCall(I, false))
7871           return;
7872         break;
7873       case LibFunc_stpcpy:
7874         if (visitStrCpyCall(I, true))
7875           return;
7876         break;
7877       case LibFunc_strcmp:
7878         if (visitStrCmpCall(I))
7879           return;
7880         break;
7881       case LibFunc_strlen:
7882         if (visitStrLenCall(I))
7883           return;
7884         break;
7885       case LibFunc_strnlen:
7886         if (visitStrNLenCall(I))
7887           return;
7888         break;
7889       }
7890     }
7891   }
7892 
7893   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7894   // have to do anything here to lower funclet bundles.
7895   // CFGuardTarget bundles are lowered in LowerCallTo.
7896   assert(!I.hasOperandBundlesOtherThan(
7897              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7898               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
7899               LLVMContext::OB_clang_arc_attachedcall}) &&
7900          "Cannot lower calls with arbitrary operand bundles!");
7901 
7902   SDValue Callee = getValue(I.getCalledOperand());
7903 
7904   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7905     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7906   else
7907     // Check if we can potentially perform a tail call. More detailed checking
7908     // is be done within LowerCallTo, after more information about the call is
7909     // known.
7910     LowerCallTo(I, Callee, I.isTailCall());
7911 }
7912 
7913 namespace {
7914 
7915 /// AsmOperandInfo - This contains information for each constraint that we are
7916 /// lowering.
7917 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7918 public:
7919   /// CallOperand - If this is the result output operand or a clobber
7920   /// this is null, otherwise it is the incoming operand to the CallInst.
7921   /// This gets modified as the asm is processed.
7922   SDValue CallOperand;
7923 
7924   /// AssignedRegs - If this is a register or register class operand, this
7925   /// contains the set of register corresponding to the operand.
7926   RegsForValue AssignedRegs;
7927 
7928   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7929     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7930   }
7931 
7932   /// Whether or not this operand accesses memory
7933   bool hasMemory(const TargetLowering &TLI) const {
7934     // Indirect operand accesses access memory.
7935     if (isIndirect)
7936       return true;
7937 
7938     for (const auto &Code : Codes)
7939       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7940         return true;
7941 
7942     return false;
7943   }
7944 
7945   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7946   /// corresponds to.  If there is no Value* for this operand, it returns
7947   /// MVT::Other.
7948   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7949                            const DataLayout &DL) const {
7950     if (!CallOperandVal) return MVT::Other;
7951 
7952     if (isa<BasicBlock>(CallOperandVal))
7953       return TLI.getProgramPointerTy(DL);
7954 
7955     llvm::Type *OpTy = CallOperandVal->getType();
7956 
7957     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7958     // If this is an indirect operand, the operand is a pointer to the
7959     // accessed type.
7960     if (isIndirect) {
7961       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7962       if (!PtrTy)
7963         report_fatal_error("Indirect operand for inline asm not a pointer!");
7964       OpTy = PtrTy->getElementType();
7965     }
7966 
7967     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7968     if (StructType *STy = dyn_cast<StructType>(OpTy))
7969       if (STy->getNumElements() == 1)
7970         OpTy = STy->getElementType(0);
7971 
7972     // If OpTy is not a single value, it may be a struct/union that we
7973     // can tile with integers.
7974     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7975       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7976       switch (BitSize) {
7977       default: break;
7978       case 1:
7979       case 8:
7980       case 16:
7981       case 32:
7982       case 64:
7983       case 128:
7984         OpTy = IntegerType::get(Context, BitSize);
7985         break;
7986       }
7987     }
7988 
7989     return TLI.getValueType(DL, OpTy, true);
7990   }
7991 };
7992 
7993 
7994 } // end anonymous namespace
7995 
7996 /// Make sure that the output operand \p OpInfo and its corresponding input
7997 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7998 /// out).
7999 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8000                                SDISelAsmOperandInfo &MatchingOpInfo,
8001                                SelectionDAG &DAG) {
8002   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8003     return;
8004 
8005   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8006   const auto &TLI = DAG.getTargetLoweringInfo();
8007 
8008   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8009       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8010                                        OpInfo.ConstraintVT);
8011   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8012       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8013                                        MatchingOpInfo.ConstraintVT);
8014   if ((OpInfo.ConstraintVT.isInteger() !=
8015        MatchingOpInfo.ConstraintVT.isInteger()) ||
8016       (MatchRC.second != InputRC.second)) {
8017     // FIXME: error out in a more elegant fashion
8018     report_fatal_error("Unsupported asm: input constraint"
8019                        " with a matching output constraint of"
8020                        " incompatible type!");
8021   }
8022   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8023 }
8024 
8025 /// Get a direct memory input to behave well as an indirect operand.
8026 /// This may introduce stores, hence the need for a \p Chain.
8027 /// \return The (possibly updated) chain.
8028 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8029                                         SDISelAsmOperandInfo &OpInfo,
8030                                         SelectionDAG &DAG) {
8031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8032 
8033   // If we don't have an indirect input, put it in the constpool if we can,
8034   // otherwise spill it to a stack slot.
8035   // TODO: This isn't quite right. We need to handle these according to
8036   // the addressing mode that the constraint wants. Also, this may take
8037   // an additional register for the computation and we don't want that
8038   // either.
8039 
8040   // If the operand is a float, integer, or vector constant, spill to a
8041   // constant pool entry to get its address.
8042   const Value *OpVal = OpInfo.CallOperandVal;
8043   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8044       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8045     OpInfo.CallOperand = DAG.getConstantPool(
8046         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8047     return Chain;
8048   }
8049 
8050   // Otherwise, create a stack slot and emit a store to it before the asm.
8051   Type *Ty = OpVal->getType();
8052   auto &DL = DAG.getDataLayout();
8053   uint64_t TySize = DL.getTypeAllocSize(Ty);
8054   MachineFunction &MF = DAG.getMachineFunction();
8055   int SSFI = MF.getFrameInfo().CreateStackObject(
8056       TySize, DL.getPrefTypeAlign(Ty), false);
8057   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8058   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8059                             MachinePointerInfo::getFixedStack(MF, SSFI),
8060                             TLI.getMemValueType(DL, Ty));
8061   OpInfo.CallOperand = StackSlot;
8062 
8063   return Chain;
8064 }
8065 
8066 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8067 /// specified operand.  We prefer to assign virtual registers, to allow the
8068 /// register allocator to handle the assignment process.  However, if the asm
8069 /// uses features that we can't model on machineinstrs, we have SDISel do the
8070 /// allocation.  This produces generally horrible, but correct, code.
8071 ///
8072 ///   OpInfo describes the operand
8073 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8074 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8075                                  SDISelAsmOperandInfo &OpInfo,
8076                                  SDISelAsmOperandInfo &RefOpInfo) {
8077   LLVMContext &Context = *DAG.getContext();
8078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8079 
8080   MachineFunction &MF = DAG.getMachineFunction();
8081   SmallVector<unsigned, 4> Regs;
8082   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8083 
8084   // No work to do for memory operations.
8085   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8086     return;
8087 
8088   // If this is a constraint for a single physreg, or a constraint for a
8089   // register class, find it.
8090   unsigned AssignedReg;
8091   const TargetRegisterClass *RC;
8092   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8093       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8094   // RC is unset only on failure. Return immediately.
8095   if (!RC)
8096     return;
8097 
8098   // Get the actual register value type.  This is important, because the user
8099   // may have asked for (e.g.) the AX register in i32 type.  We need to
8100   // remember that AX is actually i16 to get the right extension.
8101   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8102 
8103   if (OpInfo.ConstraintVT != MVT::Other) {
8104     // If this is an FP operand in an integer register (or visa versa), or more
8105     // generally if the operand value disagrees with the register class we plan
8106     // to stick it in, fix the operand type.
8107     //
8108     // If this is an input value, the bitcast to the new type is done now.
8109     // Bitcast for output value is done at the end of visitInlineAsm().
8110     if ((OpInfo.Type == InlineAsm::isOutput ||
8111          OpInfo.Type == InlineAsm::isInput) &&
8112         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8113       // Try to convert to the first EVT that the reg class contains.  If the
8114       // types are identical size, use a bitcast to convert (e.g. two differing
8115       // vector types).  Note: output bitcast is done at the end of
8116       // visitInlineAsm().
8117       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8118         // Exclude indirect inputs while they are unsupported because the code
8119         // to perform the load is missing and thus OpInfo.CallOperand still
8120         // refers to the input address rather than the pointed-to value.
8121         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8122           OpInfo.CallOperand =
8123               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8124         OpInfo.ConstraintVT = RegVT;
8125         // If the operand is an FP value and we want it in integer registers,
8126         // use the corresponding integer type. This turns an f64 value into
8127         // i64, which can be passed with two i32 values on a 32-bit machine.
8128       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8129         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8130         if (OpInfo.Type == InlineAsm::isInput)
8131           OpInfo.CallOperand =
8132               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8133         OpInfo.ConstraintVT = VT;
8134       }
8135     }
8136   }
8137 
8138   // No need to allocate a matching input constraint since the constraint it's
8139   // matching to has already been allocated.
8140   if (OpInfo.isMatchingInputConstraint())
8141     return;
8142 
8143   EVT ValueVT = OpInfo.ConstraintVT;
8144   if (OpInfo.ConstraintVT == MVT::Other)
8145     ValueVT = RegVT;
8146 
8147   // Initialize NumRegs.
8148   unsigned NumRegs = 1;
8149   if (OpInfo.ConstraintVT != MVT::Other)
8150     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8151 
8152   // If this is a constraint for a specific physical register, like {r17},
8153   // assign it now.
8154 
8155   // If this associated to a specific register, initialize iterator to correct
8156   // place. If virtual, make sure we have enough registers
8157 
8158   // Initialize iterator if necessary
8159   TargetRegisterClass::iterator I = RC->begin();
8160   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8161 
8162   // Do not check for single registers.
8163   if (AssignedReg) {
8164       for (; *I != AssignedReg; ++I)
8165         assert(I != RC->end() && "AssignedReg should be member of RC");
8166   }
8167 
8168   for (; NumRegs; --NumRegs, ++I) {
8169     assert(I != RC->end() && "Ran out of registers to allocate!");
8170     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8171     Regs.push_back(R);
8172   }
8173 
8174   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8175 }
8176 
8177 static unsigned
8178 findMatchingInlineAsmOperand(unsigned OperandNo,
8179                              const std::vector<SDValue> &AsmNodeOperands) {
8180   // Scan until we find the definition we already emitted of this operand.
8181   unsigned CurOp = InlineAsm::Op_FirstOperand;
8182   for (; OperandNo; --OperandNo) {
8183     // Advance to the next operand.
8184     unsigned OpFlag =
8185         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8186     assert((InlineAsm::isRegDefKind(OpFlag) ||
8187             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8188             InlineAsm::isMemKind(OpFlag)) &&
8189            "Skipped past definitions?");
8190     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8191   }
8192   return CurOp;
8193 }
8194 
8195 namespace {
8196 
8197 class ExtraFlags {
8198   unsigned Flags = 0;
8199 
8200 public:
8201   explicit ExtraFlags(const CallBase &Call) {
8202     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8203     if (IA->hasSideEffects())
8204       Flags |= InlineAsm::Extra_HasSideEffects;
8205     if (IA->isAlignStack())
8206       Flags |= InlineAsm::Extra_IsAlignStack;
8207     if (Call.isConvergent())
8208       Flags |= InlineAsm::Extra_IsConvergent;
8209     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8210   }
8211 
8212   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8213     // Ideally, we would only check against memory constraints.  However, the
8214     // meaning of an Other constraint can be target-specific and we can't easily
8215     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8216     // for Other constraints as well.
8217     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8218         OpInfo.ConstraintType == TargetLowering::C_Other) {
8219       if (OpInfo.Type == InlineAsm::isInput)
8220         Flags |= InlineAsm::Extra_MayLoad;
8221       else if (OpInfo.Type == InlineAsm::isOutput)
8222         Flags |= InlineAsm::Extra_MayStore;
8223       else if (OpInfo.Type == InlineAsm::isClobber)
8224         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8225     }
8226   }
8227 
8228   unsigned get() const { return Flags; }
8229 };
8230 
8231 } // end anonymous namespace
8232 
8233 /// visitInlineAsm - Handle a call to an InlineAsm object.
8234 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8235   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8236 
8237   /// ConstraintOperands - Information about all of the constraints.
8238   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8239 
8240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8241   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8242       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8243 
8244   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8245   // AsmDialect, MayLoad, MayStore).
8246   bool HasSideEffect = IA->hasSideEffects();
8247   ExtraFlags ExtraInfo(Call);
8248 
8249   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8250   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8251   unsigned NumMatchingOps = 0;
8252   for (auto &T : TargetConstraints) {
8253     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8254     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8255 
8256     // Compute the value type for each operand.
8257     if (OpInfo.Type == InlineAsm::isInput ||
8258         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8259       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8260 
8261       // Process the call argument. BasicBlocks are labels, currently appearing
8262       // only in asm's.
8263       if (isa<CallBrInst>(Call) &&
8264           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8265                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8266                         NumMatchingOps) &&
8267           (NumMatchingOps == 0 ||
8268            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8269                         NumMatchingOps))) {
8270         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8271         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8272         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8273       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8274         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8275       } else {
8276         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8277       }
8278 
8279       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8280                                            DAG.getDataLayout());
8281       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8282     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8283       // The return value of the call is this value.  As such, there is no
8284       // corresponding argument.
8285       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8286       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8287         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8288             DAG.getDataLayout(), STy->getElementType(ResNo));
8289       } else {
8290         assert(ResNo == 0 && "Asm only has one result!");
8291         OpInfo.ConstraintVT =
8292             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8293       }
8294       ++ResNo;
8295     } else {
8296       OpInfo.ConstraintVT = MVT::Other;
8297     }
8298 
8299     if (OpInfo.hasMatchingInput())
8300       ++NumMatchingOps;
8301 
8302     if (!HasSideEffect)
8303       HasSideEffect = OpInfo.hasMemory(TLI);
8304 
8305     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8306     // FIXME: Could we compute this on OpInfo rather than T?
8307 
8308     // Compute the constraint code and ConstraintType to use.
8309     TLI.ComputeConstraintToUse(T, SDValue());
8310 
8311     if (T.ConstraintType == TargetLowering::C_Immediate &&
8312         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8313       // We've delayed emitting a diagnostic like the "n" constraint because
8314       // inlining could cause an integer showing up.
8315       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8316                                           "' expects an integer constant "
8317                                           "expression");
8318 
8319     ExtraInfo.update(T);
8320   }
8321 
8322 
8323   // We won't need to flush pending loads if this asm doesn't touch
8324   // memory and is nonvolatile.
8325   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8326 
8327   bool IsCallBr = isa<CallBrInst>(Call);
8328   if (IsCallBr) {
8329     // If this is a callbr we need to flush pending exports since inlineasm_br
8330     // is a terminator. We need to do this before nodes are glued to
8331     // the inlineasm_br node.
8332     Chain = getControlRoot();
8333   }
8334 
8335   // Second pass over the constraints: compute which constraint option to use.
8336   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8337     // If this is an output operand with a matching input operand, look up the
8338     // matching input. If their types mismatch, e.g. one is an integer, the
8339     // other is floating point, or their sizes are different, flag it as an
8340     // error.
8341     if (OpInfo.hasMatchingInput()) {
8342       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8343       patchMatchingInput(OpInfo, Input, DAG);
8344     }
8345 
8346     // Compute the constraint code and ConstraintType to use.
8347     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8348 
8349     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8350         OpInfo.Type == InlineAsm::isClobber)
8351       continue;
8352 
8353     // If this is a memory input, and if the operand is not indirect, do what we
8354     // need to provide an address for the memory input.
8355     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8356         !OpInfo.isIndirect) {
8357       assert((OpInfo.isMultipleAlternative ||
8358               (OpInfo.Type == InlineAsm::isInput)) &&
8359              "Can only indirectify direct input operands!");
8360 
8361       // Memory operands really want the address of the value.
8362       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8363 
8364       // There is no longer a Value* corresponding to this operand.
8365       OpInfo.CallOperandVal = nullptr;
8366 
8367       // It is now an indirect operand.
8368       OpInfo.isIndirect = true;
8369     }
8370 
8371   }
8372 
8373   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8374   std::vector<SDValue> AsmNodeOperands;
8375   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8376   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8377       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8378 
8379   // If we have a !srcloc metadata node associated with it, we want to attach
8380   // this to the ultimately generated inline asm machineinstr.  To do this, we
8381   // pass in the third operand as this (potentially null) inline asm MDNode.
8382   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8383   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8384 
8385   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8386   // bits as operand 3.
8387   AsmNodeOperands.push_back(DAG.getTargetConstant(
8388       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8389 
8390   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8391   // this, assign virtual and physical registers for inputs and otput.
8392   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8393     // Assign Registers.
8394     SDISelAsmOperandInfo &RefOpInfo =
8395         OpInfo.isMatchingInputConstraint()
8396             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8397             : OpInfo;
8398     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8399 
8400     auto DetectWriteToReservedRegister = [&]() {
8401       const MachineFunction &MF = DAG.getMachineFunction();
8402       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8403       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8404         if (Register::isPhysicalRegister(Reg) &&
8405             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8406           const char *RegName = TRI.getName(Reg);
8407           emitInlineAsmError(Call, "write to reserved register '" +
8408                                        Twine(RegName) + "'");
8409           return true;
8410         }
8411       }
8412       return false;
8413     };
8414 
8415     switch (OpInfo.Type) {
8416     case InlineAsm::isOutput:
8417       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8418         unsigned ConstraintID =
8419             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8420         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8421                "Failed to convert memory constraint code to constraint id.");
8422 
8423         // Add information to the INLINEASM node to know about this output.
8424         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8425         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8426         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8427                                                         MVT::i32));
8428         AsmNodeOperands.push_back(OpInfo.CallOperand);
8429       } else {
8430         // Otherwise, this outputs to a register (directly for C_Register /
8431         // C_RegisterClass, and a target-defined fashion for
8432         // C_Immediate/C_Other). Find a register that we can use.
8433         if (OpInfo.AssignedRegs.Regs.empty()) {
8434           emitInlineAsmError(
8435               Call, "couldn't allocate output register for constraint '" +
8436                         Twine(OpInfo.ConstraintCode) + "'");
8437           return;
8438         }
8439 
8440         if (DetectWriteToReservedRegister())
8441           return;
8442 
8443         // Add information to the INLINEASM node to know that this register is
8444         // set.
8445         OpInfo.AssignedRegs.AddInlineAsmOperands(
8446             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8447                                   : InlineAsm::Kind_RegDef,
8448             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8449       }
8450       break;
8451 
8452     case InlineAsm::isInput: {
8453       SDValue InOperandVal = OpInfo.CallOperand;
8454 
8455       if (OpInfo.isMatchingInputConstraint()) {
8456         // If this is required to match an output register we have already set,
8457         // just use its register.
8458         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8459                                                   AsmNodeOperands);
8460         unsigned OpFlag =
8461           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8462         if (InlineAsm::isRegDefKind(OpFlag) ||
8463             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8464           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8465           if (OpInfo.isIndirect) {
8466             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8467             emitInlineAsmError(Call, "inline asm not supported yet: "
8468                                      "don't know how to handle tied "
8469                                      "indirect register inputs");
8470             return;
8471           }
8472 
8473           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8474           SmallVector<unsigned, 4> Regs;
8475 
8476           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8477             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8478             MachineRegisterInfo &RegInfo =
8479                 DAG.getMachineFunction().getRegInfo();
8480             for (unsigned i = 0; i != NumRegs; ++i)
8481               Regs.push_back(RegInfo.createVirtualRegister(RC));
8482           } else {
8483             emitInlineAsmError(Call,
8484                                "inline asm error: This value type register "
8485                                "class is not natively supported!");
8486             return;
8487           }
8488 
8489           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8490 
8491           SDLoc dl = getCurSDLoc();
8492           // Use the produced MatchedRegs object to
8493           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8494           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8495                                            true, OpInfo.getMatchedOperand(), dl,
8496                                            DAG, AsmNodeOperands);
8497           break;
8498         }
8499 
8500         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8501         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8502                "Unexpected number of operands");
8503         // Add information to the INLINEASM node to know about this input.
8504         // See InlineAsm.h isUseOperandTiedToDef.
8505         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8506         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8507                                                     OpInfo.getMatchedOperand());
8508         AsmNodeOperands.push_back(DAG.getTargetConstant(
8509             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8510         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8511         break;
8512       }
8513 
8514       // Treat indirect 'X' constraint as memory.
8515       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8516           OpInfo.isIndirect)
8517         OpInfo.ConstraintType = TargetLowering::C_Memory;
8518 
8519       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8520           OpInfo.ConstraintType == TargetLowering::C_Other) {
8521         std::vector<SDValue> Ops;
8522         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8523                                           Ops, DAG);
8524         if (Ops.empty()) {
8525           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8526             if (isa<ConstantSDNode>(InOperandVal)) {
8527               emitInlineAsmError(Call, "value out of range for constraint '" +
8528                                            Twine(OpInfo.ConstraintCode) + "'");
8529               return;
8530             }
8531 
8532           emitInlineAsmError(Call,
8533                              "invalid operand for inline asm constraint '" +
8534                                  Twine(OpInfo.ConstraintCode) + "'");
8535           return;
8536         }
8537 
8538         // Add information to the INLINEASM node to know about this input.
8539         unsigned ResOpType =
8540           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8541         AsmNodeOperands.push_back(DAG.getTargetConstant(
8542             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8543         llvm::append_range(AsmNodeOperands, Ops);
8544         break;
8545       }
8546 
8547       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8548         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8549         assert(InOperandVal.getValueType() ==
8550                    TLI.getPointerTy(DAG.getDataLayout()) &&
8551                "Memory operands expect pointer values");
8552 
8553         unsigned ConstraintID =
8554             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8555         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8556                "Failed to convert memory constraint code to constraint id.");
8557 
8558         // Add information to the INLINEASM node to know about this input.
8559         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8560         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8561         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8562                                                         getCurSDLoc(),
8563                                                         MVT::i32));
8564         AsmNodeOperands.push_back(InOperandVal);
8565         break;
8566       }
8567 
8568       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8569               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8570              "Unknown constraint type!");
8571 
8572       // TODO: Support this.
8573       if (OpInfo.isIndirect) {
8574         emitInlineAsmError(
8575             Call, "Don't know how to handle indirect register inputs yet "
8576                   "for constraint '" +
8577                       Twine(OpInfo.ConstraintCode) + "'");
8578         return;
8579       }
8580 
8581       // Copy the input into the appropriate registers.
8582       if (OpInfo.AssignedRegs.Regs.empty()) {
8583         emitInlineAsmError(Call,
8584                            "couldn't allocate input reg for constraint '" +
8585                                Twine(OpInfo.ConstraintCode) + "'");
8586         return;
8587       }
8588 
8589       if (DetectWriteToReservedRegister())
8590         return;
8591 
8592       SDLoc dl = getCurSDLoc();
8593 
8594       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8595                                         &Call);
8596 
8597       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8598                                                dl, DAG, AsmNodeOperands);
8599       break;
8600     }
8601     case InlineAsm::isClobber:
8602       // Add the clobbered value to the operand list, so that the register
8603       // allocator is aware that the physreg got clobbered.
8604       if (!OpInfo.AssignedRegs.Regs.empty())
8605         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8606                                                  false, 0, getCurSDLoc(), DAG,
8607                                                  AsmNodeOperands);
8608       break;
8609     }
8610   }
8611 
8612   // Finish up input operands.  Set the input chain and add the flag last.
8613   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8614   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8615 
8616   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8617   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8618                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8619   Flag = Chain.getValue(1);
8620 
8621   // Do additional work to generate outputs.
8622 
8623   SmallVector<EVT, 1> ResultVTs;
8624   SmallVector<SDValue, 1> ResultValues;
8625   SmallVector<SDValue, 8> OutChains;
8626 
8627   llvm::Type *CallResultType = Call.getType();
8628   ArrayRef<Type *> ResultTypes;
8629   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8630     ResultTypes = StructResult->elements();
8631   else if (!CallResultType->isVoidTy())
8632     ResultTypes = makeArrayRef(CallResultType);
8633 
8634   auto CurResultType = ResultTypes.begin();
8635   auto handleRegAssign = [&](SDValue V) {
8636     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8637     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8638     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8639     ++CurResultType;
8640     // If the type of the inline asm call site return value is different but has
8641     // same size as the type of the asm output bitcast it.  One example of this
8642     // is for vectors with different width / number of elements.  This can
8643     // happen for register classes that can contain multiple different value
8644     // types.  The preg or vreg allocated may not have the same VT as was
8645     // expected.
8646     //
8647     // This can also happen for a return value that disagrees with the register
8648     // class it is put in, eg. a double in a general-purpose register on a
8649     // 32-bit machine.
8650     if (ResultVT != V.getValueType() &&
8651         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8652       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8653     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8654              V.getValueType().isInteger()) {
8655       // If a result value was tied to an input value, the computed result
8656       // may have a wider width than the expected result.  Extract the
8657       // relevant portion.
8658       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8659     }
8660     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8661     ResultVTs.push_back(ResultVT);
8662     ResultValues.push_back(V);
8663   };
8664 
8665   // Deal with output operands.
8666   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8667     if (OpInfo.Type == InlineAsm::isOutput) {
8668       SDValue Val;
8669       // Skip trivial output operands.
8670       if (OpInfo.AssignedRegs.Regs.empty())
8671         continue;
8672 
8673       switch (OpInfo.ConstraintType) {
8674       case TargetLowering::C_Register:
8675       case TargetLowering::C_RegisterClass:
8676         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8677                                                   Chain, &Flag, &Call);
8678         break;
8679       case TargetLowering::C_Immediate:
8680       case TargetLowering::C_Other:
8681         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8682                                               OpInfo, DAG);
8683         break;
8684       case TargetLowering::C_Memory:
8685         break; // Already handled.
8686       case TargetLowering::C_Unknown:
8687         assert(false && "Unexpected unknown constraint");
8688       }
8689 
8690       // Indirect output manifest as stores. Record output chains.
8691       if (OpInfo.isIndirect) {
8692         const Value *Ptr = OpInfo.CallOperandVal;
8693         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8694         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8695                                      MachinePointerInfo(Ptr));
8696         OutChains.push_back(Store);
8697       } else {
8698         // generate CopyFromRegs to associated registers.
8699         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8700         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8701           for (const SDValue &V : Val->op_values())
8702             handleRegAssign(V);
8703         } else
8704           handleRegAssign(Val);
8705       }
8706     }
8707   }
8708 
8709   // Set results.
8710   if (!ResultValues.empty()) {
8711     assert(CurResultType == ResultTypes.end() &&
8712            "Mismatch in number of ResultTypes");
8713     assert(ResultValues.size() == ResultTypes.size() &&
8714            "Mismatch in number of output operands in asm result");
8715 
8716     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8717                             DAG.getVTList(ResultVTs), ResultValues);
8718     setValue(&Call, V);
8719   }
8720 
8721   // Collect store chains.
8722   if (!OutChains.empty())
8723     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8724 
8725   // Only Update Root if inline assembly has a memory effect.
8726   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8727     DAG.setRoot(Chain);
8728 }
8729 
8730 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8731                                              const Twine &Message) {
8732   LLVMContext &Ctx = *DAG.getContext();
8733   Ctx.emitError(&Call, Message);
8734 
8735   // Make sure we leave the DAG in a valid state
8736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8737   SmallVector<EVT, 1> ValueVTs;
8738   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8739 
8740   if (ValueVTs.empty())
8741     return;
8742 
8743   SmallVector<SDValue, 1> Ops;
8744   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8745     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8746 
8747   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8748 }
8749 
8750 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8751   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8752                           MVT::Other, getRoot(),
8753                           getValue(I.getArgOperand(0)),
8754                           DAG.getSrcValue(I.getArgOperand(0))));
8755 }
8756 
8757 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8759   const DataLayout &DL = DAG.getDataLayout();
8760   SDValue V = DAG.getVAArg(
8761       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8762       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8763       DL.getABITypeAlign(I.getType()).value());
8764   DAG.setRoot(V.getValue(1));
8765 
8766   if (I.getType()->isPointerTy())
8767     V = DAG.getPtrExtOrTrunc(
8768         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8769   setValue(&I, V);
8770 }
8771 
8772 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8773   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8774                           MVT::Other, getRoot(),
8775                           getValue(I.getArgOperand(0)),
8776                           DAG.getSrcValue(I.getArgOperand(0))));
8777 }
8778 
8779 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8780   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8781                           MVT::Other, getRoot(),
8782                           getValue(I.getArgOperand(0)),
8783                           getValue(I.getArgOperand(1)),
8784                           DAG.getSrcValue(I.getArgOperand(0)),
8785                           DAG.getSrcValue(I.getArgOperand(1))));
8786 }
8787 
8788 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8789                                                     const Instruction &I,
8790                                                     SDValue Op) {
8791   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8792   if (!Range)
8793     return Op;
8794 
8795   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8796   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8797     return Op;
8798 
8799   APInt Lo = CR.getUnsignedMin();
8800   if (!Lo.isMinValue())
8801     return Op;
8802 
8803   APInt Hi = CR.getUnsignedMax();
8804   unsigned Bits = std::max(Hi.getActiveBits(),
8805                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8806 
8807   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8808 
8809   SDLoc SL = getCurSDLoc();
8810 
8811   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8812                              DAG.getValueType(SmallVT));
8813   unsigned NumVals = Op.getNode()->getNumValues();
8814   if (NumVals == 1)
8815     return ZExt;
8816 
8817   SmallVector<SDValue, 4> Ops;
8818 
8819   Ops.push_back(ZExt);
8820   for (unsigned I = 1; I != NumVals; ++I)
8821     Ops.push_back(Op.getValue(I));
8822 
8823   return DAG.getMergeValues(Ops, SL);
8824 }
8825 
8826 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8827 /// the call being lowered.
8828 ///
8829 /// This is a helper for lowering intrinsics that follow a target calling
8830 /// convention or require stack pointer adjustment. Only a subset of the
8831 /// intrinsic's operands need to participate in the calling convention.
8832 void SelectionDAGBuilder::populateCallLoweringInfo(
8833     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8834     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8835     bool IsPatchPoint) {
8836   TargetLowering::ArgListTy Args;
8837   Args.reserve(NumArgs);
8838 
8839   // Populate the argument list.
8840   // Attributes for args start at offset 1, after the return attribute.
8841   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8842        ArgI != ArgE; ++ArgI) {
8843     const Value *V = Call->getOperand(ArgI);
8844 
8845     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8846 
8847     TargetLowering::ArgListEntry Entry;
8848     Entry.Node = getValue(V);
8849     Entry.Ty = V->getType();
8850     Entry.setAttributes(Call, ArgI);
8851     Args.push_back(Entry);
8852   }
8853 
8854   CLI.setDebugLoc(getCurSDLoc())
8855       .setChain(getRoot())
8856       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8857       .setDiscardResult(Call->use_empty())
8858       .setIsPatchPoint(IsPatchPoint)
8859       .setIsPreallocated(
8860           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8861 }
8862 
8863 /// Add a stack map intrinsic call's live variable operands to a stackmap
8864 /// or patchpoint target node's operand list.
8865 ///
8866 /// Constants are converted to TargetConstants purely as an optimization to
8867 /// avoid constant materialization and register allocation.
8868 ///
8869 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8870 /// generate addess computation nodes, and so FinalizeISel can convert the
8871 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8872 /// address materialization and register allocation, but may also be required
8873 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8874 /// alloca in the entry block, then the runtime may assume that the alloca's
8875 /// StackMap location can be read immediately after compilation and that the
8876 /// location is valid at any point during execution (this is similar to the
8877 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8878 /// only available in a register, then the runtime would need to trap when
8879 /// execution reaches the StackMap in order to read the alloca's location.
8880 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8881                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8882                                 SelectionDAGBuilder &Builder) {
8883   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8884     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8886       Ops.push_back(
8887         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8888       Ops.push_back(
8889         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8890     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8891       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8892       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8893           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8894     } else
8895       Ops.push_back(OpVal);
8896   }
8897 }
8898 
8899 /// Lower llvm.experimental.stackmap directly to its target opcode.
8900 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8901   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8902   //                                  [live variables...])
8903 
8904   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8905 
8906   SDValue Chain, InFlag, Callee, NullPtr;
8907   SmallVector<SDValue, 32> Ops;
8908 
8909   SDLoc DL = getCurSDLoc();
8910   Callee = getValue(CI.getCalledOperand());
8911   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8912 
8913   // The stackmap intrinsic only records the live variables (the arguments
8914   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8915   // intrinsic, this won't be lowered to a function call. This means we don't
8916   // have to worry about calling conventions and target specific lowering code.
8917   // Instead we perform the call lowering right here.
8918   //
8919   // chain, flag = CALLSEQ_START(chain, 0, 0)
8920   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8921   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8922   //
8923   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8924   InFlag = Chain.getValue(1);
8925 
8926   // Add the <id> and <numBytes> constants.
8927   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8928   Ops.push_back(DAG.getTargetConstant(
8929                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8930   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8931   Ops.push_back(DAG.getTargetConstant(
8932                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8933                   MVT::i32));
8934 
8935   // Push live variables for the stack map.
8936   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8937 
8938   // We are not pushing any register mask info here on the operands list,
8939   // because the stackmap doesn't clobber anything.
8940 
8941   // Push the chain and the glue flag.
8942   Ops.push_back(Chain);
8943   Ops.push_back(InFlag);
8944 
8945   // Create the STACKMAP node.
8946   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8947   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8948   Chain = SDValue(SM, 0);
8949   InFlag = Chain.getValue(1);
8950 
8951   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8952 
8953   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8954 
8955   // Set the root to the target-lowered call chain.
8956   DAG.setRoot(Chain);
8957 
8958   // Inform the Frame Information that we have a stackmap in this function.
8959   FuncInfo.MF->getFrameInfo().setHasStackMap();
8960 }
8961 
8962 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8963 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8964                                           const BasicBlock *EHPadBB) {
8965   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8966   //                                                 i32 <numBytes>,
8967   //                                                 i8* <target>,
8968   //                                                 i32 <numArgs>,
8969   //                                                 [Args...],
8970   //                                                 [live variables...])
8971 
8972   CallingConv::ID CC = CB.getCallingConv();
8973   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8974   bool HasDef = !CB.getType()->isVoidTy();
8975   SDLoc dl = getCurSDLoc();
8976   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8977 
8978   // Handle immediate and symbolic callees.
8979   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8980     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8981                                    /*isTarget=*/true);
8982   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8983     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8984                                          SDLoc(SymbolicCallee),
8985                                          SymbolicCallee->getValueType(0));
8986 
8987   // Get the real number of arguments participating in the call <numArgs>
8988   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8989   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8990 
8991   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8992   // Intrinsics include all meta-operands up to but not including CC.
8993   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8994   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8995          "Not enough arguments provided to the patchpoint intrinsic");
8996 
8997   // For AnyRegCC the arguments are lowered later on manually.
8998   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8999   Type *ReturnTy =
9000       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9001 
9002   TargetLowering::CallLoweringInfo CLI(DAG);
9003   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9004                            ReturnTy, true);
9005   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9006 
9007   SDNode *CallEnd = Result.second.getNode();
9008   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9009     CallEnd = CallEnd->getOperand(0).getNode();
9010 
9011   /// Get a call instruction from the call sequence chain.
9012   /// Tail calls are not allowed.
9013   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9014          "Expected a callseq node.");
9015   SDNode *Call = CallEnd->getOperand(0).getNode();
9016   bool HasGlue = Call->getGluedNode();
9017 
9018   // Replace the target specific call node with the patchable intrinsic.
9019   SmallVector<SDValue, 8> Ops;
9020 
9021   // Add the <id> and <numBytes> constants.
9022   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9023   Ops.push_back(DAG.getTargetConstant(
9024                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9025   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9026   Ops.push_back(DAG.getTargetConstant(
9027                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9028                   MVT::i32));
9029 
9030   // Add the callee.
9031   Ops.push_back(Callee);
9032 
9033   // Adjust <numArgs> to account for any arguments that have been passed on the
9034   // stack instead.
9035   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9036   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9037   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9038   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9039 
9040   // Add the calling convention
9041   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9042 
9043   // Add the arguments we omitted previously. The register allocator should
9044   // place these in any free register.
9045   if (IsAnyRegCC)
9046     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9047       Ops.push_back(getValue(CB.getArgOperand(i)));
9048 
9049   // Push the arguments from the call instruction up to the register mask.
9050   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9051   Ops.append(Call->op_begin() + 2, e);
9052 
9053   // Push live variables for the stack map.
9054   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9055 
9056   // Push the register mask info.
9057   if (HasGlue)
9058     Ops.push_back(*(Call->op_end()-2));
9059   else
9060     Ops.push_back(*(Call->op_end()-1));
9061 
9062   // Push the chain (this is originally the first operand of the call, but
9063   // becomes now the last or second to last operand).
9064   Ops.push_back(*(Call->op_begin()));
9065 
9066   // Push the glue flag (last operand).
9067   if (HasGlue)
9068     Ops.push_back(*(Call->op_end()-1));
9069 
9070   SDVTList NodeTys;
9071   if (IsAnyRegCC && HasDef) {
9072     // Create the return types based on the intrinsic definition
9073     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9074     SmallVector<EVT, 3> ValueVTs;
9075     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9076     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9077 
9078     // There is always a chain and a glue type at the end
9079     ValueVTs.push_back(MVT::Other);
9080     ValueVTs.push_back(MVT::Glue);
9081     NodeTys = DAG.getVTList(ValueVTs);
9082   } else
9083     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9084 
9085   // Replace the target specific call node with a PATCHPOINT node.
9086   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9087                                          dl, NodeTys, Ops);
9088 
9089   // Update the NodeMap.
9090   if (HasDef) {
9091     if (IsAnyRegCC)
9092       setValue(&CB, SDValue(MN, 0));
9093     else
9094       setValue(&CB, Result.first);
9095   }
9096 
9097   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9098   // call sequence. Furthermore the location of the chain and glue can change
9099   // when the AnyReg calling convention is used and the intrinsic returns a
9100   // value.
9101   if (IsAnyRegCC && HasDef) {
9102     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9103     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9104     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9105   } else
9106     DAG.ReplaceAllUsesWith(Call, MN);
9107   DAG.DeleteNode(Call);
9108 
9109   // Inform the Frame Information that we have a patchpoint in this function.
9110   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9111 }
9112 
9113 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9114                                             unsigned Intrinsic) {
9115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9116   SDValue Op1 = getValue(I.getArgOperand(0));
9117   SDValue Op2;
9118   if (I.getNumArgOperands() > 1)
9119     Op2 = getValue(I.getArgOperand(1));
9120   SDLoc dl = getCurSDLoc();
9121   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9122   SDValue Res;
9123   SDNodeFlags SDFlags;
9124   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9125     SDFlags.copyFMF(*FPMO);
9126 
9127   switch (Intrinsic) {
9128   case Intrinsic::vector_reduce_fadd:
9129     if (SDFlags.hasAllowReassociation())
9130       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9131                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9132                         SDFlags);
9133     else
9134       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9135     break;
9136   case Intrinsic::vector_reduce_fmul:
9137     if (SDFlags.hasAllowReassociation())
9138       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9139                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9140                         SDFlags);
9141     else
9142       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9143     break;
9144   case Intrinsic::vector_reduce_add:
9145     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9146     break;
9147   case Intrinsic::vector_reduce_mul:
9148     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9149     break;
9150   case Intrinsic::vector_reduce_and:
9151     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9152     break;
9153   case Intrinsic::vector_reduce_or:
9154     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9155     break;
9156   case Intrinsic::vector_reduce_xor:
9157     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9158     break;
9159   case Intrinsic::vector_reduce_smax:
9160     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9161     break;
9162   case Intrinsic::vector_reduce_smin:
9163     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9164     break;
9165   case Intrinsic::vector_reduce_umax:
9166     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9167     break;
9168   case Intrinsic::vector_reduce_umin:
9169     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9170     break;
9171   case Intrinsic::vector_reduce_fmax:
9172     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9173     break;
9174   case Intrinsic::vector_reduce_fmin:
9175     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9176     break;
9177   default:
9178     llvm_unreachable("Unhandled vector reduce intrinsic");
9179   }
9180   setValue(&I, Res);
9181 }
9182 
9183 /// Returns an AttributeList representing the attributes applied to the return
9184 /// value of the given call.
9185 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9186   SmallVector<Attribute::AttrKind, 2> Attrs;
9187   if (CLI.RetSExt)
9188     Attrs.push_back(Attribute::SExt);
9189   if (CLI.RetZExt)
9190     Attrs.push_back(Attribute::ZExt);
9191   if (CLI.IsInReg)
9192     Attrs.push_back(Attribute::InReg);
9193 
9194   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9195                             Attrs);
9196 }
9197 
9198 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9199 /// implementation, which just calls LowerCall.
9200 /// FIXME: When all targets are
9201 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9202 std::pair<SDValue, SDValue>
9203 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9204   // Handle the incoming return values from the call.
9205   CLI.Ins.clear();
9206   Type *OrigRetTy = CLI.RetTy;
9207   SmallVector<EVT, 4> RetTys;
9208   SmallVector<uint64_t, 4> Offsets;
9209   auto &DL = CLI.DAG.getDataLayout();
9210   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9211 
9212   if (CLI.IsPostTypeLegalization) {
9213     // If we are lowering a libcall after legalization, split the return type.
9214     SmallVector<EVT, 4> OldRetTys;
9215     SmallVector<uint64_t, 4> OldOffsets;
9216     RetTys.swap(OldRetTys);
9217     Offsets.swap(OldOffsets);
9218 
9219     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9220       EVT RetVT = OldRetTys[i];
9221       uint64_t Offset = OldOffsets[i];
9222       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9223       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9224       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9225       RetTys.append(NumRegs, RegisterVT);
9226       for (unsigned j = 0; j != NumRegs; ++j)
9227         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9228     }
9229   }
9230 
9231   SmallVector<ISD::OutputArg, 4> Outs;
9232   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9233 
9234   bool CanLowerReturn =
9235       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9236                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9237 
9238   SDValue DemoteStackSlot;
9239   int DemoteStackIdx = -100;
9240   if (!CanLowerReturn) {
9241     // FIXME: equivalent assert?
9242     // assert(!CS.hasInAllocaArgument() &&
9243     //        "sret demotion is incompatible with inalloca");
9244     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9245     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9246     MachineFunction &MF = CLI.DAG.getMachineFunction();
9247     DemoteStackIdx =
9248         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9249     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9250                                               DL.getAllocaAddrSpace());
9251 
9252     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9253     ArgListEntry Entry;
9254     Entry.Node = DemoteStackSlot;
9255     Entry.Ty = StackSlotPtrType;
9256     Entry.IsSExt = false;
9257     Entry.IsZExt = false;
9258     Entry.IsInReg = false;
9259     Entry.IsSRet = true;
9260     Entry.IsNest = false;
9261     Entry.IsByVal = false;
9262     Entry.IsByRef = false;
9263     Entry.IsReturned = false;
9264     Entry.IsSwiftSelf = false;
9265     Entry.IsSwiftError = false;
9266     Entry.IsCFGuardTarget = false;
9267     Entry.Alignment = Alignment;
9268     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9269     CLI.NumFixedArgs += 1;
9270     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9271 
9272     // sret demotion isn't compatible with tail-calls, since the sret argument
9273     // points into the callers stack frame.
9274     CLI.IsTailCall = false;
9275   } else {
9276     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9277         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9278     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9279       ISD::ArgFlagsTy Flags;
9280       if (NeedsRegBlock) {
9281         Flags.setInConsecutiveRegs();
9282         if (I == RetTys.size() - 1)
9283           Flags.setInConsecutiveRegsLast();
9284       }
9285       EVT VT = RetTys[I];
9286       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9287                                                      CLI.CallConv, VT);
9288       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9289                                                        CLI.CallConv, VT);
9290       for (unsigned i = 0; i != NumRegs; ++i) {
9291         ISD::InputArg MyFlags;
9292         MyFlags.Flags = Flags;
9293         MyFlags.VT = RegisterVT;
9294         MyFlags.ArgVT = VT;
9295         MyFlags.Used = CLI.IsReturnValueUsed;
9296         if (CLI.RetTy->isPointerTy()) {
9297           MyFlags.Flags.setPointer();
9298           MyFlags.Flags.setPointerAddrSpace(
9299               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9300         }
9301         if (CLI.RetSExt)
9302           MyFlags.Flags.setSExt();
9303         if (CLI.RetZExt)
9304           MyFlags.Flags.setZExt();
9305         if (CLI.IsInReg)
9306           MyFlags.Flags.setInReg();
9307         CLI.Ins.push_back(MyFlags);
9308       }
9309     }
9310   }
9311 
9312   // We push in swifterror return as the last element of CLI.Ins.
9313   ArgListTy &Args = CLI.getArgs();
9314   if (supportSwiftError()) {
9315     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9316       if (Args[i].IsSwiftError) {
9317         ISD::InputArg MyFlags;
9318         MyFlags.VT = getPointerTy(DL);
9319         MyFlags.ArgVT = EVT(getPointerTy(DL));
9320         MyFlags.Flags.setSwiftError();
9321         CLI.Ins.push_back(MyFlags);
9322       }
9323     }
9324   }
9325 
9326   // Handle all of the outgoing arguments.
9327   CLI.Outs.clear();
9328   CLI.OutVals.clear();
9329   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9330     SmallVector<EVT, 4> ValueVTs;
9331     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9332     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9333     Type *FinalType = Args[i].Ty;
9334     if (Args[i].IsByVal)
9335       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9336     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9337         FinalType, CLI.CallConv, CLI.IsVarArg);
9338     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9339          ++Value) {
9340       EVT VT = ValueVTs[Value];
9341       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9342       SDValue Op = SDValue(Args[i].Node.getNode(),
9343                            Args[i].Node.getResNo() + Value);
9344       ISD::ArgFlagsTy Flags;
9345 
9346       // Certain targets (such as MIPS), may have a different ABI alignment
9347       // for a type depending on the context. Give the target a chance to
9348       // specify the alignment it wants.
9349       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9350 
9351       if (Args[i].Ty->isPointerTy()) {
9352         Flags.setPointer();
9353         Flags.setPointerAddrSpace(
9354             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9355       }
9356       if (Args[i].IsZExt)
9357         Flags.setZExt();
9358       if (Args[i].IsSExt)
9359         Flags.setSExt();
9360       if (Args[i].IsInReg) {
9361         // If we are using vectorcall calling convention, a structure that is
9362         // passed InReg - is surely an HVA
9363         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9364             isa<StructType>(FinalType)) {
9365           // The first value of a structure is marked
9366           if (0 == Value)
9367             Flags.setHvaStart();
9368           Flags.setHva();
9369         }
9370         // Set InReg Flag
9371         Flags.setInReg();
9372       }
9373       if (Args[i].IsSRet)
9374         Flags.setSRet();
9375       if (Args[i].IsSwiftSelf)
9376         Flags.setSwiftSelf();
9377       if (Args[i].IsSwiftError)
9378         Flags.setSwiftError();
9379       if (Args[i].IsCFGuardTarget)
9380         Flags.setCFGuardTarget();
9381       if (Args[i].IsByVal)
9382         Flags.setByVal();
9383       if (Args[i].IsByRef)
9384         Flags.setByRef();
9385       if (Args[i].IsPreallocated) {
9386         Flags.setPreallocated();
9387         // Set the byval flag for CCAssignFn callbacks that don't know about
9388         // preallocated.  This way we can know how many bytes we should've
9389         // allocated and how many bytes a callee cleanup function will pop.  If
9390         // we port preallocated to more targets, we'll have to add custom
9391         // preallocated handling in the various CC lowering callbacks.
9392         Flags.setByVal();
9393       }
9394       if (Args[i].IsInAlloca) {
9395         Flags.setInAlloca();
9396         // Set the byval flag for CCAssignFn callbacks that don't know about
9397         // inalloca.  This way we can know how many bytes we should've allocated
9398         // and how many bytes a callee cleanup function will pop.  If we port
9399         // inalloca to more targets, we'll have to add custom inalloca handling
9400         // in the various CC lowering callbacks.
9401         Flags.setByVal();
9402       }
9403       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9404         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9405         Type *ElementTy = Ty->getElementType();
9406 
9407         unsigned FrameSize = DL.getTypeAllocSize(
9408             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9409         Flags.setByValSize(FrameSize);
9410 
9411         // info is not there but there are cases it cannot get right.
9412         Align FrameAlign;
9413         if (auto MA = Args[i].Alignment)
9414           FrameAlign = *MA;
9415         else
9416           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9417         Flags.setByValAlign(FrameAlign);
9418       }
9419       if (Args[i].IsNest)
9420         Flags.setNest();
9421       if (NeedsRegBlock)
9422         Flags.setInConsecutiveRegs();
9423       Flags.setOrigAlign(OriginalAlignment);
9424 
9425       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9426                                                  CLI.CallConv, VT);
9427       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9428                                                         CLI.CallConv, VT);
9429       SmallVector<SDValue, 4> Parts(NumParts);
9430       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9431 
9432       if (Args[i].IsSExt)
9433         ExtendKind = ISD::SIGN_EXTEND;
9434       else if (Args[i].IsZExt)
9435         ExtendKind = ISD::ZERO_EXTEND;
9436 
9437       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9438       // for now.
9439       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9440           CanLowerReturn) {
9441         assert((CLI.RetTy == Args[i].Ty ||
9442                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9443                  CLI.RetTy->getPointerAddressSpace() ==
9444                      Args[i].Ty->getPointerAddressSpace())) &&
9445                RetTys.size() == NumValues && "unexpected use of 'returned'");
9446         // Before passing 'returned' to the target lowering code, ensure that
9447         // either the register MVT and the actual EVT are the same size or that
9448         // the return value and argument are extended in the same way; in these
9449         // cases it's safe to pass the argument register value unchanged as the
9450         // return register value (although it's at the target's option whether
9451         // to do so)
9452         // TODO: allow code generation to take advantage of partially preserved
9453         // registers rather than clobbering the entire register when the
9454         // parameter extension method is not compatible with the return
9455         // extension method
9456         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9457             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9458              CLI.RetZExt == Args[i].IsZExt))
9459           Flags.setReturned();
9460       }
9461 
9462       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9463                      CLI.CallConv, ExtendKind);
9464 
9465       for (unsigned j = 0; j != NumParts; ++j) {
9466         // if it isn't first piece, alignment must be 1
9467         // For scalable vectors the scalable part is currently handled
9468         // by individual targets, so we just use the known minimum size here.
9469         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9470                     i < CLI.NumFixedArgs, i,
9471                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9472         if (NumParts > 1 && j == 0)
9473           MyFlags.Flags.setSplit();
9474         else if (j != 0) {
9475           MyFlags.Flags.setOrigAlign(Align(1));
9476           if (j == NumParts - 1)
9477             MyFlags.Flags.setSplitEnd();
9478         }
9479 
9480         CLI.Outs.push_back(MyFlags);
9481         CLI.OutVals.push_back(Parts[j]);
9482       }
9483 
9484       if (NeedsRegBlock && Value == NumValues - 1)
9485         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9486     }
9487   }
9488 
9489   SmallVector<SDValue, 4> InVals;
9490   CLI.Chain = LowerCall(CLI, InVals);
9491 
9492   // Update CLI.InVals to use outside of this function.
9493   CLI.InVals = InVals;
9494 
9495   // Verify that the target's LowerCall behaved as expected.
9496   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9497          "LowerCall didn't return a valid chain!");
9498   assert((!CLI.IsTailCall || InVals.empty()) &&
9499          "LowerCall emitted a return value for a tail call!");
9500   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9501          "LowerCall didn't emit the correct number of values!");
9502 
9503   // For a tail call, the return value is merely live-out and there aren't
9504   // any nodes in the DAG representing it. Return a special value to
9505   // indicate that a tail call has been emitted and no more Instructions
9506   // should be processed in the current block.
9507   if (CLI.IsTailCall) {
9508     CLI.DAG.setRoot(CLI.Chain);
9509     return std::make_pair(SDValue(), SDValue());
9510   }
9511 
9512 #ifndef NDEBUG
9513   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9514     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9515     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9516            "LowerCall emitted a value with the wrong type!");
9517   }
9518 #endif
9519 
9520   SmallVector<SDValue, 4> ReturnValues;
9521   if (!CanLowerReturn) {
9522     // The instruction result is the result of loading from the
9523     // hidden sret parameter.
9524     SmallVector<EVT, 1> PVTs;
9525     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9526 
9527     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9528     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9529     EVT PtrVT = PVTs[0];
9530 
9531     unsigned NumValues = RetTys.size();
9532     ReturnValues.resize(NumValues);
9533     SmallVector<SDValue, 4> Chains(NumValues);
9534 
9535     // An aggregate return value cannot wrap around the address space, so
9536     // offsets to its parts don't wrap either.
9537     SDNodeFlags Flags;
9538     Flags.setNoUnsignedWrap(true);
9539 
9540     MachineFunction &MF = CLI.DAG.getMachineFunction();
9541     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9542     for (unsigned i = 0; i < NumValues; ++i) {
9543       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9544                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9545                                                         PtrVT), Flags);
9546       SDValue L = CLI.DAG.getLoad(
9547           RetTys[i], CLI.DL, CLI.Chain, Add,
9548           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9549                                             DemoteStackIdx, Offsets[i]),
9550           HiddenSRetAlign);
9551       ReturnValues[i] = L;
9552       Chains[i] = L.getValue(1);
9553     }
9554 
9555     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9556   } else {
9557     // Collect the legal value parts into potentially illegal values
9558     // that correspond to the original function's return values.
9559     Optional<ISD::NodeType> AssertOp;
9560     if (CLI.RetSExt)
9561       AssertOp = ISD::AssertSext;
9562     else if (CLI.RetZExt)
9563       AssertOp = ISD::AssertZext;
9564     unsigned CurReg = 0;
9565     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9566       EVT VT = RetTys[I];
9567       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9568                                                      CLI.CallConv, VT);
9569       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9570                                                        CLI.CallConv, VT);
9571 
9572       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9573                                               NumRegs, RegisterVT, VT, nullptr,
9574                                               CLI.CallConv, AssertOp));
9575       CurReg += NumRegs;
9576     }
9577 
9578     // For a function returning void, there is no return value. We can't create
9579     // such a node, so we just return a null return value in that case. In
9580     // that case, nothing will actually look at the value.
9581     if (ReturnValues.empty())
9582       return std::make_pair(SDValue(), CLI.Chain);
9583   }
9584 
9585   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9586                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9587   return std::make_pair(Res, CLI.Chain);
9588 }
9589 
9590 /// Places new result values for the node in Results (their number
9591 /// and types must exactly match those of the original return values of
9592 /// the node), or leaves Results empty, which indicates that the node is not
9593 /// to be custom lowered after all.
9594 void TargetLowering::LowerOperationWrapper(SDNode *N,
9595                                            SmallVectorImpl<SDValue> &Results,
9596                                            SelectionDAG &DAG) const {
9597   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9598 
9599   if (!Res.getNode())
9600     return;
9601 
9602   // If the original node has one result, take the return value from
9603   // LowerOperation as is. It might not be result number 0.
9604   if (N->getNumValues() == 1) {
9605     Results.push_back(Res);
9606     return;
9607   }
9608 
9609   // If the original node has multiple results, then the return node should
9610   // have the same number of results.
9611   assert((N->getNumValues() == Res->getNumValues()) &&
9612       "Lowering returned the wrong number of results!");
9613 
9614   // Places new result values base on N result number.
9615   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9616     Results.push_back(Res.getValue(I));
9617 }
9618 
9619 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9620   llvm_unreachable("LowerOperation not implemented for this target!");
9621 }
9622 
9623 void
9624 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9625   SDValue Op = getNonRegisterValue(V);
9626   assert((Op.getOpcode() != ISD::CopyFromReg ||
9627           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9628          "Copy from a reg to the same reg!");
9629   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9630 
9631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9632   // If this is an InlineAsm we have to match the registers required, not the
9633   // notional registers required by the type.
9634 
9635   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9636                    None); // This is not an ABI copy.
9637   SDValue Chain = DAG.getEntryNode();
9638 
9639   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9640                               FuncInfo.PreferredExtendType.end())
9641                                  ? ISD::ANY_EXTEND
9642                                  : FuncInfo.PreferredExtendType[V];
9643   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9644   PendingExports.push_back(Chain);
9645 }
9646 
9647 #include "llvm/CodeGen/SelectionDAGISel.h"
9648 
9649 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9650 /// entry block, return true.  This includes arguments used by switches, since
9651 /// the switch may expand into multiple basic blocks.
9652 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9653   // With FastISel active, we may be splitting blocks, so force creation
9654   // of virtual registers for all non-dead arguments.
9655   if (FastISel)
9656     return A->use_empty();
9657 
9658   const BasicBlock &Entry = A->getParent()->front();
9659   for (const User *U : A->users())
9660     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9661       return false;  // Use not in entry block.
9662 
9663   return true;
9664 }
9665 
9666 using ArgCopyElisionMapTy =
9667     DenseMap<const Argument *,
9668              std::pair<const AllocaInst *, const StoreInst *>>;
9669 
9670 /// Scan the entry block of the function in FuncInfo for arguments that look
9671 /// like copies into a local alloca. Record any copied arguments in
9672 /// ArgCopyElisionCandidates.
9673 static void
9674 findArgumentCopyElisionCandidates(const DataLayout &DL,
9675                                   FunctionLoweringInfo *FuncInfo,
9676                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9677   // Record the state of every static alloca used in the entry block. Argument
9678   // allocas are all used in the entry block, so we need approximately as many
9679   // entries as we have arguments.
9680   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9681   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9682   unsigned NumArgs = FuncInfo->Fn->arg_size();
9683   StaticAllocas.reserve(NumArgs * 2);
9684 
9685   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9686     if (!V)
9687       return nullptr;
9688     V = V->stripPointerCasts();
9689     const auto *AI = dyn_cast<AllocaInst>(V);
9690     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9691       return nullptr;
9692     auto Iter = StaticAllocas.insert({AI, Unknown});
9693     return &Iter.first->second;
9694   };
9695 
9696   // Look for stores of arguments to static allocas. Look through bitcasts and
9697   // GEPs to handle type coercions, as long as the alloca is fully initialized
9698   // by the store. Any non-store use of an alloca escapes it and any subsequent
9699   // unanalyzed store might write it.
9700   // FIXME: Handle structs initialized with multiple stores.
9701   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9702     // Look for stores, and handle non-store uses conservatively.
9703     const auto *SI = dyn_cast<StoreInst>(&I);
9704     if (!SI) {
9705       // We will look through cast uses, so ignore them completely.
9706       if (I.isCast())
9707         continue;
9708       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9709       // to allocas.
9710       if (I.isDebugOrPseudoInst())
9711         continue;
9712       // This is an unknown instruction. Assume it escapes or writes to all
9713       // static alloca operands.
9714       for (const Use &U : I.operands()) {
9715         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9716           *Info = StaticAllocaInfo::Clobbered;
9717       }
9718       continue;
9719     }
9720 
9721     // If the stored value is a static alloca, mark it as escaped.
9722     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9723       *Info = StaticAllocaInfo::Clobbered;
9724 
9725     // Check if the destination is a static alloca.
9726     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9727     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9728     if (!Info)
9729       continue;
9730     const AllocaInst *AI = cast<AllocaInst>(Dst);
9731 
9732     // Skip allocas that have been initialized or clobbered.
9733     if (*Info != StaticAllocaInfo::Unknown)
9734       continue;
9735 
9736     // Check if the stored value is an argument, and that this store fully
9737     // initializes the alloca. Don't elide copies from the same argument twice.
9738     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9739     const auto *Arg = dyn_cast<Argument>(Val);
9740     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9741         Arg->getType()->isEmptyTy() ||
9742         DL.getTypeStoreSize(Arg->getType()) !=
9743             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9744         ArgCopyElisionCandidates.count(Arg)) {
9745       *Info = StaticAllocaInfo::Clobbered;
9746       continue;
9747     }
9748 
9749     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9750                       << '\n');
9751 
9752     // Mark this alloca and store for argument copy elision.
9753     *Info = StaticAllocaInfo::Elidable;
9754     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9755 
9756     // Stop scanning if we've seen all arguments. This will happen early in -O0
9757     // builds, which is useful, because -O0 builds have large entry blocks and
9758     // many allocas.
9759     if (ArgCopyElisionCandidates.size() == NumArgs)
9760       break;
9761   }
9762 }
9763 
9764 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9765 /// ArgVal is a load from a suitable fixed stack object.
9766 static void tryToElideArgumentCopy(
9767     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9768     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9769     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9770     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9771     SDValue ArgVal, bool &ArgHasUses) {
9772   // Check if this is a load from a fixed stack object.
9773   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9774   if (!LNode)
9775     return;
9776   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9777   if (!FINode)
9778     return;
9779 
9780   // Check that the fixed stack object is the right size and alignment.
9781   // Look at the alignment that the user wrote on the alloca instead of looking
9782   // at the stack object.
9783   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9784   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9785   const AllocaInst *AI = ArgCopyIter->second.first;
9786   int FixedIndex = FINode->getIndex();
9787   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9788   int OldIndex = AllocaIndex;
9789   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9790   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9791     LLVM_DEBUG(
9792         dbgs() << "  argument copy elision failed due to bad fixed stack "
9793                   "object size\n");
9794     return;
9795   }
9796   Align RequiredAlignment = AI->getAlign();
9797   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9798     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9799                          "greater than stack argument alignment ("
9800                       << DebugStr(RequiredAlignment) << " vs "
9801                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9802     return;
9803   }
9804 
9805   // Perform the elision. Delete the old stack object and replace its only use
9806   // in the variable info map. Mark the stack object as mutable.
9807   LLVM_DEBUG({
9808     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9809            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9810            << '\n';
9811   });
9812   MFI.RemoveStackObject(OldIndex);
9813   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9814   AllocaIndex = FixedIndex;
9815   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9816   Chains.push_back(ArgVal.getValue(1));
9817 
9818   // Avoid emitting code for the store implementing the copy.
9819   const StoreInst *SI = ArgCopyIter->second.second;
9820   ElidedArgCopyInstrs.insert(SI);
9821 
9822   // Check for uses of the argument again so that we can avoid exporting ArgVal
9823   // if it is't used by anything other than the store.
9824   for (const Value *U : Arg.users()) {
9825     if (U != SI) {
9826       ArgHasUses = true;
9827       break;
9828     }
9829   }
9830 }
9831 
9832 void SelectionDAGISel::LowerArguments(const Function &F) {
9833   SelectionDAG &DAG = SDB->DAG;
9834   SDLoc dl = SDB->getCurSDLoc();
9835   const DataLayout &DL = DAG.getDataLayout();
9836   SmallVector<ISD::InputArg, 16> Ins;
9837 
9838   // In Naked functions we aren't going to save any registers.
9839   if (F.hasFnAttribute(Attribute::Naked))
9840     return;
9841 
9842   if (!FuncInfo->CanLowerReturn) {
9843     // Put in an sret pointer parameter before all the other parameters.
9844     SmallVector<EVT, 1> ValueVTs;
9845     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9846                     F.getReturnType()->getPointerTo(
9847                         DAG.getDataLayout().getAllocaAddrSpace()),
9848                     ValueVTs);
9849 
9850     // NOTE: Assuming that a pointer will never break down to more than one VT
9851     // or one register.
9852     ISD::ArgFlagsTy Flags;
9853     Flags.setSRet();
9854     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9855     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9856                          ISD::InputArg::NoArgIndex, 0);
9857     Ins.push_back(RetArg);
9858   }
9859 
9860   // Look for stores of arguments to static allocas. Mark such arguments with a
9861   // flag to ask the target to give us the memory location of that argument if
9862   // available.
9863   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9864   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9865                                     ArgCopyElisionCandidates);
9866 
9867   // Set up the incoming argument description vector.
9868   for (const Argument &Arg : F.args()) {
9869     unsigned ArgNo = Arg.getArgNo();
9870     SmallVector<EVT, 4> ValueVTs;
9871     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9872     bool isArgValueUsed = !Arg.use_empty();
9873     unsigned PartBase = 0;
9874     Type *FinalType = Arg.getType();
9875     if (Arg.hasAttribute(Attribute::ByVal))
9876       FinalType = Arg.getParamByValType();
9877     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9878         FinalType, F.getCallingConv(), F.isVarArg());
9879     for (unsigned Value = 0, NumValues = ValueVTs.size();
9880          Value != NumValues; ++Value) {
9881       EVT VT = ValueVTs[Value];
9882       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9883       ISD::ArgFlagsTy Flags;
9884 
9885       // Certain targets (such as MIPS), may have a different ABI alignment
9886       // for a type depending on the context. Give the target a chance to
9887       // specify the alignment it wants.
9888       const Align OriginalAlignment(
9889           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9890 
9891       if (Arg.getType()->isPointerTy()) {
9892         Flags.setPointer();
9893         Flags.setPointerAddrSpace(
9894             cast<PointerType>(Arg.getType())->getAddressSpace());
9895       }
9896       if (Arg.hasAttribute(Attribute::ZExt))
9897         Flags.setZExt();
9898       if (Arg.hasAttribute(Attribute::SExt))
9899         Flags.setSExt();
9900       if (Arg.hasAttribute(Attribute::InReg)) {
9901         // If we are using vectorcall calling convention, a structure that is
9902         // passed InReg - is surely an HVA
9903         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9904             isa<StructType>(Arg.getType())) {
9905           // The first value of a structure is marked
9906           if (0 == Value)
9907             Flags.setHvaStart();
9908           Flags.setHva();
9909         }
9910         // Set InReg Flag
9911         Flags.setInReg();
9912       }
9913       if (Arg.hasAttribute(Attribute::StructRet))
9914         Flags.setSRet();
9915       if (Arg.hasAttribute(Attribute::SwiftSelf))
9916         Flags.setSwiftSelf();
9917       if (Arg.hasAttribute(Attribute::SwiftError))
9918         Flags.setSwiftError();
9919       if (Arg.hasAttribute(Attribute::ByVal))
9920         Flags.setByVal();
9921       if (Arg.hasAttribute(Attribute::ByRef))
9922         Flags.setByRef();
9923       if (Arg.hasAttribute(Attribute::InAlloca)) {
9924         Flags.setInAlloca();
9925         // Set the byval flag for CCAssignFn callbacks that don't know about
9926         // inalloca.  This way we can know how many bytes we should've allocated
9927         // and how many bytes a callee cleanup function will pop.  If we port
9928         // inalloca to more targets, we'll have to add custom inalloca handling
9929         // in the various CC lowering callbacks.
9930         Flags.setByVal();
9931       }
9932       if (Arg.hasAttribute(Attribute::Preallocated)) {
9933         Flags.setPreallocated();
9934         // Set the byval flag for CCAssignFn callbacks that don't know about
9935         // preallocated.  This way we can know how many bytes we should've
9936         // allocated and how many bytes a callee cleanup function will pop.  If
9937         // we port preallocated to more targets, we'll have to add custom
9938         // preallocated handling in the various CC lowering callbacks.
9939         Flags.setByVal();
9940       }
9941 
9942       Type *ArgMemTy = nullptr;
9943       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
9944           Flags.isByRef()) {
9945         if (!ArgMemTy)
9946           ArgMemTy = Arg.getPointeeInMemoryValueType();
9947 
9948         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
9949 
9950         // For in-memory arguments, size and alignment should be passed from FE.
9951         // BE will guess if this info is not there but there are cases it cannot
9952         // get right.
9953         MaybeAlign MemAlign = Arg.getParamAlign();
9954         if (!MemAlign)
9955           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
9956 
9957         if (Flags.isByRef()) {
9958           Flags.setByRefSize(MemSize);
9959           Flags.setByRefAlign(*MemAlign);
9960         } else {
9961           Flags.setByValSize(MemSize);
9962           Flags.setByValAlign(*MemAlign);
9963         }
9964       }
9965 
9966       if (Arg.hasAttribute(Attribute::Nest))
9967         Flags.setNest();
9968       if (NeedsRegBlock)
9969         Flags.setInConsecutiveRegs();
9970       Flags.setOrigAlign(OriginalAlignment);
9971       if (ArgCopyElisionCandidates.count(&Arg))
9972         Flags.setCopyElisionCandidate();
9973       if (Arg.hasAttribute(Attribute::Returned))
9974         Flags.setReturned();
9975 
9976       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9977           *CurDAG->getContext(), F.getCallingConv(), VT);
9978       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9979           *CurDAG->getContext(), F.getCallingConv(), VT);
9980       for (unsigned i = 0; i != NumRegs; ++i) {
9981         // For scalable vectors, use the minimum size; individual targets
9982         // are responsible for handling scalable vector arguments and
9983         // return values.
9984         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9985                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9986         if (NumRegs > 1 && i == 0)
9987           MyFlags.Flags.setSplit();
9988         // if it isn't first piece, alignment must be 1
9989         else if (i > 0) {
9990           MyFlags.Flags.setOrigAlign(Align(1));
9991           if (i == NumRegs - 1)
9992             MyFlags.Flags.setSplitEnd();
9993         }
9994         Ins.push_back(MyFlags);
9995       }
9996       if (NeedsRegBlock && Value == NumValues - 1)
9997         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9998       PartBase += VT.getStoreSize().getKnownMinSize();
9999     }
10000   }
10001 
10002   // Call the target to set up the argument values.
10003   SmallVector<SDValue, 8> InVals;
10004   SDValue NewRoot = TLI->LowerFormalArguments(
10005       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10006 
10007   // Verify that the target's LowerFormalArguments behaved as expected.
10008   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10009          "LowerFormalArguments didn't return a valid chain!");
10010   assert(InVals.size() == Ins.size() &&
10011          "LowerFormalArguments didn't emit the correct number of values!");
10012   LLVM_DEBUG({
10013     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10014       assert(InVals[i].getNode() &&
10015              "LowerFormalArguments emitted a null value!");
10016       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10017              "LowerFormalArguments emitted a value with the wrong type!");
10018     }
10019   });
10020 
10021   // Update the DAG with the new chain value resulting from argument lowering.
10022   DAG.setRoot(NewRoot);
10023 
10024   // Set up the argument values.
10025   unsigned i = 0;
10026   if (!FuncInfo->CanLowerReturn) {
10027     // Create a virtual register for the sret pointer, and put in a copy
10028     // from the sret argument into it.
10029     SmallVector<EVT, 1> ValueVTs;
10030     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10031                     F.getReturnType()->getPointerTo(
10032                         DAG.getDataLayout().getAllocaAddrSpace()),
10033                     ValueVTs);
10034     MVT VT = ValueVTs[0].getSimpleVT();
10035     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10036     Optional<ISD::NodeType> AssertOp = None;
10037     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10038                                         nullptr, F.getCallingConv(), AssertOp);
10039 
10040     MachineFunction& MF = SDB->DAG.getMachineFunction();
10041     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10042     Register SRetReg =
10043         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10044     FuncInfo->DemoteRegister = SRetReg;
10045     NewRoot =
10046         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10047     DAG.setRoot(NewRoot);
10048 
10049     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10050     ++i;
10051   }
10052 
10053   SmallVector<SDValue, 4> Chains;
10054   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10055   for (const Argument &Arg : F.args()) {
10056     SmallVector<SDValue, 4> ArgValues;
10057     SmallVector<EVT, 4> ValueVTs;
10058     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10059     unsigned NumValues = ValueVTs.size();
10060     if (NumValues == 0)
10061       continue;
10062 
10063     bool ArgHasUses = !Arg.use_empty();
10064 
10065     // Elide the copying store if the target loaded this argument from a
10066     // suitable fixed stack object.
10067     if (Ins[i].Flags.isCopyElisionCandidate()) {
10068       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10069                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10070                              InVals[i], ArgHasUses);
10071     }
10072 
10073     // If this argument is unused then remember its value. It is used to generate
10074     // debugging information.
10075     bool isSwiftErrorArg =
10076         TLI->supportSwiftError() &&
10077         Arg.hasAttribute(Attribute::SwiftError);
10078     if (!ArgHasUses && !isSwiftErrorArg) {
10079       SDB->setUnusedArgValue(&Arg, InVals[i]);
10080 
10081       // Also remember any frame index for use in FastISel.
10082       if (FrameIndexSDNode *FI =
10083           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10084         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10085     }
10086 
10087     for (unsigned Val = 0; Val != NumValues; ++Val) {
10088       EVT VT = ValueVTs[Val];
10089       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10090                                                       F.getCallingConv(), VT);
10091       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10092           *CurDAG->getContext(), F.getCallingConv(), VT);
10093 
10094       // Even an apparent 'unused' swifterror argument needs to be returned. So
10095       // we do generate a copy for it that can be used on return from the
10096       // function.
10097       if (ArgHasUses || isSwiftErrorArg) {
10098         Optional<ISD::NodeType> AssertOp;
10099         if (Arg.hasAttribute(Attribute::SExt))
10100           AssertOp = ISD::AssertSext;
10101         else if (Arg.hasAttribute(Attribute::ZExt))
10102           AssertOp = ISD::AssertZext;
10103 
10104         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10105                                              PartVT, VT, nullptr,
10106                                              F.getCallingConv(), AssertOp));
10107       }
10108 
10109       i += NumParts;
10110     }
10111 
10112     // We don't need to do anything else for unused arguments.
10113     if (ArgValues.empty())
10114       continue;
10115 
10116     // Note down frame index.
10117     if (FrameIndexSDNode *FI =
10118         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10119       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10120 
10121     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10122                                      SDB->getCurSDLoc());
10123 
10124     SDB->setValue(&Arg, Res);
10125     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10126       // We want to associate the argument with the frame index, among
10127       // involved operands, that correspond to the lowest address. The
10128       // getCopyFromParts function, called earlier, is swapping the order of
10129       // the operands to BUILD_PAIR depending on endianness. The result of
10130       // that swapping is that the least significant bits of the argument will
10131       // be in the first operand of the BUILD_PAIR node, and the most
10132       // significant bits will be in the second operand.
10133       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10134       if (LoadSDNode *LNode =
10135           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10136         if (FrameIndexSDNode *FI =
10137             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10138           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10139     }
10140 
10141     // Analyses past this point are naive and don't expect an assertion.
10142     if (Res.getOpcode() == ISD::AssertZext)
10143       Res = Res.getOperand(0);
10144 
10145     // Update the SwiftErrorVRegDefMap.
10146     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10147       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10148       if (Register::isVirtualRegister(Reg))
10149         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10150                                    Reg);
10151     }
10152 
10153     // If this argument is live outside of the entry block, insert a copy from
10154     // wherever we got it to the vreg that other BB's will reference it as.
10155     if (Res.getOpcode() == ISD::CopyFromReg) {
10156       // If we can, though, try to skip creating an unnecessary vreg.
10157       // FIXME: This isn't very clean... it would be nice to make this more
10158       // general.
10159       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10160       if (Register::isVirtualRegister(Reg)) {
10161         FuncInfo->ValueMap[&Arg] = Reg;
10162         continue;
10163       }
10164     }
10165     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10166       FuncInfo->InitializeRegForValue(&Arg);
10167       SDB->CopyToExportRegsIfNeeded(&Arg);
10168     }
10169   }
10170 
10171   if (!Chains.empty()) {
10172     Chains.push_back(NewRoot);
10173     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10174   }
10175 
10176   DAG.setRoot(NewRoot);
10177 
10178   assert(i == InVals.size() && "Argument register count mismatch!");
10179 
10180   // If any argument copy elisions occurred and we have debug info, update the
10181   // stale frame indices used in the dbg.declare variable info table.
10182   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10183   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10184     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10185       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10186       if (I != ArgCopyElisionFrameIndexMap.end())
10187         VI.Slot = I->second;
10188     }
10189   }
10190 
10191   // Finally, if the target has anything special to do, allow it to do so.
10192   emitFunctionEntryCode();
10193 }
10194 
10195 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10196 /// ensure constants are generated when needed.  Remember the virtual registers
10197 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10198 /// directly add them, because expansion might result in multiple MBB's for one
10199 /// BB.  As such, the start of the BB might correspond to a different MBB than
10200 /// the end.
10201 void
10202 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10203   const Instruction *TI = LLVMBB->getTerminator();
10204 
10205   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10206 
10207   // Check PHI nodes in successors that expect a value to be available from this
10208   // block.
10209   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10210     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10211     if (!isa<PHINode>(SuccBB->begin())) continue;
10212     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10213 
10214     // If this terminator has multiple identical successors (common for
10215     // switches), only handle each succ once.
10216     if (!SuccsHandled.insert(SuccMBB).second)
10217       continue;
10218 
10219     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10220 
10221     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10222     // nodes and Machine PHI nodes, but the incoming operands have not been
10223     // emitted yet.
10224     for (const PHINode &PN : SuccBB->phis()) {
10225       // Ignore dead phi's.
10226       if (PN.use_empty())
10227         continue;
10228 
10229       // Skip empty types
10230       if (PN.getType()->isEmptyTy())
10231         continue;
10232 
10233       unsigned Reg;
10234       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10235 
10236       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10237         unsigned &RegOut = ConstantsOut[C];
10238         if (RegOut == 0) {
10239           RegOut = FuncInfo.CreateRegs(C);
10240           CopyValueToVirtualRegister(C, RegOut);
10241         }
10242         Reg = RegOut;
10243       } else {
10244         DenseMap<const Value *, Register>::iterator I =
10245           FuncInfo.ValueMap.find(PHIOp);
10246         if (I != FuncInfo.ValueMap.end())
10247           Reg = I->second;
10248         else {
10249           assert(isa<AllocaInst>(PHIOp) &&
10250                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10251                  "Didn't codegen value into a register!??");
10252           Reg = FuncInfo.CreateRegs(PHIOp);
10253           CopyValueToVirtualRegister(PHIOp, Reg);
10254         }
10255       }
10256 
10257       // Remember that this register needs to added to the machine PHI node as
10258       // the input for this MBB.
10259       SmallVector<EVT, 4> ValueVTs;
10260       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10261       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10262       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10263         EVT VT = ValueVTs[vti];
10264         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10265         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10266           FuncInfo.PHINodesToUpdate.push_back(
10267               std::make_pair(&*MBBI++, Reg + i));
10268         Reg += NumRegisters;
10269       }
10270     }
10271   }
10272 
10273   ConstantsOut.clear();
10274 }
10275 
10276 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10277 /// is 0.
10278 MachineBasicBlock *
10279 SelectionDAGBuilder::StackProtectorDescriptor::
10280 AddSuccessorMBB(const BasicBlock *BB,
10281                 MachineBasicBlock *ParentMBB,
10282                 bool IsLikely,
10283                 MachineBasicBlock *SuccMBB) {
10284   // If SuccBB has not been created yet, create it.
10285   if (!SuccMBB) {
10286     MachineFunction *MF = ParentMBB->getParent();
10287     MachineFunction::iterator BBI(ParentMBB);
10288     SuccMBB = MF->CreateMachineBasicBlock(BB);
10289     MF->insert(++BBI, SuccMBB);
10290   }
10291   // Add it as a successor of ParentMBB.
10292   ParentMBB->addSuccessor(
10293       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10294   return SuccMBB;
10295 }
10296 
10297 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10298   MachineFunction::iterator I(MBB);
10299   if (++I == FuncInfo.MF->end())
10300     return nullptr;
10301   return &*I;
10302 }
10303 
10304 /// During lowering new call nodes can be created (such as memset, etc.).
10305 /// Those will become new roots of the current DAG, but complications arise
10306 /// when they are tail calls. In such cases, the call lowering will update
10307 /// the root, but the builder still needs to know that a tail call has been
10308 /// lowered in order to avoid generating an additional return.
10309 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10310   // If the node is null, we do have a tail call.
10311   if (MaybeTC.getNode() != nullptr)
10312     DAG.setRoot(MaybeTC);
10313   else
10314     HasTailCall = true;
10315 }
10316 
10317 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10318                                         MachineBasicBlock *SwitchMBB,
10319                                         MachineBasicBlock *DefaultMBB) {
10320   MachineFunction *CurMF = FuncInfo.MF;
10321   MachineBasicBlock *NextMBB = nullptr;
10322   MachineFunction::iterator BBI(W.MBB);
10323   if (++BBI != FuncInfo.MF->end())
10324     NextMBB = &*BBI;
10325 
10326   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10327 
10328   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10329 
10330   if (Size == 2 && W.MBB == SwitchMBB) {
10331     // If any two of the cases has the same destination, and if one value
10332     // is the same as the other, but has one bit unset that the other has set,
10333     // use bit manipulation to do two compares at once.  For example:
10334     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10335     // TODO: This could be extended to merge any 2 cases in switches with 3
10336     // cases.
10337     // TODO: Handle cases where W.CaseBB != SwitchBB.
10338     CaseCluster &Small = *W.FirstCluster;
10339     CaseCluster &Big = *W.LastCluster;
10340 
10341     if (Small.Low == Small.High && Big.Low == Big.High &&
10342         Small.MBB == Big.MBB) {
10343       const APInt &SmallValue = Small.Low->getValue();
10344       const APInt &BigValue = Big.Low->getValue();
10345 
10346       // Check that there is only one bit different.
10347       APInt CommonBit = BigValue ^ SmallValue;
10348       if (CommonBit.isPowerOf2()) {
10349         SDValue CondLHS = getValue(Cond);
10350         EVT VT = CondLHS.getValueType();
10351         SDLoc DL = getCurSDLoc();
10352 
10353         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10354                                  DAG.getConstant(CommonBit, DL, VT));
10355         SDValue Cond = DAG.getSetCC(
10356             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10357             ISD::SETEQ);
10358 
10359         // Update successor info.
10360         // Both Small and Big will jump to Small.BB, so we sum up the
10361         // probabilities.
10362         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10363         if (BPI)
10364           addSuccessorWithProb(
10365               SwitchMBB, DefaultMBB,
10366               // The default destination is the first successor in IR.
10367               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10368         else
10369           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10370 
10371         // Insert the true branch.
10372         SDValue BrCond =
10373             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10374                         DAG.getBasicBlock(Small.MBB));
10375         // Insert the false branch.
10376         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10377                              DAG.getBasicBlock(DefaultMBB));
10378 
10379         DAG.setRoot(BrCond);
10380         return;
10381       }
10382     }
10383   }
10384 
10385   if (TM.getOptLevel() != CodeGenOpt::None) {
10386     // Here, we order cases by probability so the most likely case will be
10387     // checked first. However, two clusters can have the same probability in
10388     // which case their relative ordering is non-deterministic. So we use Low
10389     // as a tie-breaker as clusters are guaranteed to never overlap.
10390     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10391                [](const CaseCluster &a, const CaseCluster &b) {
10392       return a.Prob != b.Prob ?
10393              a.Prob > b.Prob :
10394              a.Low->getValue().slt(b.Low->getValue());
10395     });
10396 
10397     // Rearrange the case blocks so that the last one falls through if possible
10398     // without changing the order of probabilities.
10399     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10400       --I;
10401       if (I->Prob > W.LastCluster->Prob)
10402         break;
10403       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10404         std::swap(*I, *W.LastCluster);
10405         break;
10406       }
10407     }
10408   }
10409 
10410   // Compute total probability.
10411   BranchProbability DefaultProb = W.DefaultProb;
10412   BranchProbability UnhandledProbs = DefaultProb;
10413   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10414     UnhandledProbs += I->Prob;
10415 
10416   MachineBasicBlock *CurMBB = W.MBB;
10417   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10418     bool FallthroughUnreachable = false;
10419     MachineBasicBlock *Fallthrough;
10420     if (I == W.LastCluster) {
10421       // For the last cluster, fall through to the default destination.
10422       Fallthrough = DefaultMBB;
10423       FallthroughUnreachable = isa<UnreachableInst>(
10424           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10425     } else {
10426       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10427       CurMF->insert(BBI, Fallthrough);
10428       // Put Cond in a virtual register to make it available from the new blocks.
10429       ExportFromCurrentBlock(Cond);
10430     }
10431     UnhandledProbs -= I->Prob;
10432 
10433     switch (I->Kind) {
10434       case CC_JumpTable: {
10435         // FIXME: Optimize away range check based on pivot comparisons.
10436         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10437         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10438 
10439         // The jump block hasn't been inserted yet; insert it here.
10440         MachineBasicBlock *JumpMBB = JT->MBB;
10441         CurMF->insert(BBI, JumpMBB);
10442 
10443         auto JumpProb = I->Prob;
10444         auto FallthroughProb = UnhandledProbs;
10445 
10446         // If the default statement is a target of the jump table, we evenly
10447         // distribute the default probability to successors of CurMBB. Also
10448         // update the probability on the edge from JumpMBB to Fallthrough.
10449         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10450                                               SE = JumpMBB->succ_end();
10451              SI != SE; ++SI) {
10452           if (*SI == DefaultMBB) {
10453             JumpProb += DefaultProb / 2;
10454             FallthroughProb -= DefaultProb / 2;
10455             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10456             JumpMBB->normalizeSuccProbs();
10457             break;
10458           }
10459         }
10460 
10461         if (FallthroughUnreachable) {
10462           // Skip the range check if the fallthrough block is unreachable.
10463           JTH->OmitRangeCheck = true;
10464         }
10465 
10466         if (!JTH->OmitRangeCheck)
10467           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10468         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10469         CurMBB->normalizeSuccProbs();
10470 
10471         // The jump table header will be inserted in our current block, do the
10472         // range check, and fall through to our fallthrough block.
10473         JTH->HeaderBB = CurMBB;
10474         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10475 
10476         // If we're in the right place, emit the jump table header right now.
10477         if (CurMBB == SwitchMBB) {
10478           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10479           JTH->Emitted = true;
10480         }
10481         break;
10482       }
10483       case CC_BitTests: {
10484         // FIXME: Optimize away range check based on pivot comparisons.
10485         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10486 
10487         // The bit test blocks haven't been inserted yet; insert them here.
10488         for (BitTestCase &BTC : BTB->Cases)
10489           CurMF->insert(BBI, BTC.ThisBB);
10490 
10491         // Fill in fields of the BitTestBlock.
10492         BTB->Parent = CurMBB;
10493         BTB->Default = Fallthrough;
10494 
10495         BTB->DefaultProb = UnhandledProbs;
10496         // If the cases in bit test don't form a contiguous range, we evenly
10497         // distribute the probability on the edge to Fallthrough to two
10498         // successors of CurMBB.
10499         if (!BTB->ContiguousRange) {
10500           BTB->Prob += DefaultProb / 2;
10501           BTB->DefaultProb -= DefaultProb / 2;
10502         }
10503 
10504         if (FallthroughUnreachable) {
10505           // Skip the range check if the fallthrough block is unreachable.
10506           BTB->OmitRangeCheck = true;
10507         }
10508 
10509         // If we're in the right place, emit the bit test header right now.
10510         if (CurMBB == SwitchMBB) {
10511           visitBitTestHeader(*BTB, SwitchMBB);
10512           BTB->Emitted = true;
10513         }
10514         break;
10515       }
10516       case CC_Range: {
10517         const Value *RHS, *LHS, *MHS;
10518         ISD::CondCode CC;
10519         if (I->Low == I->High) {
10520           // Check Cond == I->Low.
10521           CC = ISD::SETEQ;
10522           LHS = Cond;
10523           RHS=I->Low;
10524           MHS = nullptr;
10525         } else {
10526           // Check I->Low <= Cond <= I->High.
10527           CC = ISD::SETLE;
10528           LHS = I->Low;
10529           MHS = Cond;
10530           RHS = I->High;
10531         }
10532 
10533         // If Fallthrough is unreachable, fold away the comparison.
10534         if (FallthroughUnreachable)
10535           CC = ISD::SETTRUE;
10536 
10537         // The false probability is the sum of all unhandled cases.
10538         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10539                      getCurSDLoc(), I->Prob, UnhandledProbs);
10540 
10541         if (CurMBB == SwitchMBB)
10542           visitSwitchCase(CB, SwitchMBB);
10543         else
10544           SL->SwitchCases.push_back(CB);
10545 
10546         break;
10547       }
10548     }
10549     CurMBB = Fallthrough;
10550   }
10551 }
10552 
10553 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10554                                               CaseClusterIt First,
10555                                               CaseClusterIt Last) {
10556   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10557     if (X.Prob != CC.Prob)
10558       return X.Prob > CC.Prob;
10559 
10560     // Ties are broken by comparing the case value.
10561     return X.Low->getValue().slt(CC.Low->getValue());
10562   });
10563 }
10564 
10565 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10566                                         const SwitchWorkListItem &W,
10567                                         Value *Cond,
10568                                         MachineBasicBlock *SwitchMBB) {
10569   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10570          "Clusters not sorted?");
10571 
10572   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10573 
10574   // Balance the tree based on branch probabilities to create a near-optimal (in
10575   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10576   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10577   CaseClusterIt LastLeft = W.FirstCluster;
10578   CaseClusterIt FirstRight = W.LastCluster;
10579   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10580   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10581 
10582   // Move LastLeft and FirstRight towards each other from opposite directions to
10583   // find a partitioning of the clusters which balances the probability on both
10584   // sides. If LeftProb and RightProb are equal, alternate which side is
10585   // taken to ensure 0-probability nodes are distributed evenly.
10586   unsigned I = 0;
10587   while (LastLeft + 1 < FirstRight) {
10588     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10589       LeftProb += (++LastLeft)->Prob;
10590     else
10591       RightProb += (--FirstRight)->Prob;
10592     I++;
10593   }
10594 
10595   while (true) {
10596     // Our binary search tree differs from a typical BST in that ours can have up
10597     // to three values in each leaf. The pivot selection above doesn't take that
10598     // into account, which means the tree might require more nodes and be less
10599     // efficient. We compensate for this here.
10600 
10601     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10602     unsigned NumRight = W.LastCluster - FirstRight + 1;
10603 
10604     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10605       // If one side has less than 3 clusters, and the other has more than 3,
10606       // consider taking a cluster from the other side.
10607 
10608       if (NumLeft < NumRight) {
10609         // Consider moving the first cluster on the right to the left side.
10610         CaseCluster &CC = *FirstRight;
10611         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10612         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10613         if (LeftSideRank <= RightSideRank) {
10614           // Moving the cluster to the left does not demote it.
10615           ++LastLeft;
10616           ++FirstRight;
10617           continue;
10618         }
10619       } else {
10620         assert(NumRight < NumLeft);
10621         // Consider moving the last element on the left to the right side.
10622         CaseCluster &CC = *LastLeft;
10623         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10624         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10625         if (RightSideRank <= LeftSideRank) {
10626           // Moving the cluster to the right does not demot it.
10627           --LastLeft;
10628           --FirstRight;
10629           continue;
10630         }
10631       }
10632     }
10633     break;
10634   }
10635 
10636   assert(LastLeft + 1 == FirstRight);
10637   assert(LastLeft >= W.FirstCluster);
10638   assert(FirstRight <= W.LastCluster);
10639 
10640   // Use the first element on the right as pivot since we will make less-than
10641   // comparisons against it.
10642   CaseClusterIt PivotCluster = FirstRight;
10643   assert(PivotCluster > W.FirstCluster);
10644   assert(PivotCluster <= W.LastCluster);
10645 
10646   CaseClusterIt FirstLeft = W.FirstCluster;
10647   CaseClusterIt LastRight = W.LastCluster;
10648 
10649   const ConstantInt *Pivot = PivotCluster->Low;
10650 
10651   // New blocks will be inserted immediately after the current one.
10652   MachineFunction::iterator BBI(W.MBB);
10653   ++BBI;
10654 
10655   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10656   // we can branch to its destination directly if it's squeezed exactly in
10657   // between the known lower bound and Pivot - 1.
10658   MachineBasicBlock *LeftMBB;
10659   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10660       FirstLeft->Low == W.GE &&
10661       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10662     LeftMBB = FirstLeft->MBB;
10663   } else {
10664     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10665     FuncInfo.MF->insert(BBI, LeftMBB);
10666     WorkList.push_back(
10667         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10668     // Put Cond in a virtual register to make it available from the new blocks.
10669     ExportFromCurrentBlock(Cond);
10670   }
10671 
10672   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10673   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10674   // directly if RHS.High equals the current upper bound.
10675   MachineBasicBlock *RightMBB;
10676   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10677       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10678     RightMBB = FirstRight->MBB;
10679   } else {
10680     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10681     FuncInfo.MF->insert(BBI, RightMBB);
10682     WorkList.push_back(
10683         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10684     // Put Cond in a virtual register to make it available from the new blocks.
10685     ExportFromCurrentBlock(Cond);
10686   }
10687 
10688   // Create the CaseBlock record that will be used to lower the branch.
10689   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10690                getCurSDLoc(), LeftProb, RightProb);
10691 
10692   if (W.MBB == SwitchMBB)
10693     visitSwitchCase(CB, SwitchMBB);
10694   else
10695     SL->SwitchCases.push_back(CB);
10696 }
10697 
10698 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10699 // from the swith statement.
10700 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10701                                             BranchProbability PeeledCaseProb) {
10702   if (PeeledCaseProb == BranchProbability::getOne())
10703     return BranchProbability::getZero();
10704   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10705 
10706   uint32_t Numerator = CaseProb.getNumerator();
10707   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10708   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10709 }
10710 
10711 // Try to peel the top probability case if it exceeds the threshold.
10712 // Return current MachineBasicBlock for the switch statement if the peeling
10713 // does not occur.
10714 // If the peeling is performed, return the newly created MachineBasicBlock
10715 // for the peeled switch statement. Also update Clusters to remove the peeled
10716 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10717 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10718     const SwitchInst &SI, CaseClusterVector &Clusters,
10719     BranchProbability &PeeledCaseProb) {
10720   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10721   // Don't perform if there is only one cluster or optimizing for size.
10722   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10723       TM.getOptLevel() == CodeGenOpt::None ||
10724       SwitchMBB->getParent()->getFunction().hasMinSize())
10725     return SwitchMBB;
10726 
10727   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10728   unsigned PeeledCaseIndex = 0;
10729   bool SwitchPeeled = false;
10730   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10731     CaseCluster &CC = Clusters[Index];
10732     if (CC.Prob < TopCaseProb)
10733       continue;
10734     TopCaseProb = CC.Prob;
10735     PeeledCaseIndex = Index;
10736     SwitchPeeled = true;
10737   }
10738   if (!SwitchPeeled)
10739     return SwitchMBB;
10740 
10741   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10742                     << TopCaseProb << "\n");
10743 
10744   // Record the MBB for the peeled switch statement.
10745   MachineFunction::iterator BBI(SwitchMBB);
10746   ++BBI;
10747   MachineBasicBlock *PeeledSwitchMBB =
10748       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10749   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10750 
10751   ExportFromCurrentBlock(SI.getCondition());
10752   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10753   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10754                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10755   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10756 
10757   Clusters.erase(PeeledCaseIt);
10758   for (CaseCluster &CC : Clusters) {
10759     LLVM_DEBUG(
10760         dbgs() << "Scale the probablity for one cluster, before scaling: "
10761                << CC.Prob << "\n");
10762     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10763     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10764   }
10765   PeeledCaseProb = TopCaseProb;
10766   return PeeledSwitchMBB;
10767 }
10768 
10769 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10770   // Extract cases from the switch.
10771   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10772   CaseClusterVector Clusters;
10773   Clusters.reserve(SI.getNumCases());
10774   for (auto I : SI.cases()) {
10775     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10776     const ConstantInt *CaseVal = I.getCaseValue();
10777     BranchProbability Prob =
10778         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10779             : BranchProbability(1, SI.getNumCases() + 1);
10780     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10781   }
10782 
10783   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10784 
10785   // Cluster adjacent cases with the same destination. We do this at all
10786   // optimization levels because it's cheap to do and will make codegen faster
10787   // if there are many clusters.
10788   sortAndRangeify(Clusters);
10789 
10790   // The branch probablity of the peeled case.
10791   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10792   MachineBasicBlock *PeeledSwitchMBB =
10793       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10794 
10795   // If there is only the default destination, jump there directly.
10796   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10797   if (Clusters.empty()) {
10798     assert(PeeledSwitchMBB == SwitchMBB);
10799     SwitchMBB->addSuccessor(DefaultMBB);
10800     if (DefaultMBB != NextBlock(SwitchMBB)) {
10801       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10802                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10803     }
10804     return;
10805   }
10806 
10807   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10808   SL->findBitTestClusters(Clusters, &SI);
10809 
10810   LLVM_DEBUG({
10811     dbgs() << "Case clusters: ";
10812     for (const CaseCluster &C : Clusters) {
10813       if (C.Kind == CC_JumpTable)
10814         dbgs() << "JT:";
10815       if (C.Kind == CC_BitTests)
10816         dbgs() << "BT:";
10817 
10818       C.Low->getValue().print(dbgs(), true);
10819       if (C.Low != C.High) {
10820         dbgs() << '-';
10821         C.High->getValue().print(dbgs(), true);
10822       }
10823       dbgs() << ' ';
10824     }
10825     dbgs() << '\n';
10826   });
10827 
10828   assert(!Clusters.empty());
10829   SwitchWorkList WorkList;
10830   CaseClusterIt First = Clusters.begin();
10831   CaseClusterIt Last = Clusters.end() - 1;
10832   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10833   // Scale the branchprobability for DefaultMBB if the peel occurs and
10834   // DefaultMBB is not replaced.
10835   if (PeeledCaseProb != BranchProbability::getZero() &&
10836       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10837     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10838   WorkList.push_back(
10839       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10840 
10841   while (!WorkList.empty()) {
10842     SwitchWorkListItem W = WorkList.pop_back_val();
10843     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10844 
10845     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10846         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10847       // For optimized builds, lower large range as a balanced binary tree.
10848       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10849       continue;
10850     }
10851 
10852     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10853   }
10854 }
10855 
10856 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
10857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10858   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10859 
10860   SDLoc DL = getCurSDLoc();
10861   SDValue V = getValue(I.getOperand(0));
10862   assert(VT == V.getValueType() && "Malformed vector.reverse!");
10863 
10864   if (VT.isScalableVector()) {
10865     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
10866     return;
10867   }
10868 
10869   // Use VECTOR_SHUFFLE for the fixed-length vector
10870   // to maintain existing behavior.
10871   SmallVector<int, 8> Mask;
10872   unsigned NumElts = VT.getVectorMinNumElements();
10873   for (unsigned i = 0; i != NumElts; ++i)
10874     Mask.push_back(NumElts - 1 - i);
10875 
10876   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
10877 }
10878 
10879 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10880   SmallVector<EVT, 4> ValueVTs;
10881   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10882                   ValueVTs);
10883   unsigned NumValues = ValueVTs.size();
10884   if (NumValues == 0) return;
10885 
10886   SmallVector<SDValue, 4> Values(NumValues);
10887   SDValue Op = getValue(I.getOperand(0));
10888 
10889   for (unsigned i = 0; i != NumValues; ++i)
10890     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10891                             SDValue(Op.getNode(), Op.getResNo() + i));
10892 
10893   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10894                            DAG.getVTList(ValueVTs), Values));
10895 }
10896