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