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