xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 944cc5e0ab5c1323e6cd9c3a72e8de89bd8a67b0)
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/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         IntermediateVT.isVector()
419             ? EVT::getVectorVT(
420                   *DAG.getContext(), IntermediateVT.getScalarType(),
421                   IntermediateVT.getVectorElementCount() * NumParts)
422             : EVT::getVectorVT(*DAG.getContext(),
423                                IntermediateVT.getScalarType(),
424                                NumIntermediates);
425     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
426                                                 : ISD::BUILD_VECTOR,
427                       DL, BuiltVectorTy, Ops);
428   }
429 
430   // There is now one part, held in Val.  Correct it to match ValueVT.
431   EVT PartEVT = Val.getValueType();
432 
433   if (PartEVT == ValueVT)
434     return Val;
435 
436   if (PartEVT.isVector()) {
437     // If the element type of the source/dest vectors are the same, but the
438     // parts vector has more elements than the value vector, then we have a
439     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
440     // elements we want.
441     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
442       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
443              "Cannot narrow, it would be a lossy transformation");
444       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
445                          DAG.getVectorIdxConstant(0, DL));
446     }
447 
448     // Vector/Vector bitcast.
449     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
450       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
451 
452     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
453       "Cannot handle this kind of promotion");
454     // Promoted vector extract
455     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
456 
457   }
458 
459   // Trivial bitcast if the types are the same size and the destination
460   // vector type is legal.
461   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
462       TLI.isTypeLegal(ValueVT))
463     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464 
465   if (ValueVT.getVectorNumElements() != 1) {
466      // Certain ABIs require that vectors are passed as integers. For vectors
467      // are the same size, this is an obvious bitcast.
468      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
469        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
470      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
471        // Bitcast Val back the original type and extract the corresponding
472        // vector we want.
473        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
474        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
475                                            ValueVT.getVectorElementType(), Elts);
476        Val = DAG.getBitcast(WiderVecType, Val);
477        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
478                           DAG.getVectorIdxConstant(0, DL));
479      }
480 
481      diagnosePossiblyInvalidConstraint(
482          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
483      return DAG.getUNDEF(ValueVT);
484   }
485 
486   // Handle cases such as i8 -> <1 x i1>
487   EVT ValueSVT = ValueVT.getVectorElementType();
488   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
489     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
490       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
491     else
492       Val = ValueVT.isFloatingPoint()
493                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
494                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
495   }
496 
497   return DAG.getBuildVector(ValueVT, DL, Val);
498 }
499 
500 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
501                                  SDValue Val, SDValue *Parts, unsigned NumParts,
502                                  MVT PartVT, const Value *V,
503                                  Optional<CallingConv::ID> CallConv);
504 
505 /// getCopyToParts - Create a series of nodes that contain the specified value
506 /// split into legal parts.  If the parts contain more bits than Val, then, for
507 /// integers, ExtendKind can be used to specify how to generate the extra bits.
508 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
509                            SDValue *Parts, unsigned NumParts, MVT PartVT,
510                            const Value *V,
511                            Optional<CallingConv::ID> CallConv = None,
512                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
513   EVT ValueVT = Val.getValueType();
514 
515   // Handle the vector case separately.
516   if (ValueVT.isVector())
517     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
518                                 CallConv);
519 
520   unsigned PartBits = PartVT.getSizeInBits();
521   unsigned OrigNumParts = NumParts;
522   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
523          "Copying to an illegal type!");
524 
525   if (NumParts == 0)
526     return;
527 
528   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529   EVT PartEVT = PartVT;
530   if (PartEVT == ValueVT) {
531     assert(NumParts == 1 && "No-op copy with multiple parts!");
532     Parts[0] = Val;
533     return;
534   }
535 
536   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537     // If the parts cover more bits than the value has, promote the value.
538     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539       assert(NumParts == 1 && "Do not know what to promote to!");
540       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
541     } else {
542       if (ValueVT.isFloatingPoint()) {
543         // FP values need to be bitcast, then extended if they are being put
544         // into a larger container.
545         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
546         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
547       }
548       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549              ValueVT.isInteger() &&
550              "Unknown mismatch!");
551       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
552       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
553       if (PartVT == MVT::x86mmx)
554         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
555     }
556   } else if (PartBits == ValueVT.getSizeInBits()) {
557     // Different types of the same size.
558     assert(NumParts == 1 && PartEVT != ValueVT);
559     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561     // If the parts cover less bits than value has, truncate the value.
562     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563            ValueVT.isInteger() &&
564            "Unknown mismatch!");
565     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
567     if (PartVT == MVT::x86mmx)
568       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569   }
570 
571   // The value may have changed - recompute ValueVT.
572   ValueVT = Val.getValueType();
573   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574          "Failed to tile the value with PartVT!");
575 
576   if (NumParts == 1) {
577     if (PartEVT != ValueVT) {
578       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
579                                         "scalar-to-vector conversion failed");
580       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581     }
582 
583     Parts[0] = Val;
584     return;
585   }
586 
587   // Expand the value into multiple parts.
588   if (NumParts & (NumParts - 1)) {
589     // The number of parts is not a power of 2.  Split off and copy the tail.
590     assert(PartVT.isInteger() && ValueVT.isInteger() &&
591            "Do not know what to expand to!");
592     unsigned RoundParts = 1 << Log2_32(NumParts);
593     unsigned RoundBits = RoundParts * PartBits;
594     unsigned OddParts = NumParts - RoundParts;
595     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
596       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
597 
598     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
599                    CallConv);
600 
601     if (DAG.getDataLayout().isBigEndian())
602       // The odd parts were reversed by getCopyToParts - unreverse them.
603       std::reverse(Parts + RoundParts, Parts + NumParts);
604 
605     NumParts = RoundParts;
606     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
607     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
608   }
609 
610   // The number of parts is a power of 2.  Repeatedly bisect the value using
611   // EXTRACT_ELEMENT.
612   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
613                          EVT::getIntegerVT(*DAG.getContext(),
614                                            ValueVT.getSizeInBits()),
615                          Val);
616 
617   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618     for (unsigned i = 0; i < NumParts; i += StepSize) {
619       unsigned ThisBits = StepSize * PartBits / 2;
620       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
621       SDValue &Part0 = Parts[i];
622       SDValue &Part1 = Parts[i+StepSize/2];
623 
624       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
625                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
626       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
628 
629       if (ThisBits == PartBits && ThisVT != PartVT) {
630         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
631         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
632       }
633     }
634   }
635 
636   if (DAG.getDataLayout().isBigEndian())
637     std::reverse(Parts, Parts + OrigNumParts);
638 }
639 
640 static SDValue widenVectorToPartType(SelectionDAG &DAG,
641                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
642   if (!PartVT.isVector())
643     return SDValue();
644 
645   EVT ValueVT = Val.getValueType();
646   unsigned PartNumElts = PartVT.getVectorNumElements();
647   unsigned ValueNumElts = ValueVT.getVectorNumElements();
648   if (PartNumElts > ValueNumElts &&
649       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
650     EVT ElementVT = PartVT.getVectorElementType();
651     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
652     // undef elements.
653     SmallVector<SDValue, 16> Ops;
654     DAG.ExtractVectorElements(Val, Ops);
655     SDValue EltUndef = DAG.getUNDEF(ElementVT);
656     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
657       Ops.push_back(EltUndef);
658 
659     // FIXME: Use CONCAT for 2x -> 4x.
660     return DAG.getBuildVector(PartVT, DL, Ops);
661   }
662 
663   return SDValue();
664 }
665 
666 /// getCopyToPartsVector - Create a series of nodes that contain the specified
667 /// value split into legal parts.
668 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
669                                  SDValue Val, SDValue *Parts, unsigned NumParts,
670                                  MVT PartVT, const Value *V,
671                                  Optional<CallingConv::ID> CallConv) {
672   EVT ValueVT = Val.getValueType();
673   assert(ValueVT.isVector() && "Not a vector");
674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
675   const bool IsABIRegCopy = CallConv.hasValue();
676 
677   if (NumParts == 1) {
678     EVT PartEVT = PartVT;
679     if (PartEVT == ValueVT) {
680       // Nothing to do.
681     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
682       // Bitconvert vector->vector case.
683       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
684     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
685       Val = Widened;
686     } else if (PartVT.isVector() &&
687                PartEVT.getVectorElementType().bitsGE(
688                  ValueVT.getVectorElementType()) &&
689                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
690 
691       // Promoted vector extract
692       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
693     } else {
694       if (ValueVT.getVectorNumElements() == 1) {
695         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
696                           DAG.getVectorIdxConstant(0, DL));
697       } else {
698         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
699                "lossy conversion of vector to scalar type");
700         EVT IntermediateType =
701             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
702         Val = DAG.getBitcast(IntermediateType, Val);
703         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
704       }
705     }
706 
707     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
708     Parts[0] = Val;
709     return;
710   }
711 
712   // Handle a multi-element vector.
713   EVT IntermediateVT;
714   MVT RegisterVT;
715   unsigned NumIntermediates;
716   unsigned NumRegs;
717   if (IsABIRegCopy) {
718     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
719         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
720         NumIntermediates, RegisterVT);
721   } else {
722     NumRegs =
723         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
724                                    NumIntermediates, RegisterVT);
725   }
726 
727   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
728   NumParts = NumRegs; // Silence a compiler warning.
729   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
730 
731   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
732     IntermediateVT.getVectorNumElements() : 1;
733 
734   // Convert the vector to the appropriate type if necessary.
735   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
736 
737   EVT BuiltVectorTy = EVT::getVectorVT(
738       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
739   if (ValueVT != BuiltVectorTy) {
740     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
741       Val = Widened;
742 
743     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
744   }
745 
746   // Split the vector into intermediate operands.
747   SmallVector<SDValue, 8> Ops(NumIntermediates);
748   for (unsigned i = 0; i != NumIntermediates; ++i) {
749     if (IntermediateVT.isVector()) {
750       Ops[i] =
751           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
752                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
753     } else {
754       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
755                            DAG.getVectorIdxConstant(i, DL));
756     }
757   }
758 
759   // Split the intermediate operands into legal parts.
760   if (NumParts == NumIntermediates) {
761     // If the register was not expanded, promote or copy the value,
762     // as appropriate.
763     for (unsigned i = 0; i != NumParts; ++i)
764       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
765   } else if (NumParts > 0) {
766     // If the intermediate type was expanded, split each the value into
767     // legal parts.
768     assert(NumIntermediates != 0 && "division by zero");
769     assert(NumParts % NumIntermediates == 0 &&
770            "Must expand into a divisible number of parts!");
771     unsigned Factor = NumParts / NumIntermediates;
772     for (unsigned i = 0; i != NumIntermediates; ++i)
773       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
774                      CallConv);
775   }
776 }
777 
778 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
779                            EVT valuevt, Optional<CallingConv::ID> CC)
780     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
781       RegCount(1, regs.size()), CallConv(CC) {}
782 
783 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
784                            const DataLayout &DL, unsigned Reg, Type *Ty,
785                            Optional<CallingConv::ID> CC) {
786   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
787 
788   CallConv = CC;
789 
790   for (EVT ValueVT : ValueVTs) {
791     unsigned NumRegs =
792         isABIMangled()
793             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getNumRegisters(Context, ValueVT);
795     MVT RegisterVT =
796         isABIMangled()
797             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
798             : TLI.getRegisterType(Context, ValueVT);
799     for (unsigned i = 0; i != NumRegs; ++i)
800       Regs.push_back(Reg + i);
801     RegVTs.push_back(RegisterVT);
802     RegCount.push_back(NumRegs);
803     Reg += NumRegs;
804   }
805 }
806 
807 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
808                                       FunctionLoweringInfo &FuncInfo,
809                                       const SDLoc &dl, SDValue &Chain,
810                                       SDValue *Flag, const Value *V) const {
811   // A Value with type {} or [0 x %t] needs no registers.
812   if (ValueVTs.empty())
813     return SDValue();
814 
815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
816 
817   // Assemble the legal parts into the final values.
818   SmallVector<SDValue, 4> Values(ValueVTs.size());
819   SmallVector<SDValue, 8> Parts;
820   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
821     // Copy the legal parts from the registers.
822     EVT ValueVT = ValueVTs[Value];
823     unsigned NumRegs = RegCount[Value];
824     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
825                                           *DAG.getContext(),
826                                           CallConv.getValue(), RegVTs[Value])
827                                     : RegVTs[Value];
828 
829     Parts.resize(NumRegs);
830     for (unsigned i = 0; i != NumRegs; ++i) {
831       SDValue P;
832       if (!Flag) {
833         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
834       } else {
835         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
836         *Flag = P.getValue(2);
837       }
838 
839       Chain = P.getValue(1);
840       Parts[i] = P;
841 
842       // If the source register was virtual and if we know something about it,
843       // add an assert node.
844       if (!Register::isVirtualRegister(Regs[Part + i]) ||
845           !RegisterVT.isInteger())
846         continue;
847 
848       const FunctionLoweringInfo::LiveOutInfo *LOI =
849         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
850       if (!LOI)
851         continue;
852 
853       unsigned RegSize = RegisterVT.getScalarSizeInBits();
854       unsigned NumSignBits = LOI->NumSignBits;
855       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
856 
857       if (NumZeroBits == RegSize) {
858         // The current value is a zero.
859         // Explicitly express that as it would be easier for
860         // optimizations to kick in.
861         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
862         continue;
863       }
864 
865       // FIXME: We capture more information than the dag can represent.  For
866       // now, just use the tightest assertzext/assertsext possible.
867       bool isSExt;
868       EVT FromVT(MVT::Other);
869       if (NumZeroBits) {
870         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
871         isSExt = false;
872       } else if (NumSignBits > 1) {
873         FromVT =
874             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
875         isSExt = true;
876       } else {
877         continue;
878       }
879       // Add an assertion node.
880       assert(FromVT != MVT::Other);
881       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
882                              RegisterVT, P, DAG.getValueType(FromVT));
883     }
884 
885     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
886                                      RegisterVT, ValueVT, V, CallConv);
887     Part += NumRegs;
888     Parts.clear();
889   }
890 
891   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
892 }
893 
894 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
895                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
896                                  const Value *V,
897                                  ISD::NodeType PreferredExtendType) const {
898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
899   ISD::NodeType ExtendKind = PreferredExtendType;
900 
901   // Get the list of the values's legal parts.
902   unsigned NumRegs = Regs.size();
903   SmallVector<SDValue, 8> Parts(NumRegs);
904   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
905     unsigned NumParts = RegCount[Value];
906 
907     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
908                                           *DAG.getContext(),
909                                           CallConv.getValue(), RegVTs[Value])
910                                     : RegVTs[Value];
911 
912     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
913       ExtendKind = ISD::ZERO_EXTEND;
914 
915     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
916                    NumParts, RegisterVT, V, CallConv, ExtendKind);
917     Part += NumParts;
918   }
919 
920   // Copy the parts into the registers.
921   SmallVector<SDValue, 8> Chains(NumRegs);
922   for (unsigned i = 0; i != NumRegs; ++i) {
923     SDValue Part;
924     if (!Flag) {
925       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
926     } else {
927       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
928       *Flag = Part.getValue(1);
929     }
930 
931     Chains[i] = Part.getValue(0);
932   }
933 
934   if (NumRegs == 1 || Flag)
935     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
936     // flagged to it. That is the CopyToReg nodes and the user are considered
937     // a single scheduling unit. If we create a TokenFactor and return it as
938     // chain, then the TokenFactor is both a predecessor (operand) of the
939     // user as well as a successor (the TF operands are flagged to the user).
940     // c1, f1 = CopyToReg
941     // c2, f2 = CopyToReg
942     // c3     = TokenFactor c1, c2
943     // ...
944     //        = op c3, ..., f2
945     Chain = Chains[NumRegs-1];
946   else
947     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
948 }
949 
950 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
951                                         unsigned MatchingIdx, const SDLoc &dl,
952                                         SelectionDAG &DAG,
953                                         std::vector<SDValue> &Ops) const {
954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
955 
956   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
957   if (HasMatching)
958     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
959   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
960     // Put the register class of the virtual registers in the flag word.  That
961     // way, later passes can recompute register class constraints for inline
962     // assembly as well as normal instructions.
963     // Don't do this for tied operands that can use the regclass information
964     // from the def.
965     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
966     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
967     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
968   }
969 
970   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
971   Ops.push_back(Res);
972 
973   if (Code == InlineAsm::Kind_Clobber) {
974     // Clobbers should always have a 1:1 mapping with registers, and may
975     // reference registers that have illegal (e.g. vector) types. Hence, we
976     // shouldn't try to apply any sort of splitting logic to them.
977     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
978            "No 1:1 mapping from clobbers to regs?");
979     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
980     (void)SP;
981     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
982       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
983       assert(
984           (Regs[I] != SP ||
985            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
986           "If we clobbered the stack pointer, MFI should know about it.");
987     }
988     return;
989   }
990 
991   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
992     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
993     MVT RegisterVT = RegVTs[Value];
994     for (unsigned i = 0; i != NumRegs; ++i) {
995       assert(Reg < Regs.size() && "Mismatch in # registers expected");
996       unsigned TheReg = Regs[Reg++];
997       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
998     }
999   }
1000 }
1001 
1002 SmallVector<std::pair<unsigned, unsigned>, 4>
1003 RegsForValue::getRegsAndSizes() const {
1004   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1005   unsigned I = 0;
1006   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1007     unsigned RegCount = std::get<0>(CountAndVT);
1008     MVT RegisterVT = std::get<1>(CountAndVT);
1009     unsigned RegisterSize = RegisterVT.getSizeInBits();
1010     for (unsigned E = I + RegCount; I != E; ++I)
1011       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1012   }
1013   return OutVec;
1014 }
1015 
1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1017                                const TargetLibraryInfo *li) {
1018   AA = aa;
1019   GFI = gfi;
1020   LibInfo = li;
1021   DL = &DAG.getDataLayout();
1022   Context = DAG.getContext();
1023   LPadToCallSiteMap.clear();
1024   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1025 }
1026 
1027 void SelectionDAGBuilder::clear() {
1028   NodeMap.clear();
1029   UnusedArgNodeMap.clear();
1030   PendingLoads.clear();
1031   PendingExports.clear();
1032   PendingConstrainedFP.clear();
1033   PendingConstrainedFPStrict.clear();
1034   CurInst = nullptr;
1035   HasTailCall = false;
1036   SDNodeOrder = LowestSDNodeOrder;
1037   StatepointLowering.clear();
1038 }
1039 
1040 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1041   DanglingDebugInfoMap.clear();
1042 }
1043 
1044 // Update DAG root to include dependencies on Pending chains.
1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1046   SDValue Root = DAG.getRoot();
1047 
1048   if (Pending.empty())
1049     return Root;
1050 
1051   // Add current root to PendingChains, unless we already indirectly
1052   // depend on it.
1053   if (Root.getOpcode() != ISD::EntryToken) {
1054     unsigned i = 0, e = Pending.size();
1055     for (; i != e; ++i) {
1056       assert(Pending[i].getNode()->getNumOperands() > 1);
1057       if (Pending[i].getNode()->getOperand(0) == Root)
1058         break;  // Don't add the root if we already indirectly depend on it.
1059     }
1060 
1061     if (i == e)
1062       Pending.push_back(Root);
1063   }
1064 
1065   if (Pending.size() == 1)
1066     Root = Pending[0];
1067   else
1068     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1069 
1070   DAG.setRoot(Root);
1071   Pending.clear();
1072   return Root;
1073 }
1074 
1075 SDValue SelectionDAGBuilder::getMemoryRoot() {
1076   return updateRoot(PendingLoads);
1077 }
1078 
1079 SDValue SelectionDAGBuilder::getRoot() {
1080   // Chain up all pending constrained intrinsics together with all
1081   // pending loads, by simply appending them to PendingLoads and
1082   // then calling getMemoryRoot().
1083   PendingLoads.reserve(PendingLoads.size() +
1084                        PendingConstrainedFP.size() +
1085                        PendingConstrainedFPStrict.size());
1086   PendingLoads.append(PendingConstrainedFP.begin(),
1087                       PendingConstrainedFP.end());
1088   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1089                       PendingConstrainedFPStrict.end());
1090   PendingConstrainedFP.clear();
1091   PendingConstrainedFPStrict.clear();
1092   return getMemoryRoot();
1093 }
1094 
1095 SDValue SelectionDAGBuilder::getControlRoot() {
1096   // We need to emit pending fpexcept.strict constrained intrinsics,
1097   // so append them to the PendingExports list.
1098   PendingExports.append(PendingConstrainedFPStrict.begin(),
1099                         PendingConstrainedFPStrict.end());
1100   PendingConstrainedFPStrict.clear();
1101   return updateRoot(PendingExports);
1102 }
1103 
1104 void SelectionDAGBuilder::visit(const Instruction &I) {
1105   // Set up outgoing PHI node register values before emitting the terminator.
1106   if (I.isTerminator()) {
1107     HandlePHINodesInSuccessorBlocks(I.getParent());
1108   }
1109 
1110   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1111   if (!isa<DbgInfoIntrinsic>(I))
1112     ++SDNodeOrder;
1113 
1114   CurInst = &I;
1115 
1116   visit(I.getOpcode(), I);
1117 
1118   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1119     // ConstrainedFPIntrinsics handle their own FMF.
1120     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1121       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1122       // maps to this instruction.
1123       // TODO: We could handle all flags (nsw, etc) here.
1124       // TODO: If an IR instruction maps to >1 node, only the final node will have
1125       //       flags set.
1126       if (SDNode *Node = getNodeForIRValue(&I)) {
1127         SDNodeFlags IncomingFlags;
1128         IncomingFlags.copyFMF(*FPMO);
1129         if (!Node->getFlags().isDefined())
1130           Node->setFlags(IncomingFlags);
1131         else
1132           Node->intersectFlagsWith(IncomingFlags);
1133       }
1134     }
1135   }
1136 
1137   if (!I.isTerminator() && !HasTailCall &&
1138       !isStatepoint(&I)) // statepoints handle their exports internally
1139     CopyToExportRegsIfNeeded(&I);
1140 
1141   CurInst = nullptr;
1142 }
1143 
1144 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1145   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1146 }
1147 
1148 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1149   // Note: this doesn't use InstVisitor, because it has to work with
1150   // ConstantExpr's in addition to instructions.
1151   switch (Opcode) {
1152   default: llvm_unreachable("Unknown instruction type encountered!");
1153     // Build the switch statement using the Instruction.def file.
1154 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1155     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1156 #include "llvm/IR/Instruction.def"
1157   }
1158 }
1159 
1160 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1161                                                 const DIExpression *Expr) {
1162   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1163     const DbgValueInst *DI = DDI.getDI();
1164     DIVariable *DanglingVariable = DI->getVariable();
1165     DIExpression *DanglingExpr = DI->getExpression();
1166     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1167       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1168       return true;
1169     }
1170     return false;
1171   };
1172 
1173   for (auto &DDIMI : DanglingDebugInfoMap) {
1174     DanglingDebugInfoVector &DDIV = DDIMI.second;
1175 
1176     // If debug info is to be dropped, run it through final checks to see
1177     // whether it can be salvaged.
1178     for (auto &DDI : DDIV)
1179       if (isMatchingDbgValue(DDI))
1180         salvageUnresolvedDbgValue(DDI);
1181 
1182     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1183   }
1184 }
1185 
1186 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1187 // generate the debug data structures now that we've seen its definition.
1188 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1189                                                    SDValue Val) {
1190   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1191   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1192     return;
1193 
1194   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1195   for (auto &DDI : DDIV) {
1196     const DbgValueInst *DI = DDI.getDI();
1197     assert(DI && "Ill-formed DanglingDebugInfo");
1198     DebugLoc dl = DDI.getdl();
1199     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1200     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1201     DILocalVariable *Variable = DI->getVariable();
1202     DIExpression *Expr = DI->getExpression();
1203     assert(Variable->isValidLocationForIntrinsic(dl) &&
1204            "Expected inlined-at fields to agree");
1205     SDDbgValue *SDV;
1206     if (Val.getNode()) {
1207       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1208       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1209       // we couldn't resolve it directly when examining the DbgValue intrinsic
1210       // in the first place we should not be more successful here). Unless we
1211       // have some test case that prove this to be correct we should avoid
1212       // calling EmitFuncArgumentDbgValue here.
1213       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1214         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1215                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1216         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1217         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1218         // inserted after the definition of Val when emitting the instructions
1219         // after ISel. An alternative could be to teach
1220         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1221         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1222                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1223                    << ValSDNodeOrder << "\n");
1224         SDV = getDbgValue(Val, Variable, Expr, dl,
1225                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1226         DAG.AddDbgValue(SDV, Val.getNode(), false);
1227       } else
1228         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1229                           << "in EmitFuncArgumentDbgValue\n");
1230     } else {
1231       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1232       auto Undef =
1233           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1234       auto SDV =
1235           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1236       DAG.AddDbgValue(SDV, nullptr, false);
1237     }
1238   }
1239   DDIV.clear();
1240 }
1241 
1242 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1243   Value *V = DDI.getDI()->getValue();
1244   DILocalVariable *Var = DDI.getDI()->getVariable();
1245   DIExpression *Expr = DDI.getDI()->getExpression();
1246   DebugLoc DL = DDI.getdl();
1247   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1248   unsigned SDOrder = DDI.getSDNodeOrder();
1249 
1250   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1251   // that DW_OP_stack_value is desired.
1252   assert(isa<DbgValueInst>(DDI.getDI()));
1253   bool StackValue = true;
1254 
1255   // Can this Value can be encoded without any further work?
1256   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1257     return;
1258 
1259   // Attempt to salvage back through as many instructions as possible. Bail if
1260   // a non-instruction is seen, such as a constant expression or global
1261   // variable. FIXME: Further work could recover those too.
1262   while (isa<Instruction>(V)) {
1263     Instruction &VAsInst = *cast<Instruction>(V);
1264     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1265 
1266     // If we cannot salvage any further, and haven't yet found a suitable debug
1267     // expression, bail out.
1268     if (!NewExpr)
1269       break;
1270 
1271     // New value and expr now represent this debuginfo.
1272     V = VAsInst.getOperand(0);
1273     Expr = NewExpr;
1274 
1275     // Some kind of simplification occurred: check whether the operand of the
1276     // salvaged debug expression can be encoded in this DAG.
1277     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1278       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1279                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1280       return;
1281     }
1282   }
1283 
1284   // This was the final opportunity to salvage this debug information, and it
1285   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1286   // any earlier variable location.
1287   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1288   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1289   DAG.AddDbgValue(SDV, nullptr, false);
1290 
1291   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1292                     << "\n");
1293   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1294                     << "\n");
1295 }
1296 
1297 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1298                                            DIExpression *Expr, DebugLoc dl,
1299                                            DebugLoc InstDL, unsigned Order) {
1300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1301   SDDbgValue *SDV;
1302   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1303       isa<ConstantPointerNull>(V)) {
1304     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1305     DAG.AddDbgValue(SDV, nullptr, false);
1306     return true;
1307   }
1308 
1309   // If the Value is a frame index, we can create a FrameIndex debug value
1310   // without relying on the DAG at all.
1311   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1312     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1313     if (SI != FuncInfo.StaticAllocaMap.end()) {
1314       auto SDV =
1315           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1316                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1317       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1318       // is still available even if the SDNode gets optimized out.
1319       DAG.AddDbgValue(SDV, nullptr, false);
1320       return true;
1321     }
1322   }
1323 
1324   // Do not use getValue() in here; we don't want to generate code at
1325   // this point if it hasn't been done yet.
1326   SDValue N = NodeMap[V];
1327   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1328     N = UnusedArgNodeMap[V];
1329   if (N.getNode()) {
1330     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1331       return true;
1332     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1333     DAG.AddDbgValue(SDV, N.getNode(), false);
1334     return true;
1335   }
1336 
1337   // Special rules apply for the first dbg.values of parameter variables in a
1338   // function. Identify them by the fact they reference Argument Values, that
1339   // they're parameters, and they are parameters of the current function. We
1340   // need to let them dangle until they get an SDNode.
1341   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1342                        !InstDL.getInlinedAt();
1343   if (!IsParamOfFunc) {
1344     // The value is not used in this block yet (or it would have an SDNode).
1345     // We still want the value to appear for the user if possible -- if it has
1346     // an associated VReg, we can refer to that instead.
1347     auto VMI = FuncInfo.ValueMap.find(V);
1348     if (VMI != FuncInfo.ValueMap.end()) {
1349       unsigned Reg = VMI->second;
1350       // If this is a PHI node, it may be split up into several MI PHI nodes
1351       // (in FunctionLoweringInfo::set).
1352       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1353                        V->getType(), None);
1354       if (RFV.occupiesMultipleRegs()) {
1355         unsigned Offset = 0;
1356         unsigned BitsToDescribe = 0;
1357         if (auto VarSize = Var->getSizeInBits())
1358           BitsToDescribe = *VarSize;
1359         if (auto Fragment = Expr->getFragmentInfo())
1360           BitsToDescribe = Fragment->SizeInBits;
1361         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1362           unsigned RegisterSize = RegAndSize.second;
1363           // Bail out if all bits are described already.
1364           if (Offset >= BitsToDescribe)
1365             break;
1366           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1367               ? BitsToDescribe - Offset
1368               : RegisterSize;
1369           auto FragmentExpr = DIExpression::createFragmentExpression(
1370               Expr, Offset, FragmentSize);
1371           if (!FragmentExpr)
1372               continue;
1373           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1374                                     false, dl, SDNodeOrder);
1375           DAG.AddDbgValue(SDV, nullptr, false);
1376           Offset += RegisterSize;
1377         }
1378       } else {
1379         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1380         DAG.AddDbgValue(SDV, nullptr, false);
1381       }
1382       return true;
1383     }
1384   }
1385 
1386   return false;
1387 }
1388 
1389 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1390   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1391   for (auto &Pair : DanglingDebugInfoMap)
1392     for (auto &DDI : Pair.second)
1393       salvageUnresolvedDbgValue(DDI);
1394   clearDanglingDebugInfo();
1395 }
1396 
1397 /// getCopyFromRegs - If there was virtual register allocated for the value V
1398 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1399 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1400   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1401   SDValue Result;
1402 
1403   if (It != FuncInfo.ValueMap.end()) {
1404     Register InReg = It->second;
1405 
1406     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1407                      DAG.getDataLayout(), InReg, Ty,
1408                      None); // This is not an ABI copy.
1409     SDValue Chain = DAG.getEntryNode();
1410     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1411                                  V);
1412     resolveDanglingDebugInfo(V, Result);
1413   }
1414 
1415   return Result;
1416 }
1417 
1418 /// getValue - Return an SDValue for the given Value.
1419 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1420   // If we already have an SDValue for this value, use it. It's important
1421   // to do this first, so that we don't create a CopyFromReg if we already
1422   // have a regular SDValue.
1423   SDValue &N = NodeMap[V];
1424   if (N.getNode()) return N;
1425 
1426   // If there's a virtual register allocated and initialized for this
1427   // value, use it.
1428   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1429     return copyFromReg;
1430 
1431   // Otherwise create a new SDValue and remember it.
1432   SDValue Val = getValueImpl(V);
1433   NodeMap[V] = Val;
1434   resolveDanglingDebugInfo(V, Val);
1435   return Val;
1436 }
1437 
1438 /// getNonRegisterValue - Return an SDValue for the given Value, but
1439 /// don't look in FuncInfo.ValueMap for a virtual register.
1440 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1441   // If we already have an SDValue for this value, use it.
1442   SDValue &N = NodeMap[V];
1443   if (N.getNode()) {
1444     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1445       // Remove the debug location from the node as the node is about to be used
1446       // in a location which may differ from the original debug location.  This
1447       // is relevant to Constant and ConstantFP nodes because they can appear
1448       // as constant expressions inside PHI nodes.
1449       N->setDebugLoc(DebugLoc());
1450     }
1451     return N;
1452   }
1453 
1454   // Otherwise create a new SDValue and remember it.
1455   SDValue Val = getValueImpl(V);
1456   NodeMap[V] = Val;
1457   resolveDanglingDebugInfo(V, Val);
1458   return Val;
1459 }
1460 
1461 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1462 /// Create an SDValue for the given value.
1463 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1465 
1466   if (const Constant *C = dyn_cast<Constant>(V)) {
1467     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1468 
1469     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1470       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1471 
1472     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1473       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1474 
1475     if (isa<ConstantPointerNull>(C)) {
1476       unsigned AS = V->getType()->getPointerAddressSpace();
1477       return DAG.getConstant(0, getCurSDLoc(),
1478                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1479     }
1480 
1481     if (match(C, m_VScale(DAG.getDataLayout())))
1482       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1483 
1484     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1485       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1486 
1487     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1488       return DAG.getUNDEF(VT);
1489 
1490     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1491       visit(CE->getOpcode(), *CE);
1492       SDValue N1 = NodeMap[V];
1493       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1494       return N1;
1495     }
1496 
1497     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1498       SmallVector<SDValue, 4> Constants;
1499       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1500            OI != OE; ++OI) {
1501         SDNode *Val = getValue(*OI).getNode();
1502         // If the operand is an empty aggregate, there are no values.
1503         if (!Val) continue;
1504         // Add each leaf value from the operand to the Constants list
1505         // to form a flattened list of all the values.
1506         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1507           Constants.push_back(SDValue(Val, i));
1508       }
1509 
1510       return DAG.getMergeValues(Constants, getCurSDLoc());
1511     }
1512 
1513     if (const ConstantDataSequential *CDS =
1514           dyn_cast<ConstantDataSequential>(C)) {
1515       SmallVector<SDValue, 4> Ops;
1516       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1517         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1518         // Add each leaf value from the operand to the Constants list
1519         // to form a flattened list of all the values.
1520         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1521           Ops.push_back(SDValue(Val, i));
1522       }
1523 
1524       if (isa<ArrayType>(CDS->getType()))
1525         return DAG.getMergeValues(Ops, getCurSDLoc());
1526       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1527     }
1528 
1529     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1530       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1531              "Unknown struct or array constant!");
1532 
1533       SmallVector<EVT, 4> ValueVTs;
1534       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1535       unsigned NumElts = ValueVTs.size();
1536       if (NumElts == 0)
1537         return SDValue(); // empty struct
1538       SmallVector<SDValue, 4> Constants(NumElts);
1539       for (unsigned i = 0; i != NumElts; ++i) {
1540         EVT EltVT = ValueVTs[i];
1541         if (isa<UndefValue>(C))
1542           Constants[i] = DAG.getUNDEF(EltVT);
1543         else if (EltVT.isFloatingPoint())
1544           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1545         else
1546           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1547       }
1548 
1549       return DAG.getMergeValues(Constants, getCurSDLoc());
1550     }
1551 
1552     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1553       return DAG.getBlockAddress(BA, VT);
1554 
1555     VectorType *VecTy = cast<VectorType>(V->getType());
1556     unsigned NumElements = VecTy->getNumElements();
1557 
1558     // Now that we know the number and type of the elements, get that number of
1559     // elements into the Ops array based on what kind of constant it is.
1560     SmallVector<SDValue, 16> Ops;
1561     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1562       for (unsigned i = 0; i != NumElements; ++i)
1563         Ops.push_back(getValue(CV->getOperand(i)));
1564     } else {
1565       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1566       EVT EltVT =
1567           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1568 
1569       SDValue Op;
1570       if (EltVT.isFloatingPoint())
1571         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1572       else
1573         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1574       Ops.assign(NumElements, Op);
1575     }
1576 
1577     // Create a BUILD_VECTOR node.
1578     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1579   }
1580 
1581   // If this is a static alloca, generate it as the frameindex instead of
1582   // computation.
1583   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1584     DenseMap<const AllocaInst*, int>::iterator SI =
1585       FuncInfo.StaticAllocaMap.find(AI);
1586     if (SI != FuncInfo.StaticAllocaMap.end())
1587       return DAG.getFrameIndex(SI->second,
1588                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1589   }
1590 
1591   // If this is an instruction which fast-isel has deferred, select it now.
1592   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1593     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1594 
1595     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1596                      Inst->getType(), getABIRegCopyCC(V));
1597     SDValue Chain = DAG.getEntryNode();
1598     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1599   }
1600 
1601   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1602     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1603   }
1604   llvm_unreachable("Can't get register for value!");
1605 }
1606 
1607 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1608   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1609   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1610   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1611   bool IsSEH = isAsynchronousEHPersonality(Pers);
1612   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1613   if (!IsSEH)
1614     CatchPadMBB->setIsEHScopeEntry();
1615   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1616   if (IsMSVCCXX || IsCoreCLR)
1617     CatchPadMBB->setIsEHFuncletEntry();
1618 }
1619 
1620 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1621   // Update machine-CFG edge.
1622   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1623   FuncInfo.MBB->addSuccessor(TargetMBB);
1624 
1625   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1626   bool IsSEH = isAsynchronousEHPersonality(Pers);
1627   if (IsSEH) {
1628     // If this is not a fall-through branch or optimizations are switched off,
1629     // emit the branch.
1630     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1631         TM.getOptLevel() == CodeGenOpt::None)
1632       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1633                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1634     return;
1635   }
1636 
1637   // Figure out the funclet membership for the catchret's successor.
1638   // This will be used by the FuncletLayout pass to determine how to order the
1639   // BB's.
1640   // A 'catchret' returns to the outer scope's color.
1641   Value *ParentPad = I.getCatchSwitchParentPad();
1642   const BasicBlock *SuccessorColor;
1643   if (isa<ConstantTokenNone>(ParentPad))
1644     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1645   else
1646     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1647   assert(SuccessorColor && "No parent funclet for catchret!");
1648   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1649   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1650 
1651   // Create the terminator node.
1652   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1653                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1654                             DAG.getBasicBlock(SuccessorColorMBB));
1655   DAG.setRoot(Ret);
1656 }
1657 
1658 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1659   // Don't emit any special code for the cleanuppad instruction. It just marks
1660   // the start of an EH scope/funclet.
1661   FuncInfo.MBB->setIsEHScopeEntry();
1662   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1663   if (Pers != EHPersonality::Wasm_CXX) {
1664     FuncInfo.MBB->setIsEHFuncletEntry();
1665     FuncInfo.MBB->setIsCleanupFuncletEntry();
1666   }
1667 }
1668 
1669 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1670 // the control flow always stops at the single catch pad, as it does for a
1671 // cleanup pad. In case the exception caught is not of the types the catch pad
1672 // catches, it will be rethrown by a rethrow.
1673 static void findWasmUnwindDestinations(
1674     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1675     BranchProbability Prob,
1676     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1677         &UnwindDests) {
1678   while (EHPadBB) {
1679     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1680     if (isa<CleanupPadInst>(Pad)) {
1681       // Stop on cleanup pads.
1682       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1683       UnwindDests.back().first->setIsEHScopeEntry();
1684       break;
1685     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1686       // Add the catchpad handlers to the possible destinations. We don't
1687       // continue to the unwind destination of the catchswitch for wasm.
1688       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1689         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1690         UnwindDests.back().first->setIsEHScopeEntry();
1691       }
1692       break;
1693     } else {
1694       continue;
1695     }
1696   }
1697 }
1698 
1699 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1700 /// many places it could ultimately go. In the IR, we have a single unwind
1701 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1702 /// This function skips over imaginary basic blocks that hold catchswitch
1703 /// instructions, and finds all the "real" machine
1704 /// basic block destinations. As those destinations may not be successors of
1705 /// EHPadBB, here we also calculate the edge probability to those destinations.
1706 /// The passed-in Prob is the edge probability to EHPadBB.
1707 static void findUnwindDestinations(
1708     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1709     BranchProbability Prob,
1710     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1711         &UnwindDests) {
1712   EHPersonality Personality =
1713     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1714   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1715   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1716   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1717   bool IsSEH = isAsynchronousEHPersonality(Personality);
1718 
1719   if (IsWasmCXX) {
1720     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1721     assert(UnwindDests.size() <= 1 &&
1722            "There should be at most one unwind destination for wasm");
1723     return;
1724   }
1725 
1726   while (EHPadBB) {
1727     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1728     BasicBlock *NewEHPadBB = nullptr;
1729     if (isa<LandingPadInst>(Pad)) {
1730       // Stop on landingpads. They are not funclets.
1731       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1732       break;
1733     } else if (isa<CleanupPadInst>(Pad)) {
1734       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1735       // personalities.
1736       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1737       UnwindDests.back().first->setIsEHScopeEntry();
1738       UnwindDests.back().first->setIsEHFuncletEntry();
1739       break;
1740     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1741       // Add the catchpad handlers to the possible destinations.
1742       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1743         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1744         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1745         if (IsMSVCCXX || IsCoreCLR)
1746           UnwindDests.back().first->setIsEHFuncletEntry();
1747         if (!IsSEH)
1748           UnwindDests.back().first->setIsEHScopeEntry();
1749       }
1750       NewEHPadBB = CatchSwitch->getUnwindDest();
1751     } else {
1752       continue;
1753     }
1754 
1755     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1756     if (BPI && NewEHPadBB)
1757       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1758     EHPadBB = NewEHPadBB;
1759   }
1760 }
1761 
1762 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1763   // Update successor info.
1764   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1765   auto UnwindDest = I.getUnwindDest();
1766   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1767   BranchProbability UnwindDestProb =
1768       (BPI && UnwindDest)
1769           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1770           : BranchProbability::getZero();
1771   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1772   for (auto &UnwindDest : UnwindDests) {
1773     UnwindDest.first->setIsEHPad();
1774     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1775   }
1776   FuncInfo.MBB->normalizeSuccProbs();
1777 
1778   // Create the terminator node.
1779   SDValue Ret =
1780       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1781   DAG.setRoot(Ret);
1782 }
1783 
1784 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1785   report_fatal_error("visitCatchSwitch not yet implemented!");
1786 }
1787 
1788 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1790   auto &DL = DAG.getDataLayout();
1791   SDValue Chain = getControlRoot();
1792   SmallVector<ISD::OutputArg, 8> Outs;
1793   SmallVector<SDValue, 8> OutVals;
1794 
1795   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1796   // lower
1797   //
1798   //   %val = call <ty> @llvm.experimental.deoptimize()
1799   //   ret <ty> %val
1800   //
1801   // differently.
1802   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1803     LowerDeoptimizingReturn();
1804     return;
1805   }
1806 
1807   if (!FuncInfo.CanLowerReturn) {
1808     unsigned DemoteReg = FuncInfo.DemoteRegister;
1809     const Function *F = I.getParent()->getParent();
1810 
1811     // Emit a store of the return value through the virtual register.
1812     // Leave Outs empty so that LowerReturn won't try to load return
1813     // registers the usual way.
1814     SmallVector<EVT, 1> PtrValueVTs;
1815     ComputeValueVTs(TLI, DL,
1816                     F->getReturnType()->getPointerTo(
1817                         DAG.getDataLayout().getAllocaAddrSpace()),
1818                     PtrValueVTs);
1819 
1820     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1821                                         DemoteReg, PtrValueVTs[0]);
1822     SDValue RetOp = getValue(I.getOperand(0));
1823 
1824     SmallVector<EVT, 4> ValueVTs, MemVTs;
1825     SmallVector<uint64_t, 4> Offsets;
1826     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1827                     &Offsets);
1828     unsigned NumValues = ValueVTs.size();
1829 
1830     SmallVector<SDValue, 4> Chains(NumValues);
1831     for (unsigned i = 0; i != NumValues; ++i) {
1832       // An aggregate return value cannot wrap around the address space, so
1833       // offsets to its parts don't wrap either.
1834       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1835 
1836       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1837       if (MemVTs[i] != ValueVTs[i])
1838         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1839       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1840           // FIXME: better loc info would be nice.
1841           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1842     }
1843 
1844     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1845                         MVT::Other, Chains);
1846   } else if (I.getNumOperands() != 0) {
1847     SmallVector<EVT, 4> ValueVTs;
1848     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1849     unsigned NumValues = ValueVTs.size();
1850     if (NumValues) {
1851       SDValue RetOp = getValue(I.getOperand(0));
1852 
1853       const Function *F = I.getParent()->getParent();
1854 
1855       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1856           I.getOperand(0)->getType(), F->getCallingConv(),
1857           /*IsVarArg*/ false);
1858 
1859       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1860       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1861                                           Attribute::SExt))
1862         ExtendKind = ISD::SIGN_EXTEND;
1863       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1864                                                Attribute::ZExt))
1865         ExtendKind = ISD::ZERO_EXTEND;
1866 
1867       LLVMContext &Context = F->getContext();
1868       bool RetInReg = F->getAttributes().hasAttribute(
1869           AttributeList::ReturnIndex, Attribute::InReg);
1870 
1871       for (unsigned j = 0; j != NumValues; ++j) {
1872         EVT VT = ValueVTs[j];
1873 
1874         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1875           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1876 
1877         CallingConv::ID CC = F->getCallingConv();
1878 
1879         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1880         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1881         SmallVector<SDValue, 4> Parts(NumParts);
1882         getCopyToParts(DAG, getCurSDLoc(),
1883                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1884                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1885 
1886         // 'inreg' on function refers to return value
1887         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1888         if (RetInReg)
1889           Flags.setInReg();
1890 
1891         if (I.getOperand(0)->getType()->isPointerTy()) {
1892           Flags.setPointer();
1893           Flags.setPointerAddrSpace(
1894               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1895         }
1896 
1897         if (NeedsRegBlock) {
1898           Flags.setInConsecutiveRegs();
1899           if (j == NumValues - 1)
1900             Flags.setInConsecutiveRegsLast();
1901         }
1902 
1903         // Propagate extension type if any
1904         if (ExtendKind == ISD::SIGN_EXTEND)
1905           Flags.setSExt();
1906         else if (ExtendKind == ISD::ZERO_EXTEND)
1907           Flags.setZExt();
1908 
1909         for (unsigned i = 0; i < NumParts; ++i) {
1910           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1911                                         VT, /*isfixed=*/true, 0, 0));
1912           OutVals.push_back(Parts[i]);
1913         }
1914       }
1915     }
1916   }
1917 
1918   // Push in swifterror virtual register as the last element of Outs. This makes
1919   // sure swifterror virtual register will be returned in the swifterror
1920   // physical register.
1921   const Function *F = I.getParent()->getParent();
1922   if (TLI.supportSwiftError() &&
1923       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1924     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1925     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1926     Flags.setSwiftError();
1927     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1928                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1929                                   true /*isfixed*/, 1 /*origidx*/,
1930                                   0 /*partOffs*/));
1931     // Create SDNode for the swifterror virtual register.
1932     OutVals.push_back(
1933         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1934                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1935                         EVT(TLI.getPointerTy(DL))));
1936   }
1937 
1938   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1939   CallingConv::ID CallConv =
1940     DAG.getMachineFunction().getFunction().getCallingConv();
1941   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1942       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1943 
1944   // Verify that the target's LowerReturn behaved as expected.
1945   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1946          "LowerReturn didn't return a valid chain!");
1947 
1948   // Update the DAG with the new chain value resulting from return lowering.
1949   DAG.setRoot(Chain);
1950 }
1951 
1952 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1953 /// created for it, emit nodes to copy the value into the virtual
1954 /// registers.
1955 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1956   // Skip empty types
1957   if (V->getType()->isEmptyTy())
1958     return;
1959 
1960   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1961   if (VMI != FuncInfo.ValueMap.end()) {
1962     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1963     CopyValueToVirtualRegister(V, VMI->second);
1964   }
1965 }
1966 
1967 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1968 /// the current basic block, add it to ValueMap now so that we'll get a
1969 /// CopyTo/FromReg.
1970 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1971   // No need to export constants.
1972   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1973 
1974   // Already exported?
1975   if (FuncInfo.isExportedInst(V)) return;
1976 
1977   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1978   CopyValueToVirtualRegister(V, Reg);
1979 }
1980 
1981 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1982                                                      const BasicBlock *FromBB) {
1983   // The operands of the setcc have to be in this block.  We don't know
1984   // how to export them from some other block.
1985   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1986     // Can export from current BB.
1987     if (VI->getParent() == FromBB)
1988       return true;
1989 
1990     // Is already exported, noop.
1991     return FuncInfo.isExportedInst(V);
1992   }
1993 
1994   // If this is an argument, we can export it if the BB is the entry block or
1995   // if it is already exported.
1996   if (isa<Argument>(V)) {
1997     if (FromBB == &FromBB->getParent()->getEntryBlock())
1998       return true;
1999 
2000     // Otherwise, can only export this if it is already exported.
2001     return FuncInfo.isExportedInst(V);
2002   }
2003 
2004   // Otherwise, constants can always be exported.
2005   return true;
2006 }
2007 
2008 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2009 BranchProbability
2010 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2011                                         const MachineBasicBlock *Dst) const {
2012   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2013   const BasicBlock *SrcBB = Src->getBasicBlock();
2014   const BasicBlock *DstBB = Dst->getBasicBlock();
2015   if (!BPI) {
2016     // If BPI is not available, set the default probability as 1 / N, where N is
2017     // the number of successors.
2018     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2019     return BranchProbability(1, SuccSize);
2020   }
2021   return BPI->getEdgeProbability(SrcBB, DstBB);
2022 }
2023 
2024 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2025                                                MachineBasicBlock *Dst,
2026                                                BranchProbability Prob) {
2027   if (!FuncInfo.BPI)
2028     Src->addSuccessorWithoutProb(Dst);
2029   else {
2030     if (Prob.isUnknown())
2031       Prob = getEdgeProbability(Src, Dst);
2032     Src->addSuccessor(Dst, Prob);
2033   }
2034 }
2035 
2036 static bool InBlock(const Value *V, const BasicBlock *BB) {
2037   if (const Instruction *I = dyn_cast<Instruction>(V))
2038     return I->getParent() == BB;
2039   return true;
2040 }
2041 
2042 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2043 /// This function emits a branch and is used at the leaves of an OR or an
2044 /// AND operator tree.
2045 void
2046 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2047                                                   MachineBasicBlock *TBB,
2048                                                   MachineBasicBlock *FBB,
2049                                                   MachineBasicBlock *CurBB,
2050                                                   MachineBasicBlock *SwitchBB,
2051                                                   BranchProbability TProb,
2052                                                   BranchProbability FProb,
2053                                                   bool InvertCond) {
2054   const BasicBlock *BB = CurBB->getBasicBlock();
2055 
2056   // If the leaf of the tree is a comparison, merge the condition into
2057   // the caseblock.
2058   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2059     // The operands of the cmp have to be in this block.  We don't know
2060     // how to export them from some other block.  If this is the first block
2061     // of the sequence, no exporting is needed.
2062     if (CurBB == SwitchBB ||
2063         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2064          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2065       ISD::CondCode Condition;
2066       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2067         ICmpInst::Predicate Pred =
2068             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2069         Condition = getICmpCondCode(Pred);
2070       } else {
2071         const FCmpInst *FC = cast<FCmpInst>(Cond);
2072         FCmpInst::Predicate Pred =
2073             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2074         Condition = getFCmpCondCode(Pred);
2075         if (TM.Options.NoNaNsFPMath)
2076           Condition = getFCmpCodeWithoutNaN(Condition);
2077       }
2078 
2079       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2080                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2081       SL->SwitchCases.push_back(CB);
2082       return;
2083     }
2084   }
2085 
2086   // Create a CaseBlock record representing this branch.
2087   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2088   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2089                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2090   SL->SwitchCases.push_back(CB);
2091 }
2092 
2093 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2094                                                MachineBasicBlock *TBB,
2095                                                MachineBasicBlock *FBB,
2096                                                MachineBasicBlock *CurBB,
2097                                                MachineBasicBlock *SwitchBB,
2098                                                Instruction::BinaryOps Opc,
2099                                                BranchProbability TProb,
2100                                                BranchProbability FProb,
2101                                                bool InvertCond) {
2102   // Skip over not part of the tree and remember to invert op and operands at
2103   // next level.
2104   Value *NotCond;
2105   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2106       InBlock(NotCond, CurBB->getBasicBlock())) {
2107     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2108                          !InvertCond);
2109     return;
2110   }
2111 
2112   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2113   // Compute the effective opcode for Cond, taking into account whether it needs
2114   // to be inverted, e.g.
2115   //   and (not (or A, B)), C
2116   // gets lowered as
2117   //   and (and (not A, not B), C)
2118   unsigned BOpc = 0;
2119   if (BOp) {
2120     BOpc = BOp->getOpcode();
2121     if (InvertCond) {
2122       if (BOpc == Instruction::And)
2123         BOpc = Instruction::Or;
2124       else if (BOpc == Instruction::Or)
2125         BOpc = Instruction::And;
2126     }
2127   }
2128 
2129   // If this node is not part of the or/and tree, emit it as a branch.
2130   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2131       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2132       BOp->getParent() != CurBB->getBasicBlock() ||
2133       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2134       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2135     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2136                                  TProb, FProb, InvertCond);
2137     return;
2138   }
2139 
2140   //  Create TmpBB after CurBB.
2141   MachineFunction::iterator BBI(CurBB);
2142   MachineFunction &MF = DAG.getMachineFunction();
2143   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2144   CurBB->getParent()->insert(++BBI, TmpBB);
2145 
2146   if (Opc == Instruction::Or) {
2147     // Codegen X | Y as:
2148     // BB1:
2149     //   jmp_if_X TBB
2150     //   jmp TmpBB
2151     // TmpBB:
2152     //   jmp_if_Y TBB
2153     //   jmp FBB
2154     //
2155 
2156     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2157     // The requirement is that
2158     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2159     //     = TrueProb for original BB.
2160     // Assuming the original probabilities are A and B, one choice is to set
2161     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2162     // A/(1+B) and 2B/(1+B). This choice assumes that
2163     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2164     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2165     // TmpBB, but the math is more complicated.
2166 
2167     auto NewTrueProb = TProb / 2;
2168     auto NewFalseProb = TProb / 2 + FProb;
2169     // Emit the LHS condition.
2170     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2171                          NewTrueProb, NewFalseProb, InvertCond);
2172 
2173     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2174     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2175     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2176     // Emit the RHS condition into TmpBB.
2177     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2178                          Probs[0], Probs[1], InvertCond);
2179   } else {
2180     assert(Opc == Instruction::And && "Unknown merge op!");
2181     // Codegen X & Y as:
2182     // BB1:
2183     //   jmp_if_X TmpBB
2184     //   jmp FBB
2185     // TmpBB:
2186     //   jmp_if_Y TBB
2187     //   jmp FBB
2188     //
2189     //  This requires creation of TmpBB after CurBB.
2190 
2191     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2192     // The requirement is that
2193     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2194     //     = FalseProb for original BB.
2195     // Assuming the original probabilities are A and B, one choice is to set
2196     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2197     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2198     // TrueProb for BB1 * FalseProb for TmpBB.
2199 
2200     auto NewTrueProb = TProb + FProb / 2;
2201     auto NewFalseProb = FProb / 2;
2202     // Emit the LHS condition.
2203     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2204                          NewTrueProb, NewFalseProb, InvertCond);
2205 
2206     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2207     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2208     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2209     // Emit the RHS condition into TmpBB.
2210     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2211                          Probs[0], Probs[1], InvertCond);
2212   }
2213 }
2214 
2215 /// If the set of cases should be emitted as a series of branches, return true.
2216 /// If we should emit this as a bunch of and/or'd together conditions, return
2217 /// false.
2218 bool
2219 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2220   if (Cases.size() != 2) return true;
2221 
2222   // If this is two comparisons of the same values or'd or and'd together, they
2223   // will get folded into a single comparison, so don't emit two blocks.
2224   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2225        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2226       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2227        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2228     return false;
2229   }
2230 
2231   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2232   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2233   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2234       Cases[0].CC == Cases[1].CC &&
2235       isa<Constant>(Cases[0].CmpRHS) &&
2236       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2237     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2238       return false;
2239     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2240       return false;
2241   }
2242 
2243   return true;
2244 }
2245 
2246 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2247   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2248 
2249   // Update machine-CFG edges.
2250   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2251 
2252   if (I.isUnconditional()) {
2253     // Update machine-CFG edges.
2254     BrMBB->addSuccessor(Succ0MBB);
2255 
2256     // If this is not a fall-through branch or optimizations are switched off,
2257     // emit the branch.
2258     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2259       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2260                               MVT::Other, getControlRoot(),
2261                               DAG.getBasicBlock(Succ0MBB)));
2262 
2263     return;
2264   }
2265 
2266   // If this condition is one of the special cases we handle, do special stuff
2267   // now.
2268   const Value *CondVal = I.getCondition();
2269   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2270 
2271   // If this is a series of conditions that are or'd or and'd together, emit
2272   // this as a sequence of branches instead of setcc's with and/or operations.
2273   // As long as jumps are not expensive, this should improve performance.
2274   // For example, instead of something like:
2275   //     cmp A, B
2276   //     C = seteq
2277   //     cmp D, E
2278   //     F = setle
2279   //     or C, F
2280   //     jnz foo
2281   // Emit:
2282   //     cmp A, B
2283   //     je foo
2284   //     cmp D, E
2285   //     jle foo
2286   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2287     Instruction::BinaryOps Opcode = BOp->getOpcode();
2288     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2289         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2290         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2291       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2292                            Opcode,
2293                            getEdgeProbability(BrMBB, Succ0MBB),
2294                            getEdgeProbability(BrMBB, Succ1MBB),
2295                            /*InvertCond=*/false);
2296       // If the compares in later blocks need to use values not currently
2297       // exported from this block, export them now.  This block should always
2298       // be the first entry.
2299       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2300 
2301       // Allow some cases to be rejected.
2302       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2303         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2304           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2305           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2306         }
2307 
2308         // Emit the branch for this block.
2309         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2310         SL->SwitchCases.erase(SL->SwitchCases.begin());
2311         return;
2312       }
2313 
2314       // Okay, we decided not to do this, remove any inserted MBB's and clear
2315       // SwitchCases.
2316       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2317         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2318 
2319       SL->SwitchCases.clear();
2320     }
2321   }
2322 
2323   // Create a CaseBlock record representing this branch.
2324   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2325                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2326 
2327   // Use visitSwitchCase to actually insert the fast branch sequence for this
2328   // cond branch.
2329   visitSwitchCase(CB, BrMBB);
2330 }
2331 
2332 /// visitSwitchCase - Emits the necessary code to represent a single node in
2333 /// the binary search tree resulting from lowering a switch instruction.
2334 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2335                                           MachineBasicBlock *SwitchBB) {
2336   SDValue Cond;
2337   SDValue CondLHS = getValue(CB.CmpLHS);
2338   SDLoc dl = CB.DL;
2339 
2340   if (CB.CC == ISD::SETTRUE) {
2341     // Branch or fall through to TrueBB.
2342     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2343     SwitchBB->normalizeSuccProbs();
2344     if (CB.TrueBB != NextBlock(SwitchBB)) {
2345       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2346                               DAG.getBasicBlock(CB.TrueBB)));
2347     }
2348     return;
2349   }
2350 
2351   auto &TLI = DAG.getTargetLoweringInfo();
2352   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2353 
2354   // Build the setcc now.
2355   if (!CB.CmpMHS) {
2356     // Fold "(X == true)" to X and "(X == false)" to !X to
2357     // handle common cases produced by branch lowering.
2358     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2359         CB.CC == ISD::SETEQ)
2360       Cond = CondLHS;
2361     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2362              CB.CC == ISD::SETEQ) {
2363       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2364       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2365     } else {
2366       SDValue CondRHS = getValue(CB.CmpRHS);
2367 
2368       // If a pointer's DAG type is larger than its memory type then the DAG
2369       // values are zero-extended. This breaks signed comparisons so truncate
2370       // back to the underlying type before doing the compare.
2371       if (CondLHS.getValueType() != MemVT) {
2372         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2373         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2374       }
2375       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2376     }
2377   } else {
2378     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2379 
2380     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2381     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2382 
2383     SDValue CmpOp = getValue(CB.CmpMHS);
2384     EVT VT = CmpOp.getValueType();
2385 
2386     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2387       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2388                           ISD::SETLE);
2389     } else {
2390       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2391                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2392       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2393                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2394     }
2395   }
2396 
2397   // Update successor info
2398   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2399   // TrueBB and FalseBB are always different unless the incoming IR is
2400   // degenerate. This only happens when running llc on weird IR.
2401   if (CB.TrueBB != CB.FalseBB)
2402     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2403   SwitchBB->normalizeSuccProbs();
2404 
2405   // If the lhs block is the next block, invert the condition so that we can
2406   // fall through to the lhs instead of the rhs block.
2407   if (CB.TrueBB == NextBlock(SwitchBB)) {
2408     std::swap(CB.TrueBB, CB.FalseBB);
2409     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2410     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2411   }
2412 
2413   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2414                                MVT::Other, getControlRoot(), Cond,
2415                                DAG.getBasicBlock(CB.TrueBB));
2416 
2417   // Insert the false branch. Do this even if it's a fall through branch,
2418   // this makes it easier to do DAG optimizations which require inverting
2419   // the branch condition.
2420   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2421                        DAG.getBasicBlock(CB.FalseBB));
2422 
2423   DAG.setRoot(BrCond);
2424 }
2425 
2426 /// visitJumpTable - Emit JumpTable node in the current MBB
2427 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2428   // Emit the code for the jump table
2429   assert(JT.Reg != -1U && "Should lower JT Header first!");
2430   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2431   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2432                                      JT.Reg, PTy);
2433   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2434   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2435                                     MVT::Other, Index.getValue(1),
2436                                     Table, Index);
2437   DAG.setRoot(BrJumpTable);
2438 }
2439 
2440 /// visitJumpTableHeader - This function emits necessary code to produce index
2441 /// in the JumpTable from switch case.
2442 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2443                                                JumpTableHeader &JTH,
2444                                                MachineBasicBlock *SwitchBB) {
2445   SDLoc dl = getCurSDLoc();
2446 
2447   // Subtract the lowest switch case value from the value being switched on.
2448   SDValue SwitchOp = getValue(JTH.SValue);
2449   EVT VT = SwitchOp.getValueType();
2450   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2451                             DAG.getConstant(JTH.First, dl, VT));
2452 
2453   // The SDNode we just created, which holds the value being switched on minus
2454   // the smallest case value, needs to be copied to a virtual register so it
2455   // can be used as an index into the jump table in a subsequent basic block.
2456   // This value may be smaller or larger than the target's pointer type, and
2457   // therefore require extension or truncating.
2458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2459   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2460 
2461   unsigned JumpTableReg =
2462       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2463   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2464                                     JumpTableReg, SwitchOp);
2465   JT.Reg = JumpTableReg;
2466 
2467   if (!JTH.OmitRangeCheck) {
2468     // Emit the range check for the jump table, and branch to the default block
2469     // for the switch statement if the value being switched on exceeds the
2470     // largest case in the switch.
2471     SDValue CMP = DAG.getSetCC(
2472         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2473                                    Sub.getValueType()),
2474         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2475 
2476     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2477                                  MVT::Other, CopyTo, CMP,
2478                                  DAG.getBasicBlock(JT.Default));
2479 
2480     // Avoid emitting unnecessary branches to the next block.
2481     if (JT.MBB != NextBlock(SwitchBB))
2482       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2483                            DAG.getBasicBlock(JT.MBB));
2484 
2485     DAG.setRoot(BrCond);
2486   } else {
2487     // Avoid emitting unnecessary branches to the next block.
2488     if (JT.MBB != NextBlock(SwitchBB))
2489       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2490                               DAG.getBasicBlock(JT.MBB)));
2491     else
2492       DAG.setRoot(CopyTo);
2493   }
2494 }
2495 
2496 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2497 /// variable if there exists one.
2498 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2499                                  SDValue &Chain) {
2500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2501   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2502   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2503   MachineFunction &MF = DAG.getMachineFunction();
2504   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2505   MachineSDNode *Node =
2506       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2507   if (Global) {
2508     MachinePointerInfo MPInfo(Global);
2509     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2510                  MachineMemOperand::MODereferenceable;
2511     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2512         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2513     DAG.setNodeMemRefs(Node, {MemRef});
2514   }
2515   if (PtrTy != PtrMemTy)
2516     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2517   return SDValue(Node, 0);
2518 }
2519 
2520 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2521 /// tail spliced into a stack protector check success bb.
2522 ///
2523 /// For a high level explanation of how this fits into the stack protector
2524 /// generation see the comment on the declaration of class
2525 /// StackProtectorDescriptor.
2526 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2527                                                   MachineBasicBlock *ParentBB) {
2528 
2529   // First create the loads to the guard/stack slot for the comparison.
2530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2531   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2532   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2533 
2534   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2535   int FI = MFI.getStackProtectorIndex();
2536 
2537   SDValue Guard;
2538   SDLoc dl = getCurSDLoc();
2539   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2540   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2541   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2542 
2543   // Generate code to load the content of the guard slot.
2544   SDValue GuardVal = DAG.getLoad(
2545       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2546       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2547       MachineMemOperand::MOVolatile);
2548 
2549   if (TLI.useStackGuardXorFP())
2550     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2551 
2552   // Retrieve guard check function, nullptr if instrumentation is inlined.
2553   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2554     // The target provides a guard check function to validate the guard value.
2555     // Generate a call to that function with the content of the guard slot as
2556     // argument.
2557     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2558     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2559 
2560     TargetLowering::ArgListTy Args;
2561     TargetLowering::ArgListEntry Entry;
2562     Entry.Node = GuardVal;
2563     Entry.Ty = FnTy->getParamType(0);
2564     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2565       Entry.IsInReg = true;
2566     Args.push_back(Entry);
2567 
2568     TargetLowering::CallLoweringInfo CLI(DAG);
2569     CLI.setDebugLoc(getCurSDLoc())
2570         .setChain(DAG.getEntryNode())
2571         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2572                    getValue(GuardCheckFn), std::move(Args));
2573 
2574     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2575     DAG.setRoot(Result.second);
2576     return;
2577   }
2578 
2579   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2580   // Otherwise, emit a volatile load to retrieve the stack guard value.
2581   SDValue Chain = DAG.getEntryNode();
2582   if (TLI.useLoadStackGuardNode()) {
2583     Guard = getLoadStackGuard(DAG, dl, Chain);
2584   } else {
2585     const Value *IRGuard = TLI.getSDagStackGuard(M);
2586     SDValue GuardPtr = getValue(IRGuard);
2587 
2588     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2589                         MachinePointerInfo(IRGuard, 0), Align,
2590                         MachineMemOperand::MOVolatile);
2591   }
2592 
2593   // Perform the comparison via a getsetcc.
2594   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2595                                                         *DAG.getContext(),
2596                                                         Guard.getValueType()),
2597                              Guard, GuardVal, ISD::SETNE);
2598 
2599   // If the guard/stackslot do not equal, branch to failure MBB.
2600   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2601                                MVT::Other, GuardVal.getOperand(0),
2602                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2603   // Otherwise branch to success MBB.
2604   SDValue Br = DAG.getNode(ISD::BR, dl,
2605                            MVT::Other, BrCond,
2606                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2607 
2608   DAG.setRoot(Br);
2609 }
2610 
2611 /// Codegen the failure basic block for a stack protector check.
2612 ///
2613 /// A failure stack protector machine basic block consists simply of a call to
2614 /// __stack_chk_fail().
2615 ///
2616 /// For a high level explanation of how this fits into the stack protector
2617 /// generation see the comment on the declaration of class
2618 /// StackProtectorDescriptor.
2619 void
2620 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2622   TargetLowering::MakeLibCallOptions CallOptions;
2623   CallOptions.setDiscardResult(true);
2624   SDValue Chain =
2625       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2626                       None, CallOptions, getCurSDLoc()).second;
2627   // On PS4, the "return address" must still be within the calling function,
2628   // even if it's at the very end, so emit an explicit TRAP here.
2629   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2630   if (TM.getTargetTriple().isPS4CPU())
2631     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2632 
2633   DAG.setRoot(Chain);
2634 }
2635 
2636 /// visitBitTestHeader - This function emits necessary code to produce value
2637 /// suitable for "bit tests"
2638 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2639                                              MachineBasicBlock *SwitchBB) {
2640   SDLoc dl = getCurSDLoc();
2641 
2642   // Subtract the minimum value.
2643   SDValue SwitchOp = getValue(B.SValue);
2644   EVT VT = SwitchOp.getValueType();
2645   SDValue RangeSub =
2646       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2647 
2648   // Determine the type of the test operands.
2649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2650   bool UsePtrType = false;
2651   if (!TLI.isTypeLegal(VT)) {
2652     UsePtrType = true;
2653   } else {
2654     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2655       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2656         // Switch table case range are encoded into series of masks.
2657         // Just use pointer type, it's guaranteed to fit.
2658         UsePtrType = true;
2659         break;
2660       }
2661   }
2662   SDValue Sub = RangeSub;
2663   if (UsePtrType) {
2664     VT = TLI.getPointerTy(DAG.getDataLayout());
2665     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2666   }
2667 
2668   B.RegVT = VT.getSimpleVT();
2669   B.Reg = FuncInfo.CreateReg(B.RegVT);
2670   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2671 
2672   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2673 
2674   if (!B.OmitRangeCheck)
2675     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2676   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2677   SwitchBB->normalizeSuccProbs();
2678 
2679   SDValue Root = CopyTo;
2680   if (!B.OmitRangeCheck) {
2681     // Conditional branch to the default block.
2682     SDValue RangeCmp = DAG.getSetCC(dl,
2683         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2684                                RangeSub.getValueType()),
2685         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2686         ISD::SETUGT);
2687 
2688     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2689                        DAG.getBasicBlock(B.Default));
2690   }
2691 
2692   // Avoid emitting unnecessary branches to the next block.
2693   if (MBB != NextBlock(SwitchBB))
2694     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2695 
2696   DAG.setRoot(Root);
2697 }
2698 
2699 /// visitBitTestCase - this function produces one "bit test"
2700 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2701                                            MachineBasicBlock* NextMBB,
2702                                            BranchProbability BranchProbToNext,
2703                                            unsigned Reg,
2704                                            BitTestCase &B,
2705                                            MachineBasicBlock *SwitchBB) {
2706   SDLoc dl = getCurSDLoc();
2707   MVT VT = BB.RegVT;
2708   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2709   SDValue Cmp;
2710   unsigned PopCount = countPopulation(B.Mask);
2711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2712   if (PopCount == 1) {
2713     // Testing for a single bit; just compare the shift count with what it
2714     // would need to be to shift a 1 bit in that position.
2715     Cmp = DAG.getSetCC(
2716         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2717         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2718         ISD::SETEQ);
2719   } else if (PopCount == BB.Range) {
2720     // There is only one zero bit in the range, test for it directly.
2721     Cmp = DAG.getSetCC(
2722         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2723         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2724         ISD::SETNE);
2725   } else {
2726     // Make desired shift
2727     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2728                                     DAG.getConstant(1, dl, VT), ShiftOp);
2729 
2730     // Emit bit tests and jumps
2731     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2732                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2733     Cmp = DAG.getSetCC(
2734         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2735         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2736   }
2737 
2738   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2739   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2740   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2741   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2742   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2743   // one as they are relative probabilities (and thus work more like weights),
2744   // and hence we need to normalize them to let the sum of them become one.
2745   SwitchBB->normalizeSuccProbs();
2746 
2747   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2748                               MVT::Other, getControlRoot(),
2749                               Cmp, DAG.getBasicBlock(B.TargetBB));
2750 
2751   // Avoid emitting unnecessary branches to the next block.
2752   if (NextMBB != NextBlock(SwitchBB))
2753     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2754                         DAG.getBasicBlock(NextMBB));
2755 
2756   DAG.setRoot(BrAnd);
2757 }
2758 
2759 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2760   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2761 
2762   // Retrieve successors. Look through artificial IR level blocks like
2763   // catchswitch for successors.
2764   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2765   const BasicBlock *EHPadBB = I.getSuccessor(1);
2766 
2767   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2768   // have to do anything here to lower funclet bundles.
2769   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2770                                         LLVMContext::OB_funclet,
2771                                         LLVMContext::OB_cfguardtarget}) &&
2772          "Cannot lower invokes with arbitrary operand bundles yet!");
2773 
2774   const Value *Callee(I.getCalledValue());
2775   const Function *Fn = dyn_cast<Function>(Callee);
2776   if (isa<InlineAsm>(Callee))
2777     visitInlineAsm(I);
2778   else if (Fn && Fn->isIntrinsic()) {
2779     switch (Fn->getIntrinsicID()) {
2780     default:
2781       llvm_unreachable("Cannot invoke this intrinsic");
2782     case Intrinsic::donothing:
2783       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2784       break;
2785     case Intrinsic::experimental_patchpoint_void:
2786     case Intrinsic::experimental_patchpoint_i64:
2787       visitPatchpoint(I, EHPadBB);
2788       break;
2789     case Intrinsic::experimental_gc_statepoint:
2790       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2791       break;
2792     case Intrinsic::wasm_rethrow_in_catch: {
2793       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2794       // special because it can be invoked, so we manually lower it to a DAG
2795       // node here.
2796       SmallVector<SDValue, 8> Ops;
2797       Ops.push_back(getRoot()); // inchain
2798       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2799       Ops.push_back(
2800           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2801                                 TLI.getPointerTy(DAG.getDataLayout())));
2802       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2803       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2804       break;
2805     }
2806     }
2807   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2808     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2809     // Eventually we will support lowering the @llvm.experimental.deoptimize
2810     // intrinsic, and right now there are no plans to support other intrinsics
2811     // with deopt state.
2812     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2813   } else {
2814     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2815   }
2816 
2817   // If the value of the invoke is used outside of its defining block, make it
2818   // available as a virtual register.
2819   // We already took care of the exported value for the statepoint instruction
2820   // during call to the LowerStatepoint.
2821   if (!isStatepoint(I)) {
2822     CopyToExportRegsIfNeeded(&I);
2823   }
2824 
2825   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2826   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2827   BranchProbability EHPadBBProb =
2828       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2829           : BranchProbability::getZero();
2830   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2831 
2832   // Update successor info.
2833   addSuccessorWithProb(InvokeMBB, Return);
2834   for (auto &UnwindDest : UnwindDests) {
2835     UnwindDest.first->setIsEHPad();
2836     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2837   }
2838   InvokeMBB->normalizeSuccProbs();
2839 
2840   // Drop into normal successor.
2841   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2842                           DAG.getBasicBlock(Return)));
2843 }
2844 
2845 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2846   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2847 
2848   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2849   // have to do anything here to lower funclet bundles.
2850   assert(!I.hasOperandBundlesOtherThan(
2851              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2852          "Cannot lower callbrs with arbitrary operand bundles yet!");
2853 
2854   assert(isa<InlineAsm>(I.getCalledValue()) &&
2855          "Only know how to handle inlineasm callbr");
2856   visitInlineAsm(I);
2857   CopyToExportRegsIfNeeded(&I);
2858 
2859   // Retrieve successors.
2860   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2861   Return->setInlineAsmBrDefaultTarget();
2862 
2863   // Update successor info.
2864   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2865   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2866     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2867     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2868     CallBrMBB->addInlineAsmBrIndirectTarget(Target);
2869   }
2870   CallBrMBB->normalizeSuccProbs();
2871 
2872   // Drop into default successor.
2873   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2874                           MVT::Other, getControlRoot(),
2875                           DAG.getBasicBlock(Return)));
2876 }
2877 
2878 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2879   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2880 }
2881 
2882 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2883   assert(FuncInfo.MBB->isEHPad() &&
2884          "Call to landingpad not in landing pad!");
2885 
2886   // If there aren't registers to copy the values into (e.g., during SjLj
2887   // exceptions), then don't bother to create these DAG nodes.
2888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2889   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2890   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2891       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2892     return;
2893 
2894   // If landingpad's return type is token type, we don't create DAG nodes
2895   // for its exception pointer and selector value. The extraction of exception
2896   // pointer or selector value from token type landingpads is not currently
2897   // supported.
2898   if (LP.getType()->isTokenTy())
2899     return;
2900 
2901   SmallVector<EVT, 2> ValueVTs;
2902   SDLoc dl = getCurSDLoc();
2903   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2904   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2905 
2906   // Get the two live-in registers as SDValues. The physregs have already been
2907   // copied into virtual registers.
2908   SDValue Ops[2];
2909   if (FuncInfo.ExceptionPointerVirtReg) {
2910     Ops[0] = DAG.getZExtOrTrunc(
2911         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2912                            FuncInfo.ExceptionPointerVirtReg,
2913                            TLI.getPointerTy(DAG.getDataLayout())),
2914         dl, ValueVTs[0]);
2915   } else {
2916     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2917   }
2918   Ops[1] = DAG.getZExtOrTrunc(
2919       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2920                          FuncInfo.ExceptionSelectorVirtReg,
2921                          TLI.getPointerTy(DAG.getDataLayout())),
2922       dl, ValueVTs[1]);
2923 
2924   // Merge into one.
2925   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2926                             DAG.getVTList(ValueVTs), Ops);
2927   setValue(&LP, Res);
2928 }
2929 
2930 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2931                                            MachineBasicBlock *Last) {
2932   // Update JTCases.
2933   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2934     if (SL->JTCases[i].first.HeaderBB == First)
2935       SL->JTCases[i].first.HeaderBB = Last;
2936 
2937   // Update BitTestCases.
2938   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2939     if (SL->BitTestCases[i].Parent == First)
2940       SL->BitTestCases[i].Parent = Last;
2941 
2942   // SelectionDAGISel::FinishBasicBlock will add PHI operands for the
2943   // successors of the fallthrough block. Here, we add PHI operands for the
2944   // successors of the INLINEASM_BR block itself.
2945   if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR)
2946     for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate)
2947       if (First->isSuccessor(pair.first->getParent()))
2948         MachineInstrBuilder(*First->getParent(), pair.first)
2949             .addReg(pair.second)
2950             .addMBB(First);
2951 }
2952 
2953 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2954   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2955 
2956   // Update machine-CFG edges with unique successors.
2957   SmallSet<BasicBlock*, 32> Done;
2958   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2959     BasicBlock *BB = I.getSuccessor(i);
2960     bool Inserted = Done.insert(BB).second;
2961     if (!Inserted)
2962         continue;
2963 
2964     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2965     addSuccessorWithProb(IndirectBrMBB, Succ);
2966   }
2967   IndirectBrMBB->normalizeSuccProbs();
2968 
2969   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2970                           MVT::Other, getControlRoot(),
2971                           getValue(I.getAddress())));
2972 }
2973 
2974 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2975   if (!DAG.getTarget().Options.TrapUnreachable)
2976     return;
2977 
2978   // We may be able to ignore unreachable behind a noreturn call.
2979   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2980     const BasicBlock &BB = *I.getParent();
2981     if (&I != &BB.front()) {
2982       BasicBlock::const_iterator PredI =
2983         std::prev(BasicBlock::const_iterator(&I));
2984       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2985         if (Call->doesNotReturn())
2986           return;
2987       }
2988     }
2989   }
2990 
2991   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2992 }
2993 
2994 void SelectionDAGBuilder::visitFSub(const User &I) {
2995   // -0.0 - X --> fneg
2996   Type *Ty = I.getType();
2997   if (isa<Constant>(I.getOperand(0)) &&
2998       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2999     SDValue Op2 = getValue(I.getOperand(1));
3000     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3001                              Op2.getValueType(), Op2));
3002     return;
3003   }
3004 
3005   visitBinary(I, ISD::FSUB);
3006 }
3007 
3008 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3009   SDNodeFlags Flags;
3010 
3011   SDValue Op = getValue(I.getOperand(0));
3012   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3013                                     Op, Flags);
3014   setValue(&I, UnNodeValue);
3015 }
3016 
3017 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3018   SDNodeFlags Flags;
3019   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3020     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3021     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3022   }
3023   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3024     Flags.setExact(ExactOp->isExact());
3025   }
3026 
3027   SDValue Op1 = getValue(I.getOperand(0));
3028   SDValue Op2 = getValue(I.getOperand(1));
3029   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3030                                      Op1, Op2, Flags);
3031   setValue(&I, BinNodeValue);
3032 }
3033 
3034 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3035   SDValue Op1 = getValue(I.getOperand(0));
3036   SDValue Op2 = getValue(I.getOperand(1));
3037 
3038   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3039       Op1.getValueType(), DAG.getDataLayout());
3040 
3041   // Coerce the shift amount to the right type if we can.
3042   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3043     unsigned ShiftSize = ShiftTy.getSizeInBits();
3044     unsigned Op2Size = Op2.getValueSizeInBits();
3045     SDLoc DL = getCurSDLoc();
3046 
3047     // If the operand is smaller than the shift count type, promote it.
3048     if (ShiftSize > Op2Size)
3049       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3050 
3051     // If the operand is larger than the shift count type but the shift
3052     // count type has enough bits to represent any shift value, truncate
3053     // it now. This is a common case and it exposes the truncate to
3054     // optimization early.
3055     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3056       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3057     // Otherwise we'll need to temporarily settle for some other convenient
3058     // type.  Type legalization will make adjustments once the shiftee is split.
3059     else
3060       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3061   }
3062 
3063   bool nuw = false;
3064   bool nsw = false;
3065   bool exact = false;
3066 
3067   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3068 
3069     if (const OverflowingBinaryOperator *OFBinOp =
3070             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3071       nuw = OFBinOp->hasNoUnsignedWrap();
3072       nsw = OFBinOp->hasNoSignedWrap();
3073     }
3074     if (const PossiblyExactOperator *ExactOp =
3075             dyn_cast<const PossiblyExactOperator>(&I))
3076       exact = ExactOp->isExact();
3077   }
3078   SDNodeFlags Flags;
3079   Flags.setExact(exact);
3080   Flags.setNoSignedWrap(nsw);
3081   Flags.setNoUnsignedWrap(nuw);
3082   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3083                             Flags);
3084   setValue(&I, Res);
3085 }
3086 
3087 void SelectionDAGBuilder::visitSDiv(const User &I) {
3088   SDValue Op1 = getValue(I.getOperand(0));
3089   SDValue Op2 = getValue(I.getOperand(1));
3090 
3091   SDNodeFlags Flags;
3092   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3093                  cast<PossiblyExactOperator>(&I)->isExact());
3094   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3095                            Op2, Flags));
3096 }
3097 
3098 void SelectionDAGBuilder::visitICmp(const User &I) {
3099   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3100   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3101     predicate = IC->getPredicate();
3102   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3103     predicate = ICmpInst::Predicate(IC->getPredicate());
3104   SDValue Op1 = getValue(I.getOperand(0));
3105   SDValue Op2 = getValue(I.getOperand(1));
3106   ISD::CondCode Opcode = getICmpCondCode(predicate);
3107 
3108   auto &TLI = DAG.getTargetLoweringInfo();
3109   EVT MemVT =
3110       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3111 
3112   // If a pointer's DAG type is larger than its memory type then the DAG values
3113   // are zero-extended. This breaks signed comparisons so truncate back to the
3114   // underlying type before doing the compare.
3115   if (Op1.getValueType() != MemVT) {
3116     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3117     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3118   }
3119 
3120   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3121                                                         I.getType());
3122   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3123 }
3124 
3125 void SelectionDAGBuilder::visitFCmp(const User &I) {
3126   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3127   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3128     predicate = FC->getPredicate();
3129   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3130     predicate = FCmpInst::Predicate(FC->getPredicate());
3131   SDValue Op1 = getValue(I.getOperand(0));
3132   SDValue Op2 = getValue(I.getOperand(1));
3133 
3134   ISD::CondCode Condition = getFCmpCondCode(predicate);
3135   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3136   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3137     Condition = getFCmpCodeWithoutNaN(Condition);
3138 
3139   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3140                                                         I.getType());
3141   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3142 }
3143 
3144 // Check if the condition of the select has one use or two users that are both
3145 // selects with the same condition.
3146 static bool hasOnlySelectUsers(const Value *Cond) {
3147   return llvm::all_of(Cond->users(), [](const Value *V) {
3148     return isa<SelectInst>(V);
3149   });
3150 }
3151 
3152 void SelectionDAGBuilder::visitSelect(const User &I) {
3153   SmallVector<EVT, 4> ValueVTs;
3154   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3155                   ValueVTs);
3156   unsigned NumValues = ValueVTs.size();
3157   if (NumValues == 0) return;
3158 
3159   SmallVector<SDValue, 4> Values(NumValues);
3160   SDValue Cond     = getValue(I.getOperand(0));
3161   SDValue LHSVal   = getValue(I.getOperand(1));
3162   SDValue RHSVal   = getValue(I.getOperand(2));
3163   SmallVector<SDValue, 1> BaseOps(1, Cond);
3164   ISD::NodeType OpCode =
3165       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3166 
3167   bool IsUnaryAbs = false;
3168 
3169   // Min/max matching is only viable if all output VTs are the same.
3170   if (is_splat(ValueVTs)) {
3171     EVT VT = ValueVTs[0];
3172     LLVMContext &Ctx = *DAG.getContext();
3173     auto &TLI = DAG.getTargetLoweringInfo();
3174 
3175     // We care about the legality of the operation after it has been type
3176     // legalized.
3177     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3178       VT = TLI.getTypeToTransformTo(Ctx, VT);
3179 
3180     // If the vselect is legal, assume we want to leave this as a vector setcc +
3181     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3182     // min/max is legal on the scalar type.
3183     bool UseScalarMinMax = VT.isVector() &&
3184       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3185 
3186     Value *LHS, *RHS;
3187     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3188     ISD::NodeType Opc = ISD::DELETED_NODE;
3189     switch (SPR.Flavor) {
3190     case SPF_UMAX:    Opc = ISD::UMAX; break;
3191     case SPF_UMIN:    Opc = ISD::UMIN; break;
3192     case SPF_SMAX:    Opc = ISD::SMAX; break;
3193     case SPF_SMIN:    Opc = ISD::SMIN; break;
3194     case SPF_FMINNUM:
3195       switch (SPR.NaNBehavior) {
3196       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3197       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3198       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3199       case SPNB_RETURNS_ANY: {
3200         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3201           Opc = ISD::FMINNUM;
3202         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3203           Opc = ISD::FMINIMUM;
3204         else if (UseScalarMinMax)
3205           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3206             ISD::FMINNUM : ISD::FMINIMUM;
3207         break;
3208       }
3209       }
3210       break;
3211     case SPF_FMAXNUM:
3212       switch (SPR.NaNBehavior) {
3213       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3214       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3215       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3216       case SPNB_RETURNS_ANY:
3217 
3218         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3219           Opc = ISD::FMAXNUM;
3220         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3221           Opc = ISD::FMAXIMUM;
3222         else if (UseScalarMinMax)
3223           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3224             ISD::FMAXNUM : ISD::FMAXIMUM;
3225         break;
3226       }
3227       break;
3228     case SPF_ABS:
3229       IsUnaryAbs = true;
3230       Opc = ISD::ABS;
3231       break;
3232     case SPF_NABS:
3233       // TODO: we need to produce sub(0, abs(X)).
3234     default: break;
3235     }
3236 
3237     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3238         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3239          (UseScalarMinMax &&
3240           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3241         // If the underlying comparison instruction is used by any other
3242         // instruction, the consumed instructions won't be destroyed, so it is
3243         // not profitable to convert to a min/max.
3244         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3245       OpCode = Opc;
3246       LHSVal = getValue(LHS);
3247       RHSVal = getValue(RHS);
3248       BaseOps.clear();
3249     }
3250 
3251     if (IsUnaryAbs) {
3252       OpCode = Opc;
3253       LHSVal = getValue(LHS);
3254       BaseOps.clear();
3255     }
3256   }
3257 
3258   if (IsUnaryAbs) {
3259     for (unsigned i = 0; i != NumValues; ++i) {
3260       Values[i] =
3261           DAG.getNode(OpCode, getCurSDLoc(),
3262                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3263                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3264     }
3265   } else {
3266     for (unsigned i = 0; i != NumValues; ++i) {
3267       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3268       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3269       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3270       Values[i] = DAG.getNode(
3271           OpCode, getCurSDLoc(),
3272           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3273     }
3274   }
3275 
3276   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3277                            DAG.getVTList(ValueVTs), Values));
3278 }
3279 
3280 void SelectionDAGBuilder::visitTrunc(const User &I) {
3281   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3282   SDValue N = getValue(I.getOperand(0));
3283   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3284                                                         I.getType());
3285   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3286 }
3287 
3288 void SelectionDAGBuilder::visitZExt(const User &I) {
3289   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3290   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3291   SDValue N = getValue(I.getOperand(0));
3292   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3293                                                         I.getType());
3294   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3295 }
3296 
3297 void SelectionDAGBuilder::visitSExt(const User &I) {
3298   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3299   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3300   SDValue N = getValue(I.getOperand(0));
3301   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3302                                                         I.getType());
3303   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3304 }
3305 
3306 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3307   // FPTrunc is never a no-op cast, no need to check
3308   SDValue N = getValue(I.getOperand(0));
3309   SDLoc dl = getCurSDLoc();
3310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3311   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3312   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3313                            DAG.getTargetConstant(
3314                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3315 }
3316 
3317 void SelectionDAGBuilder::visitFPExt(const User &I) {
3318   // FPExt is never a no-op cast, no need to check
3319   SDValue N = getValue(I.getOperand(0));
3320   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3321                                                         I.getType());
3322   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3323 }
3324 
3325 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3326   // FPToUI is never a no-op cast, no need to check
3327   SDValue N = getValue(I.getOperand(0));
3328   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3329                                                         I.getType());
3330   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3331 }
3332 
3333 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3334   // FPToSI is never a no-op cast, no need to check
3335   SDValue N = getValue(I.getOperand(0));
3336   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3337                                                         I.getType());
3338   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3339 }
3340 
3341 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3342   // UIToFP is never a no-op cast, no need to check
3343   SDValue N = getValue(I.getOperand(0));
3344   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3345                                                         I.getType());
3346   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3347 }
3348 
3349 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3350   // SIToFP is never a no-op cast, no need to check
3351   SDValue N = getValue(I.getOperand(0));
3352   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3353                                                         I.getType());
3354   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3355 }
3356 
3357 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3358   // What to do depends on the size of the integer and the size of the pointer.
3359   // We can either truncate, zero extend, or no-op, accordingly.
3360   SDValue N = getValue(I.getOperand(0));
3361   auto &TLI = DAG.getTargetLoweringInfo();
3362   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3363                                                         I.getType());
3364   EVT PtrMemVT =
3365       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3366   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3367   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3368   setValue(&I, N);
3369 }
3370 
3371 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3372   // What to do depends on the size of the integer and the size of the pointer.
3373   // We can either truncate, zero extend, or no-op, accordingly.
3374   SDValue N = getValue(I.getOperand(0));
3375   auto &TLI = DAG.getTargetLoweringInfo();
3376   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3377   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3378   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3379   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3380   setValue(&I, N);
3381 }
3382 
3383 void SelectionDAGBuilder::visitBitCast(const User &I) {
3384   SDValue N = getValue(I.getOperand(0));
3385   SDLoc dl = getCurSDLoc();
3386   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3387                                                         I.getType());
3388 
3389   // BitCast assures us that source and destination are the same size so this is
3390   // either a BITCAST or a no-op.
3391   if (DestVT != N.getValueType())
3392     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3393                              DestVT, N)); // convert types.
3394   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3395   // might fold any kind of constant expression to an integer constant and that
3396   // is not what we are looking for. Only recognize a bitcast of a genuine
3397   // constant integer as an opaque constant.
3398   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3399     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3400                                  /*isOpaque*/true));
3401   else
3402     setValue(&I, N);            // noop cast.
3403 }
3404 
3405 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3407   const Value *SV = I.getOperand(0);
3408   SDValue N = getValue(SV);
3409   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3410 
3411   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3412   unsigned DestAS = I.getType()->getPointerAddressSpace();
3413 
3414   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3415     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3416 
3417   setValue(&I, N);
3418 }
3419 
3420 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3422   SDValue InVec = getValue(I.getOperand(0));
3423   SDValue InVal = getValue(I.getOperand(1));
3424   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3425                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3426   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3427                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3428                            InVec, InVal, InIdx));
3429 }
3430 
3431 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3433   SDValue InVec = getValue(I.getOperand(0));
3434   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3435                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3436   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3437                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3438                            InVec, InIdx));
3439 }
3440 
3441 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3442   SDValue Src1 = getValue(I.getOperand(0));
3443   SDValue Src2 = getValue(I.getOperand(1));
3444   ArrayRef<int> Mask;
3445   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3446     Mask = SVI->getShuffleMask();
3447   else
3448     Mask = cast<ConstantExpr>(I).getShuffleMask();
3449   SDLoc DL = getCurSDLoc();
3450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3451   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3452   EVT SrcVT = Src1.getValueType();
3453   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3454 
3455   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3456       VT.isScalableVector()) {
3457     // Canonical splat form of first element of first input vector.
3458     SDValue FirstElt =
3459         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3460                     DAG.getVectorIdxConstant(0, DL));
3461     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3462     return;
3463   }
3464 
3465   // For now, we only handle splats for scalable vectors.
3466   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3467   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3468   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3469 
3470   unsigned MaskNumElts = Mask.size();
3471 
3472   if (SrcNumElts == MaskNumElts) {
3473     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3474     return;
3475   }
3476 
3477   // Normalize the shuffle vector since mask and vector length don't match.
3478   if (SrcNumElts < MaskNumElts) {
3479     // Mask is longer than the source vectors. We can use concatenate vector to
3480     // make the mask and vectors lengths match.
3481 
3482     if (MaskNumElts % SrcNumElts == 0) {
3483       // Mask length is a multiple of the source vector length.
3484       // Check if the shuffle is some kind of concatenation of the input
3485       // vectors.
3486       unsigned NumConcat = MaskNumElts / SrcNumElts;
3487       bool IsConcat = true;
3488       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3489       for (unsigned i = 0; i != MaskNumElts; ++i) {
3490         int Idx = Mask[i];
3491         if (Idx < 0)
3492           continue;
3493         // Ensure the indices in each SrcVT sized piece are sequential and that
3494         // the same source is used for the whole piece.
3495         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3496             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3497              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3498           IsConcat = false;
3499           break;
3500         }
3501         // Remember which source this index came from.
3502         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3503       }
3504 
3505       // The shuffle is concatenating multiple vectors together. Just emit
3506       // a CONCAT_VECTORS operation.
3507       if (IsConcat) {
3508         SmallVector<SDValue, 8> ConcatOps;
3509         for (auto Src : ConcatSrcs) {
3510           if (Src < 0)
3511             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3512           else if (Src == 0)
3513             ConcatOps.push_back(Src1);
3514           else
3515             ConcatOps.push_back(Src2);
3516         }
3517         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3518         return;
3519       }
3520     }
3521 
3522     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3523     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3524     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3525                                     PaddedMaskNumElts);
3526 
3527     // Pad both vectors with undefs to make them the same length as the mask.
3528     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3529 
3530     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3531     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3532     MOps1[0] = Src1;
3533     MOps2[0] = Src2;
3534 
3535     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3536     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3537 
3538     // Readjust mask for new input vector length.
3539     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3540     for (unsigned i = 0; i != MaskNumElts; ++i) {
3541       int Idx = Mask[i];
3542       if (Idx >= (int)SrcNumElts)
3543         Idx -= SrcNumElts - PaddedMaskNumElts;
3544       MappedOps[i] = Idx;
3545     }
3546 
3547     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3548 
3549     // If the concatenated vector was padded, extract a subvector with the
3550     // correct number of elements.
3551     if (MaskNumElts != PaddedMaskNumElts)
3552       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3553                            DAG.getVectorIdxConstant(0, DL));
3554 
3555     setValue(&I, Result);
3556     return;
3557   }
3558 
3559   if (SrcNumElts > MaskNumElts) {
3560     // Analyze the access pattern of the vector to see if we can extract
3561     // two subvectors and do the shuffle.
3562     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3563     bool CanExtract = true;
3564     for (int Idx : Mask) {
3565       unsigned Input = 0;
3566       if (Idx < 0)
3567         continue;
3568 
3569       if (Idx >= (int)SrcNumElts) {
3570         Input = 1;
3571         Idx -= SrcNumElts;
3572       }
3573 
3574       // If all the indices come from the same MaskNumElts sized portion of
3575       // the sources we can use extract. Also make sure the extract wouldn't
3576       // extract past the end of the source.
3577       int NewStartIdx = alignDown(Idx, MaskNumElts);
3578       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3579           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3580         CanExtract = false;
3581       // Make sure we always update StartIdx as we use it to track if all
3582       // elements are undef.
3583       StartIdx[Input] = NewStartIdx;
3584     }
3585 
3586     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3587       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3588       return;
3589     }
3590     if (CanExtract) {
3591       // Extract appropriate subvector and generate a vector shuffle
3592       for (unsigned Input = 0; Input < 2; ++Input) {
3593         SDValue &Src = Input == 0 ? Src1 : Src2;
3594         if (StartIdx[Input] < 0)
3595           Src = DAG.getUNDEF(VT);
3596         else {
3597           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3598                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3599         }
3600       }
3601 
3602       // Calculate new mask.
3603       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3604       for (int &Idx : MappedOps) {
3605         if (Idx >= (int)SrcNumElts)
3606           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3607         else if (Idx >= 0)
3608           Idx -= StartIdx[0];
3609       }
3610 
3611       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3612       return;
3613     }
3614   }
3615 
3616   // We can't use either concat vectors or extract subvectors so fall back to
3617   // replacing the shuffle with extract and build vector.
3618   // to insert and build vector.
3619   EVT EltVT = VT.getVectorElementType();
3620   SmallVector<SDValue,8> Ops;
3621   for (int Idx : Mask) {
3622     SDValue Res;
3623 
3624     if (Idx < 0) {
3625       Res = DAG.getUNDEF(EltVT);
3626     } else {
3627       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3628       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3629 
3630       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3631                         DAG.getVectorIdxConstant(Idx, DL));
3632     }
3633 
3634     Ops.push_back(Res);
3635   }
3636 
3637   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3638 }
3639 
3640 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3641   ArrayRef<unsigned> Indices;
3642   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3643     Indices = IV->getIndices();
3644   else
3645     Indices = cast<ConstantExpr>(&I)->getIndices();
3646 
3647   const Value *Op0 = I.getOperand(0);
3648   const Value *Op1 = I.getOperand(1);
3649   Type *AggTy = I.getType();
3650   Type *ValTy = Op1->getType();
3651   bool IntoUndef = isa<UndefValue>(Op0);
3652   bool FromUndef = isa<UndefValue>(Op1);
3653 
3654   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3655 
3656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3657   SmallVector<EVT, 4> AggValueVTs;
3658   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3659   SmallVector<EVT, 4> ValValueVTs;
3660   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3661 
3662   unsigned NumAggValues = AggValueVTs.size();
3663   unsigned NumValValues = ValValueVTs.size();
3664   SmallVector<SDValue, 4> Values(NumAggValues);
3665 
3666   // Ignore an insertvalue that produces an empty object
3667   if (!NumAggValues) {
3668     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3669     return;
3670   }
3671 
3672   SDValue Agg = getValue(Op0);
3673   unsigned i = 0;
3674   // Copy the beginning value(s) from the original aggregate.
3675   for (; i != LinearIndex; ++i)
3676     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3677                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3678   // Copy values from the inserted value(s).
3679   if (NumValValues) {
3680     SDValue Val = getValue(Op1);
3681     for (; i != LinearIndex + NumValValues; ++i)
3682       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3683                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3684   }
3685   // Copy remaining value(s) from the original aggregate.
3686   for (; i != NumAggValues; ++i)
3687     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3688                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3689 
3690   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3691                            DAG.getVTList(AggValueVTs), Values));
3692 }
3693 
3694 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3695   ArrayRef<unsigned> Indices;
3696   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3697     Indices = EV->getIndices();
3698   else
3699     Indices = cast<ConstantExpr>(&I)->getIndices();
3700 
3701   const Value *Op0 = I.getOperand(0);
3702   Type *AggTy = Op0->getType();
3703   Type *ValTy = I.getType();
3704   bool OutOfUndef = isa<UndefValue>(Op0);
3705 
3706   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3707 
3708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3709   SmallVector<EVT, 4> ValValueVTs;
3710   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3711 
3712   unsigned NumValValues = ValValueVTs.size();
3713 
3714   // Ignore a extractvalue that produces an empty object
3715   if (!NumValValues) {
3716     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3717     return;
3718   }
3719 
3720   SmallVector<SDValue, 4> Values(NumValValues);
3721 
3722   SDValue Agg = getValue(Op0);
3723   // Copy out the selected value(s).
3724   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3725     Values[i - LinearIndex] =
3726       OutOfUndef ?
3727         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3728         SDValue(Agg.getNode(), Agg.getResNo() + i);
3729 
3730   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3731                            DAG.getVTList(ValValueVTs), Values));
3732 }
3733 
3734 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3735   Value *Op0 = I.getOperand(0);
3736   // Note that the pointer operand may be a vector of pointers. Take the scalar
3737   // element which holds a pointer.
3738   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3739   SDValue N = getValue(Op0);
3740   SDLoc dl = getCurSDLoc();
3741   auto &TLI = DAG.getTargetLoweringInfo();
3742   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3743   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3744 
3745   // Normalize Vector GEP - all scalar operands should be converted to the
3746   // splat vector.
3747   bool IsVectorGEP = I.getType()->isVectorTy();
3748   ElementCount VectorElementCount =
3749       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3750                   : ElementCount(0, false);
3751 
3752   if (IsVectorGEP && !N.getValueType().isVector()) {
3753     LLVMContext &Context = *DAG.getContext();
3754     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3755     if (VectorElementCount.Scalable)
3756       N = DAG.getSplatVector(VT, dl, N);
3757     else
3758       N = DAG.getSplatBuildVector(VT, dl, N);
3759   }
3760 
3761   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3762        GTI != E; ++GTI) {
3763     const Value *Idx = GTI.getOperand();
3764     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3765       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3766       if (Field) {
3767         // N = N + Offset
3768         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3769 
3770         // In an inbounds GEP with an offset that is nonnegative even when
3771         // interpreted as signed, assume there is no unsigned overflow.
3772         SDNodeFlags Flags;
3773         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3774           Flags.setNoUnsignedWrap(true);
3775 
3776         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3777                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3778       }
3779     } else {
3780       // IdxSize is the width of the arithmetic according to IR semantics.
3781       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3782       // (and fix up the result later).
3783       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3784       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3785       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3786       // We intentionally mask away the high bits here; ElementSize may not
3787       // fit in IdxTy.
3788       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3789       bool ElementScalable = ElementSize.isScalable();
3790 
3791       // If this is a scalar constant or a splat vector of constants,
3792       // handle it quickly.
3793       const auto *C = dyn_cast<Constant>(Idx);
3794       if (C && isa<VectorType>(C->getType()))
3795         C = C->getSplatValue();
3796 
3797       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3798       if (CI && CI->isZero())
3799         continue;
3800       if (CI && !ElementScalable) {
3801         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3802         LLVMContext &Context = *DAG.getContext();
3803         SDValue OffsVal;
3804         if (IsVectorGEP)
3805           OffsVal = DAG.getConstant(
3806               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3807         else
3808           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3809 
3810         // In an inbounds GEP with an offset that is nonnegative even when
3811         // interpreted as signed, assume there is no unsigned overflow.
3812         SDNodeFlags Flags;
3813         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3814           Flags.setNoUnsignedWrap(true);
3815 
3816         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3817 
3818         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3819         continue;
3820       }
3821 
3822       // N = N + Idx * ElementMul;
3823       SDValue IdxN = getValue(Idx);
3824 
3825       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3826         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3827                                   VectorElementCount);
3828         if (VectorElementCount.Scalable)
3829           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3830         else
3831           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3832       }
3833 
3834       // If the index is smaller or larger than intptr_t, truncate or extend
3835       // it.
3836       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3837 
3838       if (ElementScalable) {
3839         EVT VScaleTy = N.getValueType().getScalarType();
3840         SDValue VScale = DAG.getNode(
3841             ISD::VSCALE, dl, VScaleTy,
3842             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3843         if (IsVectorGEP)
3844           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3845         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3846       } else {
3847         // If this is a multiply by a power of two, turn it into a shl
3848         // immediately.  This is a very common case.
3849         if (ElementMul != 1) {
3850           if (ElementMul.isPowerOf2()) {
3851             unsigned Amt = ElementMul.logBase2();
3852             IdxN = DAG.getNode(ISD::SHL, dl,
3853                                N.getValueType(), IdxN,
3854                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3855           } else {
3856             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3857                                             IdxN.getValueType());
3858             IdxN = DAG.getNode(ISD::MUL, dl,
3859                                N.getValueType(), IdxN, Scale);
3860           }
3861         }
3862       }
3863 
3864       N = DAG.getNode(ISD::ADD, dl,
3865                       N.getValueType(), N, IdxN);
3866     }
3867   }
3868 
3869   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3870     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3871 
3872   setValue(&I, N);
3873 }
3874 
3875 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3876   // If this is a fixed sized alloca in the entry block of the function,
3877   // allocate it statically on the stack.
3878   if (FuncInfo.StaticAllocaMap.count(&I))
3879     return;   // getValue will auto-populate this.
3880 
3881   SDLoc dl = getCurSDLoc();
3882   Type *Ty = I.getAllocatedType();
3883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3884   auto &DL = DAG.getDataLayout();
3885   uint64_t TySize = DL.getTypeAllocSize(Ty);
3886   MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign());
3887 
3888   SDValue AllocSize = getValue(I.getArraySize());
3889 
3890   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3891   if (AllocSize.getValueType() != IntPtr)
3892     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3893 
3894   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3895                           AllocSize,
3896                           DAG.getConstant(TySize, dl, IntPtr));
3897 
3898   // Handle alignment.  If the requested alignment is less than or equal to
3899   // the stack alignment, ignore it.  If the size is greater than or equal to
3900   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3901   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3902   if (Alignment <= StackAlign)
3903     Alignment = None;
3904 
3905   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3906   // Round the size of the allocation up to the stack alignment size
3907   // by add SA-1 to the size. This doesn't overflow because we're computing
3908   // an address inside an alloca.
3909   SDNodeFlags Flags;
3910   Flags.setNoUnsignedWrap(true);
3911   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3912                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3913 
3914   // Mask out the low bits for alignment purposes.
3915   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3916                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3917 
3918   SDValue Ops[] = {
3919       getRoot(), AllocSize,
3920       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3921   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3922   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3923   setValue(&I, DSA);
3924   DAG.setRoot(DSA.getValue(1));
3925 
3926   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3927 }
3928 
3929 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3930   if (I.isAtomic())
3931     return visitAtomicLoad(I);
3932 
3933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3934   const Value *SV = I.getOperand(0);
3935   if (TLI.supportSwiftError()) {
3936     // Swifterror values can come from either a function parameter with
3937     // swifterror attribute or an alloca with swifterror attribute.
3938     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3939       if (Arg->hasSwiftErrorAttr())
3940         return visitLoadFromSwiftError(I);
3941     }
3942 
3943     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3944       if (Alloca->isSwiftError())
3945         return visitLoadFromSwiftError(I);
3946     }
3947   }
3948 
3949   SDValue Ptr = getValue(SV);
3950 
3951   Type *Ty = I.getType();
3952   Align Alignment = DL->getValueOrABITypeAlignment(I.getAlign(), Ty);
3953 
3954   AAMDNodes AAInfo;
3955   I.getAAMetadata(AAInfo);
3956   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3957 
3958   SmallVector<EVT, 4> ValueVTs, MemVTs;
3959   SmallVector<uint64_t, 4> Offsets;
3960   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3961   unsigned NumValues = ValueVTs.size();
3962   if (NumValues == 0)
3963     return;
3964 
3965   bool isVolatile = I.isVolatile();
3966 
3967   SDValue Root;
3968   bool ConstantMemory = false;
3969   if (isVolatile)
3970     // Serialize volatile loads with other side effects.
3971     Root = getRoot();
3972   else if (NumValues > MaxParallelChains)
3973     Root = getMemoryRoot();
3974   else if (AA &&
3975            AA->pointsToConstantMemory(MemoryLocation(
3976                SV,
3977                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3978                AAInfo))) {
3979     // Do not serialize (non-volatile) loads of constant memory with anything.
3980     Root = DAG.getEntryNode();
3981     ConstantMemory = true;
3982   } else {
3983     // Do not serialize non-volatile loads against each other.
3984     Root = DAG.getRoot();
3985   }
3986 
3987   SDLoc dl = getCurSDLoc();
3988 
3989   if (isVolatile)
3990     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3991 
3992   // An aggregate load cannot wrap around the address space, so offsets to its
3993   // parts don't wrap either.
3994   SDNodeFlags Flags;
3995   Flags.setNoUnsignedWrap(true);
3996 
3997   SmallVector<SDValue, 4> Values(NumValues);
3998   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3999   EVT PtrVT = Ptr.getValueType();
4000 
4001   MachineMemOperand::Flags MMOFlags
4002     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4003 
4004   unsigned ChainI = 0;
4005   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4006     // Serializing loads here may result in excessive register pressure, and
4007     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4008     // could recover a bit by hoisting nodes upward in the chain by recognizing
4009     // they are side-effect free or do not alias. The optimizer should really
4010     // avoid this case by converting large object/array copies to llvm.memcpy
4011     // (MaxParallelChains should always remain as failsafe).
4012     if (ChainI == MaxParallelChains) {
4013       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4014       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4015                                   makeArrayRef(Chains.data(), ChainI));
4016       Root = Chain;
4017       ChainI = 0;
4018     }
4019     SDValue A = DAG.getNode(ISD::ADD, dl,
4020                             PtrVT, Ptr,
4021                             DAG.getConstant(Offsets[i], dl, PtrVT),
4022                             Flags);
4023 
4024     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4025                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4026                             MMOFlags, AAInfo, Ranges);
4027     Chains[ChainI] = L.getValue(1);
4028 
4029     if (MemVTs[i] != ValueVTs[i])
4030       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4031 
4032     Values[i] = L;
4033   }
4034 
4035   if (!ConstantMemory) {
4036     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4037                                 makeArrayRef(Chains.data(), ChainI));
4038     if (isVolatile)
4039       DAG.setRoot(Chain);
4040     else
4041       PendingLoads.push_back(Chain);
4042   }
4043 
4044   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4045                            DAG.getVTList(ValueVTs), Values));
4046 }
4047 
4048 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4049   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4050          "call visitStoreToSwiftError when backend supports swifterror");
4051 
4052   SmallVector<EVT, 4> ValueVTs;
4053   SmallVector<uint64_t, 4> Offsets;
4054   const Value *SrcV = I.getOperand(0);
4055   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4056                   SrcV->getType(), ValueVTs, &Offsets);
4057   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4058          "expect a single EVT for swifterror");
4059 
4060   SDValue Src = getValue(SrcV);
4061   // Create a virtual register, then update the virtual register.
4062   Register VReg =
4063       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4064   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4065   // Chain can be getRoot or getControlRoot.
4066   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4067                                       SDValue(Src.getNode(), Src.getResNo()));
4068   DAG.setRoot(CopyNode);
4069 }
4070 
4071 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4072   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4073          "call visitLoadFromSwiftError when backend supports swifterror");
4074 
4075   assert(!I.isVolatile() &&
4076          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4077          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4078          "Support volatile, non temporal, invariant for load_from_swift_error");
4079 
4080   const Value *SV = I.getOperand(0);
4081   Type *Ty = I.getType();
4082   AAMDNodes AAInfo;
4083   I.getAAMetadata(AAInfo);
4084   assert(
4085       (!AA ||
4086        !AA->pointsToConstantMemory(MemoryLocation(
4087            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4088            AAInfo))) &&
4089       "load_from_swift_error should not be constant memory");
4090 
4091   SmallVector<EVT, 4> ValueVTs;
4092   SmallVector<uint64_t, 4> Offsets;
4093   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4094                   ValueVTs, &Offsets);
4095   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4096          "expect a single EVT for swifterror");
4097 
4098   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4099   SDValue L = DAG.getCopyFromReg(
4100       getRoot(), getCurSDLoc(),
4101       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4102 
4103   setValue(&I, L);
4104 }
4105 
4106 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4107   if (I.isAtomic())
4108     return visitAtomicStore(I);
4109 
4110   const Value *SrcV = I.getOperand(0);
4111   const Value *PtrV = I.getOperand(1);
4112 
4113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4114   if (TLI.supportSwiftError()) {
4115     // Swifterror values can come from either a function parameter with
4116     // swifterror attribute or an alloca with swifterror attribute.
4117     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4118       if (Arg->hasSwiftErrorAttr())
4119         return visitStoreToSwiftError(I);
4120     }
4121 
4122     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4123       if (Alloca->isSwiftError())
4124         return visitStoreToSwiftError(I);
4125     }
4126   }
4127 
4128   SmallVector<EVT, 4> ValueVTs, MemVTs;
4129   SmallVector<uint64_t, 4> Offsets;
4130   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4131                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4132   unsigned NumValues = ValueVTs.size();
4133   if (NumValues == 0)
4134     return;
4135 
4136   // Get the lowered operands. Note that we do this after
4137   // checking if NumResults is zero, because with zero results
4138   // the operands won't have values in the map.
4139   SDValue Src = getValue(SrcV);
4140   SDValue Ptr = getValue(PtrV);
4141 
4142   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4143   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4144   SDLoc dl = getCurSDLoc();
4145   Align Alignment =
4146       DL->getValueOrABITypeAlignment(I.getAlign(), SrcV->getType());
4147   AAMDNodes AAInfo;
4148   I.getAAMetadata(AAInfo);
4149 
4150   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4151 
4152   // An aggregate load cannot wrap around the address space, so offsets to its
4153   // parts don't wrap either.
4154   SDNodeFlags Flags;
4155   Flags.setNoUnsignedWrap(true);
4156 
4157   unsigned ChainI = 0;
4158   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4159     // See visitLoad comments.
4160     if (ChainI == MaxParallelChains) {
4161       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4162                                   makeArrayRef(Chains.data(), ChainI));
4163       Root = Chain;
4164       ChainI = 0;
4165     }
4166     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4167     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4168     if (MemVTs[i] != ValueVTs[i])
4169       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4170     SDValue St =
4171         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4172                      Alignment, MMOFlags, AAInfo);
4173     Chains[ChainI] = St;
4174   }
4175 
4176   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4177                                   makeArrayRef(Chains.data(), ChainI));
4178   DAG.setRoot(StoreNode);
4179 }
4180 
4181 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4182                                            bool IsCompressing) {
4183   SDLoc sdl = getCurSDLoc();
4184 
4185   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4186                                MaybeAlign &Alignment) {
4187     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4188     Src0 = I.getArgOperand(0);
4189     Ptr = I.getArgOperand(1);
4190     Alignment =
4191         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4192     Mask = I.getArgOperand(3);
4193   };
4194   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4195                                     MaybeAlign &Alignment) {
4196     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4197     Src0 = I.getArgOperand(0);
4198     Ptr = I.getArgOperand(1);
4199     Mask = I.getArgOperand(2);
4200     Alignment = None;
4201   };
4202 
4203   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4204   MaybeAlign Alignment;
4205   if (IsCompressing)
4206     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4207   else
4208     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4209 
4210   SDValue Ptr = getValue(PtrOperand);
4211   SDValue Src0 = getValue(Src0Operand);
4212   SDValue Mask = getValue(MaskOperand);
4213   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4214 
4215   EVT VT = Src0.getValueType();
4216   if (!Alignment)
4217     Alignment = DAG.getEVTAlign(VT);
4218 
4219   AAMDNodes AAInfo;
4220   I.getAAMetadata(AAInfo);
4221 
4222   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4223       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4224       // TODO: Make MachineMemOperands aware of scalable
4225       // vectors.
4226       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4227   SDValue StoreNode =
4228       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4229                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4230   DAG.setRoot(StoreNode);
4231   setValue(&I, StoreNode);
4232 }
4233 
4234 // Get a uniform base for the Gather/Scatter intrinsic.
4235 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4236 // We try to represent it as a base pointer + vector of indices.
4237 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4238 // The first operand of the GEP may be a single pointer or a vector of pointers
4239 // Example:
4240 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4241 //  or
4242 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4243 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4244 //
4245 // When the first GEP operand is a single pointer - it is the uniform base we
4246 // are looking for. If first operand of the GEP is a splat vector - we
4247 // extract the splat value and use it as a uniform base.
4248 // In all other cases the function returns 'false'.
4249 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4250                            ISD::MemIndexType &IndexType, SDValue &Scale,
4251                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4252   SelectionDAG& DAG = SDB->DAG;
4253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4254   const DataLayout &DL = DAG.getDataLayout();
4255 
4256   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4257 
4258   // Handle splat constant pointer.
4259   if (auto *C = dyn_cast<Constant>(Ptr)) {
4260     C = C->getSplatValue();
4261     if (!C)
4262       return false;
4263 
4264     Base = SDB->getValue(C);
4265 
4266     unsigned NumElts = Ptr->getType()->getVectorNumElements();
4267     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4268     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4269     IndexType = ISD::SIGNED_SCALED;
4270     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4271     return true;
4272   }
4273 
4274   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4275   if (!GEP || GEP->getParent() != CurBB)
4276     return false;
4277 
4278   if (GEP->getNumOperands() != 2)
4279     return false;
4280 
4281   const Value *BasePtr = GEP->getPointerOperand();
4282   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4283 
4284   // Make sure the base is scalar and the index is a vector.
4285   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4286     return false;
4287 
4288   Base = SDB->getValue(BasePtr);
4289   Index = SDB->getValue(IndexVal);
4290   IndexType = ISD::SIGNED_SCALED;
4291   Scale = DAG.getTargetConstant(
4292               DL.getTypeAllocSize(GEP->getResultElementType()),
4293               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4294   return true;
4295 }
4296 
4297 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4298   SDLoc sdl = getCurSDLoc();
4299 
4300   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4301   const Value *Ptr = I.getArgOperand(1);
4302   SDValue Src0 = getValue(I.getArgOperand(0));
4303   SDValue Mask = getValue(I.getArgOperand(3));
4304   EVT VT = Src0.getValueType();
4305   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4306   if (!Alignment)
4307     Alignment = DAG.getEVTAlign(VT);
4308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4309 
4310   AAMDNodes AAInfo;
4311   I.getAAMetadata(AAInfo);
4312 
4313   SDValue Base;
4314   SDValue Index;
4315   ISD::MemIndexType IndexType;
4316   SDValue Scale;
4317   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4318                                     I.getParent());
4319 
4320   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4321   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4322       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4323       // TODO: Make MachineMemOperands aware of scalable
4324       // vectors.
4325       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4326   if (!UniformBase) {
4327     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4328     Index = getValue(Ptr);
4329     IndexType = ISD::SIGNED_SCALED;
4330     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4331   }
4332   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4333   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4334                                          Ops, MMO, IndexType);
4335   DAG.setRoot(Scatter);
4336   setValue(&I, Scatter);
4337 }
4338 
4339 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4340   SDLoc sdl = getCurSDLoc();
4341 
4342   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4343                               MaybeAlign &Alignment) {
4344     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4345     Ptr = I.getArgOperand(0);
4346     Alignment =
4347         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4348     Mask = I.getArgOperand(2);
4349     Src0 = I.getArgOperand(3);
4350   };
4351   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4352                                  MaybeAlign &Alignment) {
4353     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4354     Ptr = I.getArgOperand(0);
4355     Alignment = None;
4356     Mask = I.getArgOperand(1);
4357     Src0 = I.getArgOperand(2);
4358   };
4359 
4360   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4361   MaybeAlign Alignment;
4362   if (IsExpanding)
4363     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4364   else
4365     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4366 
4367   SDValue Ptr = getValue(PtrOperand);
4368   SDValue Src0 = getValue(Src0Operand);
4369   SDValue Mask = getValue(MaskOperand);
4370   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4371 
4372   EVT VT = Src0.getValueType();
4373   if (!Alignment)
4374     Alignment = DAG.getEVTAlign(VT);
4375 
4376   AAMDNodes AAInfo;
4377   I.getAAMetadata(AAInfo);
4378   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4379 
4380   // Do not serialize masked loads of constant memory with anything.
4381   MemoryLocation ML;
4382   if (VT.isScalableVector())
4383     ML = MemoryLocation(PtrOperand);
4384   else
4385     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4386                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4387                            AAInfo);
4388   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4389 
4390   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4391 
4392   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4393       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4394       // TODO: Make MachineMemOperands aware of scalable
4395       // vectors.
4396       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4397 
4398   SDValue Load =
4399       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4400                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4401   if (AddToChain)
4402     PendingLoads.push_back(Load.getValue(1));
4403   setValue(&I, Load);
4404 }
4405 
4406 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4407   SDLoc sdl = getCurSDLoc();
4408 
4409   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4410   const Value *Ptr = I.getArgOperand(0);
4411   SDValue Src0 = getValue(I.getArgOperand(3));
4412   SDValue Mask = getValue(I.getArgOperand(2));
4413 
4414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4415   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4416   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4417   if (!Alignment)
4418     Alignment = DAG.getEVTAlign(VT);
4419 
4420   AAMDNodes AAInfo;
4421   I.getAAMetadata(AAInfo);
4422   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4423 
4424   SDValue Root = DAG.getRoot();
4425   SDValue Base;
4426   SDValue Index;
4427   ISD::MemIndexType IndexType;
4428   SDValue Scale;
4429   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4430                                     I.getParent());
4431   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4432   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4433       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4434       // TODO: Make MachineMemOperands aware of scalable
4435       // vectors.
4436       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4437 
4438   if (!UniformBase) {
4439     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4440     Index = getValue(Ptr);
4441     IndexType = ISD::SIGNED_SCALED;
4442     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4443   }
4444   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4445   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4446                                        Ops, MMO, IndexType);
4447 
4448   PendingLoads.push_back(Gather.getValue(1));
4449   setValue(&I, Gather);
4450 }
4451 
4452 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4453   SDLoc dl = getCurSDLoc();
4454   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4455   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4456   SyncScope::ID SSID = I.getSyncScopeID();
4457 
4458   SDValue InChain = getRoot();
4459 
4460   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4461   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4462 
4463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4464   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4465 
4466   MachineFunction &MF = DAG.getMachineFunction();
4467   MachineMemOperand *MMO = MF.getMachineMemOperand(
4468       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4469       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4470       FailureOrdering);
4471 
4472   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4473                                    dl, MemVT, VTs, InChain,
4474                                    getValue(I.getPointerOperand()),
4475                                    getValue(I.getCompareOperand()),
4476                                    getValue(I.getNewValOperand()), MMO);
4477 
4478   SDValue OutChain = L.getValue(2);
4479 
4480   setValue(&I, L);
4481   DAG.setRoot(OutChain);
4482 }
4483 
4484 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4485   SDLoc dl = getCurSDLoc();
4486   ISD::NodeType NT;
4487   switch (I.getOperation()) {
4488   default: llvm_unreachable("Unknown atomicrmw operation");
4489   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4490   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4491   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4492   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4493   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4494   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4495   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4496   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4497   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4498   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4499   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4500   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4501   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4502   }
4503   AtomicOrdering Ordering = I.getOrdering();
4504   SyncScope::ID SSID = I.getSyncScopeID();
4505 
4506   SDValue InChain = getRoot();
4507 
4508   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4510   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4511 
4512   MachineFunction &MF = DAG.getMachineFunction();
4513   MachineMemOperand *MMO = MF.getMachineMemOperand(
4514       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4515       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4516 
4517   SDValue L =
4518     DAG.getAtomic(NT, dl, MemVT, InChain,
4519                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4520                   MMO);
4521 
4522   SDValue OutChain = L.getValue(1);
4523 
4524   setValue(&I, L);
4525   DAG.setRoot(OutChain);
4526 }
4527 
4528 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4529   SDLoc dl = getCurSDLoc();
4530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4531   SDValue Ops[3];
4532   Ops[0] = getRoot();
4533   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4534                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4535   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4536                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4537   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4538 }
4539 
4540 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4541   SDLoc dl = getCurSDLoc();
4542   AtomicOrdering Order = I.getOrdering();
4543   SyncScope::ID SSID = I.getSyncScopeID();
4544 
4545   SDValue InChain = getRoot();
4546 
4547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4548   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4549   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4550 
4551   if (!TLI.supportsUnalignedAtomics() &&
4552       I.getAlignment() < MemVT.getSizeInBits() / 8)
4553     report_fatal_error("Cannot generate unaligned atomic load");
4554 
4555   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4556 
4557   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4558       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4559       *I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4560 
4561   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4562 
4563   SDValue Ptr = getValue(I.getPointerOperand());
4564 
4565   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4566     // TODO: Once this is better exercised by tests, it should be merged with
4567     // the normal path for loads to prevent future divergence.
4568     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4569     if (MemVT != VT)
4570       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4571 
4572     setValue(&I, L);
4573     SDValue OutChain = L.getValue(1);
4574     if (!I.isUnordered())
4575       DAG.setRoot(OutChain);
4576     else
4577       PendingLoads.push_back(OutChain);
4578     return;
4579   }
4580 
4581   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4582                             Ptr, MMO);
4583 
4584   SDValue OutChain = L.getValue(1);
4585   if (MemVT != VT)
4586     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4587 
4588   setValue(&I, L);
4589   DAG.setRoot(OutChain);
4590 }
4591 
4592 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4593   SDLoc dl = getCurSDLoc();
4594 
4595   AtomicOrdering Ordering = I.getOrdering();
4596   SyncScope::ID SSID = I.getSyncScopeID();
4597 
4598   SDValue InChain = getRoot();
4599 
4600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4601   EVT MemVT =
4602       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4603 
4604   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4605     report_fatal_error("Cannot generate unaligned atomic store");
4606 
4607   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4608 
4609   MachineFunction &MF = DAG.getMachineFunction();
4610   MachineMemOperand *MMO = MF.getMachineMemOperand(
4611       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4612       *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4613 
4614   SDValue Val = getValue(I.getValueOperand());
4615   if (Val.getValueType() != MemVT)
4616     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4617   SDValue Ptr = getValue(I.getPointerOperand());
4618 
4619   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4620     // TODO: Once this is better exercised by tests, it should be merged with
4621     // the normal path for stores to prevent future divergence.
4622     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4623     DAG.setRoot(S);
4624     return;
4625   }
4626   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4627                                    Ptr, Val, MMO);
4628 
4629 
4630   DAG.setRoot(OutChain);
4631 }
4632 
4633 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4634 /// node.
4635 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4636                                                unsigned Intrinsic) {
4637   // Ignore the callsite's attributes. A specific call site may be marked with
4638   // readnone, but the lowering code will expect the chain based on the
4639   // definition.
4640   const Function *F = I.getCalledFunction();
4641   bool HasChain = !F->doesNotAccessMemory();
4642   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4643 
4644   // Build the operand list.
4645   SmallVector<SDValue, 8> Ops;
4646   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4647     if (OnlyLoad) {
4648       // We don't need to serialize loads against other loads.
4649       Ops.push_back(DAG.getRoot());
4650     } else {
4651       Ops.push_back(getRoot());
4652     }
4653   }
4654 
4655   // Info is set by getTgtMemInstrinsic
4656   TargetLowering::IntrinsicInfo Info;
4657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4658   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4659                                                DAG.getMachineFunction(),
4660                                                Intrinsic);
4661 
4662   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4663   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4664       Info.opc == ISD::INTRINSIC_W_CHAIN)
4665     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4666                                         TLI.getPointerTy(DAG.getDataLayout())));
4667 
4668   // Add all operands of the call to the operand list.
4669   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4670     const Value *Arg = I.getArgOperand(i);
4671     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4672       Ops.push_back(getValue(Arg));
4673       continue;
4674     }
4675 
4676     // Use TargetConstant instead of a regular constant for immarg.
4677     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4678     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4679       assert(CI->getBitWidth() <= 64 &&
4680              "large intrinsic immediates not handled");
4681       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4682     } else {
4683       Ops.push_back(
4684           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4685     }
4686   }
4687 
4688   SmallVector<EVT, 4> ValueVTs;
4689   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4690 
4691   if (HasChain)
4692     ValueVTs.push_back(MVT::Other);
4693 
4694   SDVTList VTs = DAG.getVTList(ValueVTs);
4695 
4696   // Create the node.
4697   SDValue Result;
4698   if (IsTgtIntrinsic) {
4699     // This is target intrinsic that touches memory
4700     AAMDNodes AAInfo;
4701     I.getAAMetadata(AAInfo);
4702     Result =
4703         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4704                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4705                                 Info.align, Info.flags, Info.size, AAInfo);
4706   } else if (!HasChain) {
4707     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4708   } else if (!I.getType()->isVoidTy()) {
4709     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4710   } else {
4711     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4712   }
4713 
4714   if (HasChain) {
4715     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4716     if (OnlyLoad)
4717       PendingLoads.push_back(Chain);
4718     else
4719       DAG.setRoot(Chain);
4720   }
4721 
4722   if (!I.getType()->isVoidTy()) {
4723     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4724       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4725       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4726     } else
4727       Result = lowerRangeToAssertZExt(DAG, I, Result);
4728 
4729     setValue(&I, Result);
4730   }
4731 }
4732 
4733 /// GetSignificand - Get the significand and build it into a floating-point
4734 /// number with exponent of 1:
4735 ///
4736 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4737 ///
4738 /// where Op is the hexadecimal representation of floating point value.
4739 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4740   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4741                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4742   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4743                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4744   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4745 }
4746 
4747 /// GetExponent - Get the exponent:
4748 ///
4749 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4750 ///
4751 /// where Op is the hexadecimal representation of floating point value.
4752 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4753                            const TargetLowering &TLI, const SDLoc &dl) {
4754   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4755                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4756   SDValue t1 = DAG.getNode(
4757       ISD::SRL, dl, MVT::i32, t0,
4758       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4759   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4760                            DAG.getConstant(127, dl, MVT::i32));
4761   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4762 }
4763 
4764 /// getF32Constant - Get 32-bit floating point constant.
4765 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4766                               const SDLoc &dl) {
4767   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4768                            MVT::f32);
4769 }
4770 
4771 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4772                                        SelectionDAG &DAG) {
4773   // TODO: What fast-math-flags should be set on the floating-point nodes?
4774 
4775   //   IntegerPartOfX = ((int32_t)(t0);
4776   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4777 
4778   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4779   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4780   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4781 
4782   //   IntegerPartOfX <<= 23;
4783   IntegerPartOfX = DAG.getNode(
4784       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4785       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4786                                   DAG.getDataLayout())));
4787 
4788   SDValue TwoToFractionalPartOfX;
4789   if (LimitFloatPrecision <= 6) {
4790     // For floating-point precision of 6:
4791     //
4792     //   TwoToFractionalPartOfX =
4793     //     0.997535578f +
4794     //       (0.735607626f + 0.252464424f * x) * x;
4795     //
4796     // error 0.0144103317, which is 6 bits
4797     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4798                              getF32Constant(DAG, 0x3e814304, dl));
4799     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4800                              getF32Constant(DAG, 0x3f3c50c8, dl));
4801     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4802     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4803                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4804   } else if (LimitFloatPrecision <= 12) {
4805     // For floating-point precision of 12:
4806     //
4807     //   TwoToFractionalPartOfX =
4808     //     0.999892986f +
4809     //       (0.696457318f +
4810     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4811     //
4812     // error 0.000107046256, which is 13 to 14 bits
4813     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4814                              getF32Constant(DAG, 0x3da235e3, dl));
4815     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4816                              getF32Constant(DAG, 0x3e65b8f3, 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, 0x3f324b07, dl));
4820     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4821     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4822                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4823   } else { // LimitFloatPrecision <= 18
4824     // For floating-point precision of 18:
4825     //
4826     //   TwoToFractionalPartOfX =
4827     //     0.999999982f +
4828     //       (0.693148872f +
4829     //         (0.240227044f +
4830     //           (0.554906021e-1f +
4831     //             (0.961591928e-2f +
4832     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4833     // error 2.47208000*10^(-7), which is better than 18 bits
4834     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4835                              getF32Constant(DAG, 0x3924b03e, dl));
4836     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4837                              getF32Constant(DAG, 0x3ab24b87, dl));
4838     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4839     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4840                              getF32Constant(DAG, 0x3c1d8c17, dl));
4841     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4842     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4843                              getF32Constant(DAG, 0x3d634a1d, dl));
4844     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4845     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4846                              getF32Constant(DAG, 0x3e75fe14, dl));
4847     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4848     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4849                               getF32Constant(DAG, 0x3f317234, dl));
4850     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4851     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4852                                          getF32Constant(DAG, 0x3f800000, dl));
4853   }
4854 
4855   // Add the exponent into the result in integer domain.
4856   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4857   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4858                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4859 }
4860 
4861 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4862 /// limited-precision mode.
4863 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4864                          const TargetLowering &TLI) {
4865   if (Op.getValueType() == MVT::f32 &&
4866       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4867 
4868     // Put the exponent in the right bit position for later addition to the
4869     // final result:
4870     //
4871     // t0 = Op * log2(e)
4872 
4873     // TODO: What fast-math-flags should be set here?
4874     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4875                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4876     return getLimitedPrecisionExp2(t0, dl, DAG);
4877   }
4878 
4879   // No special expansion.
4880   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4881 }
4882 
4883 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4884 /// limited-precision mode.
4885 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4886                          const TargetLowering &TLI) {
4887   // TODO: What fast-math-flags should be set on the floating-point nodes?
4888 
4889   if (Op.getValueType() == MVT::f32 &&
4890       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4891     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4892 
4893     // Scale the exponent by log(2).
4894     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4895     SDValue LogOfExponent =
4896         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4897                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4898 
4899     // Get the significand and build it into a floating-point number with
4900     // exponent of 1.
4901     SDValue X = GetSignificand(DAG, Op1, dl);
4902 
4903     SDValue LogOfMantissa;
4904     if (LimitFloatPrecision <= 6) {
4905       // For floating-point precision of 6:
4906       //
4907       //   LogofMantissa =
4908       //     -1.1609546f +
4909       //       (1.4034025f - 0.23903021f * x) * x;
4910       //
4911       // error 0.0034276066, which is better than 8 bits
4912       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4913                                getF32Constant(DAG, 0xbe74c456, dl));
4914       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4915                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4916       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4917       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4918                                   getF32Constant(DAG, 0x3f949a29, dl));
4919     } else if (LimitFloatPrecision <= 12) {
4920       // For floating-point precision of 12:
4921       //
4922       //   LogOfMantissa =
4923       //     -1.7417939f +
4924       //       (2.8212026f +
4925       //         (-1.4699568f +
4926       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4927       //
4928       // error 0.000061011436, which is 14 bits
4929       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4930                                getF32Constant(DAG, 0xbd67b6d6, dl));
4931       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4932                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4933       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4934       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4935                                getF32Constant(DAG, 0x3fbc278b, dl));
4936       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4937       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4938                                getF32Constant(DAG, 0x40348e95, dl));
4939       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4940       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4941                                   getF32Constant(DAG, 0x3fdef31a, dl));
4942     } else { // LimitFloatPrecision <= 18
4943       // For floating-point precision of 18:
4944       //
4945       //   LogOfMantissa =
4946       //     -2.1072184f +
4947       //       (4.2372794f +
4948       //         (-3.7029485f +
4949       //           (2.2781945f +
4950       //             (-0.87823314f +
4951       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4952       //
4953       // error 0.0000023660568, which is better than 18 bits
4954       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4955                                getF32Constant(DAG, 0xbc91e5ac, dl));
4956       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4957                                getF32Constant(DAG, 0x3e4350aa, dl));
4958       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4959       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4960                                getF32Constant(DAG, 0x3f60d3e3, dl));
4961       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4962       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4963                                getF32Constant(DAG, 0x4011cdf0, dl));
4964       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4965       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4966                                getF32Constant(DAG, 0x406cfd1c, dl));
4967       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4968       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4969                                getF32Constant(DAG, 0x408797cb, dl));
4970       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4971       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4972                                   getF32Constant(DAG, 0x4006dcab, dl));
4973     }
4974 
4975     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4976   }
4977 
4978   // No special expansion.
4979   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4980 }
4981 
4982 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4983 /// limited-precision mode.
4984 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4985                           const TargetLowering &TLI) {
4986   // TODO: What fast-math-flags should be set on the floating-point nodes?
4987 
4988   if (Op.getValueType() == MVT::f32 &&
4989       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4990     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4991 
4992     // Get the exponent.
4993     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4994 
4995     // Get the significand and build it into a floating-point number with
4996     // exponent of 1.
4997     SDValue X = GetSignificand(DAG, Op1, dl);
4998 
4999     // Different possible minimax approximations of significand in
5000     // floating-point for various degrees of accuracy over [1,2].
5001     SDValue Log2ofMantissa;
5002     if (LimitFloatPrecision <= 6) {
5003       // For floating-point precision of 6:
5004       //
5005       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5006       //
5007       // error 0.0049451742, which is more than 7 bits
5008       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5009                                getF32Constant(DAG, 0xbeb08fe0, dl));
5010       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5011                                getF32Constant(DAG, 0x40019463, dl));
5012       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5013       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5014                                    getF32Constant(DAG, 0x3fd6633d, dl));
5015     } else if (LimitFloatPrecision <= 12) {
5016       // For floating-point precision of 12:
5017       //
5018       //   Log2ofMantissa =
5019       //     -2.51285454f +
5020       //       (4.07009056f +
5021       //         (-2.12067489f +
5022       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5023       //
5024       // error 0.0000876136000, which is better than 13 bits
5025       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5026                                getF32Constant(DAG, 0xbda7262e, dl));
5027       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5028                                getF32Constant(DAG, 0x3f25280b, dl));
5029       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5030       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5031                                getF32Constant(DAG, 0x4007b923, dl));
5032       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5033       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5034                                getF32Constant(DAG, 0x40823e2f, dl));
5035       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5036       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5037                                    getF32Constant(DAG, 0x4020d29c, dl));
5038     } else { // LimitFloatPrecision <= 18
5039       // For floating-point precision of 18:
5040       //
5041       //   Log2ofMantissa =
5042       //     -3.0400495f +
5043       //       (6.1129976f +
5044       //         (-5.3420409f +
5045       //           (3.2865683f +
5046       //             (-1.2669343f +
5047       //               (0.27515199f -
5048       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5049       //
5050       // error 0.0000018516, which is better than 18 bits
5051       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5052                                getF32Constant(DAG, 0xbcd2769e, dl));
5053       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5054                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5055       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5056       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5057                                getF32Constant(DAG, 0x3fa22ae7, dl));
5058       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5059       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5060                                getF32Constant(DAG, 0x40525723, dl));
5061       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5062       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5063                                getF32Constant(DAG, 0x40aaf200, dl));
5064       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5065       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5066                                getF32Constant(DAG, 0x40c39dad, dl));
5067       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5068       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5069                                    getF32Constant(DAG, 0x4042902c, dl));
5070     }
5071 
5072     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5073   }
5074 
5075   // No special expansion.
5076   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5077 }
5078 
5079 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5080 /// limited-precision mode.
5081 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5082                            const TargetLowering &TLI) {
5083   // TODO: What fast-math-flags should be set on the floating-point nodes?
5084 
5085   if (Op.getValueType() == MVT::f32 &&
5086       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5087     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5088 
5089     // Scale the exponent by log10(2) [0.30102999f].
5090     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5091     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5092                                         getF32Constant(DAG, 0x3e9a209a, dl));
5093 
5094     // Get the significand and build it into a floating-point number with
5095     // exponent of 1.
5096     SDValue X = GetSignificand(DAG, Op1, dl);
5097 
5098     SDValue Log10ofMantissa;
5099     if (LimitFloatPrecision <= 6) {
5100       // For floating-point precision of 6:
5101       //
5102       //   Log10ofMantissa =
5103       //     -0.50419619f +
5104       //       (0.60948995f - 0.10380950f * x) * x;
5105       //
5106       // error 0.0014886165, which is 6 bits
5107       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5108                                getF32Constant(DAG, 0xbdd49a13, dl));
5109       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5110                                getF32Constant(DAG, 0x3f1c0789, dl));
5111       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5112       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5113                                     getF32Constant(DAG, 0x3f011300, dl));
5114     } else if (LimitFloatPrecision <= 12) {
5115       // For floating-point precision of 12:
5116       //
5117       //   Log10ofMantissa =
5118       //     -0.64831180f +
5119       //       (0.91751397f +
5120       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5121       //
5122       // error 0.00019228036, which is better than 12 bits
5123       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5124                                getF32Constant(DAG, 0x3d431f31, dl));
5125       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5126                                getF32Constant(DAG, 0x3ea21fb2, 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, 0x3f6ae232, dl));
5130       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5131       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5132                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5133     } else { // LimitFloatPrecision <= 18
5134       // For floating-point precision of 18:
5135       //
5136       //   Log10ofMantissa =
5137       //     -0.84299375f +
5138       //       (1.5327582f +
5139       //         (-1.0688956f +
5140       //           (0.49102474f +
5141       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5142       //
5143       // error 0.0000037995730, which is better than 18 bits
5144       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5145                                getF32Constant(DAG, 0x3c5d51ce, dl));
5146       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5147                                getF32Constant(DAG, 0x3e00685a, dl));
5148       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5149       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5150                                getF32Constant(DAG, 0x3efb6798, dl));
5151       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5152       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5153                                getF32Constant(DAG, 0x3f88d192, dl));
5154       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5155       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5156                                getF32Constant(DAG, 0x3fc4316c, dl));
5157       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5158       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5159                                     getF32Constant(DAG, 0x3f57ce70, dl));
5160     }
5161 
5162     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5163   }
5164 
5165   // No special expansion.
5166   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5167 }
5168 
5169 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5170 /// limited-precision mode.
5171 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5172                           const TargetLowering &TLI) {
5173   if (Op.getValueType() == MVT::f32 &&
5174       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5175     return getLimitedPrecisionExp2(Op, dl, DAG);
5176 
5177   // No special expansion.
5178   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5179 }
5180 
5181 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5182 /// limited-precision mode with x == 10.0f.
5183 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5184                          SelectionDAG &DAG, const TargetLowering &TLI) {
5185   bool IsExp10 = false;
5186   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5187       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5188     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5189       APFloat Ten(10.0f);
5190       IsExp10 = LHSC->isExactlyValue(Ten);
5191     }
5192   }
5193 
5194   // TODO: What fast-math-flags should be set on the FMUL node?
5195   if (IsExp10) {
5196     // Put the exponent in the right bit position for later addition to the
5197     // final result:
5198     //
5199     //   #define LOG2OF10 3.3219281f
5200     //   t0 = Op * LOG2OF10;
5201     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5202                              getF32Constant(DAG, 0x40549a78, dl));
5203     return getLimitedPrecisionExp2(t0, dl, DAG);
5204   }
5205 
5206   // No special expansion.
5207   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5208 }
5209 
5210 /// ExpandPowI - Expand a llvm.powi intrinsic.
5211 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5212                           SelectionDAG &DAG) {
5213   // If RHS is a constant, we can expand this out to a multiplication tree,
5214   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5215   // optimizing for size, we only want to do this if the expansion would produce
5216   // a small number of multiplies, otherwise we do the full expansion.
5217   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5218     // Get the exponent as a positive value.
5219     unsigned Val = RHSC->getSExtValue();
5220     if ((int)Val < 0) Val = -Val;
5221 
5222     // powi(x, 0) -> 1.0
5223     if (Val == 0)
5224       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5225 
5226     bool OptForSize = DAG.shouldOptForSize();
5227     if (!OptForSize ||
5228         // If optimizing for size, don't insert too many multiplies.
5229         // This inserts up to 5 multiplies.
5230         countPopulation(Val) + Log2_32(Val) < 7) {
5231       // We use the simple binary decomposition method to generate the multiply
5232       // sequence.  There are more optimal ways to do this (for example,
5233       // powi(x,15) generates one more multiply than it should), but this has
5234       // the benefit of being both really simple and much better than a libcall.
5235       SDValue Res;  // Logically starts equal to 1.0
5236       SDValue CurSquare = LHS;
5237       // TODO: Intrinsics should have fast-math-flags that propagate to these
5238       // nodes.
5239       while (Val) {
5240         if (Val & 1) {
5241           if (Res.getNode())
5242             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5243           else
5244             Res = CurSquare;  // 1.0*CurSquare.
5245         }
5246 
5247         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5248                                 CurSquare, CurSquare);
5249         Val >>= 1;
5250       }
5251 
5252       // If the original was negative, invert the result, producing 1/(x*x*x).
5253       if (RHSC->getSExtValue() < 0)
5254         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5255                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5256       return Res;
5257     }
5258   }
5259 
5260   // Otherwise, expand to a libcall.
5261   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5262 }
5263 
5264 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5265                             SDValue LHS, SDValue RHS, SDValue Scale,
5266                             SelectionDAG &DAG, const TargetLowering &TLI) {
5267   EVT VT = LHS.getValueType();
5268   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5269   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5270   LLVMContext &Ctx = *DAG.getContext();
5271 
5272   // If the type is legal but the operation isn't, this node might survive all
5273   // the way to operation legalization. If we end up there and we do not have
5274   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5275   // node.
5276 
5277   // Coax the legalizer into expanding the node during type legalization instead
5278   // by bumping the size by one bit. This will force it to Promote, enabling the
5279   // early expansion and avoiding the need to expand later.
5280 
5281   // We don't have to do this if Scale is 0; that can always be expanded, unless
5282   // it's a saturating signed operation. Those can experience true integer
5283   // division overflow, a case which we must avoid.
5284 
5285   // FIXME: We wouldn't have to do this (or any of the early
5286   // expansion/promotion) if it was possible to expand a libcall of an
5287   // illegal type during operation legalization. But it's not, so things
5288   // get a bit hacky.
5289   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5290   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5291       (TLI.isTypeLegal(VT) ||
5292        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5293     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5294         Opcode, VT, ScaleInt);
5295     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5296       EVT PromVT;
5297       if (VT.isScalarInteger())
5298         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5299       else if (VT.isVector()) {
5300         PromVT = VT.getVectorElementType();
5301         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5302         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5303       } else
5304         llvm_unreachable("Wrong VT for DIVFIX?");
5305       if (Signed) {
5306         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5307         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5308       } else {
5309         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5310         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5311       }
5312       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5313       // For saturating operations, we need to shift up the LHS to get the
5314       // proper saturation width, and then shift down again afterwards.
5315       if (Saturating)
5316         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5317                           DAG.getConstant(1, DL, ShiftTy));
5318       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5319       if (Saturating)
5320         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5321                           DAG.getConstant(1, DL, ShiftTy));
5322       return DAG.getZExtOrTrunc(Res, DL, VT);
5323     }
5324   }
5325 
5326   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5327 }
5328 
5329 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5330 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5331 static void
5332 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5333                      const SDValue &N) {
5334   switch (N.getOpcode()) {
5335   case ISD::CopyFromReg: {
5336     SDValue Op = N.getOperand(1);
5337     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5338                       Op.getValueType().getSizeInBits());
5339     return;
5340   }
5341   case ISD::BITCAST:
5342   case ISD::AssertZext:
5343   case ISD::AssertSext:
5344   case ISD::TRUNCATE:
5345     getUnderlyingArgRegs(Regs, N.getOperand(0));
5346     return;
5347   case ISD::BUILD_PAIR:
5348   case ISD::BUILD_VECTOR:
5349   case ISD::CONCAT_VECTORS:
5350     for (SDValue Op : N->op_values())
5351       getUnderlyingArgRegs(Regs, Op);
5352     return;
5353   default:
5354     return;
5355   }
5356 }
5357 
5358 /// If the DbgValueInst is a dbg_value of a function argument, create the
5359 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5360 /// instruction selection, they will be inserted to the entry BB.
5361 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5362     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5363     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5364   const Argument *Arg = dyn_cast<Argument>(V);
5365   if (!Arg)
5366     return false;
5367 
5368   if (!IsDbgDeclare) {
5369     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5370     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5371     // the entry block.
5372     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5373     if (!IsInEntryBlock)
5374       return false;
5375 
5376     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5377     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5378     // variable that also is a param.
5379     //
5380     // Although, if we are at the top of the entry block already, we can still
5381     // emit using ArgDbgValue. This might catch some situations when the
5382     // dbg.value refers to an argument that isn't used in the entry block, so
5383     // any CopyToReg node would be optimized out and the only way to express
5384     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5385     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5386     // we should only emit as ArgDbgValue if the Variable is an argument to the
5387     // current function, and the dbg.value intrinsic is found in the entry
5388     // block.
5389     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5390         !DL->getInlinedAt();
5391     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5392     if (!IsInPrologue && !VariableIsFunctionInputArg)
5393       return false;
5394 
5395     // Here we assume that a function argument on IR level only can be used to
5396     // describe one input parameter on source level. If we for example have
5397     // source code like this
5398     //
5399     //    struct A { long x, y; };
5400     //    void foo(struct A a, long b) {
5401     //      ...
5402     //      b = a.x;
5403     //      ...
5404     //    }
5405     //
5406     // and IR like this
5407     //
5408     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5409     //  entry:
5410     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5411     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5412     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5413     //    ...
5414     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5415     //    ...
5416     //
5417     // then the last dbg.value is describing a parameter "b" using a value that
5418     // is an argument. But since we already has used %a1 to describe a parameter
5419     // we should not handle that last dbg.value here (that would result in an
5420     // incorrect hoisting of the DBG_VALUE to the function entry).
5421     // Notice that we allow one dbg.value per IR level argument, to accommodate
5422     // for the situation with fragments above.
5423     if (VariableIsFunctionInputArg) {
5424       unsigned ArgNo = Arg->getArgNo();
5425       if (ArgNo >= FuncInfo.DescribedArgs.size())
5426         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5427       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5428         return false;
5429       FuncInfo.DescribedArgs.set(ArgNo);
5430     }
5431   }
5432 
5433   MachineFunction &MF = DAG.getMachineFunction();
5434   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5435 
5436   bool IsIndirect = false;
5437   Optional<MachineOperand> Op;
5438   // Some arguments' frame index is recorded during argument lowering.
5439   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5440   if (FI != std::numeric_limits<int>::max())
5441     Op = MachineOperand::CreateFI(FI);
5442 
5443   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5444   if (!Op && N.getNode()) {
5445     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5446     Register Reg;
5447     if (ArgRegsAndSizes.size() == 1)
5448       Reg = ArgRegsAndSizes.front().first;
5449 
5450     if (Reg && Reg.isVirtual()) {
5451       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5452       Register PR = RegInfo.getLiveInPhysReg(Reg);
5453       if (PR)
5454         Reg = PR;
5455     }
5456     if (Reg) {
5457       Op = MachineOperand::CreateReg(Reg, false);
5458       IsIndirect = IsDbgDeclare;
5459     }
5460   }
5461 
5462   if (!Op && N.getNode()) {
5463     // Check if frame index is available.
5464     SDValue LCandidate = peekThroughBitcasts(N);
5465     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5466       if (FrameIndexSDNode *FINode =
5467           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5468         Op = MachineOperand::CreateFI(FINode->getIndex());
5469   }
5470 
5471   if (!Op) {
5472     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5473     auto splitMultiRegDbgValue
5474       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5475       unsigned Offset = 0;
5476       for (auto RegAndSize : SplitRegs) {
5477         // If the expression is already a fragment, the current register
5478         // offset+size might extend beyond the fragment. In this case, only
5479         // the register bits that are inside the fragment are relevant.
5480         int RegFragmentSizeInBits = RegAndSize.second;
5481         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5482           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5483           // The register is entirely outside the expression fragment,
5484           // so is irrelevant for debug info.
5485           if (Offset >= ExprFragmentSizeInBits)
5486             break;
5487           // The register is partially outside the expression fragment, only
5488           // the low bits within the fragment are relevant for debug info.
5489           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5490             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5491           }
5492         }
5493 
5494         auto FragmentExpr = DIExpression::createFragmentExpression(
5495             Expr, Offset, RegFragmentSizeInBits);
5496         Offset += RegAndSize.second;
5497         // If a valid fragment expression cannot be created, the variable's
5498         // correct value cannot be determined and so it is set as Undef.
5499         if (!FragmentExpr) {
5500           SDDbgValue *SDV = DAG.getConstantDbgValue(
5501               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5502           DAG.AddDbgValue(SDV, nullptr, false);
5503           continue;
5504         }
5505         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5506         FuncInfo.ArgDbgValues.push_back(
5507           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5508                   RegAndSize.first, Variable, *FragmentExpr));
5509       }
5510     };
5511 
5512     // Check if ValueMap has reg number.
5513     DenseMap<const Value *, Register>::const_iterator
5514       VMI = FuncInfo.ValueMap.find(V);
5515     if (VMI != FuncInfo.ValueMap.end()) {
5516       const auto &TLI = DAG.getTargetLoweringInfo();
5517       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5518                        V->getType(), getABIRegCopyCC(V));
5519       if (RFV.occupiesMultipleRegs()) {
5520         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5521         return true;
5522       }
5523 
5524       Op = MachineOperand::CreateReg(VMI->second, false);
5525       IsIndirect = IsDbgDeclare;
5526     } else if (ArgRegsAndSizes.size() > 1) {
5527       // This was split due to the calling convention, and no virtual register
5528       // mapping exists for the value.
5529       splitMultiRegDbgValue(ArgRegsAndSizes);
5530       return true;
5531     }
5532   }
5533 
5534   if (!Op)
5535     return false;
5536 
5537   assert(Variable->isValidLocationForIntrinsic(DL) &&
5538          "Expected inlined-at fields to agree");
5539   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5540   FuncInfo.ArgDbgValues.push_back(
5541       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5542               *Op, Variable, Expr));
5543 
5544   return true;
5545 }
5546 
5547 /// Return the appropriate SDDbgValue based on N.
5548 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5549                                              DILocalVariable *Variable,
5550                                              DIExpression *Expr,
5551                                              const DebugLoc &dl,
5552                                              unsigned DbgSDNodeOrder) {
5553   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5554     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5555     // stack slot locations.
5556     //
5557     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5558     // debug values here after optimization:
5559     //
5560     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5561     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5562     //
5563     // Both describe the direct values of their associated variables.
5564     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5565                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5566   }
5567   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5568                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5569 }
5570 
5571 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5572   switch (Intrinsic) {
5573   case Intrinsic::smul_fix:
5574     return ISD::SMULFIX;
5575   case Intrinsic::umul_fix:
5576     return ISD::UMULFIX;
5577   case Intrinsic::smul_fix_sat:
5578     return ISD::SMULFIXSAT;
5579   case Intrinsic::umul_fix_sat:
5580     return ISD::UMULFIXSAT;
5581   case Intrinsic::sdiv_fix:
5582     return ISD::SDIVFIX;
5583   case Intrinsic::udiv_fix:
5584     return ISD::UDIVFIX;
5585   case Intrinsic::sdiv_fix_sat:
5586     return ISD::SDIVFIXSAT;
5587   case Intrinsic::udiv_fix_sat:
5588     return ISD::UDIVFIXSAT;
5589   default:
5590     llvm_unreachable("Unhandled fixed point intrinsic");
5591   }
5592 }
5593 
5594 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5595                                            const char *FunctionName) {
5596   assert(FunctionName && "FunctionName must not be nullptr");
5597   SDValue Callee = DAG.getExternalSymbol(
5598       FunctionName,
5599       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5600   LowerCallTo(I, Callee, I.isTailCall());
5601 }
5602 
5603 /// Lower the call to the specified intrinsic function.
5604 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5605                                              unsigned Intrinsic) {
5606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5607   SDLoc sdl = getCurSDLoc();
5608   DebugLoc dl = getCurDebugLoc();
5609   SDValue Res;
5610 
5611   switch (Intrinsic) {
5612   default:
5613     // By default, turn this into a target intrinsic node.
5614     visitTargetIntrinsic(I, Intrinsic);
5615     return;
5616   case Intrinsic::vscale: {
5617     match(&I, m_VScale(DAG.getDataLayout()));
5618     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5619     setValue(&I,
5620              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5621     return;
5622   }
5623   case Intrinsic::vastart:  visitVAStart(I); return;
5624   case Intrinsic::vaend:    visitVAEnd(I); return;
5625   case Intrinsic::vacopy:   visitVACopy(I); return;
5626   case Intrinsic::returnaddress:
5627     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5628                              TLI.getPointerTy(DAG.getDataLayout()),
5629                              getValue(I.getArgOperand(0))));
5630     return;
5631   case Intrinsic::addressofreturnaddress:
5632     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5633                              TLI.getPointerTy(DAG.getDataLayout())));
5634     return;
5635   case Intrinsic::sponentry:
5636     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5637                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5638     return;
5639   case Intrinsic::frameaddress:
5640     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5641                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5642                              getValue(I.getArgOperand(0))));
5643     return;
5644   case Intrinsic::read_register: {
5645     Value *Reg = I.getArgOperand(0);
5646     SDValue Chain = getRoot();
5647     SDValue RegName =
5648         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5649     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5650     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5651       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5652     setValue(&I, Res);
5653     DAG.setRoot(Res.getValue(1));
5654     return;
5655   }
5656   case Intrinsic::write_register: {
5657     Value *Reg = I.getArgOperand(0);
5658     Value *RegValue = I.getArgOperand(1);
5659     SDValue Chain = getRoot();
5660     SDValue RegName =
5661         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5662     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5663                             RegName, getValue(RegValue)));
5664     return;
5665   }
5666   case Intrinsic::memcpy: {
5667     const auto &MCI = cast<MemCpyInst>(I);
5668     SDValue Op1 = getValue(I.getArgOperand(0));
5669     SDValue Op2 = getValue(I.getArgOperand(1));
5670     SDValue Op3 = getValue(I.getArgOperand(2));
5671     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5672     Align DstAlign = MCI.getDestAlign().valueOrOne();
5673     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5674     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5675     bool isVol = MCI.isVolatile();
5676     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5677     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5678     // node.
5679     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5680     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5681                                /* AlwaysInline */ false, isTC,
5682                                MachinePointerInfo(I.getArgOperand(0)),
5683                                MachinePointerInfo(I.getArgOperand(1)));
5684     updateDAGForMaybeTailCall(MC);
5685     return;
5686   }
5687   case Intrinsic::memcpy_inline: {
5688     const auto &MCI = cast<MemCpyInlineInst>(I);
5689     SDValue Dst = getValue(I.getArgOperand(0));
5690     SDValue Src = getValue(I.getArgOperand(1));
5691     SDValue Size = getValue(I.getArgOperand(2));
5692     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5693     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5694     Align DstAlign = MCI.getDestAlign().valueOrOne();
5695     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5696     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5697     bool isVol = MCI.isVolatile();
5698     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5699     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5700     // node.
5701     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5702                                /* AlwaysInline */ true, isTC,
5703                                MachinePointerInfo(I.getArgOperand(0)),
5704                                MachinePointerInfo(I.getArgOperand(1)));
5705     updateDAGForMaybeTailCall(MC);
5706     return;
5707   }
5708   case Intrinsic::memset: {
5709     const auto &MSI = cast<MemSetInst>(I);
5710     SDValue Op1 = getValue(I.getArgOperand(0));
5711     SDValue Op2 = getValue(I.getArgOperand(1));
5712     SDValue Op3 = getValue(I.getArgOperand(2));
5713     // @llvm.memset defines 0 and 1 to both mean no alignment.
5714     Align Alignment = MSI.getDestAlign().valueOrOne();
5715     bool isVol = MSI.isVolatile();
5716     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5717     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5718     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5719                                MachinePointerInfo(I.getArgOperand(0)));
5720     updateDAGForMaybeTailCall(MS);
5721     return;
5722   }
5723   case Intrinsic::memmove: {
5724     const auto &MMI = cast<MemMoveInst>(I);
5725     SDValue Op1 = getValue(I.getArgOperand(0));
5726     SDValue Op2 = getValue(I.getArgOperand(1));
5727     SDValue Op3 = getValue(I.getArgOperand(2));
5728     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5729     Align DstAlign = MMI.getDestAlign().valueOrOne();
5730     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5731     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5732     bool isVol = MMI.isVolatile();
5733     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5734     // FIXME: Support passing different dest/src alignments to the memmove DAG
5735     // node.
5736     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5737     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5738                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5739                                 MachinePointerInfo(I.getArgOperand(1)));
5740     updateDAGForMaybeTailCall(MM);
5741     return;
5742   }
5743   case Intrinsic::memcpy_element_unordered_atomic: {
5744     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5745     SDValue Dst = getValue(MI.getRawDest());
5746     SDValue Src = getValue(MI.getRawSource());
5747     SDValue Length = getValue(MI.getLength());
5748 
5749     unsigned DstAlign = MI.getDestAlignment();
5750     unsigned SrcAlign = MI.getSourceAlignment();
5751     Type *LengthTy = MI.getLength()->getType();
5752     unsigned ElemSz = MI.getElementSizeInBytes();
5753     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5754     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5755                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5756                                      MachinePointerInfo(MI.getRawDest()),
5757                                      MachinePointerInfo(MI.getRawSource()));
5758     updateDAGForMaybeTailCall(MC);
5759     return;
5760   }
5761   case Intrinsic::memmove_element_unordered_atomic: {
5762     auto &MI = cast<AtomicMemMoveInst>(I);
5763     SDValue Dst = getValue(MI.getRawDest());
5764     SDValue Src = getValue(MI.getRawSource());
5765     SDValue Length = getValue(MI.getLength());
5766 
5767     unsigned DstAlign = MI.getDestAlignment();
5768     unsigned SrcAlign = MI.getSourceAlignment();
5769     Type *LengthTy = MI.getLength()->getType();
5770     unsigned ElemSz = MI.getElementSizeInBytes();
5771     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5772     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5773                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5774                                       MachinePointerInfo(MI.getRawDest()),
5775                                       MachinePointerInfo(MI.getRawSource()));
5776     updateDAGForMaybeTailCall(MC);
5777     return;
5778   }
5779   case Intrinsic::memset_element_unordered_atomic: {
5780     auto &MI = cast<AtomicMemSetInst>(I);
5781     SDValue Dst = getValue(MI.getRawDest());
5782     SDValue Val = getValue(MI.getValue());
5783     SDValue Length = getValue(MI.getLength());
5784 
5785     unsigned DstAlign = MI.getDestAlignment();
5786     Type *LengthTy = MI.getLength()->getType();
5787     unsigned ElemSz = MI.getElementSizeInBytes();
5788     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5789     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5790                                      LengthTy, ElemSz, isTC,
5791                                      MachinePointerInfo(MI.getRawDest()));
5792     updateDAGForMaybeTailCall(MC);
5793     return;
5794   }
5795   case Intrinsic::dbg_addr:
5796   case Intrinsic::dbg_declare: {
5797     const auto &DI = cast<DbgVariableIntrinsic>(I);
5798     DILocalVariable *Variable = DI.getVariable();
5799     DIExpression *Expression = DI.getExpression();
5800     dropDanglingDebugInfo(Variable, Expression);
5801     assert(Variable && "Missing variable");
5802     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5803                       << "\n");
5804     // Check if address has undef value.
5805     const Value *Address = DI.getVariableLocation();
5806     if (!Address || isa<UndefValue>(Address) ||
5807         (Address->use_empty() && !isa<Argument>(Address))) {
5808       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5809                         << " (bad/undef/unused-arg address)\n");
5810       return;
5811     }
5812 
5813     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5814 
5815     // Check if this variable can be described by a frame index, typically
5816     // either as a static alloca or a byval parameter.
5817     int FI = std::numeric_limits<int>::max();
5818     if (const auto *AI =
5819             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5820       if (AI->isStaticAlloca()) {
5821         auto I = FuncInfo.StaticAllocaMap.find(AI);
5822         if (I != FuncInfo.StaticAllocaMap.end())
5823           FI = I->second;
5824       }
5825     } else if (const auto *Arg = dyn_cast<Argument>(
5826                    Address->stripInBoundsConstantOffsets())) {
5827       FI = FuncInfo.getArgumentFrameIndex(Arg);
5828     }
5829 
5830     // llvm.dbg.addr is control dependent and always generates indirect
5831     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5832     // the MachineFunction variable table.
5833     if (FI != std::numeric_limits<int>::max()) {
5834       if (Intrinsic == Intrinsic::dbg_addr) {
5835         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5836             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5837         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5838       } else {
5839         LLVM_DEBUG(dbgs() << "Skipping " << DI
5840                           << " (variable info stashed in MF side table)\n");
5841       }
5842       return;
5843     }
5844 
5845     SDValue &N = NodeMap[Address];
5846     if (!N.getNode() && isa<Argument>(Address))
5847       // Check unused arguments map.
5848       N = UnusedArgNodeMap[Address];
5849     SDDbgValue *SDV;
5850     if (N.getNode()) {
5851       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5852         Address = BCI->getOperand(0);
5853       // Parameters are handled specially.
5854       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5855       if (isParameter && FINode) {
5856         // Byval parameter. We have a frame index at this point.
5857         SDV =
5858             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5859                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5860       } else if (isa<Argument>(Address)) {
5861         // Address is an argument, so try to emit its dbg value using
5862         // virtual register info from the FuncInfo.ValueMap.
5863         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5864         return;
5865       } else {
5866         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5867                               true, dl, SDNodeOrder);
5868       }
5869       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5870     } else {
5871       // If Address is an argument then try to emit its dbg value using
5872       // virtual register info from the FuncInfo.ValueMap.
5873       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5874                                     N)) {
5875         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5876                           << " (could not emit func-arg dbg_value)\n");
5877       }
5878     }
5879     return;
5880   }
5881   case Intrinsic::dbg_label: {
5882     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5883     DILabel *Label = DI.getLabel();
5884     assert(Label && "Missing label");
5885 
5886     SDDbgLabel *SDV;
5887     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5888     DAG.AddDbgLabel(SDV);
5889     return;
5890   }
5891   case Intrinsic::dbg_value: {
5892     const DbgValueInst &DI = cast<DbgValueInst>(I);
5893     assert(DI.getVariable() && "Missing variable");
5894 
5895     DILocalVariable *Variable = DI.getVariable();
5896     DIExpression *Expression = DI.getExpression();
5897     dropDanglingDebugInfo(Variable, Expression);
5898     const Value *V = DI.getValue();
5899     if (!V)
5900       return;
5901 
5902     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5903         SDNodeOrder))
5904       return;
5905 
5906     // TODO: Dangling debug info will eventually either be resolved or produce
5907     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5908     // between the original dbg.value location and its resolved DBG_VALUE, which
5909     // we should ideally fill with an extra Undef DBG_VALUE.
5910 
5911     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5912     return;
5913   }
5914 
5915   case Intrinsic::eh_typeid_for: {
5916     // Find the type id for the given typeinfo.
5917     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5918     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5919     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5920     setValue(&I, Res);
5921     return;
5922   }
5923 
5924   case Intrinsic::eh_return_i32:
5925   case Intrinsic::eh_return_i64:
5926     DAG.getMachineFunction().setCallsEHReturn(true);
5927     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5928                             MVT::Other,
5929                             getControlRoot(),
5930                             getValue(I.getArgOperand(0)),
5931                             getValue(I.getArgOperand(1))));
5932     return;
5933   case Intrinsic::eh_unwind_init:
5934     DAG.getMachineFunction().setCallsUnwindInit(true);
5935     return;
5936   case Intrinsic::eh_dwarf_cfa:
5937     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5938                              TLI.getPointerTy(DAG.getDataLayout()),
5939                              getValue(I.getArgOperand(0))));
5940     return;
5941   case Intrinsic::eh_sjlj_callsite: {
5942     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5943     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5944     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5945     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5946 
5947     MMI.setCurrentCallSite(CI->getZExtValue());
5948     return;
5949   }
5950   case Intrinsic::eh_sjlj_functioncontext: {
5951     // Get and store the index of the function context.
5952     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5953     AllocaInst *FnCtx =
5954       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5955     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5956     MFI.setFunctionContextIndex(FI);
5957     return;
5958   }
5959   case Intrinsic::eh_sjlj_setjmp: {
5960     SDValue Ops[2];
5961     Ops[0] = getRoot();
5962     Ops[1] = getValue(I.getArgOperand(0));
5963     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5964                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5965     setValue(&I, Op.getValue(0));
5966     DAG.setRoot(Op.getValue(1));
5967     return;
5968   }
5969   case Intrinsic::eh_sjlj_longjmp:
5970     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5971                             getRoot(), getValue(I.getArgOperand(0))));
5972     return;
5973   case Intrinsic::eh_sjlj_setup_dispatch:
5974     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5975                             getRoot()));
5976     return;
5977   case Intrinsic::masked_gather:
5978     visitMaskedGather(I);
5979     return;
5980   case Intrinsic::masked_load:
5981     visitMaskedLoad(I);
5982     return;
5983   case Intrinsic::masked_scatter:
5984     visitMaskedScatter(I);
5985     return;
5986   case Intrinsic::masked_store:
5987     visitMaskedStore(I);
5988     return;
5989   case Intrinsic::masked_expandload:
5990     visitMaskedLoad(I, true /* IsExpanding */);
5991     return;
5992   case Intrinsic::masked_compressstore:
5993     visitMaskedStore(I, true /* IsCompressing */);
5994     return;
5995   case Intrinsic::powi:
5996     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5997                             getValue(I.getArgOperand(1)), DAG));
5998     return;
5999   case Intrinsic::log:
6000     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6001     return;
6002   case Intrinsic::log2:
6003     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6004     return;
6005   case Intrinsic::log10:
6006     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6007     return;
6008   case Intrinsic::exp:
6009     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6010     return;
6011   case Intrinsic::exp2:
6012     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6013     return;
6014   case Intrinsic::pow:
6015     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6016                            getValue(I.getArgOperand(1)), DAG, TLI));
6017     return;
6018   case Intrinsic::sqrt:
6019   case Intrinsic::fabs:
6020   case Intrinsic::sin:
6021   case Intrinsic::cos:
6022   case Intrinsic::floor:
6023   case Intrinsic::ceil:
6024   case Intrinsic::trunc:
6025   case Intrinsic::rint:
6026   case Intrinsic::nearbyint:
6027   case Intrinsic::round:
6028   case Intrinsic::canonicalize: {
6029     unsigned Opcode;
6030     switch (Intrinsic) {
6031     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6032     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6033     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6034     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6035     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6036     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6037     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6038     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6039     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6040     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6041     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6042     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6043     }
6044 
6045     setValue(&I, DAG.getNode(Opcode, sdl,
6046                              getValue(I.getArgOperand(0)).getValueType(),
6047                              getValue(I.getArgOperand(0))));
6048     return;
6049   }
6050   case Intrinsic::lround:
6051   case Intrinsic::llround:
6052   case Intrinsic::lrint:
6053   case Intrinsic::llrint: {
6054     unsigned Opcode;
6055     switch (Intrinsic) {
6056     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6057     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6058     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6059     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6060     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6061     }
6062 
6063     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6064     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6065                              getValue(I.getArgOperand(0))));
6066     return;
6067   }
6068   case Intrinsic::minnum:
6069     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6070                              getValue(I.getArgOperand(0)).getValueType(),
6071                              getValue(I.getArgOperand(0)),
6072                              getValue(I.getArgOperand(1))));
6073     return;
6074   case Intrinsic::maxnum:
6075     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6076                              getValue(I.getArgOperand(0)).getValueType(),
6077                              getValue(I.getArgOperand(0)),
6078                              getValue(I.getArgOperand(1))));
6079     return;
6080   case Intrinsic::minimum:
6081     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6082                              getValue(I.getArgOperand(0)).getValueType(),
6083                              getValue(I.getArgOperand(0)),
6084                              getValue(I.getArgOperand(1))));
6085     return;
6086   case Intrinsic::maximum:
6087     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6088                              getValue(I.getArgOperand(0)).getValueType(),
6089                              getValue(I.getArgOperand(0)),
6090                              getValue(I.getArgOperand(1))));
6091     return;
6092   case Intrinsic::copysign:
6093     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6094                              getValue(I.getArgOperand(0)).getValueType(),
6095                              getValue(I.getArgOperand(0)),
6096                              getValue(I.getArgOperand(1))));
6097     return;
6098   case Intrinsic::fma:
6099     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6100                              getValue(I.getArgOperand(0)).getValueType(),
6101                              getValue(I.getArgOperand(0)),
6102                              getValue(I.getArgOperand(1)),
6103                              getValue(I.getArgOperand(2))));
6104     return;
6105 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6106   case Intrinsic::INTRINSIC:
6107 #include "llvm/IR/ConstrainedOps.def"
6108     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6109     return;
6110   case Intrinsic::fmuladd: {
6111     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6112     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6113         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6114       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6115                                getValue(I.getArgOperand(0)).getValueType(),
6116                                getValue(I.getArgOperand(0)),
6117                                getValue(I.getArgOperand(1)),
6118                                getValue(I.getArgOperand(2))));
6119     } else {
6120       // TODO: Intrinsic calls should have fast-math-flags.
6121       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6122                                 getValue(I.getArgOperand(0)).getValueType(),
6123                                 getValue(I.getArgOperand(0)),
6124                                 getValue(I.getArgOperand(1)));
6125       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6126                                 getValue(I.getArgOperand(0)).getValueType(),
6127                                 Mul,
6128                                 getValue(I.getArgOperand(2)));
6129       setValue(&I, Add);
6130     }
6131     return;
6132   }
6133   case Intrinsic::convert_to_fp16:
6134     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6135                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6136                                          getValue(I.getArgOperand(0)),
6137                                          DAG.getTargetConstant(0, sdl,
6138                                                                MVT::i32))));
6139     return;
6140   case Intrinsic::convert_from_fp16:
6141     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6142                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6143                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6144                                          getValue(I.getArgOperand(0)))));
6145     return;
6146   case Intrinsic::pcmarker: {
6147     SDValue Tmp = getValue(I.getArgOperand(0));
6148     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6149     return;
6150   }
6151   case Intrinsic::readcyclecounter: {
6152     SDValue Op = getRoot();
6153     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6154                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6155     setValue(&I, Res);
6156     DAG.setRoot(Res.getValue(1));
6157     return;
6158   }
6159   case Intrinsic::bitreverse:
6160     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6161                              getValue(I.getArgOperand(0)).getValueType(),
6162                              getValue(I.getArgOperand(0))));
6163     return;
6164   case Intrinsic::bswap:
6165     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6166                              getValue(I.getArgOperand(0)).getValueType(),
6167                              getValue(I.getArgOperand(0))));
6168     return;
6169   case Intrinsic::cttz: {
6170     SDValue Arg = getValue(I.getArgOperand(0));
6171     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6172     EVT Ty = Arg.getValueType();
6173     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6174                              sdl, Ty, Arg));
6175     return;
6176   }
6177   case Intrinsic::ctlz: {
6178     SDValue Arg = getValue(I.getArgOperand(0));
6179     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6180     EVT Ty = Arg.getValueType();
6181     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6182                              sdl, Ty, Arg));
6183     return;
6184   }
6185   case Intrinsic::ctpop: {
6186     SDValue Arg = getValue(I.getArgOperand(0));
6187     EVT Ty = Arg.getValueType();
6188     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6189     return;
6190   }
6191   case Intrinsic::fshl:
6192   case Intrinsic::fshr: {
6193     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6194     SDValue X = getValue(I.getArgOperand(0));
6195     SDValue Y = getValue(I.getArgOperand(1));
6196     SDValue Z = getValue(I.getArgOperand(2));
6197     EVT VT = X.getValueType();
6198     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6199     SDValue Zero = DAG.getConstant(0, sdl, VT);
6200     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6201 
6202     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6203     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6204       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6205       return;
6206     }
6207 
6208     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6209     // avoid the select that is necessary in the general case to filter out
6210     // the 0-shift possibility that leads to UB.
6211     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6212       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6213       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6214         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6215         return;
6216       }
6217 
6218       // Some targets only rotate one way. Try the opposite direction.
6219       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6220       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6221         // Negate the shift amount because it is safe to ignore the high bits.
6222         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6223         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6224         return;
6225       }
6226 
6227       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6228       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6229       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6230       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6231       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6232       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6233       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6234       return;
6235     }
6236 
6237     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6238     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6239     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6240     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6241     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6242     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6243 
6244     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6245     // and that is undefined. We must compare and select to avoid UB.
6246     EVT CCVT = MVT::i1;
6247     if (VT.isVector())
6248       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6249 
6250     // For fshl, 0-shift returns the 1st arg (X).
6251     // For fshr, 0-shift returns the 2nd arg (Y).
6252     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6253     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6254     return;
6255   }
6256   case Intrinsic::sadd_sat: {
6257     SDValue Op1 = getValue(I.getArgOperand(0));
6258     SDValue Op2 = getValue(I.getArgOperand(1));
6259     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6260     return;
6261   }
6262   case Intrinsic::uadd_sat: {
6263     SDValue Op1 = getValue(I.getArgOperand(0));
6264     SDValue Op2 = getValue(I.getArgOperand(1));
6265     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6266     return;
6267   }
6268   case Intrinsic::ssub_sat: {
6269     SDValue Op1 = getValue(I.getArgOperand(0));
6270     SDValue Op2 = getValue(I.getArgOperand(1));
6271     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6272     return;
6273   }
6274   case Intrinsic::usub_sat: {
6275     SDValue Op1 = getValue(I.getArgOperand(0));
6276     SDValue Op2 = getValue(I.getArgOperand(1));
6277     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6278     return;
6279   }
6280   case Intrinsic::smul_fix:
6281   case Intrinsic::umul_fix:
6282   case Intrinsic::smul_fix_sat:
6283   case Intrinsic::umul_fix_sat: {
6284     SDValue Op1 = getValue(I.getArgOperand(0));
6285     SDValue Op2 = getValue(I.getArgOperand(1));
6286     SDValue Op3 = getValue(I.getArgOperand(2));
6287     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6288                              Op1.getValueType(), Op1, Op2, Op3));
6289     return;
6290   }
6291   case Intrinsic::sdiv_fix:
6292   case Intrinsic::udiv_fix:
6293   case Intrinsic::sdiv_fix_sat:
6294   case Intrinsic::udiv_fix_sat: {
6295     SDValue Op1 = getValue(I.getArgOperand(0));
6296     SDValue Op2 = getValue(I.getArgOperand(1));
6297     SDValue Op3 = getValue(I.getArgOperand(2));
6298     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6299                               Op1, Op2, Op3, DAG, TLI));
6300     return;
6301   }
6302   case Intrinsic::stacksave: {
6303     SDValue Op = getRoot();
6304     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6305     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6306     setValue(&I, Res);
6307     DAG.setRoot(Res.getValue(1));
6308     return;
6309   }
6310   case Intrinsic::stackrestore:
6311     Res = getValue(I.getArgOperand(0));
6312     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6313     return;
6314   case Intrinsic::get_dynamic_area_offset: {
6315     SDValue Op = getRoot();
6316     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6317     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6318     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6319     // target.
6320     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6321       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6322                          " intrinsic!");
6323     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6324                       Op);
6325     DAG.setRoot(Op);
6326     setValue(&I, Res);
6327     return;
6328   }
6329   case Intrinsic::stackguard: {
6330     MachineFunction &MF = DAG.getMachineFunction();
6331     const Module &M = *MF.getFunction().getParent();
6332     SDValue Chain = getRoot();
6333     if (TLI.useLoadStackGuardNode()) {
6334       Res = getLoadStackGuard(DAG, sdl, Chain);
6335     } else {
6336       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6337       const Value *Global = TLI.getSDagStackGuard(M);
6338       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6339       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6340                         MachinePointerInfo(Global, 0), Align,
6341                         MachineMemOperand::MOVolatile);
6342     }
6343     if (TLI.useStackGuardXorFP())
6344       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6345     DAG.setRoot(Chain);
6346     setValue(&I, Res);
6347     return;
6348   }
6349   case Intrinsic::stackprotector: {
6350     // Emit code into the DAG to store the stack guard onto the stack.
6351     MachineFunction &MF = DAG.getMachineFunction();
6352     MachineFrameInfo &MFI = MF.getFrameInfo();
6353     SDValue Src, Chain = getRoot();
6354 
6355     if (TLI.useLoadStackGuardNode())
6356       Src = getLoadStackGuard(DAG, sdl, Chain);
6357     else
6358       Src = getValue(I.getArgOperand(0));   // The guard's value.
6359 
6360     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6361 
6362     int FI = FuncInfo.StaticAllocaMap[Slot];
6363     MFI.setStackProtectorIndex(FI);
6364     EVT PtrTy = Src.getValueType();
6365 
6366     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6367 
6368     // Store the stack protector onto the stack.
6369     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6370                                                  DAG.getMachineFunction(), FI),
6371                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6372     setValue(&I, Res);
6373     DAG.setRoot(Res);
6374     return;
6375   }
6376   case Intrinsic::objectsize:
6377     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6378 
6379   case Intrinsic::is_constant:
6380     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6381 
6382   case Intrinsic::annotation:
6383   case Intrinsic::ptr_annotation:
6384   case Intrinsic::launder_invariant_group:
6385   case Intrinsic::strip_invariant_group:
6386     // Drop the intrinsic, but forward the value
6387     setValue(&I, getValue(I.getOperand(0)));
6388     return;
6389   case Intrinsic::assume:
6390   case Intrinsic::var_annotation:
6391   case Intrinsic::sideeffect:
6392     // Discard annotate attributes, assumptions, and artificial side-effects.
6393     return;
6394 
6395   case Intrinsic::codeview_annotation: {
6396     // Emit a label associated with this metadata.
6397     MachineFunction &MF = DAG.getMachineFunction();
6398     MCSymbol *Label =
6399         MF.getMMI().getContext().createTempSymbol("annotation", true);
6400     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6401     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6402     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6403     DAG.setRoot(Res);
6404     return;
6405   }
6406 
6407   case Intrinsic::init_trampoline: {
6408     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6409 
6410     SDValue Ops[6];
6411     Ops[0] = getRoot();
6412     Ops[1] = getValue(I.getArgOperand(0));
6413     Ops[2] = getValue(I.getArgOperand(1));
6414     Ops[3] = getValue(I.getArgOperand(2));
6415     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6416     Ops[5] = DAG.getSrcValue(F);
6417 
6418     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6419 
6420     DAG.setRoot(Res);
6421     return;
6422   }
6423   case Intrinsic::adjust_trampoline:
6424     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6425                              TLI.getPointerTy(DAG.getDataLayout()),
6426                              getValue(I.getArgOperand(0))));
6427     return;
6428   case Intrinsic::gcroot: {
6429     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6430            "only valid in functions with gc specified, enforced by Verifier");
6431     assert(GFI && "implied by previous");
6432     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6433     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6434 
6435     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6436     GFI->addStackRoot(FI->getIndex(), TypeMap);
6437     return;
6438   }
6439   case Intrinsic::gcread:
6440   case Intrinsic::gcwrite:
6441     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6442   case Intrinsic::flt_rounds:
6443     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6444     setValue(&I, Res);
6445     DAG.setRoot(Res.getValue(1));
6446     return;
6447 
6448   case Intrinsic::expect:
6449     // Just replace __builtin_expect(exp, c) with EXP.
6450     setValue(&I, getValue(I.getArgOperand(0)));
6451     return;
6452 
6453   case Intrinsic::debugtrap:
6454   case Intrinsic::trap: {
6455     StringRef TrapFuncName =
6456         I.getAttributes()
6457             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6458             .getValueAsString();
6459     if (TrapFuncName.empty()) {
6460       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6461         ISD::TRAP : ISD::DEBUGTRAP;
6462       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6463       return;
6464     }
6465     TargetLowering::ArgListTy Args;
6466 
6467     TargetLowering::CallLoweringInfo CLI(DAG);
6468     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6469         CallingConv::C, I.getType(),
6470         DAG.getExternalSymbol(TrapFuncName.data(),
6471                               TLI.getPointerTy(DAG.getDataLayout())),
6472         std::move(Args));
6473 
6474     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6475     DAG.setRoot(Result.second);
6476     return;
6477   }
6478 
6479   case Intrinsic::uadd_with_overflow:
6480   case Intrinsic::sadd_with_overflow:
6481   case Intrinsic::usub_with_overflow:
6482   case Intrinsic::ssub_with_overflow:
6483   case Intrinsic::umul_with_overflow:
6484   case Intrinsic::smul_with_overflow: {
6485     ISD::NodeType Op;
6486     switch (Intrinsic) {
6487     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6488     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6489     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6490     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6491     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6492     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6493     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6494     }
6495     SDValue Op1 = getValue(I.getArgOperand(0));
6496     SDValue Op2 = getValue(I.getArgOperand(1));
6497 
6498     EVT ResultVT = Op1.getValueType();
6499     EVT OverflowVT = MVT::i1;
6500     if (ResultVT.isVector())
6501       OverflowVT = EVT::getVectorVT(
6502           *Context, OverflowVT, ResultVT.getVectorNumElements());
6503 
6504     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6505     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6506     return;
6507   }
6508   case Intrinsic::prefetch: {
6509     SDValue Ops[5];
6510     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6511     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6512     Ops[0] = DAG.getRoot();
6513     Ops[1] = getValue(I.getArgOperand(0));
6514     Ops[2] = getValue(I.getArgOperand(1));
6515     Ops[3] = getValue(I.getArgOperand(2));
6516     Ops[4] = getValue(I.getArgOperand(3));
6517     SDValue Result = DAG.getMemIntrinsicNode(
6518         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6519         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6520         /* align */ None, Flags);
6521 
6522     // Chain the prefetch in parallell with any pending loads, to stay out of
6523     // the way of later optimizations.
6524     PendingLoads.push_back(Result);
6525     Result = getRoot();
6526     DAG.setRoot(Result);
6527     return;
6528   }
6529   case Intrinsic::lifetime_start:
6530   case Intrinsic::lifetime_end: {
6531     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6532     // Stack coloring is not enabled in O0, discard region information.
6533     if (TM.getOptLevel() == CodeGenOpt::None)
6534       return;
6535 
6536     const int64_t ObjectSize =
6537         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6538     Value *const ObjectPtr = I.getArgOperand(1);
6539     SmallVector<const Value *, 4> Allocas;
6540     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6541 
6542     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6543            E = Allocas.end(); Object != E; ++Object) {
6544       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6545 
6546       // Could not find an Alloca.
6547       if (!LifetimeObject)
6548         continue;
6549 
6550       // First check that the Alloca is static, otherwise it won't have a
6551       // valid frame index.
6552       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6553       if (SI == FuncInfo.StaticAllocaMap.end())
6554         return;
6555 
6556       const int FrameIndex = SI->second;
6557       int64_t Offset;
6558       if (GetPointerBaseWithConstantOffset(
6559               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6560         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6561       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6562                                 Offset);
6563       DAG.setRoot(Res);
6564     }
6565     return;
6566   }
6567   case Intrinsic::invariant_start:
6568     // Discard region information.
6569     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6570     return;
6571   case Intrinsic::invariant_end:
6572     // Discard region information.
6573     return;
6574   case Intrinsic::clear_cache:
6575     /// FunctionName may be null.
6576     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6577       lowerCallToExternalSymbol(I, FunctionName);
6578     return;
6579   case Intrinsic::donothing:
6580     // ignore
6581     return;
6582   case Intrinsic::experimental_stackmap:
6583     visitStackmap(I);
6584     return;
6585   case Intrinsic::experimental_patchpoint_void:
6586   case Intrinsic::experimental_patchpoint_i64:
6587     visitPatchpoint(I);
6588     return;
6589   case Intrinsic::experimental_gc_statepoint:
6590     LowerStatepoint(ImmutableStatepoint(&I));
6591     return;
6592   case Intrinsic::experimental_gc_result:
6593     visitGCResult(cast<GCResultInst>(I));
6594     return;
6595   case Intrinsic::experimental_gc_relocate:
6596     visitGCRelocate(cast<GCRelocateInst>(I));
6597     return;
6598   case Intrinsic::instrprof_increment:
6599     llvm_unreachable("instrprof failed to lower an increment");
6600   case Intrinsic::instrprof_value_profile:
6601     llvm_unreachable("instrprof failed to lower a value profiling call");
6602   case Intrinsic::localescape: {
6603     MachineFunction &MF = DAG.getMachineFunction();
6604     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6605 
6606     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6607     // is the same on all targets.
6608     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6609       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6610       if (isa<ConstantPointerNull>(Arg))
6611         continue; // Skip null pointers. They represent a hole in index space.
6612       AllocaInst *Slot = cast<AllocaInst>(Arg);
6613       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6614              "can only escape static allocas");
6615       int FI = FuncInfo.StaticAllocaMap[Slot];
6616       MCSymbol *FrameAllocSym =
6617           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6618               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6619       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6620               TII->get(TargetOpcode::LOCAL_ESCAPE))
6621           .addSym(FrameAllocSym)
6622           .addFrameIndex(FI);
6623     }
6624 
6625     return;
6626   }
6627 
6628   case Intrinsic::localrecover: {
6629     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6630     MachineFunction &MF = DAG.getMachineFunction();
6631 
6632     // Get the symbol that defines the frame offset.
6633     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6634     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6635     unsigned IdxVal =
6636         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6637     MCSymbol *FrameAllocSym =
6638         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6639             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6640 
6641     Value *FP = I.getArgOperand(1);
6642     SDValue FPVal = getValue(FP);
6643     EVT PtrVT = FPVal.getValueType();
6644 
6645     // Create a MCSymbol for the label to avoid any target lowering
6646     // that would make this PC relative.
6647     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6648     SDValue OffsetVal =
6649         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6650 
6651     // Add the offset to the FP.
6652     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6653     setValue(&I, Add);
6654 
6655     return;
6656   }
6657 
6658   case Intrinsic::eh_exceptionpointer:
6659   case Intrinsic::eh_exceptioncode: {
6660     // Get the exception pointer vreg, copy from it, and resize it to fit.
6661     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6662     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6663     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6664     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6665     SDValue N =
6666         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6667     if (Intrinsic == Intrinsic::eh_exceptioncode)
6668       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6669     setValue(&I, N);
6670     return;
6671   }
6672   case Intrinsic::xray_customevent: {
6673     // Here we want to make sure that the intrinsic behaves as if it has a
6674     // specific calling convention, and only for x86_64.
6675     // FIXME: Support other platforms later.
6676     const auto &Triple = DAG.getTarget().getTargetTriple();
6677     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6678       return;
6679 
6680     SDLoc DL = getCurSDLoc();
6681     SmallVector<SDValue, 8> Ops;
6682 
6683     // We want to say that we always want the arguments in registers.
6684     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6685     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6686     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6687     SDValue Chain = getRoot();
6688     Ops.push_back(LogEntryVal);
6689     Ops.push_back(StrSizeVal);
6690     Ops.push_back(Chain);
6691 
6692     // We need to enforce the calling convention for the callsite, so that
6693     // argument ordering is enforced correctly, and that register allocation can
6694     // see that some registers may be assumed clobbered and have to preserve
6695     // them across calls to the intrinsic.
6696     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6697                                            DL, NodeTys, Ops);
6698     SDValue patchableNode = SDValue(MN, 0);
6699     DAG.setRoot(patchableNode);
6700     setValue(&I, patchableNode);
6701     return;
6702   }
6703   case Intrinsic::xray_typedevent: {
6704     // Here we want to make sure that the intrinsic behaves as if it has a
6705     // specific calling convention, and only for x86_64.
6706     // FIXME: Support other platforms later.
6707     const auto &Triple = DAG.getTarget().getTargetTriple();
6708     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6709       return;
6710 
6711     SDLoc DL = getCurSDLoc();
6712     SmallVector<SDValue, 8> Ops;
6713 
6714     // We want to say that we always want the arguments in registers.
6715     // It's unclear to me how manipulating the selection DAG here forces callers
6716     // to provide arguments in registers instead of on the stack.
6717     SDValue LogTypeId = getValue(I.getArgOperand(0));
6718     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6719     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6720     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6721     SDValue Chain = getRoot();
6722     Ops.push_back(LogTypeId);
6723     Ops.push_back(LogEntryVal);
6724     Ops.push_back(StrSizeVal);
6725     Ops.push_back(Chain);
6726 
6727     // We need to enforce the calling convention for the callsite, so that
6728     // argument ordering is enforced correctly, and that register allocation can
6729     // see that some registers may be assumed clobbered and have to preserve
6730     // them across calls to the intrinsic.
6731     MachineSDNode *MN = DAG.getMachineNode(
6732         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6733     SDValue patchableNode = SDValue(MN, 0);
6734     DAG.setRoot(patchableNode);
6735     setValue(&I, patchableNode);
6736     return;
6737   }
6738   case Intrinsic::experimental_deoptimize:
6739     LowerDeoptimizeCall(&I);
6740     return;
6741 
6742   case Intrinsic::experimental_vector_reduce_v2_fadd:
6743   case Intrinsic::experimental_vector_reduce_v2_fmul:
6744   case Intrinsic::experimental_vector_reduce_add:
6745   case Intrinsic::experimental_vector_reduce_mul:
6746   case Intrinsic::experimental_vector_reduce_and:
6747   case Intrinsic::experimental_vector_reduce_or:
6748   case Intrinsic::experimental_vector_reduce_xor:
6749   case Intrinsic::experimental_vector_reduce_smax:
6750   case Intrinsic::experimental_vector_reduce_smin:
6751   case Intrinsic::experimental_vector_reduce_umax:
6752   case Intrinsic::experimental_vector_reduce_umin:
6753   case Intrinsic::experimental_vector_reduce_fmax:
6754   case Intrinsic::experimental_vector_reduce_fmin:
6755     visitVectorReduce(I, Intrinsic);
6756     return;
6757 
6758   case Intrinsic::icall_branch_funnel: {
6759     SmallVector<SDValue, 16> Ops;
6760     Ops.push_back(getValue(I.getArgOperand(0)));
6761 
6762     int64_t Offset;
6763     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6764         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6765     if (!Base)
6766       report_fatal_error(
6767           "llvm.icall.branch.funnel operand must be a GlobalValue");
6768     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6769 
6770     struct BranchFunnelTarget {
6771       int64_t Offset;
6772       SDValue Target;
6773     };
6774     SmallVector<BranchFunnelTarget, 8> Targets;
6775 
6776     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6777       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6778           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6779       if (ElemBase != Base)
6780         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6781                            "to the same GlobalValue");
6782 
6783       SDValue Val = getValue(I.getArgOperand(Op + 1));
6784       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6785       if (!GA)
6786         report_fatal_error(
6787             "llvm.icall.branch.funnel operand must be a GlobalValue");
6788       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6789                                      GA->getGlobal(), getCurSDLoc(),
6790                                      Val.getValueType(), GA->getOffset())});
6791     }
6792     llvm::sort(Targets,
6793                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6794                  return T1.Offset < T2.Offset;
6795                });
6796 
6797     for (auto &T : Targets) {
6798       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6799       Ops.push_back(T.Target);
6800     }
6801 
6802     Ops.push_back(DAG.getRoot()); // Chain
6803     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6804                                  getCurSDLoc(), MVT::Other, Ops),
6805               0);
6806     DAG.setRoot(N);
6807     setValue(&I, N);
6808     HasTailCall = true;
6809     return;
6810   }
6811 
6812   case Intrinsic::wasm_landingpad_index:
6813     // Information this intrinsic contained has been transferred to
6814     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6815     // delete it now.
6816     return;
6817 
6818   case Intrinsic::aarch64_settag:
6819   case Intrinsic::aarch64_settag_zero: {
6820     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6821     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6822     SDValue Val = TSI.EmitTargetCodeForSetTag(
6823         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6824         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6825         ZeroMemory);
6826     DAG.setRoot(Val);
6827     setValue(&I, Val);
6828     return;
6829   }
6830   case Intrinsic::ptrmask: {
6831     SDValue Ptr = getValue(I.getOperand(0));
6832     SDValue Const = getValue(I.getOperand(1));
6833 
6834     EVT DestVT =
6835         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6836 
6837     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6838                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6839     return;
6840   }
6841   }
6842 }
6843 
6844 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6845     const ConstrainedFPIntrinsic &FPI) {
6846   SDLoc sdl = getCurSDLoc();
6847 
6848   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6849   SmallVector<EVT, 4> ValueVTs;
6850   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6851   ValueVTs.push_back(MVT::Other); // Out chain
6852 
6853   // We do not need to serialize constrained FP intrinsics against
6854   // each other or against (nonvolatile) loads, so they can be
6855   // chained like loads.
6856   SDValue Chain = DAG.getRoot();
6857   SmallVector<SDValue, 4> Opers;
6858   Opers.push_back(Chain);
6859   if (FPI.isUnaryOp()) {
6860     Opers.push_back(getValue(FPI.getArgOperand(0)));
6861   } else if (FPI.isTernaryOp()) {
6862     Opers.push_back(getValue(FPI.getArgOperand(0)));
6863     Opers.push_back(getValue(FPI.getArgOperand(1)));
6864     Opers.push_back(getValue(FPI.getArgOperand(2)));
6865   } else {
6866     Opers.push_back(getValue(FPI.getArgOperand(0)));
6867     Opers.push_back(getValue(FPI.getArgOperand(1)));
6868   }
6869 
6870   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6871     assert(Result.getNode()->getNumValues() == 2);
6872 
6873     // Push node to the appropriate list so that future instructions can be
6874     // chained up correctly.
6875     SDValue OutChain = Result.getValue(1);
6876     switch (EB) {
6877     case fp::ExceptionBehavior::ebIgnore:
6878       // The only reason why ebIgnore nodes still need to be chained is that
6879       // they might depend on the current rounding mode, and therefore must
6880       // not be moved across instruction that may change that mode.
6881       LLVM_FALLTHROUGH;
6882     case fp::ExceptionBehavior::ebMayTrap:
6883       // These must not be moved across calls or instructions that may change
6884       // floating-point exception masks.
6885       PendingConstrainedFP.push_back(OutChain);
6886       break;
6887     case fp::ExceptionBehavior::ebStrict:
6888       // These must not be moved across calls or instructions that may change
6889       // floating-point exception masks or read floating-point exception flags.
6890       // In addition, they cannot be optimized out even if unused.
6891       PendingConstrainedFPStrict.push_back(OutChain);
6892       break;
6893     }
6894   };
6895 
6896   SDVTList VTs = DAG.getVTList(ValueVTs);
6897   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6898 
6899   SDNodeFlags Flags;
6900   if (EB == fp::ExceptionBehavior::ebIgnore)
6901     Flags.setNoFPExcept(true);
6902 
6903   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6904     Flags.copyFMF(*FPOp);
6905 
6906   unsigned Opcode;
6907   switch (FPI.getIntrinsicID()) {
6908   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6909 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6910   case Intrinsic::INTRINSIC:                                                   \
6911     Opcode = ISD::STRICT_##DAGN;                                               \
6912     break;
6913 #include "llvm/IR/ConstrainedOps.def"
6914   case Intrinsic::experimental_constrained_fmuladd: {
6915     Opcode = ISD::STRICT_FMA;
6916     // Break fmuladd into fmul and fadd.
6917     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6918         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6919                                         ValueVTs[0])) {
6920       Opers.pop_back();
6921       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6922       pushOutChain(Mul, EB);
6923       Opcode = ISD::STRICT_FADD;
6924       Opers.clear();
6925       Opers.push_back(Mul.getValue(1));
6926       Opers.push_back(Mul.getValue(0));
6927       Opers.push_back(getValue(FPI.getArgOperand(2)));
6928     }
6929     break;
6930   }
6931   }
6932 
6933   // A few strict DAG nodes carry additional operands that are not
6934   // set up by the default code above.
6935   switch (Opcode) {
6936   default: break;
6937   case ISD::STRICT_FP_ROUND:
6938     Opers.push_back(
6939         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6940     break;
6941   case ISD::STRICT_FSETCC:
6942   case ISD::STRICT_FSETCCS: {
6943     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6944     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6945     break;
6946   }
6947   }
6948 
6949   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
6950   pushOutChain(Result, EB);
6951 
6952   SDValue FPResult = Result.getValue(0);
6953   setValue(&FPI, FPResult);
6954 }
6955 
6956 std::pair<SDValue, SDValue>
6957 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6958                                     const BasicBlock *EHPadBB) {
6959   MachineFunction &MF = DAG.getMachineFunction();
6960   MachineModuleInfo &MMI = MF.getMMI();
6961   MCSymbol *BeginLabel = nullptr;
6962 
6963   if (EHPadBB) {
6964     // Insert a label before the invoke call to mark the try range.  This can be
6965     // used to detect deletion of the invoke via the MachineModuleInfo.
6966     BeginLabel = MMI.getContext().createTempSymbol();
6967 
6968     // For SjLj, keep track of which landing pads go with which invokes
6969     // so as to maintain the ordering of pads in the LSDA.
6970     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6971     if (CallSiteIndex) {
6972       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6973       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6974 
6975       // Now that the call site is handled, stop tracking it.
6976       MMI.setCurrentCallSite(0);
6977     }
6978 
6979     // Both PendingLoads and PendingExports must be flushed here;
6980     // this call might not return.
6981     (void)getRoot();
6982     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6983 
6984     CLI.setChain(getRoot());
6985   }
6986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6987   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6988 
6989   assert((CLI.IsTailCall || Result.second.getNode()) &&
6990          "Non-null chain expected with non-tail call!");
6991   assert((Result.second.getNode() || !Result.first.getNode()) &&
6992          "Null value expected with tail call!");
6993 
6994   if (!Result.second.getNode()) {
6995     // As a special case, a null chain means that a tail call has been emitted
6996     // and the DAG root is already updated.
6997     HasTailCall = true;
6998 
6999     // Since there's no actual continuation from this block, nothing can be
7000     // relying on us setting vregs for them.
7001     PendingExports.clear();
7002   } else {
7003     DAG.setRoot(Result.second);
7004   }
7005 
7006   if (EHPadBB) {
7007     // Insert a label at the end of the invoke call to mark the try range.  This
7008     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7009     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7010     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7011 
7012     // Inform MachineModuleInfo of range.
7013     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7014     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7015     // actually use outlined funclets and their LSDA info style.
7016     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7017       assert(CLI.CB);
7018       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7019       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7020     } else if (!isScopedEHPersonality(Pers)) {
7021       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7022     }
7023   }
7024 
7025   return Result;
7026 }
7027 
7028 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7029                                       bool isTailCall,
7030                                       const BasicBlock *EHPadBB) {
7031   auto &DL = DAG.getDataLayout();
7032   FunctionType *FTy = CB.getFunctionType();
7033   Type *RetTy = CB.getType();
7034 
7035   TargetLowering::ArgListTy Args;
7036   Args.reserve(CB.arg_size());
7037 
7038   const Value *SwiftErrorVal = nullptr;
7039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7040 
7041   if (isTailCall) {
7042     // Avoid emitting tail calls in functions with the disable-tail-calls
7043     // attribute.
7044     auto *Caller = CB.getParent()->getParent();
7045     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7046         "true")
7047       isTailCall = false;
7048 
7049     // We can't tail call inside a function with a swifterror argument. Lowering
7050     // does not support this yet. It would have to move into the swifterror
7051     // register before the call.
7052     if (TLI.supportSwiftError() &&
7053         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7054       isTailCall = false;
7055   }
7056 
7057   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7058     TargetLowering::ArgListEntry Entry;
7059     const Value *V = *I;
7060 
7061     // Skip empty types
7062     if (V->getType()->isEmptyTy())
7063       continue;
7064 
7065     SDValue ArgNode = getValue(V);
7066     Entry.Node = ArgNode; Entry.Ty = V->getType();
7067 
7068     Entry.setAttributes(&CB, I - CB.arg_begin());
7069 
7070     // Use swifterror virtual register as input to the call.
7071     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7072       SwiftErrorVal = V;
7073       // We find the virtual register for the actual swifterror argument.
7074       // Instead of using the Value, we use the virtual register instead.
7075       Entry.Node =
7076           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7077                           EVT(TLI.getPointerTy(DL)));
7078     }
7079 
7080     Args.push_back(Entry);
7081 
7082     // If we have an explicit sret argument that is an Instruction, (i.e., it
7083     // might point to function-local memory), we can't meaningfully tail-call.
7084     if (Entry.IsSRet && isa<Instruction>(V))
7085       isTailCall = false;
7086   }
7087 
7088   // If call site has a cfguardtarget operand bundle, create and add an
7089   // additional ArgListEntry.
7090   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7091     TargetLowering::ArgListEntry Entry;
7092     Value *V = Bundle->Inputs[0];
7093     SDValue ArgNode = getValue(V);
7094     Entry.Node = ArgNode;
7095     Entry.Ty = V->getType();
7096     Entry.IsCFGuardTarget = true;
7097     Args.push_back(Entry);
7098   }
7099 
7100   // Check if target-independent constraints permit a tail call here.
7101   // Target-dependent constraints are checked within TLI->LowerCallTo.
7102   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7103     isTailCall = false;
7104 
7105   // Disable tail calls if there is an swifterror argument. Targets have not
7106   // been updated to support tail calls.
7107   if (TLI.supportSwiftError() && SwiftErrorVal)
7108     isTailCall = false;
7109 
7110   TargetLowering::CallLoweringInfo CLI(DAG);
7111   CLI.setDebugLoc(getCurSDLoc())
7112       .setChain(getRoot())
7113       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7114       .setTailCall(isTailCall)
7115       .setConvergent(CB.isConvergent());
7116   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7117 
7118   if (Result.first.getNode()) {
7119     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7120     setValue(&CB, Result.first);
7121   }
7122 
7123   // The last element of CLI.InVals has the SDValue for swifterror return.
7124   // Here we copy it to a virtual register and update SwiftErrorMap for
7125   // book-keeping.
7126   if (SwiftErrorVal && TLI.supportSwiftError()) {
7127     // Get the last element of InVals.
7128     SDValue Src = CLI.InVals.back();
7129     Register VReg =
7130         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7131     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7132     DAG.setRoot(CopyNode);
7133   }
7134 }
7135 
7136 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7137                              SelectionDAGBuilder &Builder) {
7138   // Check to see if this load can be trivially constant folded, e.g. if the
7139   // input is from a string literal.
7140   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7141     // Cast pointer to the type we really want to load.
7142     Type *LoadTy =
7143         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7144     if (LoadVT.isVector())
7145       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7146 
7147     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7148                                          PointerType::getUnqual(LoadTy));
7149 
7150     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7151             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7152       return Builder.getValue(LoadCst);
7153   }
7154 
7155   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7156   // still constant memory, the input chain can be the entry node.
7157   SDValue Root;
7158   bool ConstantMemory = false;
7159 
7160   // Do not serialize (non-volatile) loads of constant memory with anything.
7161   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7162     Root = Builder.DAG.getEntryNode();
7163     ConstantMemory = true;
7164   } else {
7165     // Do not serialize non-volatile loads against each other.
7166     Root = Builder.DAG.getRoot();
7167   }
7168 
7169   SDValue Ptr = Builder.getValue(PtrVal);
7170   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7171                                         Ptr, MachinePointerInfo(PtrVal),
7172                                         /* Alignment = */ 1);
7173 
7174   if (!ConstantMemory)
7175     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7176   return LoadVal;
7177 }
7178 
7179 /// Record the value for an instruction that produces an integer result,
7180 /// converting the type where necessary.
7181 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7182                                                   SDValue Value,
7183                                                   bool IsSigned) {
7184   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7185                                                     I.getType(), true);
7186   if (IsSigned)
7187     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7188   else
7189     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7190   setValue(&I, Value);
7191 }
7192 
7193 /// See if we can lower a memcmp call into an optimized form. If so, return
7194 /// true and lower it. Otherwise return false, and it will be lowered like a
7195 /// normal call.
7196 /// The caller already checked that \p I calls the appropriate LibFunc with a
7197 /// correct prototype.
7198 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7199   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7200   const Value *Size = I.getArgOperand(2);
7201   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7202   if (CSize && CSize->getZExtValue() == 0) {
7203     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7204                                                           I.getType(), true);
7205     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7206     return true;
7207   }
7208 
7209   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7210   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7211       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7212       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7213   if (Res.first.getNode()) {
7214     processIntegerCallValue(I, Res.first, true);
7215     PendingLoads.push_back(Res.second);
7216     return true;
7217   }
7218 
7219   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7220   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7221   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7222     return false;
7223 
7224   // If the target has a fast compare for the given size, it will return a
7225   // preferred load type for that size. Require that the load VT is legal and
7226   // that the target supports unaligned loads of that type. Otherwise, return
7227   // INVALID.
7228   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7229     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7230     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7231     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7232       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7233       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7234       // TODO: Check alignment of src and dest ptrs.
7235       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7236       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7237       if (!TLI.isTypeLegal(LVT) ||
7238           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7239           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7240         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7241     }
7242 
7243     return LVT;
7244   };
7245 
7246   // This turns into unaligned loads. We only do this if the target natively
7247   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7248   // we'll only produce a small number of byte loads.
7249   MVT LoadVT;
7250   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7251   switch (NumBitsToCompare) {
7252   default:
7253     return false;
7254   case 16:
7255     LoadVT = MVT::i16;
7256     break;
7257   case 32:
7258     LoadVT = MVT::i32;
7259     break;
7260   case 64:
7261   case 128:
7262   case 256:
7263     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7264     break;
7265   }
7266 
7267   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7268     return false;
7269 
7270   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7271   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7272 
7273   // Bitcast to a wide integer type if the loads are vectors.
7274   if (LoadVT.isVector()) {
7275     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7276     LoadL = DAG.getBitcast(CmpVT, LoadL);
7277     LoadR = DAG.getBitcast(CmpVT, LoadR);
7278   }
7279 
7280   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7281   processIntegerCallValue(I, Cmp, false);
7282   return true;
7283 }
7284 
7285 /// See if we can lower a memchr call into an optimized form. If so, return
7286 /// true and lower it. Otherwise return false, and it will be lowered like a
7287 /// normal call.
7288 /// The caller already checked that \p I calls the appropriate LibFunc with a
7289 /// correct prototype.
7290 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7291   const Value *Src = I.getArgOperand(0);
7292   const Value *Char = I.getArgOperand(1);
7293   const Value *Length = I.getArgOperand(2);
7294 
7295   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7296   std::pair<SDValue, SDValue> Res =
7297     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7298                                 getValue(Src), getValue(Char), getValue(Length),
7299                                 MachinePointerInfo(Src));
7300   if (Res.first.getNode()) {
7301     setValue(&I, Res.first);
7302     PendingLoads.push_back(Res.second);
7303     return true;
7304   }
7305 
7306   return false;
7307 }
7308 
7309 /// See if we can lower a mempcpy call into an optimized form. If so, return
7310 /// true and lower it. Otherwise return false, and it will be lowered like a
7311 /// normal call.
7312 /// The caller already checked that \p I calls the appropriate LibFunc with a
7313 /// correct prototype.
7314 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7315   SDValue Dst = getValue(I.getArgOperand(0));
7316   SDValue Src = getValue(I.getArgOperand(1));
7317   SDValue Size = getValue(I.getArgOperand(2));
7318 
7319   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7320   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7321   // DAG::getMemcpy needs Alignment to be defined.
7322   Align Alignment = std::min(DstAlign, SrcAlign);
7323 
7324   bool isVol = false;
7325   SDLoc sdl = getCurSDLoc();
7326 
7327   // In the mempcpy context we need to pass in a false value for isTailCall
7328   // because the return pointer needs to be adjusted by the size of
7329   // the copied memory.
7330   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7331   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7332                              /*isTailCall=*/false,
7333                              MachinePointerInfo(I.getArgOperand(0)),
7334                              MachinePointerInfo(I.getArgOperand(1)));
7335   assert(MC.getNode() != nullptr &&
7336          "** memcpy should not be lowered as TailCall in mempcpy context **");
7337   DAG.setRoot(MC);
7338 
7339   // Check if Size needs to be truncated or extended.
7340   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7341 
7342   // Adjust return pointer to point just past the last dst byte.
7343   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7344                                     Dst, Size);
7345   setValue(&I, DstPlusSize);
7346   return true;
7347 }
7348 
7349 /// See if we can lower a strcpy call into an optimized form.  If so, return
7350 /// true and lower it, otherwise return false and it will be lowered like a
7351 /// normal call.
7352 /// The caller already checked that \p I calls the appropriate LibFunc with a
7353 /// correct prototype.
7354 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7355   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7356 
7357   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7358   std::pair<SDValue, SDValue> Res =
7359     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7360                                 getValue(Arg0), getValue(Arg1),
7361                                 MachinePointerInfo(Arg0),
7362                                 MachinePointerInfo(Arg1), isStpcpy);
7363   if (Res.first.getNode()) {
7364     setValue(&I, Res.first);
7365     DAG.setRoot(Res.second);
7366     return true;
7367   }
7368 
7369   return false;
7370 }
7371 
7372 /// See if we can lower a strcmp call into an optimized form.  If so, return
7373 /// true and lower it, otherwise return false and it will be lowered like a
7374 /// normal call.
7375 /// The caller already checked that \p I calls the appropriate LibFunc with a
7376 /// correct prototype.
7377 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7378   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7379 
7380   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7381   std::pair<SDValue, SDValue> Res =
7382     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7383                                 getValue(Arg0), getValue(Arg1),
7384                                 MachinePointerInfo(Arg0),
7385                                 MachinePointerInfo(Arg1));
7386   if (Res.first.getNode()) {
7387     processIntegerCallValue(I, Res.first, true);
7388     PendingLoads.push_back(Res.second);
7389     return true;
7390   }
7391 
7392   return false;
7393 }
7394 
7395 /// See if we can lower a strlen call into an optimized form.  If so, return
7396 /// true and lower it, otherwise return false and it will be lowered like a
7397 /// normal call.
7398 /// The caller already checked that \p I calls the appropriate LibFunc with a
7399 /// correct prototype.
7400 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7401   const Value *Arg0 = I.getArgOperand(0);
7402 
7403   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7404   std::pair<SDValue, SDValue> Res =
7405     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7406                                 getValue(Arg0), MachinePointerInfo(Arg0));
7407   if (Res.first.getNode()) {
7408     processIntegerCallValue(I, Res.first, false);
7409     PendingLoads.push_back(Res.second);
7410     return true;
7411   }
7412 
7413   return false;
7414 }
7415 
7416 /// See if we can lower a strnlen call into an optimized form.  If so, return
7417 /// true and lower it, otherwise return false and it will be lowered like a
7418 /// normal call.
7419 /// The caller already checked that \p I calls the appropriate LibFunc with a
7420 /// correct prototype.
7421 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7422   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7423 
7424   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7425   std::pair<SDValue, SDValue> Res =
7426     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7427                                  getValue(Arg0), getValue(Arg1),
7428                                  MachinePointerInfo(Arg0));
7429   if (Res.first.getNode()) {
7430     processIntegerCallValue(I, Res.first, false);
7431     PendingLoads.push_back(Res.second);
7432     return true;
7433   }
7434 
7435   return false;
7436 }
7437 
7438 /// See if we can lower a unary floating-point operation into an SDNode with
7439 /// the specified Opcode.  If so, return true and lower it, otherwise return
7440 /// false and it will be lowered like a normal call.
7441 /// The caller already checked that \p I calls the appropriate LibFunc with a
7442 /// correct prototype.
7443 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7444                                               unsigned Opcode) {
7445   // We already checked this call's prototype; verify it doesn't modify errno.
7446   if (!I.onlyReadsMemory())
7447     return false;
7448 
7449   SDValue Tmp = getValue(I.getArgOperand(0));
7450   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7451   return true;
7452 }
7453 
7454 /// See if we can lower a binary floating-point operation into an SDNode with
7455 /// the specified Opcode. If so, return true and lower it. Otherwise return
7456 /// false, and it will be lowered like a normal call.
7457 /// The caller already checked that \p I calls the appropriate LibFunc with a
7458 /// correct prototype.
7459 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7460                                                unsigned Opcode) {
7461   // We already checked this call's prototype; verify it doesn't modify errno.
7462   if (!I.onlyReadsMemory())
7463     return false;
7464 
7465   SDValue Tmp0 = getValue(I.getArgOperand(0));
7466   SDValue Tmp1 = getValue(I.getArgOperand(1));
7467   EVT VT = Tmp0.getValueType();
7468   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7469   return true;
7470 }
7471 
7472 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7473   // Handle inline assembly differently.
7474   if (isa<InlineAsm>(I.getCalledValue())) {
7475     visitInlineAsm(I);
7476     return;
7477   }
7478 
7479   if (Function *F = I.getCalledFunction()) {
7480     if (F->isDeclaration()) {
7481       // Is this an LLVM intrinsic or a target-specific intrinsic?
7482       unsigned IID = F->getIntrinsicID();
7483       if (!IID)
7484         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7485           IID = II->getIntrinsicID(F);
7486 
7487       if (IID) {
7488         visitIntrinsicCall(I, IID);
7489         return;
7490       }
7491     }
7492 
7493     // Check for well-known libc/libm calls.  If the function is internal, it
7494     // can't be a library call.  Don't do the check if marked as nobuiltin for
7495     // some reason or the call site requires strict floating point semantics.
7496     LibFunc Func;
7497     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7498         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7499         LibInfo->hasOptimizedCodeGen(Func)) {
7500       switch (Func) {
7501       default: break;
7502       case LibFunc_copysign:
7503       case LibFunc_copysignf:
7504       case LibFunc_copysignl:
7505         // We already checked this call's prototype; verify it doesn't modify
7506         // errno.
7507         if (I.onlyReadsMemory()) {
7508           SDValue LHS = getValue(I.getArgOperand(0));
7509           SDValue RHS = getValue(I.getArgOperand(1));
7510           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7511                                    LHS.getValueType(), LHS, RHS));
7512           return;
7513         }
7514         break;
7515       case LibFunc_fabs:
7516       case LibFunc_fabsf:
7517       case LibFunc_fabsl:
7518         if (visitUnaryFloatCall(I, ISD::FABS))
7519           return;
7520         break;
7521       case LibFunc_fmin:
7522       case LibFunc_fminf:
7523       case LibFunc_fminl:
7524         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7525           return;
7526         break;
7527       case LibFunc_fmax:
7528       case LibFunc_fmaxf:
7529       case LibFunc_fmaxl:
7530         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7531           return;
7532         break;
7533       case LibFunc_sin:
7534       case LibFunc_sinf:
7535       case LibFunc_sinl:
7536         if (visitUnaryFloatCall(I, ISD::FSIN))
7537           return;
7538         break;
7539       case LibFunc_cos:
7540       case LibFunc_cosf:
7541       case LibFunc_cosl:
7542         if (visitUnaryFloatCall(I, ISD::FCOS))
7543           return;
7544         break;
7545       case LibFunc_sqrt:
7546       case LibFunc_sqrtf:
7547       case LibFunc_sqrtl:
7548       case LibFunc_sqrt_finite:
7549       case LibFunc_sqrtf_finite:
7550       case LibFunc_sqrtl_finite:
7551         if (visitUnaryFloatCall(I, ISD::FSQRT))
7552           return;
7553         break;
7554       case LibFunc_floor:
7555       case LibFunc_floorf:
7556       case LibFunc_floorl:
7557         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7558           return;
7559         break;
7560       case LibFunc_nearbyint:
7561       case LibFunc_nearbyintf:
7562       case LibFunc_nearbyintl:
7563         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7564           return;
7565         break;
7566       case LibFunc_ceil:
7567       case LibFunc_ceilf:
7568       case LibFunc_ceill:
7569         if (visitUnaryFloatCall(I, ISD::FCEIL))
7570           return;
7571         break;
7572       case LibFunc_rint:
7573       case LibFunc_rintf:
7574       case LibFunc_rintl:
7575         if (visitUnaryFloatCall(I, ISD::FRINT))
7576           return;
7577         break;
7578       case LibFunc_round:
7579       case LibFunc_roundf:
7580       case LibFunc_roundl:
7581         if (visitUnaryFloatCall(I, ISD::FROUND))
7582           return;
7583         break;
7584       case LibFunc_trunc:
7585       case LibFunc_truncf:
7586       case LibFunc_truncl:
7587         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7588           return;
7589         break;
7590       case LibFunc_log2:
7591       case LibFunc_log2f:
7592       case LibFunc_log2l:
7593         if (visitUnaryFloatCall(I, ISD::FLOG2))
7594           return;
7595         break;
7596       case LibFunc_exp2:
7597       case LibFunc_exp2f:
7598       case LibFunc_exp2l:
7599         if (visitUnaryFloatCall(I, ISD::FEXP2))
7600           return;
7601         break;
7602       case LibFunc_memcmp:
7603         if (visitMemCmpCall(I))
7604           return;
7605         break;
7606       case LibFunc_mempcpy:
7607         if (visitMemPCpyCall(I))
7608           return;
7609         break;
7610       case LibFunc_memchr:
7611         if (visitMemChrCall(I))
7612           return;
7613         break;
7614       case LibFunc_strcpy:
7615         if (visitStrCpyCall(I, false))
7616           return;
7617         break;
7618       case LibFunc_stpcpy:
7619         if (visitStrCpyCall(I, true))
7620           return;
7621         break;
7622       case LibFunc_strcmp:
7623         if (visitStrCmpCall(I))
7624           return;
7625         break;
7626       case LibFunc_strlen:
7627         if (visitStrLenCall(I))
7628           return;
7629         break;
7630       case LibFunc_strnlen:
7631         if (visitStrNLenCall(I))
7632           return;
7633         break;
7634       }
7635     }
7636   }
7637 
7638   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7639   // have to do anything here to lower funclet bundles.
7640   // CFGuardTarget bundles are lowered in LowerCallTo.
7641   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7642                                         LLVMContext::OB_funclet,
7643                                         LLVMContext::OB_cfguardtarget}) &&
7644          "Cannot lower calls with arbitrary operand bundles!");
7645 
7646   SDValue Callee = getValue(I.getCalledValue());
7647 
7648   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7649     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7650   else
7651     // Check if we can potentially perform a tail call. More detailed checking
7652     // is be done within LowerCallTo, after more information about the call is
7653     // known.
7654     LowerCallTo(I, Callee, I.isTailCall());
7655 }
7656 
7657 namespace {
7658 
7659 /// AsmOperandInfo - This contains information for each constraint that we are
7660 /// lowering.
7661 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7662 public:
7663   /// CallOperand - If this is the result output operand or a clobber
7664   /// this is null, otherwise it is the incoming operand to the CallInst.
7665   /// This gets modified as the asm is processed.
7666   SDValue CallOperand;
7667 
7668   /// AssignedRegs - If this is a register or register class operand, this
7669   /// contains the set of register corresponding to the operand.
7670   RegsForValue AssignedRegs;
7671 
7672   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7673     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7674   }
7675 
7676   /// Whether or not this operand accesses memory
7677   bool hasMemory(const TargetLowering &TLI) const {
7678     // Indirect operand accesses access memory.
7679     if (isIndirect)
7680       return true;
7681 
7682     for (const auto &Code : Codes)
7683       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7684         return true;
7685 
7686     return false;
7687   }
7688 
7689   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7690   /// corresponds to.  If there is no Value* for this operand, it returns
7691   /// MVT::Other.
7692   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7693                            const DataLayout &DL) const {
7694     if (!CallOperandVal) return MVT::Other;
7695 
7696     if (isa<BasicBlock>(CallOperandVal))
7697       return TLI.getProgramPointerTy(DL);
7698 
7699     llvm::Type *OpTy = CallOperandVal->getType();
7700 
7701     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7702     // If this is an indirect operand, the operand is a pointer to the
7703     // accessed type.
7704     if (isIndirect) {
7705       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7706       if (!PtrTy)
7707         report_fatal_error("Indirect operand for inline asm not a pointer!");
7708       OpTy = PtrTy->getElementType();
7709     }
7710 
7711     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7712     if (StructType *STy = dyn_cast<StructType>(OpTy))
7713       if (STy->getNumElements() == 1)
7714         OpTy = STy->getElementType(0);
7715 
7716     // If OpTy is not a single value, it may be a struct/union that we
7717     // can tile with integers.
7718     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7719       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7720       switch (BitSize) {
7721       default: break;
7722       case 1:
7723       case 8:
7724       case 16:
7725       case 32:
7726       case 64:
7727       case 128:
7728         OpTy = IntegerType::get(Context, BitSize);
7729         break;
7730       }
7731     }
7732 
7733     return TLI.getValueType(DL, OpTy, true);
7734   }
7735 };
7736 
7737 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7738 
7739 } // end anonymous namespace
7740 
7741 /// Make sure that the output operand \p OpInfo and its corresponding input
7742 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7743 /// out).
7744 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7745                                SDISelAsmOperandInfo &MatchingOpInfo,
7746                                SelectionDAG &DAG) {
7747   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7748     return;
7749 
7750   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7751   const auto &TLI = DAG.getTargetLoweringInfo();
7752 
7753   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7754       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7755                                        OpInfo.ConstraintVT);
7756   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7757       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7758                                        MatchingOpInfo.ConstraintVT);
7759   if ((OpInfo.ConstraintVT.isInteger() !=
7760        MatchingOpInfo.ConstraintVT.isInteger()) ||
7761       (MatchRC.second != InputRC.second)) {
7762     // FIXME: error out in a more elegant fashion
7763     report_fatal_error("Unsupported asm: input constraint"
7764                        " with a matching output constraint of"
7765                        " incompatible type!");
7766   }
7767   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7768 }
7769 
7770 /// Get a direct memory input to behave well as an indirect operand.
7771 /// This may introduce stores, hence the need for a \p Chain.
7772 /// \return The (possibly updated) chain.
7773 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7774                                         SDISelAsmOperandInfo &OpInfo,
7775                                         SelectionDAG &DAG) {
7776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7777 
7778   // If we don't have an indirect input, put it in the constpool if we can,
7779   // otherwise spill it to a stack slot.
7780   // TODO: This isn't quite right. We need to handle these according to
7781   // the addressing mode that the constraint wants. Also, this may take
7782   // an additional register for the computation and we don't want that
7783   // either.
7784 
7785   // If the operand is a float, integer, or vector constant, spill to a
7786   // constant pool entry to get its address.
7787   const Value *OpVal = OpInfo.CallOperandVal;
7788   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7789       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7790     OpInfo.CallOperand = DAG.getConstantPool(
7791         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7792     return Chain;
7793   }
7794 
7795   // Otherwise, create a stack slot and emit a store to it before the asm.
7796   Type *Ty = OpVal->getType();
7797   auto &DL = DAG.getDataLayout();
7798   uint64_t TySize = DL.getTypeAllocSize(Ty);
7799   unsigned Align = DL.getPrefTypeAlignment(Ty);
7800   MachineFunction &MF = DAG.getMachineFunction();
7801   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7802   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7803   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7804                             MachinePointerInfo::getFixedStack(MF, SSFI),
7805                             TLI.getMemValueType(DL, Ty));
7806   OpInfo.CallOperand = StackSlot;
7807 
7808   return Chain;
7809 }
7810 
7811 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7812 /// specified operand.  We prefer to assign virtual registers, to allow the
7813 /// register allocator to handle the assignment process.  However, if the asm
7814 /// uses features that we can't model on machineinstrs, we have SDISel do the
7815 /// allocation.  This produces generally horrible, but correct, code.
7816 ///
7817 ///   OpInfo describes the operand
7818 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7819 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7820                                  SDISelAsmOperandInfo &OpInfo,
7821                                  SDISelAsmOperandInfo &RefOpInfo) {
7822   LLVMContext &Context = *DAG.getContext();
7823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7824 
7825   MachineFunction &MF = DAG.getMachineFunction();
7826   SmallVector<unsigned, 4> Regs;
7827   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7828 
7829   // No work to do for memory operations.
7830   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7831     return;
7832 
7833   // If this is a constraint for a single physreg, or a constraint for a
7834   // register class, find it.
7835   unsigned AssignedReg;
7836   const TargetRegisterClass *RC;
7837   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7838       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7839   // RC is unset only on failure. Return immediately.
7840   if (!RC)
7841     return;
7842 
7843   // Get the actual register value type.  This is important, because the user
7844   // may have asked for (e.g.) the AX register in i32 type.  We need to
7845   // remember that AX is actually i16 to get the right extension.
7846   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7847 
7848   if (OpInfo.ConstraintVT != MVT::Other) {
7849     // If this is an FP operand in an integer register (or visa versa), or more
7850     // generally if the operand value disagrees with the register class we plan
7851     // to stick it in, fix the operand type.
7852     //
7853     // If this is an input value, the bitcast to the new type is done now.
7854     // Bitcast for output value is done at the end of visitInlineAsm().
7855     if ((OpInfo.Type == InlineAsm::isOutput ||
7856          OpInfo.Type == InlineAsm::isInput) &&
7857         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7858       // Try to convert to the first EVT that the reg class contains.  If the
7859       // types are identical size, use a bitcast to convert (e.g. two differing
7860       // vector types).  Note: output bitcast is done at the end of
7861       // visitInlineAsm().
7862       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7863         // Exclude indirect inputs while they are unsupported because the code
7864         // to perform the load is missing and thus OpInfo.CallOperand still
7865         // refers to the input address rather than the pointed-to value.
7866         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7867           OpInfo.CallOperand =
7868               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7869         OpInfo.ConstraintVT = RegVT;
7870         // If the operand is an FP value and we want it in integer registers,
7871         // use the corresponding integer type. This turns an f64 value into
7872         // i64, which can be passed with two i32 values on a 32-bit machine.
7873       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7874         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7875         if (OpInfo.Type == InlineAsm::isInput)
7876           OpInfo.CallOperand =
7877               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7878         OpInfo.ConstraintVT = VT;
7879       }
7880     }
7881   }
7882 
7883   // No need to allocate a matching input constraint since the constraint it's
7884   // matching to has already been allocated.
7885   if (OpInfo.isMatchingInputConstraint())
7886     return;
7887 
7888   EVT ValueVT = OpInfo.ConstraintVT;
7889   if (OpInfo.ConstraintVT == MVT::Other)
7890     ValueVT = RegVT;
7891 
7892   // Initialize NumRegs.
7893   unsigned NumRegs = 1;
7894   if (OpInfo.ConstraintVT != MVT::Other)
7895     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7896 
7897   // If this is a constraint for a specific physical register, like {r17},
7898   // assign it now.
7899 
7900   // If this associated to a specific register, initialize iterator to correct
7901   // place. If virtual, make sure we have enough registers
7902 
7903   // Initialize iterator if necessary
7904   TargetRegisterClass::iterator I = RC->begin();
7905   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7906 
7907   // Do not check for single registers.
7908   if (AssignedReg) {
7909       for (; *I != AssignedReg; ++I)
7910         assert(I != RC->end() && "AssignedReg should be member of RC");
7911   }
7912 
7913   for (; NumRegs; --NumRegs, ++I) {
7914     assert(I != RC->end() && "Ran out of registers to allocate!");
7915     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7916     Regs.push_back(R);
7917   }
7918 
7919   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7920 }
7921 
7922 static unsigned
7923 findMatchingInlineAsmOperand(unsigned OperandNo,
7924                              const std::vector<SDValue> &AsmNodeOperands) {
7925   // Scan until we find the definition we already emitted of this operand.
7926   unsigned CurOp = InlineAsm::Op_FirstOperand;
7927   for (; OperandNo; --OperandNo) {
7928     // Advance to the next operand.
7929     unsigned OpFlag =
7930         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7931     assert((InlineAsm::isRegDefKind(OpFlag) ||
7932             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7933             InlineAsm::isMemKind(OpFlag)) &&
7934            "Skipped past definitions?");
7935     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7936   }
7937   return CurOp;
7938 }
7939 
7940 namespace {
7941 
7942 class ExtraFlags {
7943   unsigned Flags = 0;
7944 
7945 public:
7946   explicit ExtraFlags(const CallBase &Call) {
7947     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue());
7948     if (IA->hasSideEffects())
7949       Flags |= InlineAsm::Extra_HasSideEffects;
7950     if (IA->isAlignStack())
7951       Flags |= InlineAsm::Extra_IsAlignStack;
7952     if (Call.isConvergent())
7953       Flags |= InlineAsm::Extra_IsConvergent;
7954     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7955   }
7956 
7957   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7958     // Ideally, we would only check against memory constraints.  However, the
7959     // meaning of an Other constraint can be target-specific and we can't easily
7960     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7961     // for Other constraints as well.
7962     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7963         OpInfo.ConstraintType == TargetLowering::C_Other) {
7964       if (OpInfo.Type == InlineAsm::isInput)
7965         Flags |= InlineAsm::Extra_MayLoad;
7966       else if (OpInfo.Type == InlineAsm::isOutput)
7967         Flags |= InlineAsm::Extra_MayStore;
7968       else if (OpInfo.Type == InlineAsm::isClobber)
7969         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7970     }
7971   }
7972 
7973   unsigned get() const { return Flags; }
7974 };
7975 
7976 } // end anonymous namespace
7977 
7978 /// visitInlineAsm - Handle a call to an InlineAsm object.
7979 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
7980   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue());
7981 
7982   /// ConstraintOperands - Information about all of the constraints.
7983   SDISelAsmOperandInfoVector ConstraintOperands;
7984 
7985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7986   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7987       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
7988 
7989   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7990   // AsmDialect, MayLoad, MayStore).
7991   bool HasSideEffect = IA->hasSideEffects();
7992   ExtraFlags ExtraInfo(Call);
7993 
7994   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7995   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7996   unsigned NumMatchingOps = 0;
7997   for (auto &T : TargetConstraints) {
7998     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7999     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8000 
8001     // Compute the value type for each operand.
8002     if (OpInfo.Type == InlineAsm::isInput ||
8003         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8004       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8005 
8006       // Process the call argument. BasicBlocks are labels, currently appearing
8007       // only in asm's.
8008       if (isa<CallBrInst>(Call) &&
8009           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8010                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8011                         NumMatchingOps) &&
8012           (NumMatchingOps == 0 ||
8013            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8014                         NumMatchingOps))) {
8015         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8016         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8017         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8018       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8019         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8020       } else {
8021         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8022       }
8023 
8024       OpInfo.ConstraintVT =
8025           OpInfo
8026               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8027               .getSimpleVT();
8028     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8029       // The return value of the call is this value.  As such, there is no
8030       // corresponding argument.
8031       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8032       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8033         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8034             DAG.getDataLayout(), STy->getElementType(ResNo));
8035       } else {
8036         assert(ResNo == 0 && "Asm only has one result!");
8037         OpInfo.ConstraintVT =
8038             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8039       }
8040       ++ResNo;
8041     } else {
8042       OpInfo.ConstraintVT = MVT::Other;
8043     }
8044 
8045     if (OpInfo.hasMatchingInput())
8046       ++NumMatchingOps;
8047 
8048     if (!HasSideEffect)
8049       HasSideEffect = OpInfo.hasMemory(TLI);
8050 
8051     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8052     // FIXME: Could we compute this on OpInfo rather than T?
8053 
8054     // Compute the constraint code and ConstraintType to use.
8055     TLI.ComputeConstraintToUse(T, SDValue());
8056 
8057     if (T.ConstraintType == TargetLowering::C_Immediate &&
8058         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8059       // We've delayed emitting a diagnostic like the "n" constraint because
8060       // inlining could cause an integer showing up.
8061       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8062                                           "' expects an integer constant "
8063                                           "expression");
8064 
8065     ExtraInfo.update(T);
8066   }
8067 
8068 
8069   // We won't need to flush pending loads if this asm doesn't touch
8070   // memory and is nonvolatile.
8071   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8072 
8073   bool IsCallBr = isa<CallBrInst>(Call);
8074   if (IsCallBr) {
8075     // If this is a callbr we need to flush pending exports since inlineasm_br
8076     // is a terminator. We need to do this before nodes are glued to
8077     // the inlineasm_br node.
8078     Chain = getControlRoot();
8079   }
8080 
8081   // Second pass over the constraints: compute which constraint option to use.
8082   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8083     // If this is an output operand with a matching input operand, look up the
8084     // matching input. If their types mismatch, e.g. one is an integer, the
8085     // other is floating point, or their sizes are different, flag it as an
8086     // error.
8087     if (OpInfo.hasMatchingInput()) {
8088       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8089       patchMatchingInput(OpInfo, Input, DAG);
8090     }
8091 
8092     // Compute the constraint code and ConstraintType to use.
8093     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8094 
8095     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8096         OpInfo.Type == InlineAsm::isClobber)
8097       continue;
8098 
8099     // If this is a memory input, and if the operand is not indirect, do what we
8100     // need to provide an address for the memory input.
8101     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8102         !OpInfo.isIndirect) {
8103       assert((OpInfo.isMultipleAlternative ||
8104               (OpInfo.Type == InlineAsm::isInput)) &&
8105              "Can only indirectify direct input operands!");
8106 
8107       // Memory operands really want the address of the value.
8108       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8109 
8110       // There is no longer a Value* corresponding to this operand.
8111       OpInfo.CallOperandVal = nullptr;
8112 
8113       // It is now an indirect operand.
8114       OpInfo.isIndirect = true;
8115     }
8116 
8117   }
8118 
8119   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8120   std::vector<SDValue> AsmNodeOperands;
8121   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8122   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8123       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8124 
8125   // If we have a !srcloc metadata node associated with it, we want to attach
8126   // this to the ultimately generated inline asm machineinstr.  To do this, we
8127   // pass in the third operand as this (potentially null) inline asm MDNode.
8128   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8129   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8130 
8131   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8132   // bits as operand 3.
8133   AsmNodeOperands.push_back(DAG.getTargetConstant(
8134       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8135 
8136   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8137   // this, assign virtual and physical registers for inputs and otput.
8138   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8139     // Assign Registers.
8140     SDISelAsmOperandInfo &RefOpInfo =
8141         OpInfo.isMatchingInputConstraint()
8142             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8143             : OpInfo;
8144     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8145 
8146     auto DetectWriteToReservedRegister = [&]() {
8147       const MachineFunction &MF = DAG.getMachineFunction();
8148       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8149       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8150         if (Register::isPhysicalRegister(Reg) &&
8151             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8152           const char *RegName = TRI.getName(Reg);
8153           emitInlineAsmError(Call, "write to reserved register '" +
8154                                        Twine(RegName) + "'");
8155           return true;
8156         }
8157       }
8158       return false;
8159     };
8160 
8161     switch (OpInfo.Type) {
8162     case InlineAsm::isOutput:
8163       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8164         unsigned ConstraintID =
8165             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8166         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8167                "Failed to convert memory constraint code to constraint id.");
8168 
8169         // Add information to the INLINEASM node to know about this output.
8170         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8171         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8172         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8173                                                         MVT::i32));
8174         AsmNodeOperands.push_back(OpInfo.CallOperand);
8175       } else {
8176         // Otherwise, this outputs to a register (directly for C_Register /
8177         // C_RegisterClass, and a target-defined fashion for
8178         // C_Immediate/C_Other). Find a register that we can use.
8179         if (OpInfo.AssignedRegs.Regs.empty()) {
8180           emitInlineAsmError(
8181               Call, "couldn't allocate output register for constraint '" +
8182                         Twine(OpInfo.ConstraintCode) + "'");
8183           return;
8184         }
8185 
8186         if (DetectWriteToReservedRegister())
8187           return;
8188 
8189         // Add information to the INLINEASM node to know that this register is
8190         // set.
8191         OpInfo.AssignedRegs.AddInlineAsmOperands(
8192             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8193                                   : InlineAsm::Kind_RegDef,
8194             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8195       }
8196       break;
8197 
8198     case InlineAsm::isInput: {
8199       SDValue InOperandVal = OpInfo.CallOperand;
8200 
8201       if (OpInfo.isMatchingInputConstraint()) {
8202         // If this is required to match an output register we have already set,
8203         // just use its register.
8204         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8205                                                   AsmNodeOperands);
8206         unsigned OpFlag =
8207           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8208         if (InlineAsm::isRegDefKind(OpFlag) ||
8209             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8210           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8211           if (OpInfo.isIndirect) {
8212             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8213             emitInlineAsmError(Call, "inline asm not supported yet: "
8214                                      "don't know how to handle tied "
8215                                      "indirect register inputs");
8216             return;
8217           }
8218 
8219           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8220           SmallVector<unsigned, 4> Regs;
8221 
8222           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8223             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8224             MachineRegisterInfo &RegInfo =
8225                 DAG.getMachineFunction().getRegInfo();
8226             for (unsigned i = 0; i != NumRegs; ++i)
8227               Regs.push_back(RegInfo.createVirtualRegister(RC));
8228           } else {
8229             emitInlineAsmError(Call,
8230                                "inline asm error: This value type register "
8231                                "class is not natively supported!");
8232             return;
8233           }
8234 
8235           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8236 
8237           SDLoc dl = getCurSDLoc();
8238           // Use the produced MatchedRegs object to
8239           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8240           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8241                                            true, OpInfo.getMatchedOperand(), dl,
8242                                            DAG, AsmNodeOperands);
8243           break;
8244         }
8245 
8246         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8247         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8248                "Unexpected number of operands");
8249         // Add information to the INLINEASM node to know about this input.
8250         // See InlineAsm.h isUseOperandTiedToDef.
8251         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8252         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8253                                                     OpInfo.getMatchedOperand());
8254         AsmNodeOperands.push_back(DAG.getTargetConstant(
8255             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8256         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8257         break;
8258       }
8259 
8260       // Treat indirect 'X' constraint as memory.
8261       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8262           OpInfo.isIndirect)
8263         OpInfo.ConstraintType = TargetLowering::C_Memory;
8264 
8265       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8266           OpInfo.ConstraintType == TargetLowering::C_Other) {
8267         std::vector<SDValue> Ops;
8268         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8269                                           Ops, DAG);
8270         if (Ops.empty()) {
8271           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8272             if (isa<ConstantSDNode>(InOperandVal)) {
8273               emitInlineAsmError(Call, "value out of range for constraint '" +
8274                                            Twine(OpInfo.ConstraintCode) + "'");
8275               return;
8276             }
8277 
8278           emitInlineAsmError(Call,
8279                              "invalid operand for inline asm constraint '" +
8280                                  Twine(OpInfo.ConstraintCode) + "'");
8281           return;
8282         }
8283 
8284         // Add information to the INLINEASM node to know about this input.
8285         unsigned ResOpType =
8286           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8287         AsmNodeOperands.push_back(DAG.getTargetConstant(
8288             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8289         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8290         break;
8291       }
8292 
8293       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8294         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8295         assert(InOperandVal.getValueType() ==
8296                    TLI.getPointerTy(DAG.getDataLayout()) &&
8297                "Memory operands expect pointer values");
8298 
8299         unsigned ConstraintID =
8300             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8301         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8302                "Failed to convert memory constraint code to constraint id.");
8303 
8304         // Add information to the INLINEASM node to know about this input.
8305         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8306         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8307         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8308                                                         getCurSDLoc(),
8309                                                         MVT::i32));
8310         AsmNodeOperands.push_back(InOperandVal);
8311         break;
8312       }
8313 
8314       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8315               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8316              "Unknown constraint type!");
8317 
8318       // TODO: Support this.
8319       if (OpInfo.isIndirect) {
8320         emitInlineAsmError(
8321             Call, "Don't know how to handle indirect register inputs yet "
8322                   "for constraint '" +
8323                       Twine(OpInfo.ConstraintCode) + "'");
8324         return;
8325       }
8326 
8327       // Copy the input into the appropriate registers.
8328       if (OpInfo.AssignedRegs.Regs.empty()) {
8329         emitInlineAsmError(Call,
8330                            "couldn't allocate input reg for constraint '" +
8331                                Twine(OpInfo.ConstraintCode) + "'");
8332         return;
8333       }
8334 
8335       if (DetectWriteToReservedRegister())
8336         return;
8337 
8338       SDLoc dl = getCurSDLoc();
8339 
8340       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8341                                         &Call);
8342 
8343       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8344                                                dl, DAG, AsmNodeOperands);
8345       break;
8346     }
8347     case InlineAsm::isClobber:
8348       // Add the clobbered value to the operand list, so that the register
8349       // allocator is aware that the physreg got clobbered.
8350       if (!OpInfo.AssignedRegs.Regs.empty())
8351         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8352                                                  false, 0, getCurSDLoc(), DAG,
8353                                                  AsmNodeOperands);
8354       break;
8355     }
8356   }
8357 
8358   // Finish up input operands.  Set the input chain and add the flag last.
8359   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8360   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8361 
8362   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8363   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8364                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8365   Flag = Chain.getValue(1);
8366 
8367   // Do additional work to generate outputs.
8368 
8369   SmallVector<EVT, 1> ResultVTs;
8370   SmallVector<SDValue, 1> ResultValues;
8371   SmallVector<SDValue, 8> OutChains;
8372 
8373   llvm::Type *CallResultType = Call.getType();
8374   ArrayRef<Type *> ResultTypes;
8375   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8376     ResultTypes = StructResult->elements();
8377   else if (!CallResultType->isVoidTy())
8378     ResultTypes = makeArrayRef(CallResultType);
8379 
8380   auto CurResultType = ResultTypes.begin();
8381   auto handleRegAssign = [&](SDValue V) {
8382     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8383     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8384     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8385     ++CurResultType;
8386     // If the type of the inline asm call site return value is different but has
8387     // same size as the type of the asm output bitcast it.  One example of this
8388     // is for vectors with different width / number of elements.  This can
8389     // happen for register classes that can contain multiple different value
8390     // types.  The preg or vreg allocated may not have the same VT as was
8391     // expected.
8392     //
8393     // This can also happen for a return value that disagrees with the register
8394     // class it is put in, eg. a double in a general-purpose register on a
8395     // 32-bit machine.
8396     if (ResultVT != V.getValueType() &&
8397         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8398       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8399     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8400              V.getValueType().isInteger()) {
8401       // If a result value was tied to an input value, the computed result
8402       // may have a wider width than the expected result.  Extract the
8403       // relevant portion.
8404       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8405     }
8406     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8407     ResultVTs.push_back(ResultVT);
8408     ResultValues.push_back(V);
8409   };
8410 
8411   // Deal with output operands.
8412   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8413     if (OpInfo.Type == InlineAsm::isOutput) {
8414       SDValue Val;
8415       // Skip trivial output operands.
8416       if (OpInfo.AssignedRegs.Regs.empty())
8417         continue;
8418 
8419       switch (OpInfo.ConstraintType) {
8420       case TargetLowering::C_Register:
8421       case TargetLowering::C_RegisterClass:
8422         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8423                                                   Chain, &Flag, &Call);
8424         break;
8425       case TargetLowering::C_Immediate:
8426       case TargetLowering::C_Other:
8427         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8428                                               OpInfo, DAG);
8429         break;
8430       case TargetLowering::C_Memory:
8431         break; // Already handled.
8432       case TargetLowering::C_Unknown:
8433         assert(false && "Unexpected unknown constraint");
8434       }
8435 
8436       // Indirect output manifest as stores. Record output chains.
8437       if (OpInfo.isIndirect) {
8438         const Value *Ptr = OpInfo.CallOperandVal;
8439         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8440         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8441                                      MachinePointerInfo(Ptr));
8442         OutChains.push_back(Store);
8443       } else {
8444         // generate CopyFromRegs to associated registers.
8445         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8446         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8447           for (const SDValue &V : Val->op_values())
8448             handleRegAssign(V);
8449         } else
8450           handleRegAssign(Val);
8451       }
8452     }
8453   }
8454 
8455   // Set results.
8456   if (!ResultValues.empty()) {
8457     assert(CurResultType == ResultTypes.end() &&
8458            "Mismatch in number of ResultTypes");
8459     assert(ResultValues.size() == ResultTypes.size() &&
8460            "Mismatch in number of output operands in asm result");
8461 
8462     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8463                             DAG.getVTList(ResultVTs), ResultValues);
8464     setValue(&Call, V);
8465   }
8466 
8467   // Collect store chains.
8468   if (!OutChains.empty())
8469     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8470 
8471   // Only Update Root if inline assembly has a memory effect.
8472   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8473     DAG.setRoot(Chain);
8474 }
8475 
8476 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8477                                              const Twine &Message) {
8478   LLVMContext &Ctx = *DAG.getContext();
8479   Ctx.emitError(&Call, Message);
8480 
8481   // Make sure we leave the DAG in a valid state
8482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8483   SmallVector<EVT, 1> ValueVTs;
8484   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8485 
8486   if (ValueVTs.empty())
8487     return;
8488 
8489   SmallVector<SDValue, 1> Ops;
8490   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8491     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8492 
8493   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8494 }
8495 
8496 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8497   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8498                           MVT::Other, getRoot(),
8499                           getValue(I.getArgOperand(0)),
8500                           DAG.getSrcValue(I.getArgOperand(0))));
8501 }
8502 
8503 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8505   const DataLayout &DL = DAG.getDataLayout();
8506   SDValue V = DAG.getVAArg(
8507       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8508       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8509       DL.getABITypeAlignment(I.getType()));
8510   DAG.setRoot(V.getValue(1));
8511 
8512   if (I.getType()->isPointerTy())
8513     V = DAG.getPtrExtOrTrunc(
8514         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8515   setValue(&I, V);
8516 }
8517 
8518 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8519   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8520                           MVT::Other, getRoot(),
8521                           getValue(I.getArgOperand(0)),
8522                           DAG.getSrcValue(I.getArgOperand(0))));
8523 }
8524 
8525 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8526   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8527                           MVT::Other, getRoot(),
8528                           getValue(I.getArgOperand(0)),
8529                           getValue(I.getArgOperand(1)),
8530                           DAG.getSrcValue(I.getArgOperand(0)),
8531                           DAG.getSrcValue(I.getArgOperand(1))));
8532 }
8533 
8534 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8535                                                     const Instruction &I,
8536                                                     SDValue Op) {
8537   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8538   if (!Range)
8539     return Op;
8540 
8541   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8542   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8543     return Op;
8544 
8545   APInt Lo = CR.getUnsignedMin();
8546   if (!Lo.isMinValue())
8547     return Op;
8548 
8549   APInt Hi = CR.getUnsignedMax();
8550   unsigned Bits = std::max(Hi.getActiveBits(),
8551                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8552 
8553   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8554 
8555   SDLoc SL = getCurSDLoc();
8556 
8557   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8558                              DAG.getValueType(SmallVT));
8559   unsigned NumVals = Op.getNode()->getNumValues();
8560   if (NumVals == 1)
8561     return ZExt;
8562 
8563   SmallVector<SDValue, 4> Ops;
8564 
8565   Ops.push_back(ZExt);
8566   for (unsigned I = 1; I != NumVals; ++I)
8567     Ops.push_back(Op.getValue(I));
8568 
8569   return DAG.getMergeValues(Ops, SL);
8570 }
8571 
8572 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8573 /// the call being lowered.
8574 ///
8575 /// This is a helper for lowering intrinsics that follow a target calling
8576 /// convention or require stack pointer adjustment. Only a subset of the
8577 /// intrinsic's operands need to participate in the calling convention.
8578 void SelectionDAGBuilder::populateCallLoweringInfo(
8579     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8580     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8581     bool IsPatchPoint) {
8582   TargetLowering::ArgListTy Args;
8583   Args.reserve(NumArgs);
8584 
8585   // Populate the argument list.
8586   // Attributes for args start at offset 1, after the return attribute.
8587   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8588        ArgI != ArgE; ++ArgI) {
8589     const Value *V = Call->getOperand(ArgI);
8590 
8591     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8592 
8593     TargetLowering::ArgListEntry Entry;
8594     Entry.Node = getValue(V);
8595     Entry.Ty = V->getType();
8596     Entry.setAttributes(Call, ArgI);
8597     Args.push_back(Entry);
8598   }
8599 
8600   CLI.setDebugLoc(getCurSDLoc())
8601       .setChain(getRoot())
8602       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8603       .setDiscardResult(Call->use_empty())
8604       .setIsPatchPoint(IsPatchPoint);
8605 }
8606 
8607 /// Add a stack map intrinsic call's live variable operands to a stackmap
8608 /// or patchpoint target node's operand list.
8609 ///
8610 /// Constants are converted to TargetConstants purely as an optimization to
8611 /// avoid constant materialization and register allocation.
8612 ///
8613 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8614 /// generate addess computation nodes, and so FinalizeISel can convert the
8615 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8616 /// address materialization and register allocation, but may also be required
8617 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8618 /// alloca in the entry block, then the runtime may assume that the alloca's
8619 /// StackMap location can be read immediately after compilation and that the
8620 /// location is valid at any point during execution (this is similar to the
8621 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8622 /// only available in a register, then the runtime would need to trap when
8623 /// execution reaches the StackMap in order to read the alloca's location.
8624 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8625                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8626                                 SelectionDAGBuilder &Builder) {
8627   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8628     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8629     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8630       Ops.push_back(
8631         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8632       Ops.push_back(
8633         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8634     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8635       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8636       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8637           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8638     } else
8639       Ops.push_back(OpVal);
8640   }
8641 }
8642 
8643 /// Lower llvm.experimental.stackmap directly to its target opcode.
8644 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8645   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8646   //                                  [live variables...])
8647 
8648   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8649 
8650   SDValue Chain, InFlag, Callee, NullPtr;
8651   SmallVector<SDValue, 32> Ops;
8652 
8653   SDLoc DL = getCurSDLoc();
8654   Callee = getValue(CI.getCalledValue());
8655   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8656 
8657   // The stackmap intrinsic only records the live variables (the arguments
8658   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8659   // intrinsic, this won't be lowered to a function call. This means we don't
8660   // have to worry about calling conventions and target specific lowering code.
8661   // Instead we perform the call lowering right here.
8662   //
8663   // chain, flag = CALLSEQ_START(chain, 0, 0)
8664   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8665   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8666   //
8667   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8668   InFlag = Chain.getValue(1);
8669 
8670   // Add the <id> and <numBytes> constants.
8671   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8672   Ops.push_back(DAG.getTargetConstant(
8673                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8674   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8675   Ops.push_back(DAG.getTargetConstant(
8676                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8677                   MVT::i32));
8678 
8679   // Push live variables for the stack map.
8680   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8681 
8682   // We are not pushing any register mask info here on the operands list,
8683   // because the stackmap doesn't clobber anything.
8684 
8685   // Push the chain and the glue flag.
8686   Ops.push_back(Chain);
8687   Ops.push_back(InFlag);
8688 
8689   // Create the STACKMAP node.
8690   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8691   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8692   Chain = SDValue(SM, 0);
8693   InFlag = Chain.getValue(1);
8694 
8695   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8696 
8697   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8698 
8699   // Set the root to the target-lowered call chain.
8700   DAG.setRoot(Chain);
8701 
8702   // Inform the Frame Information that we have a stackmap in this function.
8703   FuncInfo.MF->getFrameInfo().setHasStackMap();
8704 }
8705 
8706 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8707 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8708                                           const BasicBlock *EHPadBB) {
8709   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8710   //                                                 i32 <numBytes>,
8711   //                                                 i8* <target>,
8712   //                                                 i32 <numArgs>,
8713   //                                                 [Args...],
8714   //                                                 [live variables...])
8715 
8716   CallingConv::ID CC = CB.getCallingConv();
8717   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8718   bool HasDef = !CB.getType()->isVoidTy();
8719   SDLoc dl = getCurSDLoc();
8720   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8721 
8722   // Handle immediate and symbolic callees.
8723   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8724     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8725                                    /*isTarget=*/true);
8726   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8727     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8728                                          SDLoc(SymbolicCallee),
8729                                          SymbolicCallee->getValueType(0));
8730 
8731   // Get the real number of arguments participating in the call <numArgs>
8732   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8733   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8734 
8735   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8736   // Intrinsics include all meta-operands up to but not including CC.
8737   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8738   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8739          "Not enough arguments provided to the patchpoint intrinsic");
8740 
8741   // For AnyRegCC the arguments are lowered later on manually.
8742   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8743   Type *ReturnTy =
8744       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8745 
8746   TargetLowering::CallLoweringInfo CLI(DAG);
8747   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8748                            ReturnTy, true);
8749   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8750 
8751   SDNode *CallEnd = Result.second.getNode();
8752   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8753     CallEnd = CallEnd->getOperand(0).getNode();
8754 
8755   /// Get a call instruction from the call sequence chain.
8756   /// Tail calls are not allowed.
8757   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8758          "Expected a callseq node.");
8759   SDNode *Call = CallEnd->getOperand(0).getNode();
8760   bool HasGlue = Call->getGluedNode();
8761 
8762   // Replace the target specific call node with the patchable intrinsic.
8763   SmallVector<SDValue, 8> Ops;
8764 
8765   // Add the <id> and <numBytes> constants.
8766   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8767   Ops.push_back(DAG.getTargetConstant(
8768                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8769   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8770   Ops.push_back(DAG.getTargetConstant(
8771                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8772                   MVT::i32));
8773 
8774   // Add the callee.
8775   Ops.push_back(Callee);
8776 
8777   // Adjust <numArgs> to account for any arguments that have been passed on the
8778   // stack instead.
8779   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8780   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8781   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8782   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8783 
8784   // Add the calling convention
8785   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8786 
8787   // Add the arguments we omitted previously. The register allocator should
8788   // place these in any free register.
8789   if (IsAnyRegCC)
8790     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8791       Ops.push_back(getValue(CB.getArgOperand(i)));
8792 
8793   // Push the arguments from the call instruction up to the register mask.
8794   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8795   Ops.append(Call->op_begin() + 2, e);
8796 
8797   // Push live variables for the stack map.
8798   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8799 
8800   // Push the register mask info.
8801   if (HasGlue)
8802     Ops.push_back(*(Call->op_end()-2));
8803   else
8804     Ops.push_back(*(Call->op_end()-1));
8805 
8806   // Push the chain (this is originally the first operand of the call, but
8807   // becomes now the last or second to last operand).
8808   Ops.push_back(*(Call->op_begin()));
8809 
8810   // Push the glue flag (last operand).
8811   if (HasGlue)
8812     Ops.push_back(*(Call->op_end()-1));
8813 
8814   SDVTList NodeTys;
8815   if (IsAnyRegCC && HasDef) {
8816     // Create the return types based on the intrinsic definition
8817     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8818     SmallVector<EVT, 3> ValueVTs;
8819     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8820     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8821 
8822     // There is always a chain and a glue type at the end
8823     ValueVTs.push_back(MVT::Other);
8824     ValueVTs.push_back(MVT::Glue);
8825     NodeTys = DAG.getVTList(ValueVTs);
8826   } else
8827     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8828 
8829   // Replace the target specific call node with a PATCHPOINT node.
8830   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8831                                          dl, NodeTys, Ops);
8832 
8833   // Update the NodeMap.
8834   if (HasDef) {
8835     if (IsAnyRegCC)
8836       setValue(&CB, SDValue(MN, 0));
8837     else
8838       setValue(&CB, Result.first);
8839   }
8840 
8841   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8842   // call sequence. Furthermore the location of the chain and glue can change
8843   // when the AnyReg calling convention is used and the intrinsic returns a
8844   // value.
8845   if (IsAnyRegCC && HasDef) {
8846     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8847     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8848     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8849   } else
8850     DAG.ReplaceAllUsesWith(Call, MN);
8851   DAG.DeleteNode(Call);
8852 
8853   // Inform the Frame Information that we have a patchpoint in this function.
8854   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8855 }
8856 
8857 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8858                                             unsigned Intrinsic) {
8859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8860   SDValue Op1 = getValue(I.getArgOperand(0));
8861   SDValue Op2;
8862   if (I.getNumArgOperands() > 1)
8863     Op2 = getValue(I.getArgOperand(1));
8864   SDLoc dl = getCurSDLoc();
8865   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8866   SDValue Res;
8867   FastMathFlags FMF;
8868   if (isa<FPMathOperator>(I))
8869     FMF = I.getFastMathFlags();
8870 
8871   switch (Intrinsic) {
8872   case Intrinsic::experimental_vector_reduce_v2_fadd:
8873     if (FMF.allowReassoc())
8874       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8875                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8876     else
8877       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8878     break;
8879   case Intrinsic::experimental_vector_reduce_v2_fmul:
8880     if (FMF.allowReassoc())
8881       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8882                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8883     else
8884       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8885     break;
8886   case Intrinsic::experimental_vector_reduce_add:
8887     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8888     break;
8889   case Intrinsic::experimental_vector_reduce_mul:
8890     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8891     break;
8892   case Intrinsic::experimental_vector_reduce_and:
8893     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8894     break;
8895   case Intrinsic::experimental_vector_reduce_or:
8896     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8897     break;
8898   case Intrinsic::experimental_vector_reduce_xor:
8899     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8900     break;
8901   case Intrinsic::experimental_vector_reduce_smax:
8902     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8903     break;
8904   case Intrinsic::experimental_vector_reduce_smin:
8905     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8906     break;
8907   case Intrinsic::experimental_vector_reduce_umax:
8908     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8909     break;
8910   case Intrinsic::experimental_vector_reduce_umin:
8911     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8912     break;
8913   case Intrinsic::experimental_vector_reduce_fmax:
8914     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8915     break;
8916   case Intrinsic::experimental_vector_reduce_fmin:
8917     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8918     break;
8919   default:
8920     llvm_unreachable("Unhandled vector reduce intrinsic");
8921   }
8922   setValue(&I, Res);
8923 }
8924 
8925 /// Returns an AttributeList representing the attributes applied to the return
8926 /// value of the given call.
8927 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8928   SmallVector<Attribute::AttrKind, 2> Attrs;
8929   if (CLI.RetSExt)
8930     Attrs.push_back(Attribute::SExt);
8931   if (CLI.RetZExt)
8932     Attrs.push_back(Attribute::ZExt);
8933   if (CLI.IsInReg)
8934     Attrs.push_back(Attribute::InReg);
8935 
8936   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8937                             Attrs);
8938 }
8939 
8940 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8941 /// implementation, which just calls LowerCall.
8942 /// FIXME: When all targets are
8943 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8944 std::pair<SDValue, SDValue>
8945 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8946   // Handle the incoming return values from the call.
8947   CLI.Ins.clear();
8948   Type *OrigRetTy = CLI.RetTy;
8949   SmallVector<EVT, 4> RetTys;
8950   SmallVector<uint64_t, 4> Offsets;
8951   auto &DL = CLI.DAG.getDataLayout();
8952   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8953 
8954   if (CLI.IsPostTypeLegalization) {
8955     // If we are lowering a libcall after legalization, split the return type.
8956     SmallVector<EVT, 4> OldRetTys;
8957     SmallVector<uint64_t, 4> OldOffsets;
8958     RetTys.swap(OldRetTys);
8959     Offsets.swap(OldOffsets);
8960 
8961     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8962       EVT RetVT = OldRetTys[i];
8963       uint64_t Offset = OldOffsets[i];
8964       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8965       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8966       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8967       RetTys.append(NumRegs, RegisterVT);
8968       for (unsigned j = 0; j != NumRegs; ++j)
8969         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8970     }
8971   }
8972 
8973   SmallVector<ISD::OutputArg, 4> Outs;
8974   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8975 
8976   bool CanLowerReturn =
8977       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8978                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8979 
8980   SDValue DemoteStackSlot;
8981   int DemoteStackIdx = -100;
8982   if (!CanLowerReturn) {
8983     // FIXME: equivalent assert?
8984     // assert(!CS.hasInAllocaArgument() &&
8985     //        "sret demotion is incompatible with inalloca");
8986     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8987     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
8988     MachineFunction &MF = CLI.DAG.getMachineFunction();
8989     DemoteStackIdx =
8990         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
8991     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8992                                               DL.getAllocaAddrSpace());
8993 
8994     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8995     ArgListEntry Entry;
8996     Entry.Node = DemoteStackSlot;
8997     Entry.Ty = StackSlotPtrType;
8998     Entry.IsSExt = false;
8999     Entry.IsZExt = false;
9000     Entry.IsInReg = false;
9001     Entry.IsSRet = true;
9002     Entry.IsNest = false;
9003     Entry.IsByVal = false;
9004     Entry.IsReturned = false;
9005     Entry.IsSwiftSelf = false;
9006     Entry.IsSwiftError = false;
9007     Entry.IsCFGuardTarget = false;
9008     Entry.Alignment = Alignment;
9009     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9010     CLI.NumFixedArgs += 1;
9011     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9012 
9013     // sret demotion isn't compatible with tail-calls, since the sret argument
9014     // points into the callers stack frame.
9015     CLI.IsTailCall = false;
9016   } else {
9017     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9018         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9019     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9020       ISD::ArgFlagsTy Flags;
9021       if (NeedsRegBlock) {
9022         Flags.setInConsecutiveRegs();
9023         if (I == RetTys.size() - 1)
9024           Flags.setInConsecutiveRegsLast();
9025       }
9026       EVT VT = RetTys[I];
9027       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9028                                                      CLI.CallConv, VT);
9029       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9030                                                        CLI.CallConv, VT);
9031       for (unsigned i = 0; i != NumRegs; ++i) {
9032         ISD::InputArg MyFlags;
9033         MyFlags.Flags = Flags;
9034         MyFlags.VT = RegisterVT;
9035         MyFlags.ArgVT = VT;
9036         MyFlags.Used = CLI.IsReturnValueUsed;
9037         if (CLI.RetTy->isPointerTy()) {
9038           MyFlags.Flags.setPointer();
9039           MyFlags.Flags.setPointerAddrSpace(
9040               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9041         }
9042         if (CLI.RetSExt)
9043           MyFlags.Flags.setSExt();
9044         if (CLI.RetZExt)
9045           MyFlags.Flags.setZExt();
9046         if (CLI.IsInReg)
9047           MyFlags.Flags.setInReg();
9048         CLI.Ins.push_back(MyFlags);
9049       }
9050     }
9051   }
9052 
9053   // We push in swifterror return as the last element of CLI.Ins.
9054   ArgListTy &Args = CLI.getArgs();
9055   if (supportSwiftError()) {
9056     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9057       if (Args[i].IsSwiftError) {
9058         ISD::InputArg MyFlags;
9059         MyFlags.VT = getPointerTy(DL);
9060         MyFlags.ArgVT = EVT(getPointerTy(DL));
9061         MyFlags.Flags.setSwiftError();
9062         CLI.Ins.push_back(MyFlags);
9063       }
9064     }
9065   }
9066 
9067   // Handle all of the outgoing arguments.
9068   CLI.Outs.clear();
9069   CLI.OutVals.clear();
9070   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9071     SmallVector<EVT, 4> ValueVTs;
9072     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9073     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9074     Type *FinalType = Args[i].Ty;
9075     if (Args[i].IsByVal)
9076       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9077     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9078         FinalType, CLI.CallConv, CLI.IsVarArg);
9079     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9080          ++Value) {
9081       EVT VT = ValueVTs[Value];
9082       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9083       SDValue Op = SDValue(Args[i].Node.getNode(),
9084                            Args[i].Node.getResNo() + Value);
9085       ISD::ArgFlagsTy Flags;
9086 
9087       // Certain targets (such as MIPS), may have a different ABI alignment
9088       // for a type depending on the context. Give the target a chance to
9089       // specify the alignment it wants.
9090       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9091 
9092       if (Args[i].Ty->isPointerTy()) {
9093         Flags.setPointer();
9094         Flags.setPointerAddrSpace(
9095             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9096       }
9097       if (Args[i].IsZExt)
9098         Flags.setZExt();
9099       if (Args[i].IsSExt)
9100         Flags.setSExt();
9101       if (Args[i].IsInReg) {
9102         // If we are using vectorcall calling convention, a structure that is
9103         // passed InReg - is surely an HVA
9104         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9105             isa<StructType>(FinalType)) {
9106           // The first value of a structure is marked
9107           if (0 == Value)
9108             Flags.setHvaStart();
9109           Flags.setHva();
9110         }
9111         // Set InReg Flag
9112         Flags.setInReg();
9113       }
9114       if (Args[i].IsSRet)
9115         Flags.setSRet();
9116       if (Args[i].IsSwiftSelf)
9117         Flags.setSwiftSelf();
9118       if (Args[i].IsSwiftError)
9119         Flags.setSwiftError();
9120       if (Args[i].IsCFGuardTarget)
9121         Flags.setCFGuardTarget();
9122       if (Args[i].IsByVal)
9123         Flags.setByVal();
9124       if (Args[i].IsInAlloca) {
9125         Flags.setInAlloca();
9126         // Set the byval flag for CCAssignFn callbacks that don't know about
9127         // inalloca.  This way we can know how many bytes we should've allocated
9128         // and how many bytes a callee cleanup function will pop.  If we port
9129         // inalloca to more targets, we'll have to add custom inalloca handling
9130         // in the various CC lowering callbacks.
9131         Flags.setByVal();
9132       }
9133       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9134         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9135         Type *ElementTy = Ty->getElementType();
9136 
9137         unsigned FrameSize = DL.getTypeAllocSize(
9138             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9139         Flags.setByValSize(FrameSize);
9140 
9141         // info is not there but there are cases it cannot get right.
9142         Align FrameAlign;
9143         if (auto MA = Args[i].Alignment)
9144           FrameAlign = *MA;
9145         else
9146           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9147         Flags.setByValAlign(FrameAlign);
9148       }
9149       if (Args[i].IsNest)
9150         Flags.setNest();
9151       if (NeedsRegBlock)
9152         Flags.setInConsecutiveRegs();
9153       Flags.setOrigAlign(OriginalAlignment);
9154 
9155       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9156                                                  CLI.CallConv, VT);
9157       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9158                                                         CLI.CallConv, VT);
9159       SmallVector<SDValue, 4> Parts(NumParts);
9160       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9161 
9162       if (Args[i].IsSExt)
9163         ExtendKind = ISD::SIGN_EXTEND;
9164       else if (Args[i].IsZExt)
9165         ExtendKind = ISD::ZERO_EXTEND;
9166 
9167       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9168       // for now.
9169       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9170           CanLowerReturn) {
9171         assert((CLI.RetTy == Args[i].Ty ||
9172                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9173                  CLI.RetTy->getPointerAddressSpace() ==
9174                      Args[i].Ty->getPointerAddressSpace())) &&
9175                RetTys.size() == NumValues && "unexpected use of 'returned'");
9176         // Before passing 'returned' to the target lowering code, ensure that
9177         // either the register MVT and the actual EVT are the same size or that
9178         // the return value and argument are extended in the same way; in these
9179         // cases it's safe to pass the argument register value unchanged as the
9180         // return register value (although it's at the target's option whether
9181         // to do so)
9182         // TODO: allow code generation to take advantage of partially preserved
9183         // registers rather than clobbering the entire register when the
9184         // parameter extension method is not compatible with the return
9185         // extension method
9186         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9187             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9188              CLI.RetZExt == Args[i].IsZExt))
9189           Flags.setReturned();
9190       }
9191 
9192       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9193                      CLI.CallConv, ExtendKind);
9194 
9195       for (unsigned j = 0; j != NumParts; ++j) {
9196         // if it isn't first piece, alignment must be 1
9197         // For scalable vectors the scalable part is currently handled
9198         // by individual targets, so we just use the known minimum size here.
9199         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9200                     i < CLI.NumFixedArgs, i,
9201                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9202         if (NumParts > 1 && j == 0)
9203           MyFlags.Flags.setSplit();
9204         else if (j != 0) {
9205           MyFlags.Flags.setOrigAlign(Align(1));
9206           if (j == NumParts - 1)
9207             MyFlags.Flags.setSplitEnd();
9208         }
9209 
9210         CLI.Outs.push_back(MyFlags);
9211         CLI.OutVals.push_back(Parts[j]);
9212       }
9213 
9214       if (NeedsRegBlock && Value == NumValues - 1)
9215         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9216     }
9217   }
9218 
9219   SmallVector<SDValue, 4> InVals;
9220   CLI.Chain = LowerCall(CLI, InVals);
9221 
9222   // Update CLI.InVals to use outside of this function.
9223   CLI.InVals = InVals;
9224 
9225   // Verify that the target's LowerCall behaved as expected.
9226   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9227          "LowerCall didn't return a valid chain!");
9228   assert((!CLI.IsTailCall || InVals.empty()) &&
9229          "LowerCall emitted a return value for a tail call!");
9230   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9231          "LowerCall didn't emit the correct number of values!");
9232 
9233   // For a tail call, the return value is merely live-out and there aren't
9234   // any nodes in the DAG representing it. Return a special value to
9235   // indicate that a tail call has been emitted and no more Instructions
9236   // should be processed in the current block.
9237   if (CLI.IsTailCall) {
9238     CLI.DAG.setRoot(CLI.Chain);
9239     return std::make_pair(SDValue(), SDValue());
9240   }
9241 
9242 #ifndef NDEBUG
9243   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9244     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9245     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9246            "LowerCall emitted a value with the wrong type!");
9247   }
9248 #endif
9249 
9250   SmallVector<SDValue, 4> ReturnValues;
9251   if (!CanLowerReturn) {
9252     // The instruction result is the result of loading from the
9253     // hidden sret parameter.
9254     SmallVector<EVT, 1> PVTs;
9255     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9256 
9257     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9258     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9259     EVT PtrVT = PVTs[0];
9260 
9261     unsigned NumValues = RetTys.size();
9262     ReturnValues.resize(NumValues);
9263     SmallVector<SDValue, 4> Chains(NumValues);
9264 
9265     // An aggregate return value cannot wrap around the address space, so
9266     // offsets to its parts don't wrap either.
9267     SDNodeFlags Flags;
9268     Flags.setNoUnsignedWrap(true);
9269 
9270     for (unsigned i = 0; i < NumValues; ++i) {
9271       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9272                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9273                                                         PtrVT), Flags);
9274       SDValue L = CLI.DAG.getLoad(
9275           RetTys[i], CLI.DL, CLI.Chain, Add,
9276           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9277                                             DemoteStackIdx, Offsets[i]),
9278           /* Alignment = */ 1);
9279       ReturnValues[i] = L;
9280       Chains[i] = L.getValue(1);
9281     }
9282 
9283     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9284   } else {
9285     // Collect the legal value parts into potentially illegal values
9286     // that correspond to the original function's return values.
9287     Optional<ISD::NodeType> AssertOp;
9288     if (CLI.RetSExt)
9289       AssertOp = ISD::AssertSext;
9290     else if (CLI.RetZExt)
9291       AssertOp = ISD::AssertZext;
9292     unsigned CurReg = 0;
9293     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9294       EVT VT = RetTys[I];
9295       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9296                                                      CLI.CallConv, VT);
9297       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9298                                                        CLI.CallConv, VT);
9299 
9300       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9301                                               NumRegs, RegisterVT, VT, nullptr,
9302                                               CLI.CallConv, AssertOp));
9303       CurReg += NumRegs;
9304     }
9305 
9306     // For a function returning void, there is no return value. We can't create
9307     // such a node, so we just return a null return value in that case. In
9308     // that case, nothing will actually look at the value.
9309     if (ReturnValues.empty())
9310       return std::make_pair(SDValue(), CLI.Chain);
9311   }
9312 
9313   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9314                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9315   return std::make_pair(Res, CLI.Chain);
9316 }
9317 
9318 void TargetLowering::LowerOperationWrapper(SDNode *N,
9319                                            SmallVectorImpl<SDValue> &Results,
9320                                            SelectionDAG &DAG) const {
9321   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9322     Results.push_back(Res);
9323 }
9324 
9325 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9326   llvm_unreachable("LowerOperation not implemented for this target!");
9327 }
9328 
9329 void
9330 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9331   SDValue Op = getNonRegisterValue(V);
9332   assert((Op.getOpcode() != ISD::CopyFromReg ||
9333           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9334          "Copy from a reg to the same reg!");
9335   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9336 
9337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9338   // If this is an InlineAsm we have to match the registers required, not the
9339   // notional registers required by the type.
9340 
9341   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9342                    None); // This is not an ABI copy.
9343   SDValue Chain = DAG.getEntryNode();
9344 
9345   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9346                               FuncInfo.PreferredExtendType.end())
9347                                  ? ISD::ANY_EXTEND
9348                                  : FuncInfo.PreferredExtendType[V];
9349   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9350   PendingExports.push_back(Chain);
9351 }
9352 
9353 #include "llvm/CodeGen/SelectionDAGISel.h"
9354 
9355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9356 /// entry block, return true.  This includes arguments used by switches, since
9357 /// the switch may expand into multiple basic blocks.
9358 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9359   // With FastISel active, we may be splitting blocks, so force creation
9360   // of virtual registers for all non-dead arguments.
9361   if (FastISel)
9362     return A->use_empty();
9363 
9364   const BasicBlock &Entry = A->getParent()->front();
9365   for (const User *U : A->users())
9366     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9367       return false;  // Use not in entry block.
9368 
9369   return true;
9370 }
9371 
9372 using ArgCopyElisionMapTy =
9373     DenseMap<const Argument *,
9374              std::pair<const AllocaInst *, const StoreInst *>>;
9375 
9376 /// Scan the entry block of the function in FuncInfo for arguments that look
9377 /// like copies into a local alloca. Record any copied arguments in
9378 /// ArgCopyElisionCandidates.
9379 static void
9380 findArgumentCopyElisionCandidates(const DataLayout &DL,
9381                                   FunctionLoweringInfo *FuncInfo,
9382                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9383   // Record the state of every static alloca used in the entry block. Argument
9384   // allocas are all used in the entry block, so we need approximately as many
9385   // entries as we have arguments.
9386   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9387   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9388   unsigned NumArgs = FuncInfo->Fn->arg_size();
9389   StaticAllocas.reserve(NumArgs * 2);
9390 
9391   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9392     if (!V)
9393       return nullptr;
9394     V = V->stripPointerCasts();
9395     const auto *AI = dyn_cast<AllocaInst>(V);
9396     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9397       return nullptr;
9398     auto Iter = StaticAllocas.insert({AI, Unknown});
9399     return &Iter.first->second;
9400   };
9401 
9402   // Look for stores of arguments to static allocas. Look through bitcasts and
9403   // GEPs to handle type coercions, as long as the alloca is fully initialized
9404   // by the store. Any non-store use of an alloca escapes it and any subsequent
9405   // unanalyzed store might write it.
9406   // FIXME: Handle structs initialized with multiple stores.
9407   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9408     // Look for stores, and handle non-store uses conservatively.
9409     const auto *SI = dyn_cast<StoreInst>(&I);
9410     if (!SI) {
9411       // We will look through cast uses, so ignore them completely.
9412       if (I.isCast())
9413         continue;
9414       // Ignore debug info intrinsics, they don't escape or store to allocas.
9415       if (isa<DbgInfoIntrinsic>(I))
9416         continue;
9417       // This is an unknown instruction. Assume it escapes or writes to all
9418       // static alloca operands.
9419       for (const Use &U : I.operands()) {
9420         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9421           *Info = StaticAllocaInfo::Clobbered;
9422       }
9423       continue;
9424     }
9425 
9426     // If the stored value is a static alloca, mark it as escaped.
9427     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9428       *Info = StaticAllocaInfo::Clobbered;
9429 
9430     // Check if the destination is a static alloca.
9431     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9432     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9433     if (!Info)
9434       continue;
9435     const AllocaInst *AI = cast<AllocaInst>(Dst);
9436 
9437     // Skip allocas that have been initialized or clobbered.
9438     if (*Info != StaticAllocaInfo::Unknown)
9439       continue;
9440 
9441     // Check if the stored value is an argument, and that this store fully
9442     // initializes the alloca. Don't elide copies from the same argument twice.
9443     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9444     const auto *Arg = dyn_cast<Argument>(Val);
9445     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9446         Arg->getType()->isEmptyTy() ||
9447         DL.getTypeStoreSize(Arg->getType()) !=
9448             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9449         ArgCopyElisionCandidates.count(Arg)) {
9450       *Info = StaticAllocaInfo::Clobbered;
9451       continue;
9452     }
9453 
9454     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9455                       << '\n');
9456 
9457     // Mark this alloca and store for argument copy elision.
9458     *Info = StaticAllocaInfo::Elidable;
9459     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9460 
9461     // Stop scanning if we've seen all arguments. This will happen early in -O0
9462     // builds, which is useful, because -O0 builds have large entry blocks and
9463     // many allocas.
9464     if (ArgCopyElisionCandidates.size() == NumArgs)
9465       break;
9466   }
9467 }
9468 
9469 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9470 /// ArgVal is a load from a suitable fixed stack object.
9471 static void tryToElideArgumentCopy(
9472     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9473     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9474     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9475     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9476     SDValue ArgVal, bool &ArgHasUses) {
9477   // Check if this is a load from a fixed stack object.
9478   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9479   if (!LNode)
9480     return;
9481   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9482   if (!FINode)
9483     return;
9484 
9485   // Check that the fixed stack object is the right size and alignment.
9486   // Look at the alignment that the user wrote on the alloca instead of looking
9487   // at the stack object.
9488   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9489   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9490   const AllocaInst *AI = ArgCopyIter->second.first;
9491   int FixedIndex = FINode->getIndex();
9492   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9493   int OldIndex = AllocaIndex;
9494   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9495   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9496     LLVM_DEBUG(
9497         dbgs() << "  argument copy elision failed due to bad fixed stack "
9498                   "object size\n");
9499     return;
9500   }
9501   Align RequiredAlignment = AI->getAlign().getValueOr(
9502       FuncInfo.MF->getDataLayout().getABITypeAlign(AI->getAllocatedType()));
9503   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9504     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9505                          "greater than stack argument alignment ("
9506                       << DebugStr(RequiredAlignment) << " vs "
9507                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9508     return;
9509   }
9510 
9511   // Perform the elision. Delete the old stack object and replace its only use
9512   // in the variable info map. Mark the stack object as mutable.
9513   LLVM_DEBUG({
9514     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9515            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9516            << '\n';
9517   });
9518   MFI.RemoveStackObject(OldIndex);
9519   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9520   AllocaIndex = FixedIndex;
9521   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9522   Chains.push_back(ArgVal.getValue(1));
9523 
9524   // Avoid emitting code for the store implementing the copy.
9525   const StoreInst *SI = ArgCopyIter->second.second;
9526   ElidedArgCopyInstrs.insert(SI);
9527 
9528   // Check for uses of the argument again so that we can avoid exporting ArgVal
9529   // if it is't used by anything other than the store.
9530   for (const Value *U : Arg.users()) {
9531     if (U != SI) {
9532       ArgHasUses = true;
9533       break;
9534     }
9535   }
9536 }
9537 
9538 void SelectionDAGISel::LowerArguments(const Function &F) {
9539   SelectionDAG &DAG = SDB->DAG;
9540   SDLoc dl = SDB->getCurSDLoc();
9541   const DataLayout &DL = DAG.getDataLayout();
9542   SmallVector<ISD::InputArg, 16> Ins;
9543 
9544   if (!FuncInfo->CanLowerReturn) {
9545     // Put in an sret pointer parameter before all the other parameters.
9546     SmallVector<EVT, 1> ValueVTs;
9547     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9548                     F.getReturnType()->getPointerTo(
9549                         DAG.getDataLayout().getAllocaAddrSpace()),
9550                     ValueVTs);
9551 
9552     // NOTE: Assuming that a pointer will never break down to more than one VT
9553     // or one register.
9554     ISD::ArgFlagsTy Flags;
9555     Flags.setSRet();
9556     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9557     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9558                          ISD::InputArg::NoArgIndex, 0);
9559     Ins.push_back(RetArg);
9560   }
9561 
9562   // Look for stores of arguments to static allocas. Mark such arguments with a
9563   // flag to ask the target to give us the memory location of that argument if
9564   // available.
9565   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9566   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9567                                     ArgCopyElisionCandidates);
9568 
9569   // Set up the incoming argument description vector.
9570   for (const Argument &Arg : F.args()) {
9571     unsigned ArgNo = Arg.getArgNo();
9572     SmallVector<EVT, 4> ValueVTs;
9573     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9574     bool isArgValueUsed = !Arg.use_empty();
9575     unsigned PartBase = 0;
9576     Type *FinalType = Arg.getType();
9577     if (Arg.hasAttribute(Attribute::ByVal))
9578       FinalType = Arg.getParamByValType();
9579     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9580         FinalType, F.getCallingConv(), F.isVarArg());
9581     for (unsigned Value = 0, NumValues = ValueVTs.size();
9582          Value != NumValues; ++Value) {
9583       EVT VT = ValueVTs[Value];
9584       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9585       ISD::ArgFlagsTy Flags;
9586 
9587       // Certain targets (such as MIPS), may have a different ABI alignment
9588       // for a type depending on the context. Give the target a chance to
9589       // specify the alignment it wants.
9590       const Align OriginalAlignment(
9591           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9592 
9593       if (Arg.getType()->isPointerTy()) {
9594         Flags.setPointer();
9595         Flags.setPointerAddrSpace(
9596             cast<PointerType>(Arg.getType())->getAddressSpace());
9597       }
9598       if (Arg.hasAttribute(Attribute::ZExt))
9599         Flags.setZExt();
9600       if (Arg.hasAttribute(Attribute::SExt))
9601         Flags.setSExt();
9602       if (Arg.hasAttribute(Attribute::InReg)) {
9603         // If we are using vectorcall calling convention, a structure that is
9604         // passed InReg - is surely an HVA
9605         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9606             isa<StructType>(Arg.getType())) {
9607           // The first value of a structure is marked
9608           if (0 == Value)
9609             Flags.setHvaStart();
9610           Flags.setHva();
9611         }
9612         // Set InReg Flag
9613         Flags.setInReg();
9614       }
9615       if (Arg.hasAttribute(Attribute::StructRet))
9616         Flags.setSRet();
9617       if (Arg.hasAttribute(Attribute::SwiftSelf))
9618         Flags.setSwiftSelf();
9619       if (Arg.hasAttribute(Attribute::SwiftError))
9620         Flags.setSwiftError();
9621       if (Arg.hasAttribute(Attribute::ByVal))
9622         Flags.setByVal();
9623       if (Arg.hasAttribute(Attribute::InAlloca)) {
9624         Flags.setInAlloca();
9625         // Set the byval flag for CCAssignFn callbacks that don't know about
9626         // inalloca.  This way we can know how many bytes we should've allocated
9627         // and how many bytes a callee cleanup function will pop.  If we port
9628         // inalloca to more targets, we'll have to add custom inalloca handling
9629         // in the various CC lowering callbacks.
9630         Flags.setByVal();
9631       }
9632       if (F.getCallingConv() == CallingConv::X86_INTR) {
9633         // IA Interrupt passes frame (1st parameter) by value in the stack.
9634         if (ArgNo == 0)
9635           Flags.setByVal();
9636       }
9637       if (Flags.isByVal() || Flags.isInAlloca()) {
9638         Type *ElementTy = Arg.getParamByValType();
9639 
9640         // For ByVal, size and alignment should be passed from FE.  BE will
9641         // guess if this info is not there but there are cases it cannot get
9642         // right.
9643         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9644         Flags.setByValSize(FrameSize);
9645 
9646         unsigned FrameAlign;
9647         if (Arg.getParamAlignment())
9648           FrameAlign = Arg.getParamAlignment();
9649         else
9650           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9651         Flags.setByValAlign(Align(FrameAlign));
9652       }
9653       if (Arg.hasAttribute(Attribute::Nest))
9654         Flags.setNest();
9655       if (NeedsRegBlock)
9656         Flags.setInConsecutiveRegs();
9657       Flags.setOrigAlign(OriginalAlignment);
9658       if (ArgCopyElisionCandidates.count(&Arg))
9659         Flags.setCopyElisionCandidate();
9660       if (Arg.hasAttribute(Attribute::Returned))
9661         Flags.setReturned();
9662 
9663       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9664           *CurDAG->getContext(), F.getCallingConv(), VT);
9665       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9666           *CurDAG->getContext(), F.getCallingConv(), VT);
9667       for (unsigned i = 0; i != NumRegs; ++i) {
9668         // For scalable vectors, use the minimum size; individual targets
9669         // are responsible for handling scalable vector arguments and
9670         // return values.
9671         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9672                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9673         if (NumRegs > 1 && i == 0)
9674           MyFlags.Flags.setSplit();
9675         // if it isn't first piece, alignment must be 1
9676         else if (i > 0) {
9677           MyFlags.Flags.setOrigAlign(Align(1));
9678           if (i == NumRegs - 1)
9679             MyFlags.Flags.setSplitEnd();
9680         }
9681         Ins.push_back(MyFlags);
9682       }
9683       if (NeedsRegBlock && Value == NumValues - 1)
9684         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9685       PartBase += VT.getStoreSize().getKnownMinSize();
9686     }
9687   }
9688 
9689   // Call the target to set up the argument values.
9690   SmallVector<SDValue, 8> InVals;
9691   SDValue NewRoot = TLI->LowerFormalArguments(
9692       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9693 
9694   // Verify that the target's LowerFormalArguments behaved as expected.
9695   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9696          "LowerFormalArguments didn't return a valid chain!");
9697   assert(InVals.size() == Ins.size() &&
9698          "LowerFormalArguments didn't emit the correct number of values!");
9699   LLVM_DEBUG({
9700     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9701       assert(InVals[i].getNode() &&
9702              "LowerFormalArguments emitted a null value!");
9703       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9704              "LowerFormalArguments emitted a value with the wrong type!");
9705     }
9706   });
9707 
9708   // Update the DAG with the new chain value resulting from argument lowering.
9709   DAG.setRoot(NewRoot);
9710 
9711   // Set up the argument values.
9712   unsigned i = 0;
9713   if (!FuncInfo->CanLowerReturn) {
9714     // Create a virtual register for the sret pointer, and put in a copy
9715     // from the sret argument into it.
9716     SmallVector<EVT, 1> ValueVTs;
9717     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9718                     F.getReturnType()->getPointerTo(
9719                         DAG.getDataLayout().getAllocaAddrSpace()),
9720                     ValueVTs);
9721     MVT VT = ValueVTs[0].getSimpleVT();
9722     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9723     Optional<ISD::NodeType> AssertOp = None;
9724     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9725                                         nullptr, F.getCallingConv(), AssertOp);
9726 
9727     MachineFunction& MF = SDB->DAG.getMachineFunction();
9728     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9729     Register SRetReg =
9730         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9731     FuncInfo->DemoteRegister = SRetReg;
9732     NewRoot =
9733         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9734     DAG.setRoot(NewRoot);
9735 
9736     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9737     ++i;
9738   }
9739 
9740   SmallVector<SDValue, 4> Chains;
9741   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9742   for (const Argument &Arg : F.args()) {
9743     SmallVector<SDValue, 4> ArgValues;
9744     SmallVector<EVT, 4> ValueVTs;
9745     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9746     unsigned NumValues = ValueVTs.size();
9747     if (NumValues == 0)
9748       continue;
9749 
9750     bool ArgHasUses = !Arg.use_empty();
9751 
9752     // Elide the copying store if the target loaded this argument from a
9753     // suitable fixed stack object.
9754     if (Ins[i].Flags.isCopyElisionCandidate()) {
9755       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9756                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9757                              InVals[i], ArgHasUses);
9758     }
9759 
9760     // If this argument is unused then remember its value. It is used to generate
9761     // debugging information.
9762     bool isSwiftErrorArg =
9763         TLI->supportSwiftError() &&
9764         Arg.hasAttribute(Attribute::SwiftError);
9765     if (!ArgHasUses && !isSwiftErrorArg) {
9766       SDB->setUnusedArgValue(&Arg, InVals[i]);
9767 
9768       // Also remember any frame index for use in FastISel.
9769       if (FrameIndexSDNode *FI =
9770           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9771         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9772     }
9773 
9774     for (unsigned Val = 0; Val != NumValues; ++Val) {
9775       EVT VT = ValueVTs[Val];
9776       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9777                                                       F.getCallingConv(), VT);
9778       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9779           *CurDAG->getContext(), F.getCallingConv(), VT);
9780 
9781       // Even an apparent 'unused' swifterror argument needs to be returned. So
9782       // we do generate a copy for it that can be used on return from the
9783       // function.
9784       if (ArgHasUses || isSwiftErrorArg) {
9785         Optional<ISD::NodeType> AssertOp;
9786         if (Arg.hasAttribute(Attribute::SExt))
9787           AssertOp = ISD::AssertSext;
9788         else if (Arg.hasAttribute(Attribute::ZExt))
9789           AssertOp = ISD::AssertZext;
9790 
9791         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9792                                              PartVT, VT, nullptr,
9793                                              F.getCallingConv(), AssertOp));
9794       }
9795 
9796       i += NumParts;
9797     }
9798 
9799     // We don't need to do anything else for unused arguments.
9800     if (ArgValues.empty())
9801       continue;
9802 
9803     // Note down frame index.
9804     if (FrameIndexSDNode *FI =
9805         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9806       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9807 
9808     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9809                                      SDB->getCurSDLoc());
9810 
9811     SDB->setValue(&Arg, Res);
9812     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9813       // We want to associate the argument with the frame index, among
9814       // involved operands, that correspond to the lowest address. The
9815       // getCopyFromParts function, called earlier, is swapping the order of
9816       // the operands to BUILD_PAIR depending on endianness. The result of
9817       // that swapping is that the least significant bits of the argument will
9818       // be in the first operand of the BUILD_PAIR node, and the most
9819       // significant bits will be in the second operand.
9820       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9821       if (LoadSDNode *LNode =
9822           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9823         if (FrameIndexSDNode *FI =
9824             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9825           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9826     }
9827 
9828     // Analyses past this point are naive and don't expect an assertion.
9829     if (Res.getOpcode() == ISD::AssertZext)
9830       Res = Res.getOperand(0);
9831 
9832     // Update the SwiftErrorVRegDefMap.
9833     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9834       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9835       if (Register::isVirtualRegister(Reg))
9836         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9837                                    Reg);
9838     }
9839 
9840     // If this argument is live outside of the entry block, insert a copy from
9841     // wherever we got it to the vreg that other BB's will reference it as.
9842     if (Res.getOpcode() == ISD::CopyFromReg) {
9843       // If we can, though, try to skip creating an unnecessary vreg.
9844       // FIXME: This isn't very clean... it would be nice to make this more
9845       // general.
9846       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9847       if (Register::isVirtualRegister(Reg)) {
9848         FuncInfo->ValueMap[&Arg] = Reg;
9849         continue;
9850       }
9851     }
9852     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9853       FuncInfo->InitializeRegForValue(&Arg);
9854       SDB->CopyToExportRegsIfNeeded(&Arg);
9855     }
9856   }
9857 
9858   if (!Chains.empty()) {
9859     Chains.push_back(NewRoot);
9860     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9861   }
9862 
9863   DAG.setRoot(NewRoot);
9864 
9865   assert(i == InVals.size() && "Argument register count mismatch!");
9866 
9867   // If any argument copy elisions occurred and we have debug info, update the
9868   // stale frame indices used in the dbg.declare variable info table.
9869   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9870   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9871     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9872       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9873       if (I != ArgCopyElisionFrameIndexMap.end())
9874         VI.Slot = I->second;
9875     }
9876   }
9877 
9878   // Finally, if the target has anything special to do, allow it to do so.
9879   emitFunctionEntryCode();
9880 }
9881 
9882 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9883 /// ensure constants are generated when needed.  Remember the virtual registers
9884 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9885 /// directly add them, because expansion might result in multiple MBB's for one
9886 /// BB.  As such, the start of the BB might correspond to a different MBB than
9887 /// the end.
9888 void
9889 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9890   const Instruction *TI = LLVMBB->getTerminator();
9891 
9892   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9893 
9894   // Check PHI nodes in successors that expect a value to be available from this
9895   // block.
9896   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9897     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9898     if (!isa<PHINode>(SuccBB->begin())) continue;
9899     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9900 
9901     // If this terminator has multiple identical successors (common for
9902     // switches), only handle each succ once.
9903     if (!SuccsHandled.insert(SuccMBB).second)
9904       continue;
9905 
9906     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9907 
9908     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9909     // nodes and Machine PHI nodes, but the incoming operands have not been
9910     // emitted yet.
9911     for (const PHINode &PN : SuccBB->phis()) {
9912       // Ignore dead phi's.
9913       if (PN.use_empty())
9914         continue;
9915 
9916       // Skip empty types
9917       if (PN.getType()->isEmptyTy())
9918         continue;
9919 
9920       unsigned Reg;
9921       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9922 
9923       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9924         unsigned &RegOut = ConstantsOut[C];
9925         if (RegOut == 0) {
9926           RegOut = FuncInfo.CreateRegs(C);
9927           CopyValueToVirtualRegister(C, RegOut);
9928         }
9929         Reg = RegOut;
9930       } else {
9931         DenseMap<const Value *, Register>::iterator I =
9932           FuncInfo.ValueMap.find(PHIOp);
9933         if (I != FuncInfo.ValueMap.end())
9934           Reg = I->second;
9935         else {
9936           assert(isa<AllocaInst>(PHIOp) &&
9937                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9938                  "Didn't codegen value into a register!??");
9939           Reg = FuncInfo.CreateRegs(PHIOp);
9940           CopyValueToVirtualRegister(PHIOp, Reg);
9941         }
9942       }
9943 
9944       // Remember that this register needs to added to the machine PHI node as
9945       // the input for this MBB.
9946       SmallVector<EVT, 4> ValueVTs;
9947       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9948       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9949       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9950         EVT VT = ValueVTs[vti];
9951         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9952         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9953           FuncInfo.PHINodesToUpdate.push_back(
9954               std::make_pair(&*MBBI++, Reg + i));
9955         Reg += NumRegisters;
9956       }
9957     }
9958   }
9959 
9960   ConstantsOut.clear();
9961 }
9962 
9963 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9964 /// is 0.
9965 MachineBasicBlock *
9966 SelectionDAGBuilder::StackProtectorDescriptor::
9967 AddSuccessorMBB(const BasicBlock *BB,
9968                 MachineBasicBlock *ParentMBB,
9969                 bool IsLikely,
9970                 MachineBasicBlock *SuccMBB) {
9971   // If SuccBB has not been created yet, create it.
9972   if (!SuccMBB) {
9973     MachineFunction *MF = ParentMBB->getParent();
9974     MachineFunction::iterator BBI(ParentMBB);
9975     SuccMBB = MF->CreateMachineBasicBlock(BB);
9976     MF->insert(++BBI, SuccMBB);
9977   }
9978   // Add it as a successor of ParentMBB.
9979   ParentMBB->addSuccessor(
9980       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9981   return SuccMBB;
9982 }
9983 
9984 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9985   MachineFunction::iterator I(MBB);
9986   if (++I == FuncInfo.MF->end())
9987     return nullptr;
9988   return &*I;
9989 }
9990 
9991 /// During lowering new call nodes can be created (such as memset, etc.).
9992 /// Those will become new roots of the current DAG, but complications arise
9993 /// when they are tail calls. In such cases, the call lowering will update
9994 /// the root, but the builder still needs to know that a tail call has been
9995 /// lowered in order to avoid generating an additional return.
9996 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9997   // If the node is null, we do have a tail call.
9998   if (MaybeTC.getNode() != nullptr)
9999     DAG.setRoot(MaybeTC);
10000   else
10001     HasTailCall = true;
10002 }
10003 
10004 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10005                                         MachineBasicBlock *SwitchMBB,
10006                                         MachineBasicBlock *DefaultMBB) {
10007   MachineFunction *CurMF = FuncInfo.MF;
10008   MachineBasicBlock *NextMBB = nullptr;
10009   MachineFunction::iterator BBI(W.MBB);
10010   if (++BBI != FuncInfo.MF->end())
10011     NextMBB = &*BBI;
10012 
10013   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10014 
10015   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10016 
10017   if (Size == 2 && W.MBB == SwitchMBB) {
10018     // If any two of the cases has the same destination, and if one value
10019     // is the same as the other, but has one bit unset that the other has set,
10020     // use bit manipulation to do two compares at once.  For example:
10021     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10022     // TODO: This could be extended to merge any 2 cases in switches with 3
10023     // cases.
10024     // TODO: Handle cases where W.CaseBB != SwitchBB.
10025     CaseCluster &Small = *W.FirstCluster;
10026     CaseCluster &Big = *W.LastCluster;
10027 
10028     if (Small.Low == Small.High && Big.Low == Big.High &&
10029         Small.MBB == Big.MBB) {
10030       const APInt &SmallValue = Small.Low->getValue();
10031       const APInt &BigValue = Big.Low->getValue();
10032 
10033       // Check that there is only one bit different.
10034       APInt CommonBit = BigValue ^ SmallValue;
10035       if (CommonBit.isPowerOf2()) {
10036         SDValue CondLHS = getValue(Cond);
10037         EVT VT = CondLHS.getValueType();
10038         SDLoc DL = getCurSDLoc();
10039 
10040         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10041                                  DAG.getConstant(CommonBit, DL, VT));
10042         SDValue Cond = DAG.getSetCC(
10043             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10044             ISD::SETEQ);
10045 
10046         // Update successor info.
10047         // Both Small and Big will jump to Small.BB, so we sum up the
10048         // probabilities.
10049         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10050         if (BPI)
10051           addSuccessorWithProb(
10052               SwitchMBB, DefaultMBB,
10053               // The default destination is the first successor in IR.
10054               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10055         else
10056           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10057 
10058         // Insert the true branch.
10059         SDValue BrCond =
10060             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10061                         DAG.getBasicBlock(Small.MBB));
10062         // Insert the false branch.
10063         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10064                              DAG.getBasicBlock(DefaultMBB));
10065 
10066         DAG.setRoot(BrCond);
10067         return;
10068       }
10069     }
10070   }
10071 
10072   if (TM.getOptLevel() != CodeGenOpt::None) {
10073     // Here, we order cases by probability so the most likely case will be
10074     // checked first. However, two clusters can have the same probability in
10075     // which case their relative ordering is non-deterministic. So we use Low
10076     // as a tie-breaker as clusters are guaranteed to never overlap.
10077     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10078                [](const CaseCluster &a, const CaseCluster &b) {
10079       return a.Prob != b.Prob ?
10080              a.Prob > b.Prob :
10081              a.Low->getValue().slt(b.Low->getValue());
10082     });
10083 
10084     // Rearrange the case blocks so that the last one falls through if possible
10085     // without changing the order of probabilities.
10086     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10087       --I;
10088       if (I->Prob > W.LastCluster->Prob)
10089         break;
10090       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10091         std::swap(*I, *W.LastCluster);
10092         break;
10093       }
10094     }
10095   }
10096 
10097   // Compute total probability.
10098   BranchProbability DefaultProb = W.DefaultProb;
10099   BranchProbability UnhandledProbs = DefaultProb;
10100   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10101     UnhandledProbs += I->Prob;
10102 
10103   MachineBasicBlock *CurMBB = W.MBB;
10104   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10105     bool FallthroughUnreachable = false;
10106     MachineBasicBlock *Fallthrough;
10107     if (I == W.LastCluster) {
10108       // For the last cluster, fall through to the default destination.
10109       Fallthrough = DefaultMBB;
10110       FallthroughUnreachable = isa<UnreachableInst>(
10111           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10112     } else {
10113       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10114       CurMF->insert(BBI, Fallthrough);
10115       // Put Cond in a virtual register to make it available from the new blocks.
10116       ExportFromCurrentBlock(Cond);
10117     }
10118     UnhandledProbs -= I->Prob;
10119 
10120     switch (I->Kind) {
10121       case CC_JumpTable: {
10122         // FIXME: Optimize away range check based on pivot comparisons.
10123         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10124         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10125 
10126         // The jump block hasn't been inserted yet; insert it here.
10127         MachineBasicBlock *JumpMBB = JT->MBB;
10128         CurMF->insert(BBI, JumpMBB);
10129 
10130         auto JumpProb = I->Prob;
10131         auto FallthroughProb = UnhandledProbs;
10132 
10133         // If the default statement is a target of the jump table, we evenly
10134         // distribute the default probability to successors of CurMBB. Also
10135         // update the probability on the edge from JumpMBB to Fallthrough.
10136         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10137                                               SE = JumpMBB->succ_end();
10138              SI != SE; ++SI) {
10139           if (*SI == DefaultMBB) {
10140             JumpProb += DefaultProb / 2;
10141             FallthroughProb -= DefaultProb / 2;
10142             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10143             JumpMBB->normalizeSuccProbs();
10144             break;
10145           }
10146         }
10147 
10148         if (FallthroughUnreachable) {
10149           // Skip the range check if the fallthrough block is unreachable.
10150           JTH->OmitRangeCheck = true;
10151         }
10152 
10153         if (!JTH->OmitRangeCheck)
10154           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10155         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10156         CurMBB->normalizeSuccProbs();
10157 
10158         // The jump table header will be inserted in our current block, do the
10159         // range check, and fall through to our fallthrough block.
10160         JTH->HeaderBB = CurMBB;
10161         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10162 
10163         // If we're in the right place, emit the jump table header right now.
10164         if (CurMBB == SwitchMBB) {
10165           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10166           JTH->Emitted = true;
10167         }
10168         break;
10169       }
10170       case CC_BitTests: {
10171         // FIXME: Optimize away range check based on pivot comparisons.
10172         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10173 
10174         // The bit test blocks haven't been inserted yet; insert them here.
10175         for (BitTestCase &BTC : BTB->Cases)
10176           CurMF->insert(BBI, BTC.ThisBB);
10177 
10178         // Fill in fields of the BitTestBlock.
10179         BTB->Parent = CurMBB;
10180         BTB->Default = Fallthrough;
10181 
10182         BTB->DefaultProb = UnhandledProbs;
10183         // If the cases in bit test don't form a contiguous range, we evenly
10184         // distribute the probability on the edge to Fallthrough to two
10185         // successors of CurMBB.
10186         if (!BTB->ContiguousRange) {
10187           BTB->Prob += DefaultProb / 2;
10188           BTB->DefaultProb -= DefaultProb / 2;
10189         }
10190 
10191         if (FallthroughUnreachable) {
10192           // Skip the range check if the fallthrough block is unreachable.
10193           BTB->OmitRangeCheck = true;
10194         }
10195 
10196         // If we're in the right place, emit the bit test header right now.
10197         if (CurMBB == SwitchMBB) {
10198           visitBitTestHeader(*BTB, SwitchMBB);
10199           BTB->Emitted = true;
10200         }
10201         break;
10202       }
10203       case CC_Range: {
10204         const Value *RHS, *LHS, *MHS;
10205         ISD::CondCode CC;
10206         if (I->Low == I->High) {
10207           // Check Cond == I->Low.
10208           CC = ISD::SETEQ;
10209           LHS = Cond;
10210           RHS=I->Low;
10211           MHS = nullptr;
10212         } else {
10213           // Check I->Low <= Cond <= I->High.
10214           CC = ISD::SETLE;
10215           LHS = I->Low;
10216           MHS = Cond;
10217           RHS = I->High;
10218         }
10219 
10220         // If Fallthrough is unreachable, fold away the comparison.
10221         if (FallthroughUnreachable)
10222           CC = ISD::SETTRUE;
10223 
10224         // The false probability is the sum of all unhandled cases.
10225         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10226                      getCurSDLoc(), I->Prob, UnhandledProbs);
10227 
10228         if (CurMBB == SwitchMBB)
10229           visitSwitchCase(CB, SwitchMBB);
10230         else
10231           SL->SwitchCases.push_back(CB);
10232 
10233         break;
10234       }
10235     }
10236     CurMBB = Fallthrough;
10237   }
10238 }
10239 
10240 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10241                                               CaseClusterIt First,
10242                                               CaseClusterIt Last) {
10243   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10244     if (X.Prob != CC.Prob)
10245       return X.Prob > CC.Prob;
10246 
10247     // Ties are broken by comparing the case value.
10248     return X.Low->getValue().slt(CC.Low->getValue());
10249   });
10250 }
10251 
10252 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10253                                         const SwitchWorkListItem &W,
10254                                         Value *Cond,
10255                                         MachineBasicBlock *SwitchMBB) {
10256   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10257          "Clusters not sorted?");
10258 
10259   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10260 
10261   // Balance the tree based on branch probabilities to create a near-optimal (in
10262   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10263   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10264   CaseClusterIt LastLeft = W.FirstCluster;
10265   CaseClusterIt FirstRight = W.LastCluster;
10266   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10267   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10268 
10269   // Move LastLeft and FirstRight towards each other from opposite directions to
10270   // find a partitioning of the clusters which balances the probability on both
10271   // sides. If LeftProb and RightProb are equal, alternate which side is
10272   // taken to ensure 0-probability nodes are distributed evenly.
10273   unsigned I = 0;
10274   while (LastLeft + 1 < FirstRight) {
10275     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10276       LeftProb += (++LastLeft)->Prob;
10277     else
10278       RightProb += (--FirstRight)->Prob;
10279     I++;
10280   }
10281 
10282   while (true) {
10283     // Our binary search tree differs from a typical BST in that ours can have up
10284     // to three values in each leaf. The pivot selection above doesn't take that
10285     // into account, which means the tree might require more nodes and be less
10286     // efficient. We compensate for this here.
10287 
10288     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10289     unsigned NumRight = W.LastCluster - FirstRight + 1;
10290 
10291     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10292       // If one side has less than 3 clusters, and the other has more than 3,
10293       // consider taking a cluster from the other side.
10294 
10295       if (NumLeft < NumRight) {
10296         // Consider moving the first cluster on the right to the left side.
10297         CaseCluster &CC = *FirstRight;
10298         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10299         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10300         if (LeftSideRank <= RightSideRank) {
10301           // Moving the cluster to the left does not demote it.
10302           ++LastLeft;
10303           ++FirstRight;
10304           continue;
10305         }
10306       } else {
10307         assert(NumRight < NumLeft);
10308         // Consider moving the last element on the left to the right side.
10309         CaseCluster &CC = *LastLeft;
10310         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10311         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10312         if (RightSideRank <= LeftSideRank) {
10313           // Moving the cluster to the right does not demot it.
10314           --LastLeft;
10315           --FirstRight;
10316           continue;
10317         }
10318       }
10319     }
10320     break;
10321   }
10322 
10323   assert(LastLeft + 1 == FirstRight);
10324   assert(LastLeft >= W.FirstCluster);
10325   assert(FirstRight <= W.LastCluster);
10326 
10327   // Use the first element on the right as pivot since we will make less-than
10328   // comparisons against it.
10329   CaseClusterIt PivotCluster = FirstRight;
10330   assert(PivotCluster > W.FirstCluster);
10331   assert(PivotCluster <= W.LastCluster);
10332 
10333   CaseClusterIt FirstLeft = W.FirstCluster;
10334   CaseClusterIt LastRight = W.LastCluster;
10335 
10336   const ConstantInt *Pivot = PivotCluster->Low;
10337 
10338   // New blocks will be inserted immediately after the current one.
10339   MachineFunction::iterator BBI(W.MBB);
10340   ++BBI;
10341 
10342   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10343   // we can branch to its destination directly if it's squeezed exactly in
10344   // between the known lower bound and Pivot - 1.
10345   MachineBasicBlock *LeftMBB;
10346   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10347       FirstLeft->Low == W.GE &&
10348       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10349     LeftMBB = FirstLeft->MBB;
10350   } else {
10351     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10352     FuncInfo.MF->insert(BBI, LeftMBB);
10353     WorkList.push_back(
10354         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10355     // Put Cond in a virtual register to make it available from the new blocks.
10356     ExportFromCurrentBlock(Cond);
10357   }
10358 
10359   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10360   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10361   // directly if RHS.High equals the current upper bound.
10362   MachineBasicBlock *RightMBB;
10363   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10364       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10365     RightMBB = FirstRight->MBB;
10366   } else {
10367     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10368     FuncInfo.MF->insert(BBI, RightMBB);
10369     WorkList.push_back(
10370         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10371     // Put Cond in a virtual register to make it available from the new blocks.
10372     ExportFromCurrentBlock(Cond);
10373   }
10374 
10375   // Create the CaseBlock record that will be used to lower the branch.
10376   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10377                getCurSDLoc(), LeftProb, RightProb);
10378 
10379   if (W.MBB == SwitchMBB)
10380     visitSwitchCase(CB, SwitchMBB);
10381   else
10382     SL->SwitchCases.push_back(CB);
10383 }
10384 
10385 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10386 // from the swith statement.
10387 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10388                                             BranchProbability PeeledCaseProb) {
10389   if (PeeledCaseProb == BranchProbability::getOne())
10390     return BranchProbability::getZero();
10391   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10392 
10393   uint32_t Numerator = CaseProb.getNumerator();
10394   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10395   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10396 }
10397 
10398 // Try to peel the top probability case if it exceeds the threshold.
10399 // Return current MachineBasicBlock for the switch statement if the peeling
10400 // does not occur.
10401 // If the peeling is performed, return the newly created MachineBasicBlock
10402 // for the peeled switch statement. Also update Clusters to remove the peeled
10403 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10404 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10405     const SwitchInst &SI, CaseClusterVector &Clusters,
10406     BranchProbability &PeeledCaseProb) {
10407   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10408   // Don't perform if there is only one cluster or optimizing for size.
10409   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10410       TM.getOptLevel() == CodeGenOpt::None ||
10411       SwitchMBB->getParent()->getFunction().hasMinSize())
10412     return SwitchMBB;
10413 
10414   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10415   unsigned PeeledCaseIndex = 0;
10416   bool SwitchPeeled = false;
10417   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10418     CaseCluster &CC = Clusters[Index];
10419     if (CC.Prob < TopCaseProb)
10420       continue;
10421     TopCaseProb = CC.Prob;
10422     PeeledCaseIndex = Index;
10423     SwitchPeeled = true;
10424   }
10425   if (!SwitchPeeled)
10426     return SwitchMBB;
10427 
10428   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10429                     << TopCaseProb << "\n");
10430 
10431   // Record the MBB for the peeled switch statement.
10432   MachineFunction::iterator BBI(SwitchMBB);
10433   ++BBI;
10434   MachineBasicBlock *PeeledSwitchMBB =
10435       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10436   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10437 
10438   ExportFromCurrentBlock(SI.getCondition());
10439   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10440   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10441                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10442   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10443 
10444   Clusters.erase(PeeledCaseIt);
10445   for (CaseCluster &CC : Clusters) {
10446     LLVM_DEBUG(
10447         dbgs() << "Scale the probablity for one cluster, before scaling: "
10448                << CC.Prob << "\n");
10449     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10450     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10451   }
10452   PeeledCaseProb = TopCaseProb;
10453   return PeeledSwitchMBB;
10454 }
10455 
10456 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10457   // Extract cases from the switch.
10458   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10459   CaseClusterVector Clusters;
10460   Clusters.reserve(SI.getNumCases());
10461   for (auto I : SI.cases()) {
10462     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10463     const ConstantInt *CaseVal = I.getCaseValue();
10464     BranchProbability Prob =
10465         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10466             : BranchProbability(1, SI.getNumCases() + 1);
10467     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10468   }
10469 
10470   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10471 
10472   // Cluster adjacent cases with the same destination. We do this at all
10473   // optimization levels because it's cheap to do and will make codegen faster
10474   // if there are many clusters.
10475   sortAndRangeify(Clusters);
10476 
10477   // The branch probablity of the peeled case.
10478   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10479   MachineBasicBlock *PeeledSwitchMBB =
10480       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10481 
10482   // If there is only the default destination, jump there directly.
10483   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10484   if (Clusters.empty()) {
10485     assert(PeeledSwitchMBB == SwitchMBB);
10486     SwitchMBB->addSuccessor(DefaultMBB);
10487     if (DefaultMBB != NextBlock(SwitchMBB)) {
10488       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10489                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10490     }
10491     return;
10492   }
10493 
10494   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10495   SL->findBitTestClusters(Clusters, &SI);
10496 
10497   LLVM_DEBUG({
10498     dbgs() << "Case clusters: ";
10499     for (const CaseCluster &C : Clusters) {
10500       if (C.Kind == CC_JumpTable)
10501         dbgs() << "JT:";
10502       if (C.Kind == CC_BitTests)
10503         dbgs() << "BT:";
10504 
10505       C.Low->getValue().print(dbgs(), true);
10506       if (C.Low != C.High) {
10507         dbgs() << '-';
10508         C.High->getValue().print(dbgs(), true);
10509       }
10510       dbgs() << ' ';
10511     }
10512     dbgs() << '\n';
10513   });
10514 
10515   assert(!Clusters.empty());
10516   SwitchWorkList WorkList;
10517   CaseClusterIt First = Clusters.begin();
10518   CaseClusterIt Last = Clusters.end() - 1;
10519   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10520   // Scale the branchprobability for DefaultMBB if the peel occurs and
10521   // DefaultMBB is not replaced.
10522   if (PeeledCaseProb != BranchProbability::getZero() &&
10523       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10524     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10525   WorkList.push_back(
10526       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10527 
10528   while (!WorkList.empty()) {
10529     SwitchWorkListItem W = WorkList.back();
10530     WorkList.pop_back();
10531     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10532 
10533     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10534         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10535       // For optimized builds, lower large range as a balanced binary tree.
10536       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10537       continue;
10538     }
10539 
10540     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10541   }
10542 }
10543 
10544 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10545   SmallVector<EVT, 4> ValueVTs;
10546   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10547                   ValueVTs);
10548   unsigned NumValues = ValueVTs.size();
10549   if (NumValues == 0) return;
10550 
10551   SmallVector<SDValue, 4> Values(NumValues);
10552   SDValue Op = getValue(I.getOperand(0));
10553 
10554   for (unsigned i = 0; i != NumValues; ++i)
10555     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10556                             SDValue(Op.getNode(), Op.getResNo() + i));
10557 
10558   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10559                            DAG.getVTList(ValueVTs), Values));
10560 }
10561