xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 431df3d873e9ebde40a014883060ec8e976194dd)
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         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
442                          DAG.getVectorIdxConstant(0, DL));
443     }
444 
445     // Vector/Vector bitcast.
446     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
447       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
450       "Cannot handle this kind of promotion");
451     // Promoted vector extract
452     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 
454   }
455 
456   // Trivial bitcast if the types are the same size and the destination
457   // vector type is legal.
458   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
459       TLI.isTypeLegal(ValueVT))
460     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461 
462   if (ValueVT.getVectorNumElements() != 1) {
463      // Certain ABIs require that vectors are passed as integers. For vectors
464      // are the same size, this is an obvious bitcast.
465      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
466        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
467      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
468        // Bitcast Val back the original type and extract the corresponding
469        // vector we want.
470        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
471        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
472                                            ValueVT.getVectorElementType(), Elts);
473        Val = DAG.getBitcast(WiderVecType, Val);
474        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
475                           DAG.getVectorIdxConstant(0, DL));
476      }
477 
478      diagnosePossiblyInvalidConstraint(
479          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
480      return DAG.getUNDEF(ValueVT);
481   }
482 
483   // Handle cases such as i8 -> <1 x i1>
484   EVT ValueSVT = ValueVT.getVectorElementType();
485   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
486     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
487       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
488     else
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  Optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
506                            SDValue *Parts, unsigned NumParts, MVT PartVT,
507                            const Value *V,
508                            Optional<CallingConv::ID> CallConv = None,
509                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   EVT ValueVT = Val.getValueType();
511 
512   // Handle the vector case separately.
513   if (ValueVT.isVector())
514     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
515                                 CallConv);
516 
517   unsigned PartBits = PartVT.getSizeInBits();
518   unsigned OrigNumParts = NumParts;
519   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
520          "Copying to an illegal type!");
521 
522   if (NumParts == 0)
523     return;
524 
525   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
526   EVT PartEVT = PartVT;
527   if (PartEVT == ValueVT) {
528     assert(NumParts == 1 && "No-op copy with multiple parts!");
529     Parts[0] = Val;
530     return;
531   }
532 
533   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
534     // If the parts cover more bits than the value has, promote the value.
535     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
536       assert(NumParts == 1 && "Do not know what to promote to!");
537       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
538     } else {
539       if (ValueVT.isFloatingPoint()) {
540         // FP values need to be bitcast, then extended if they are being put
541         // into a larger container.
542         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
543         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
544       }
545       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
546              ValueVT.isInteger() &&
547              "Unknown mismatch!");
548       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
549       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
550       if (PartVT == MVT::x86mmx)
551         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552     }
553   } else if (PartBits == ValueVT.getSizeInBits()) {
554     // Different types of the same size.
555     assert(NumParts == 1 && PartEVT != ValueVT);
556     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558     // If the parts cover less bits than value has, truncate the value.
559     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
560            ValueVT.isInteger() &&
561            "Unknown mismatch!");
562     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
563     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
564     if (PartVT == MVT::x86mmx)
565       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
566   }
567 
568   // The value may have changed - recompute ValueVT.
569   ValueVT = Val.getValueType();
570   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
571          "Failed to tile the value with PartVT!");
572 
573   if (NumParts == 1) {
574     if (PartEVT != ValueVT) {
575       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
576                                         "scalar-to-vector conversion failed");
577       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
578     }
579 
580     Parts[0] = Val;
581     return;
582   }
583 
584   // Expand the value into multiple parts.
585   if (NumParts & (NumParts - 1)) {
586     // The number of parts is not a power of 2.  Split off and copy the tail.
587     assert(PartVT.isInteger() && ValueVT.isInteger() &&
588            "Do not know what to expand to!");
589     unsigned RoundParts = 1 << Log2_32(NumParts);
590     unsigned RoundBits = RoundParts * PartBits;
591     unsigned OddParts = NumParts - RoundParts;
592     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
593       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
594 
595     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
596                    CallConv);
597 
598     if (DAG.getDataLayout().isBigEndian())
599       // The odd parts were reversed by getCopyToParts - unreverse them.
600       std::reverse(Parts + RoundParts, Parts + NumParts);
601 
602     NumParts = RoundParts;
603     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
604     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
605   }
606 
607   // The number of parts is a power of 2.  Repeatedly bisect the value using
608   // EXTRACT_ELEMENT.
609   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
610                          EVT::getIntegerVT(*DAG.getContext(),
611                                            ValueVT.getSizeInBits()),
612                          Val);
613 
614   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
615     for (unsigned i = 0; i < NumParts; i += StepSize) {
616       unsigned ThisBits = StepSize * PartBits / 2;
617       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
618       SDValue &Part0 = Parts[i];
619       SDValue &Part1 = Parts[i+StepSize/2];
620 
621       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
622                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
623       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
625 
626       if (ThisBits == PartBits && ThisVT != PartVT) {
627         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
628         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
629       }
630     }
631   }
632 
633   if (DAG.getDataLayout().isBigEndian())
634     std::reverse(Parts, Parts + OrigNumParts);
635 }
636 
637 static SDValue widenVectorToPartType(SelectionDAG &DAG,
638                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
639   if (!PartVT.isVector())
640     return SDValue();
641 
642   EVT ValueVT = Val.getValueType();
643   unsigned PartNumElts = PartVT.getVectorNumElements();
644   unsigned ValueNumElts = ValueVT.getVectorNumElements();
645   if (PartNumElts > ValueNumElts &&
646       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
647     EVT ElementVT = PartVT.getVectorElementType();
648     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
649     // undef elements.
650     SmallVector<SDValue, 16> Ops;
651     DAG.ExtractVectorElements(Val, Ops);
652     SDValue EltUndef = DAG.getUNDEF(ElementVT);
653     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
654       Ops.push_back(EltUndef);
655 
656     // FIXME: Use CONCAT for 2x -> 4x.
657     return DAG.getBuildVector(PartVT, DL, Ops);
658   }
659 
660   return SDValue();
661 }
662 
663 /// getCopyToPartsVector - Create a series of nodes that contain the specified
664 /// value split into legal parts.
665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
666                                  SDValue Val, SDValue *Parts, unsigned NumParts,
667                                  MVT PartVT, const Value *V,
668                                  Optional<CallingConv::ID> CallConv) {
669   EVT ValueVT = Val.getValueType();
670   assert(ValueVT.isVector() && "Not a vector");
671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
672   const bool IsABIRegCopy = CallConv.hasValue();
673 
674   if (NumParts == 1) {
675     EVT PartEVT = PartVT;
676     if (PartEVT == ValueVT) {
677       // Nothing to do.
678     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
679       // Bitconvert vector->vector case.
680       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
681     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
682       Val = Widened;
683     } else if (PartVT.isVector() &&
684                PartEVT.getVectorElementType().bitsGE(
685                  ValueVT.getVectorElementType()) &&
686                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
687 
688       // Promoted vector extract
689       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
690     } else {
691       if (ValueVT.getVectorNumElements() == 1) {
692         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
693                           DAG.getVectorIdxConstant(0, DL));
694       } else {
695         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
696                "lossy conversion of vector to scalar type");
697         EVT IntermediateType =
698             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
699         Val = DAG.getBitcast(IntermediateType, Val);
700         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
701       }
702     }
703 
704     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
705     Parts[0] = Val;
706     return;
707   }
708 
709   // Handle a multi-element vector.
710   EVT IntermediateVT;
711   MVT RegisterVT;
712   unsigned NumIntermediates;
713   unsigned NumRegs;
714   if (IsABIRegCopy) {
715     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
716         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
717         NumIntermediates, RegisterVT);
718   } else {
719     NumRegs =
720         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
721                                    NumIntermediates, RegisterVT);
722   }
723 
724   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
725   NumParts = NumRegs; // Silence a compiler warning.
726   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
727 
728   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
729     IntermediateVT.getVectorNumElements() : 1;
730 
731   // Convert the vector to the appropriate type if necessary.
732   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
733 
734   EVT BuiltVectorTy = EVT::getVectorVT(
735       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
736   if (ValueVT != BuiltVectorTy) {
737     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
738       Val = Widened;
739 
740     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
741   }
742 
743   // Split the vector into intermediate operands.
744   SmallVector<SDValue, 8> Ops(NumIntermediates);
745   for (unsigned i = 0; i != NumIntermediates; ++i) {
746     if (IntermediateVT.isVector()) {
747       Ops[i] =
748           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
749                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
750     } else {
751       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
752                            DAG.getVectorIdxConstant(i, DL));
753     }
754   }
755 
756   // Split the intermediate operands into legal parts.
757   if (NumParts == NumIntermediates) {
758     // If the register was not expanded, promote or copy the value,
759     // as appropriate.
760     for (unsigned i = 0; i != NumParts; ++i)
761       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
762   } else if (NumParts > 0) {
763     // If the intermediate type was expanded, split each the value into
764     // legal parts.
765     assert(NumIntermediates != 0 && "division by zero");
766     assert(NumParts % NumIntermediates == 0 &&
767            "Must expand into a divisible number of parts!");
768     unsigned Factor = NumParts / NumIntermediates;
769     for (unsigned i = 0; i != NumIntermediates; ++i)
770       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
771                      CallConv);
772   }
773 }
774 
775 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
776                            EVT valuevt, Optional<CallingConv::ID> CC)
777     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
778       RegCount(1, regs.size()), CallConv(CC) {}
779 
780 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
781                            const DataLayout &DL, unsigned Reg, Type *Ty,
782                            Optional<CallingConv::ID> CC) {
783   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
784 
785   CallConv = CC;
786 
787   for (EVT ValueVT : ValueVTs) {
788     unsigned NumRegs =
789         isABIMangled()
790             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
791             : TLI.getNumRegisters(Context, ValueVT);
792     MVT RegisterVT =
793         isABIMangled()
794             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
795             : TLI.getRegisterType(Context, ValueVT);
796     for (unsigned i = 0; i != NumRegs; ++i)
797       Regs.push_back(Reg + i);
798     RegVTs.push_back(RegisterVT);
799     RegCount.push_back(NumRegs);
800     Reg += NumRegs;
801   }
802 }
803 
804 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
805                                       FunctionLoweringInfo &FuncInfo,
806                                       const SDLoc &dl, SDValue &Chain,
807                                       SDValue *Flag, const Value *V) const {
808   // A Value with type {} or [0 x %t] needs no registers.
809   if (ValueVTs.empty())
810     return SDValue();
811 
812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
813 
814   // Assemble the legal parts into the final values.
815   SmallVector<SDValue, 4> Values(ValueVTs.size());
816   SmallVector<SDValue, 8> Parts;
817   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
818     // Copy the legal parts from the registers.
819     EVT ValueVT = ValueVTs[Value];
820     unsigned NumRegs = RegCount[Value];
821     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
822                                           *DAG.getContext(),
823                                           CallConv.getValue(), RegVTs[Value])
824                                     : RegVTs[Value];
825 
826     Parts.resize(NumRegs);
827     for (unsigned i = 0; i != NumRegs; ++i) {
828       SDValue P;
829       if (!Flag) {
830         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
831       } else {
832         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
833         *Flag = P.getValue(2);
834       }
835 
836       Chain = P.getValue(1);
837       Parts[i] = P;
838 
839       // If the source register was virtual and if we know something about it,
840       // add an assert node.
841       if (!Register::isVirtualRegister(Regs[Part + i]) ||
842           !RegisterVT.isInteger())
843         continue;
844 
845       const FunctionLoweringInfo::LiveOutInfo *LOI =
846         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
847       if (!LOI)
848         continue;
849 
850       unsigned RegSize = RegisterVT.getScalarSizeInBits();
851       unsigned NumSignBits = LOI->NumSignBits;
852       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
853 
854       if (NumZeroBits == RegSize) {
855         // The current value is a zero.
856         // Explicitly express that as it would be easier for
857         // optimizations to kick in.
858         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
859         continue;
860       }
861 
862       // FIXME: We capture more information than the dag can represent.  For
863       // now, just use the tightest assertzext/assertsext possible.
864       bool isSExt;
865       EVT FromVT(MVT::Other);
866       if (NumZeroBits) {
867         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
868         isSExt = false;
869       } else if (NumSignBits > 1) {
870         FromVT =
871             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
872         isSExt = true;
873       } else {
874         continue;
875       }
876       // Add an assertion node.
877       assert(FromVT != MVT::Other);
878       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
879                              RegisterVT, P, DAG.getValueType(FromVT));
880     }
881 
882     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
883                                      RegisterVT, ValueVT, V, CallConv);
884     Part += NumRegs;
885     Parts.clear();
886   }
887 
888   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
889 }
890 
891 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
892                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
893                                  const Value *V,
894                                  ISD::NodeType PreferredExtendType) const {
895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
896   ISD::NodeType ExtendKind = PreferredExtendType;
897 
898   // Get the list of the values's legal parts.
899   unsigned NumRegs = Regs.size();
900   SmallVector<SDValue, 8> Parts(NumRegs);
901   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
902     unsigned NumParts = RegCount[Value];
903 
904     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
905                                           *DAG.getContext(),
906                                           CallConv.getValue(), RegVTs[Value])
907                                     : RegVTs[Value];
908 
909     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
910       ExtendKind = ISD::ZERO_EXTEND;
911 
912     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
913                    NumParts, RegisterVT, V, CallConv, ExtendKind);
914     Part += NumParts;
915   }
916 
917   // Copy the parts into the registers.
918   SmallVector<SDValue, 8> Chains(NumRegs);
919   for (unsigned i = 0; i != NumRegs; ++i) {
920     SDValue Part;
921     if (!Flag) {
922       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
923     } else {
924       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
925       *Flag = Part.getValue(1);
926     }
927 
928     Chains[i] = Part.getValue(0);
929   }
930 
931   if (NumRegs == 1 || Flag)
932     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
933     // flagged to it. That is the CopyToReg nodes and the user are considered
934     // a single scheduling unit. If we create a TokenFactor and return it as
935     // chain, then the TokenFactor is both a predecessor (operand) of the
936     // user as well as a successor (the TF operands are flagged to the user).
937     // c1, f1 = CopyToReg
938     // c2, f2 = CopyToReg
939     // c3     = TokenFactor c1, c2
940     // ...
941     //        = op c3, ..., f2
942     Chain = Chains[NumRegs-1];
943   else
944     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
945 }
946 
947 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
948                                         unsigned MatchingIdx, const SDLoc &dl,
949                                         SelectionDAG &DAG,
950                                         std::vector<SDValue> &Ops) const {
951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
952 
953   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
954   if (HasMatching)
955     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
956   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
957     // Put the register class of the virtual registers in the flag word.  That
958     // way, later passes can recompute register class constraints for inline
959     // assembly as well as normal instructions.
960     // Don't do this for tied operands that can use the regclass information
961     // from the def.
962     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
963     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
964     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
965   }
966 
967   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
968   Ops.push_back(Res);
969 
970   if (Code == InlineAsm::Kind_Clobber) {
971     // Clobbers should always have a 1:1 mapping with registers, and may
972     // reference registers that have illegal (e.g. vector) types. Hence, we
973     // shouldn't try to apply any sort of splitting logic to them.
974     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
975            "No 1:1 mapping from clobbers to regs?");
976     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
977     (void)SP;
978     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
979       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
980       assert(
981           (Regs[I] != SP ||
982            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
983           "If we clobbered the stack pointer, MFI should know about it.");
984     }
985     return;
986   }
987 
988   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
989     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
990     MVT RegisterVT = RegVTs[Value];
991     for (unsigned i = 0; i != NumRegs; ++i) {
992       assert(Reg < Regs.size() && "Mismatch in # registers expected");
993       unsigned TheReg = Regs[Reg++];
994       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
995     }
996   }
997 }
998 
999 SmallVector<std::pair<unsigned, unsigned>, 4>
1000 RegsForValue::getRegsAndSizes() const {
1001   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1002   unsigned I = 0;
1003   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1004     unsigned RegCount = std::get<0>(CountAndVT);
1005     MVT RegisterVT = std::get<1>(CountAndVT);
1006     unsigned RegisterSize = RegisterVT.getSizeInBits();
1007     for (unsigned E = I + RegCount; I != E; ++I)
1008       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1009   }
1010   return OutVec;
1011 }
1012 
1013 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1014                                const TargetLibraryInfo *li) {
1015   AA = aa;
1016   GFI = gfi;
1017   LibInfo = li;
1018   DL = &DAG.getDataLayout();
1019   Context = DAG.getContext();
1020   LPadToCallSiteMap.clear();
1021   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1022 }
1023 
1024 void SelectionDAGBuilder::clear() {
1025   NodeMap.clear();
1026   UnusedArgNodeMap.clear();
1027   PendingLoads.clear();
1028   PendingExports.clear();
1029   PendingConstrainedFP.clear();
1030   PendingConstrainedFPStrict.clear();
1031   CurInst = nullptr;
1032   HasTailCall = false;
1033   SDNodeOrder = LowestSDNodeOrder;
1034   StatepointLowering.clear();
1035 }
1036 
1037 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1038   DanglingDebugInfoMap.clear();
1039 }
1040 
1041 // Update DAG root to include dependencies on Pending chains.
1042 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (Pending.empty())
1046     return Root;
1047 
1048   // Add current root to PendingChains, unless we already indirectly
1049   // depend on it.
1050   if (Root.getOpcode() != ISD::EntryToken) {
1051     unsigned i = 0, e = Pending.size();
1052     for (; i != e; ++i) {
1053       assert(Pending[i].getNode()->getNumOperands() > 1);
1054       if (Pending[i].getNode()->getOperand(0) == Root)
1055         break;  // Don't add the root if we already indirectly depend on it.
1056     }
1057 
1058     if (i == e)
1059       Pending.push_back(Root);
1060   }
1061 
1062   if (Pending.size() == 1)
1063     Root = Pending[0];
1064   else
1065     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1066 
1067   DAG.setRoot(Root);
1068   Pending.clear();
1069   return Root;
1070 }
1071 
1072 SDValue SelectionDAGBuilder::getMemoryRoot() {
1073   return updateRoot(PendingLoads);
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getRoot() {
1077   // Chain up all pending constrained intrinsics together with all
1078   // pending loads, by simply appending them to PendingLoads and
1079   // then calling getMemoryRoot().
1080   PendingLoads.reserve(PendingLoads.size() +
1081                        PendingConstrainedFP.size() +
1082                        PendingConstrainedFPStrict.size());
1083   PendingLoads.append(PendingConstrainedFP.begin(),
1084                       PendingConstrainedFP.end());
1085   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1086                       PendingConstrainedFPStrict.end());
1087   PendingConstrainedFP.clear();
1088   PendingConstrainedFPStrict.clear();
1089   return getMemoryRoot();
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getControlRoot() {
1093   // We need to emit pending fpexcept.strict constrained intrinsics,
1094   // so append them to the PendingExports list.
1095   PendingExports.append(PendingConstrainedFPStrict.begin(),
1096                         PendingConstrainedFPStrict.end());
1097   PendingConstrainedFPStrict.clear();
1098   return updateRoot(PendingExports);
1099 }
1100 
1101 void SelectionDAGBuilder::visit(const Instruction &I) {
1102   // Set up outgoing PHI node register values before emitting the terminator.
1103   if (I.isTerminator()) {
1104     HandlePHINodesInSuccessorBlocks(I.getParent());
1105   }
1106 
1107   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1108   if (!isa<DbgInfoIntrinsic>(I))
1109     ++SDNodeOrder;
1110 
1111   CurInst = &I;
1112 
1113   visit(I.getOpcode(), I);
1114 
1115   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1116     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1117     // maps to this instruction.
1118     // TODO: We could handle all flags (nsw, etc) here.
1119     // TODO: If an IR instruction maps to >1 node, only the final node will have
1120     //       flags set.
1121     if (SDNode *Node = getNodeForIRValue(&I)) {
1122       SDNodeFlags IncomingFlags;
1123       IncomingFlags.copyFMF(*FPMO);
1124       if (!Node->getFlags().isDefined())
1125         Node->setFlags(IncomingFlags);
1126       else
1127         Node->intersectFlagsWith(IncomingFlags);
1128     }
1129   }
1130   // Constrained FP intrinsics with fpexcept.ignore should also get
1131   // the NoFPExcept flag.
1132   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1133     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1134       if (SDNode *Node = getNodeForIRValue(&I)) {
1135         SDNodeFlags Flags = Node->getFlags();
1136         Flags.setNoFPExcept(true);
1137         Node->setFlags(Flags);
1138       }
1139 
1140   if (!I.isTerminator() && !HasTailCall &&
1141       !isStatepoint(&I)) // statepoints handle their exports internally
1142     CopyToExportRegsIfNeeded(&I);
1143 
1144   CurInst = nullptr;
1145 }
1146 
1147 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1148   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1149 }
1150 
1151 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1152   // Note: this doesn't use InstVisitor, because it has to work with
1153   // ConstantExpr's in addition to instructions.
1154   switch (Opcode) {
1155   default: llvm_unreachable("Unknown instruction type encountered!");
1156     // Build the switch statement using the Instruction.def file.
1157 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1158     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1159 #include "llvm/IR/Instruction.def"
1160   }
1161 }
1162 
1163 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1164                                                 const DIExpression *Expr) {
1165   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1166     const DbgValueInst *DI = DDI.getDI();
1167     DIVariable *DanglingVariable = DI->getVariable();
1168     DIExpression *DanglingExpr = DI->getExpression();
1169     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1170       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1171       return true;
1172     }
1173     return false;
1174   };
1175 
1176   for (auto &DDIMI : DanglingDebugInfoMap) {
1177     DanglingDebugInfoVector &DDIV = DDIMI.second;
1178 
1179     // If debug info is to be dropped, run it through final checks to see
1180     // whether it can be salvaged.
1181     for (auto &DDI : DDIV)
1182       if (isMatchingDbgValue(DDI))
1183         salvageUnresolvedDbgValue(DDI);
1184 
1185     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1186   }
1187 }
1188 
1189 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1190 // generate the debug data structures now that we've seen its definition.
1191 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1192                                                    SDValue Val) {
1193   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1194   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1195     return;
1196 
1197   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1198   for (auto &DDI : DDIV) {
1199     const DbgValueInst *DI = DDI.getDI();
1200     assert(DI && "Ill-formed DanglingDebugInfo");
1201     DebugLoc dl = DDI.getdl();
1202     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1203     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1204     DILocalVariable *Variable = DI->getVariable();
1205     DIExpression *Expr = DI->getExpression();
1206     assert(Variable->isValidLocationForIntrinsic(dl) &&
1207            "Expected inlined-at fields to agree");
1208     SDDbgValue *SDV;
1209     if (Val.getNode()) {
1210       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1211       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1212       // we couldn't resolve it directly when examining the DbgValue intrinsic
1213       // in the first place we should not be more successful here). Unless we
1214       // have some test case that prove this to be correct we should avoid
1215       // calling EmitFuncArgumentDbgValue here.
1216       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1217         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1218                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1219         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1220         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1221         // inserted after the definition of Val when emitting the instructions
1222         // after ISel. An alternative could be to teach
1223         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1224         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1225                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1226                    << ValSDNodeOrder << "\n");
1227         SDV = getDbgValue(Val, Variable, Expr, dl,
1228                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1229         DAG.AddDbgValue(SDV, Val.getNode(), false);
1230       } else
1231         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1232                           << "in EmitFuncArgumentDbgValue\n");
1233     } else {
1234       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1235       auto Undef =
1236           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1237       auto SDV =
1238           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1239       DAG.AddDbgValue(SDV, nullptr, false);
1240     }
1241   }
1242   DDIV.clear();
1243 }
1244 
1245 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1246   Value *V = DDI.getDI()->getValue();
1247   DILocalVariable *Var = DDI.getDI()->getVariable();
1248   DIExpression *Expr = DDI.getDI()->getExpression();
1249   DebugLoc DL = DDI.getdl();
1250   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1251   unsigned SDOrder = DDI.getSDNodeOrder();
1252 
1253   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1254   // that DW_OP_stack_value is desired.
1255   assert(isa<DbgValueInst>(DDI.getDI()));
1256   bool StackValue = true;
1257 
1258   // Can this Value can be encoded without any further work?
1259   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1260     return;
1261 
1262   // Attempt to salvage back through as many instructions as possible. Bail if
1263   // a non-instruction is seen, such as a constant expression or global
1264   // variable. FIXME: Further work could recover those too.
1265   while (isa<Instruction>(V)) {
1266     Instruction &VAsInst = *cast<Instruction>(V);
1267     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1268 
1269     // If we cannot salvage any further, and haven't yet found a suitable debug
1270     // expression, bail out.
1271     if (!NewExpr)
1272       break;
1273 
1274     // New value and expr now represent this debuginfo.
1275     V = VAsInst.getOperand(0);
1276     Expr = NewExpr;
1277 
1278     // Some kind of simplification occurred: check whether the operand of the
1279     // salvaged debug expression can be encoded in this DAG.
1280     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1281       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1282                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1283       return;
1284     }
1285   }
1286 
1287   // This was the final opportunity to salvage this debug information, and it
1288   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1289   // any earlier variable location.
1290   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1291   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1292   DAG.AddDbgValue(SDV, nullptr, false);
1293 
1294   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1295                     << "\n");
1296   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1297                     << "\n");
1298 }
1299 
1300 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1301                                            DIExpression *Expr, DebugLoc dl,
1302                                            DebugLoc InstDL, unsigned Order) {
1303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1304   SDDbgValue *SDV;
1305   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1306       isa<ConstantPointerNull>(V)) {
1307     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1308     DAG.AddDbgValue(SDV, nullptr, false);
1309     return true;
1310   }
1311 
1312   // If the Value is a frame index, we can create a FrameIndex debug value
1313   // without relying on the DAG at all.
1314   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1315     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1316     if (SI != FuncInfo.StaticAllocaMap.end()) {
1317       auto SDV =
1318           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1319                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1320       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1321       // is still available even if the SDNode gets optimized out.
1322       DAG.AddDbgValue(SDV, nullptr, false);
1323       return true;
1324     }
1325   }
1326 
1327   // Do not use getValue() in here; we don't want to generate code at
1328   // this point if it hasn't been done yet.
1329   SDValue N = NodeMap[V];
1330   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1331     N = UnusedArgNodeMap[V];
1332   if (N.getNode()) {
1333     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1334       return true;
1335     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1336     DAG.AddDbgValue(SDV, N.getNode(), false);
1337     return true;
1338   }
1339 
1340   // Special rules apply for the first dbg.values of parameter variables in a
1341   // function. Identify them by the fact they reference Argument Values, that
1342   // they're parameters, and they are parameters of the current function. We
1343   // need to let them dangle until they get an SDNode.
1344   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1345                        !InstDL.getInlinedAt();
1346   if (!IsParamOfFunc) {
1347     // The value is not used in this block yet (or it would have an SDNode).
1348     // We still want the value to appear for the user if possible -- if it has
1349     // an associated VReg, we can refer to that instead.
1350     auto VMI = FuncInfo.ValueMap.find(V);
1351     if (VMI != FuncInfo.ValueMap.end()) {
1352       unsigned Reg = VMI->second;
1353       // If this is a PHI node, it may be split up into several MI PHI nodes
1354       // (in FunctionLoweringInfo::set).
1355       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1356                        V->getType(), None);
1357       if (RFV.occupiesMultipleRegs()) {
1358         unsigned Offset = 0;
1359         unsigned BitsToDescribe = 0;
1360         if (auto VarSize = Var->getSizeInBits())
1361           BitsToDescribe = *VarSize;
1362         if (auto Fragment = Expr->getFragmentInfo())
1363           BitsToDescribe = Fragment->SizeInBits;
1364         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1365           unsigned RegisterSize = RegAndSize.second;
1366           // Bail out if all bits are described already.
1367           if (Offset >= BitsToDescribe)
1368             break;
1369           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1370               ? BitsToDescribe - Offset
1371               : RegisterSize;
1372           auto FragmentExpr = DIExpression::createFragmentExpression(
1373               Expr, Offset, FragmentSize);
1374           if (!FragmentExpr)
1375               continue;
1376           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1377                                     false, dl, SDNodeOrder);
1378           DAG.AddDbgValue(SDV, nullptr, false);
1379           Offset += RegisterSize;
1380         }
1381       } else {
1382         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1383         DAG.AddDbgValue(SDV, nullptr, false);
1384       }
1385       return true;
1386     }
1387   }
1388 
1389   return false;
1390 }
1391 
1392 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1393   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1394   for (auto &Pair : DanglingDebugInfoMap)
1395     for (auto &DDI : Pair.second)
1396       salvageUnresolvedDbgValue(DDI);
1397   clearDanglingDebugInfo();
1398 }
1399 
1400 /// getCopyFromRegs - If there was virtual register allocated for the value V
1401 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1402 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1403   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1404   SDValue Result;
1405 
1406   if (It != FuncInfo.ValueMap.end()) {
1407     unsigned InReg = It->second;
1408 
1409     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1410                      DAG.getDataLayout(), InReg, Ty,
1411                      None); // This is not an ABI copy.
1412     SDValue Chain = DAG.getEntryNode();
1413     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1414                                  V);
1415     resolveDanglingDebugInfo(V, Result);
1416   }
1417 
1418   return Result;
1419 }
1420 
1421 /// getValue - Return an SDValue for the given Value.
1422 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1423   // If we already have an SDValue for this value, use it. It's important
1424   // to do this first, so that we don't create a CopyFromReg if we already
1425   // have a regular SDValue.
1426   SDValue &N = NodeMap[V];
1427   if (N.getNode()) return N;
1428 
1429   // If there's a virtual register allocated and initialized for this
1430   // value, use it.
1431   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1432     return copyFromReg;
1433 
1434   // Otherwise create a new SDValue and remember it.
1435   SDValue Val = getValueImpl(V);
1436   NodeMap[V] = Val;
1437   resolveDanglingDebugInfo(V, Val);
1438   return Val;
1439 }
1440 
1441 // Return true if SDValue exists for the given Value
1442 bool SelectionDAGBuilder::findValue(const Value *V) const {
1443   return (NodeMap.find(V) != NodeMap.end()) ||
1444     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1445 }
1446 
1447 /// getNonRegisterValue - Return an SDValue for the given Value, but
1448 /// don't look in FuncInfo.ValueMap for a virtual register.
1449 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1450   // If we already have an SDValue for this value, use it.
1451   SDValue &N = NodeMap[V];
1452   if (N.getNode()) {
1453     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1454       // Remove the debug location from the node as the node is about to be used
1455       // in a location which may differ from the original debug location.  This
1456       // is relevant to Constant and ConstantFP nodes because they can appear
1457       // as constant expressions inside PHI nodes.
1458       N->setDebugLoc(DebugLoc());
1459     }
1460     return N;
1461   }
1462 
1463   // Otherwise create a new SDValue and remember it.
1464   SDValue Val = getValueImpl(V);
1465   NodeMap[V] = Val;
1466   resolveDanglingDebugInfo(V, Val);
1467   return Val;
1468 }
1469 
1470 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1471 /// Create an SDValue for the given value.
1472 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1474 
1475   if (const Constant *C = dyn_cast<Constant>(V)) {
1476     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1477 
1478     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1479       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1480 
1481     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1482       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1483 
1484     if (isa<ConstantPointerNull>(C)) {
1485       unsigned AS = V->getType()->getPointerAddressSpace();
1486       return DAG.getConstant(0, getCurSDLoc(),
1487                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1488     }
1489 
1490     if (match(C, m_VScale(DAG.getDataLayout())))
1491       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1492 
1493     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1494       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1495 
1496     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1497       return DAG.getUNDEF(VT);
1498 
1499     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1500       visit(CE->getOpcode(), *CE);
1501       SDValue N1 = NodeMap[V];
1502       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1503       return N1;
1504     }
1505 
1506     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1507       SmallVector<SDValue, 4> Constants;
1508       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1509            OI != OE; ++OI) {
1510         SDNode *Val = getValue(*OI).getNode();
1511         // If the operand is an empty aggregate, there are no values.
1512         if (!Val) continue;
1513         // Add each leaf value from the operand to the Constants list
1514         // to form a flattened list of all the values.
1515         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1516           Constants.push_back(SDValue(Val, i));
1517       }
1518 
1519       return DAG.getMergeValues(Constants, getCurSDLoc());
1520     }
1521 
1522     if (const ConstantDataSequential *CDS =
1523           dyn_cast<ConstantDataSequential>(C)) {
1524       SmallVector<SDValue, 4> Ops;
1525       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1526         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1527         // Add each leaf value from the operand to the Constants list
1528         // to form a flattened list of all the values.
1529         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1530           Ops.push_back(SDValue(Val, i));
1531       }
1532 
1533       if (isa<ArrayType>(CDS->getType()))
1534         return DAG.getMergeValues(Ops, getCurSDLoc());
1535       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1536     }
1537 
1538     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1539       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1540              "Unknown struct or array constant!");
1541 
1542       SmallVector<EVT, 4> ValueVTs;
1543       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1544       unsigned NumElts = ValueVTs.size();
1545       if (NumElts == 0)
1546         return SDValue(); // empty struct
1547       SmallVector<SDValue, 4> Constants(NumElts);
1548       for (unsigned i = 0; i != NumElts; ++i) {
1549         EVT EltVT = ValueVTs[i];
1550         if (isa<UndefValue>(C))
1551           Constants[i] = DAG.getUNDEF(EltVT);
1552         else if (EltVT.isFloatingPoint())
1553           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1554         else
1555           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1556       }
1557 
1558       return DAG.getMergeValues(Constants, getCurSDLoc());
1559     }
1560 
1561     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1562       return DAG.getBlockAddress(BA, VT);
1563 
1564     VectorType *VecTy = cast<VectorType>(V->getType());
1565     unsigned NumElements = VecTy->getNumElements();
1566 
1567     // Now that we know the number and type of the elements, get that number of
1568     // elements into the Ops array based on what kind of constant it is.
1569     SmallVector<SDValue, 16> Ops;
1570     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1571       for (unsigned i = 0; i != NumElements; ++i)
1572         Ops.push_back(getValue(CV->getOperand(i)));
1573     } else {
1574       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1575       EVT EltVT =
1576           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1577 
1578       SDValue Op;
1579       if (EltVT.isFloatingPoint())
1580         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1581       else
1582         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1583       Ops.assign(NumElements, Op);
1584     }
1585 
1586     // Create a BUILD_VECTOR node.
1587     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1588   }
1589 
1590   // If this is a static alloca, generate it as the frameindex instead of
1591   // computation.
1592   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1593     DenseMap<const AllocaInst*, int>::iterator SI =
1594       FuncInfo.StaticAllocaMap.find(AI);
1595     if (SI != FuncInfo.StaticAllocaMap.end())
1596       return DAG.getFrameIndex(SI->second,
1597                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1598   }
1599 
1600   // If this is an instruction which fast-isel has deferred, select it now.
1601   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1602     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1603 
1604     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1605                      Inst->getType(), getABIRegCopyCC(V));
1606     SDValue Chain = DAG.getEntryNode();
1607     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1608   }
1609 
1610   llvm_unreachable("Can't get register for value!");
1611 }
1612 
1613 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1614   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1615   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1616   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1617   bool IsSEH = isAsynchronousEHPersonality(Pers);
1618   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1619   if (!IsSEH)
1620     CatchPadMBB->setIsEHScopeEntry();
1621   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1622   if (IsMSVCCXX || IsCoreCLR)
1623     CatchPadMBB->setIsEHFuncletEntry();
1624 }
1625 
1626 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1627   // Update machine-CFG edge.
1628   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1629   FuncInfo.MBB->addSuccessor(TargetMBB);
1630 
1631   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1632   bool IsSEH = isAsynchronousEHPersonality(Pers);
1633   if (IsSEH) {
1634     // If this is not a fall-through branch or optimizations are switched off,
1635     // emit the branch.
1636     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1637         TM.getOptLevel() == CodeGenOpt::None)
1638       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1639                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1640     return;
1641   }
1642 
1643   // Figure out the funclet membership for the catchret's successor.
1644   // This will be used by the FuncletLayout pass to determine how to order the
1645   // BB's.
1646   // A 'catchret' returns to the outer scope's color.
1647   Value *ParentPad = I.getCatchSwitchParentPad();
1648   const BasicBlock *SuccessorColor;
1649   if (isa<ConstantTokenNone>(ParentPad))
1650     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1651   else
1652     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1653   assert(SuccessorColor && "No parent funclet for catchret!");
1654   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1655   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1656 
1657   // Create the terminator node.
1658   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1659                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1660                             DAG.getBasicBlock(SuccessorColorMBB));
1661   DAG.setRoot(Ret);
1662 }
1663 
1664 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1665   // Don't emit any special code for the cleanuppad instruction. It just marks
1666   // the start of an EH scope/funclet.
1667   FuncInfo.MBB->setIsEHScopeEntry();
1668   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1669   if (Pers != EHPersonality::Wasm_CXX) {
1670     FuncInfo.MBB->setIsEHFuncletEntry();
1671     FuncInfo.MBB->setIsCleanupFuncletEntry();
1672   }
1673 }
1674 
1675 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1676 // the control flow always stops at the single catch pad, as it does for a
1677 // cleanup pad. In case the exception caught is not of the types the catch pad
1678 // catches, it will be rethrown by a rethrow.
1679 static void findWasmUnwindDestinations(
1680     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1681     BranchProbability Prob,
1682     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1683         &UnwindDests) {
1684   while (EHPadBB) {
1685     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1686     if (isa<CleanupPadInst>(Pad)) {
1687       // Stop on cleanup pads.
1688       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1689       UnwindDests.back().first->setIsEHScopeEntry();
1690       break;
1691     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1692       // Add the catchpad handlers to the possible destinations. We don't
1693       // continue to the unwind destination of the catchswitch for wasm.
1694       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1695         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1696         UnwindDests.back().first->setIsEHScopeEntry();
1697       }
1698       break;
1699     } else {
1700       continue;
1701     }
1702   }
1703 }
1704 
1705 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1706 /// many places it could ultimately go. In the IR, we have a single unwind
1707 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1708 /// This function skips over imaginary basic blocks that hold catchswitch
1709 /// instructions, and finds all the "real" machine
1710 /// basic block destinations. As those destinations may not be successors of
1711 /// EHPadBB, here we also calculate the edge probability to those destinations.
1712 /// The passed-in Prob is the edge probability to EHPadBB.
1713 static void findUnwindDestinations(
1714     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1715     BranchProbability Prob,
1716     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1717         &UnwindDests) {
1718   EHPersonality Personality =
1719     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1720   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1721   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1722   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1723   bool IsSEH = isAsynchronousEHPersonality(Personality);
1724 
1725   if (IsWasmCXX) {
1726     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1727     assert(UnwindDests.size() <= 1 &&
1728            "There should be at most one unwind destination for wasm");
1729     return;
1730   }
1731 
1732   while (EHPadBB) {
1733     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1734     BasicBlock *NewEHPadBB = nullptr;
1735     if (isa<LandingPadInst>(Pad)) {
1736       // Stop on landingpads. They are not funclets.
1737       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1738       break;
1739     } else if (isa<CleanupPadInst>(Pad)) {
1740       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1741       // personalities.
1742       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1743       UnwindDests.back().first->setIsEHScopeEntry();
1744       UnwindDests.back().first->setIsEHFuncletEntry();
1745       break;
1746     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1747       // Add the catchpad handlers to the possible destinations.
1748       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1749         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1750         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1751         if (IsMSVCCXX || IsCoreCLR)
1752           UnwindDests.back().first->setIsEHFuncletEntry();
1753         if (!IsSEH)
1754           UnwindDests.back().first->setIsEHScopeEntry();
1755       }
1756       NewEHPadBB = CatchSwitch->getUnwindDest();
1757     } else {
1758       continue;
1759     }
1760 
1761     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1762     if (BPI && NewEHPadBB)
1763       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1764     EHPadBB = NewEHPadBB;
1765   }
1766 }
1767 
1768 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1769   // Update successor info.
1770   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1771   auto UnwindDest = I.getUnwindDest();
1772   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1773   BranchProbability UnwindDestProb =
1774       (BPI && UnwindDest)
1775           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1776           : BranchProbability::getZero();
1777   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1778   for (auto &UnwindDest : UnwindDests) {
1779     UnwindDest.first->setIsEHPad();
1780     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1781   }
1782   FuncInfo.MBB->normalizeSuccProbs();
1783 
1784   // Create the terminator node.
1785   SDValue Ret =
1786       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1787   DAG.setRoot(Ret);
1788 }
1789 
1790 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1791   report_fatal_error("visitCatchSwitch not yet implemented!");
1792 }
1793 
1794 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796   auto &DL = DAG.getDataLayout();
1797   SDValue Chain = getControlRoot();
1798   SmallVector<ISD::OutputArg, 8> Outs;
1799   SmallVector<SDValue, 8> OutVals;
1800 
1801   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1802   // lower
1803   //
1804   //   %val = call <ty> @llvm.experimental.deoptimize()
1805   //   ret <ty> %val
1806   //
1807   // differently.
1808   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1809     LowerDeoptimizingReturn();
1810     return;
1811   }
1812 
1813   if (!FuncInfo.CanLowerReturn) {
1814     unsigned DemoteReg = FuncInfo.DemoteRegister;
1815     const Function *F = I.getParent()->getParent();
1816 
1817     // Emit a store of the return value through the virtual register.
1818     // Leave Outs empty so that LowerReturn won't try to load return
1819     // registers the usual way.
1820     SmallVector<EVT, 1> PtrValueVTs;
1821     ComputeValueVTs(TLI, DL,
1822                     F->getReturnType()->getPointerTo(
1823                         DAG.getDataLayout().getAllocaAddrSpace()),
1824                     PtrValueVTs);
1825 
1826     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1827                                         DemoteReg, PtrValueVTs[0]);
1828     SDValue RetOp = getValue(I.getOperand(0));
1829 
1830     SmallVector<EVT, 4> ValueVTs, MemVTs;
1831     SmallVector<uint64_t, 4> Offsets;
1832     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1833                     &Offsets);
1834     unsigned NumValues = ValueVTs.size();
1835 
1836     SmallVector<SDValue, 4> Chains(NumValues);
1837     for (unsigned i = 0; i != NumValues; ++i) {
1838       // An aggregate return value cannot wrap around the address space, so
1839       // offsets to its parts don't wrap either.
1840       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1841 
1842       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1843       if (MemVTs[i] != ValueVTs[i])
1844         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1845       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1846           // FIXME: better loc info would be nice.
1847           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1848     }
1849 
1850     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1851                         MVT::Other, Chains);
1852   } else if (I.getNumOperands() != 0) {
1853     SmallVector<EVT, 4> ValueVTs;
1854     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1855     unsigned NumValues = ValueVTs.size();
1856     if (NumValues) {
1857       SDValue RetOp = getValue(I.getOperand(0));
1858 
1859       const Function *F = I.getParent()->getParent();
1860 
1861       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1862           I.getOperand(0)->getType(), F->getCallingConv(),
1863           /*IsVarArg*/ false);
1864 
1865       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1866       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1867                                           Attribute::SExt))
1868         ExtendKind = ISD::SIGN_EXTEND;
1869       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1870                                                Attribute::ZExt))
1871         ExtendKind = ISD::ZERO_EXTEND;
1872 
1873       LLVMContext &Context = F->getContext();
1874       bool RetInReg = F->getAttributes().hasAttribute(
1875           AttributeList::ReturnIndex, Attribute::InReg);
1876 
1877       for (unsigned j = 0; j != NumValues; ++j) {
1878         EVT VT = ValueVTs[j];
1879 
1880         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1881           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1882 
1883         CallingConv::ID CC = F->getCallingConv();
1884 
1885         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1886         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1887         SmallVector<SDValue, 4> Parts(NumParts);
1888         getCopyToParts(DAG, getCurSDLoc(),
1889                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1890                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1891 
1892         // 'inreg' on function refers to return value
1893         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1894         if (RetInReg)
1895           Flags.setInReg();
1896 
1897         if (I.getOperand(0)->getType()->isPointerTy()) {
1898           Flags.setPointer();
1899           Flags.setPointerAddrSpace(
1900               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1901         }
1902 
1903         if (NeedsRegBlock) {
1904           Flags.setInConsecutiveRegs();
1905           if (j == NumValues - 1)
1906             Flags.setInConsecutiveRegsLast();
1907         }
1908 
1909         // Propagate extension type if any
1910         if (ExtendKind == ISD::SIGN_EXTEND)
1911           Flags.setSExt();
1912         else if (ExtendKind == ISD::ZERO_EXTEND)
1913           Flags.setZExt();
1914 
1915         for (unsigned i = 0; i < NumParts; ++i) {
1916           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1917                                         VT, /*isfixed=*/true, 0, 0));
1918           OutVals.push_back(Parts[i]);
1919         }
1920       }
1921     }
1922   }
1923 
1924   // Push in swifterror virtual register as the last element of Outs. This makes
1925   // sure swifterror virtual register will be returned in the swifterror
1926   // physical register.
1927   const Function *F = I.getParent()->getParent();
1928   if (TLI.supportSwiftError() &&
1929       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1930     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1931     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1932     Flags.setSwiftError();
1933     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1934                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1935                                   true /*isfixed*/, 1 /*origidx*/,
1936                                   0 /*partOffs*/));
1937     // Create SDNode for the swifterror virtual register.
1938     OutVals.push_back(
1939         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1940                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1941                         EVT(TLI.getPointerTy(DL))));
1942   }
1943 
1944   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1945   CallingConv::ID CallConv =
1946     DAG.getMachineFunction().getFunction().getCallingConv();
1947   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1948       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1949 
1950   // Verify that the target's LowerReturn behaved as expected.
1951   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1952          "LowerReturn didn't return a valid chain!");
1953 
1954   // Update the DAG with the new chain value resulting from return lowering.
1955   DAG.setRoot(Chain);
1956 }
1957 
1958 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1959 /// created for it, emit nodes to copy the value into the virtual
1960 /// registers.
1961 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1962   // Skip empty types
1963   if (V->getType()->isEmptyTy())
1964     return;
1965 
1966   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1967   if (VMI != FuncInfo.ValueMap.end()) {
1968     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1969     CopyValueToVirtualRegister(V, VMI->second);
1970   }
1971 }
1972 
1973 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1974 /// the current basic block, add it to ValueMap now so that we'll get a
1975 /// CopyTo/FromReg.
1976 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1977   // No need to export constants.
1978   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1979 
1980   // Already exported?
1981   if (FuncInfo.isExportedInst(V)) return;
1982 
1983   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1984   CopyValueToVirtualRegister(V, Reg);
1985 }
1986 
1987 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1988                                                      const BasicBlock *FromBB) {
1989   // The operands of the setcc have to be in this block.  We don't know
1990   // how to export them from some other block.
1991   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1992     // Can export from current BB.
1993     if (VI->getParent() == FromBB)
1994       return true;
1995 
1996     // Is already exported, noop.
1997     return FuncInfo.isExportedInst(V);
1998   }
1999 
2000   // If this is an argument, we can export it if the BB is the entry block or
2001   // if it is already exported.
2002   if (isa<Argument>(V)) {
2003     if (FromBB == &FromBB->getParent()->getEntryBlock())
2004       return true;
2005 
2006     // Otherwise, can only export this if it is already exported.
2007     return FuncInfo.isExportedInst(V);
2008   }
2009 
2010   // Otherwise, constants can always be exported.
2011   return true;
2012 }
2013 
2014 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2015 BranchProbability
2016 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2017                                         const MachineBasicBlock *Dst) const {
2018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2019   const BasicBlock *SrcBB = Src->getBasicBlock();
2020   const BasicBlock *DstBB = Dst->getBasicBlock();
2021   if (!BPI) {
2022     // If BPI is not available, set the default probability as 1 / N, where N is
2023     // the number of successors.
2024     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2025     return BranchProbability(1, SuccSize);
2026   }
2027   return BPI->getEdgeProbability(SrcBB, DstBB);
2028 }
2029 
2030 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2031                                                MachineBasicBlock *Dst,
2032                                                BranchProbability Prob) {
2033   if (!FuncInfo.BPI)
2034     Src->addSuccessorWithoutProb(Dst);
2035   else {
2036     if (Prob.isUnknown())
2037       Prob = getEdgeProbability(Src, Dst);
2038     Src->addSuccessor(Dst, Prob);
2039   }
2040 }
2041 
2042 static bool InBlock(const Value *V, const BasicBlock *BB) {
2043   if (const Instruction *I = dyn_cast<Instruction>(V))
2044     return I->getParent() == BB;
2045   return true;
2046 }
2047 
2048 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2049 /// This function emits a branch and is used at the leaves of an OR or an
2050 /// AND operator tree.
2051 void
2052 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2053                                                   MachineBasicBlock *TBB,
2054                                                   MachineBasicBlock *FBB,
2055                                                   MachineBasicBlock *CurBB,
2056                                                   MachineBasicBlock *SwitchBB,
2057                                                   BranchProbability TProb,
2058                                                   BranchProbability FProb,
2059                                                   bool InvertCond) {
2060   const BasicBlock *BB = CurBB->getBasicBlock();
2061 
2062   // If the leaf of the tree is a comparison, merge the condition into
2063   // the caseblock.
2064   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2065     // The operands of the cmp have to be in this block.  We don't know
2066     // how to export them from some other block.  If this is the first block
2067     // of the sequence, no exporting is needed.
2068     if (CurBB == SwitchBB ||
2069         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2070          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2071       ISD::CondCode Condition;
2072       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2073         ICmpInst::Predicate Pred =
2074             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2075         Condition = getICmpCondCode(Pred);
2076       } else {
2077         const FCmpInst *FC = cast<FCmpInst>(Cond);
2078         FCmpInst::Predicate Pred =
2079             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2080         Condition = getFCmpCondCode(Pred);
2081         if (TM.Options.NoNaNsFPMath)
2082           Condition = getFCmpCodeWithoutNaN(Condition);
2083       }
2084 
2085       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2086                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2087       SL->SwitchCases.push_back(CB);
2088       return;
2089     }
2090   }
2091 
2092   // Create a CaseBlock record representing this branch.
2093   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2094   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2095                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2096   SL->SwitchCases.push_back(CB);
2097 }
2098 
2099 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2100                                                MachineBasicBlock *TBB,
2101                                                MachineBasicBlock *FBB,
2102                                                MachineBasicBlock *CurBB,
2103                                                MachineBasicBlock *SwitchBB,
2104                                                Instruction::BinaryOps Opc,
2105                                                BranchProbability TProb,
2106                                                BranchProbability FProb,
2107                                                bool InvertCond) {
2108   // Skip over not part of the tree and remember to invert op and operands at
2109   // next level.
2110   Value *NotCond;
2111   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2112       InBlock(NotCond, CurBB->getBasicBlock())) {
2113     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2114                          !InvertCond);
2115     return;
2116   }
2117 
2118   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2119   // Compute the effective opcode for Cond, taking into account whether it needs
2120   // to be inverted, e.g.
2121   //   and (not (or A, B)), C
2122   // gets lowered as
2123   //   and (and (not A, not B), C)
2124   unsigned BOpc = 0;
2125   if (BOp) {
2126     BOpc = BOp->getOpcode();
2127     if (InvertCond) {
2128       if (BOpc == Instruction::And)
2129         BOpc = Instruction::Or;
2130       else if (BOpc == Instruction::Or)
2131         BOpc = Instruction::And;
2132     }
2133   }
2134 
2135   // If this node is not part of the or/and tree, emit it as a branch.
2136   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2137       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2138       BOp->getParent() != CurBB->getBasicBlock() ||
2139       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2140       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2141     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2142                                  TProb, FProb, InvertCond);
2143     return;
2144   }
2145 
2146   //  Create TmpBB after CurBB.
2147   MachineFunction::iterator BBI(CurBB);
2148   MachineFunction &MF = DAG.getMachineFunction();
2149   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2150   CurBB->getParent()->insert(++BBI, TmpBB);
2151 
2152   if (Opc == Instruction::Or) {
2153     // Codegen X | Y as:
2154     // BB1:
2155     //   jmp_if_X TBB
2156     //   jmp TmpBB
2157     // TmpBB:
2158     //   jmp_if_Y TBB
2159     //   jmp FBB
2160     //
2161 
2162     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2163     // The requirement is that
2164     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2165     //     = TrueProb for original BB.
2166     // Assuming the original probabilities are A and B, one choice is to set
2167     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2168     // A/(1+B) and 2B/(1+B). This choice assumes that
2169     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2170     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2171     // TmpBB, but the math is more complicated.
2172 
2173     auto NewTrueProb = TProb / 2;
2174     auto NewFalseProb = TProb / 2 + FProb;
2175     // Emit the LHS condition.
2176     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2177                          NewTrueProb, NewFalseProb, InvertCond);
2178 
2179     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2180     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2181     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2182     // Emit the RHS condition into TmpBB.
2183     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2184                          Probs[0], Probs[1], InvertCond);
2185   } else {
2186     assert(Opc == Instruction::And && "Unknown merge op!");
2187     // Codegen X & Y as:
2188     // BB1:
2189     //   jmp_if_X TmpBB
2190     //   jmp FBB
2191     // TmpBB:
2192     //   jmp_if_Y TBB
2193     //   jmp FBB
2194     //
2195     //  This requires creation of TmpBB after CurBB.
2196 
2197     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2198     // The requirement is that
2199     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2200     //     = FalseProb for original BB.
2201     // Assuming the original probabilities are A and B, one choice is to set
2202     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2203     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2204     // TrueProb for BB1 * FalseProb for TmpBB.
2205 
2206     auto NewTrueProb = TProb + FProb / 2;
2207     auto NewFalseProb = FProb / 2;
2208     // Emit the LHS condition.
2209     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2210                          NewTrueProb, NewFalseProb, InvertCond);
2211 
2212     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2213     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2214     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2215     // Emit the RHS condition into TmpBB.
2216     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2217                          Probs[0], Probs[1], InvertCond);
2218   }
2219 }
2220 
2221 /// If the set of cases should be emitted as a series of branches, return true.
2222 /// If we should emit this as a bunch of and/or'd together conditions, return
2223 /// false.
2224 bool
2225 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2226   if (Cases.size() != 2) return true;
2227 
2228   // If this is two comparisons of the same values or'd or and'd together, they
2229   // will get folded into a single comparison, so don't emit two blocks.
2230   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2231        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2232       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2233        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2234     return false;
2235   }
2236 
2237   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2238   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2239   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2240       Cases[0].CC == Cases[1].CC &&
2241       isa<Constant>(Cases[0].CmpRHS) &&
2242       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2243     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2244       return false;
2245     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2246       return false;
2247   }
2248 
2249   return true;
2250 }
2251 
2252 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2253   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2254 
2255   // Update machine-CFG edges.
2256   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2257 
2258   if (I.isUnconditional()) {
2259     // Update machine-CFG edges.
2260     BrMBB->addSuccessor(Succ0MBB);
2261 
2262     // If this is not a fall-through branch or optimizations are switched off,
2263     // emit the branch.
2264     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2265       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2266                               MVT::Other, getControlRoot(),
2267                               DAG.getBasicBlock(Succ0MBB)));
2268 
2269     return;
2270   }
2271 
2272   // If this condition is one of the special cases we handle, do special stuff
2273   // now.
2274   const Value *CondVal = I.getCondition();
2275   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2276 
2277   // If this is a series of conditions that are or'd or and'd together, emit
2278   // this as a sequence of branches instead of setcc's with and/or operations.
2279   // As long as jumps are not expensive, this should improve performance.
2280   // For example, instead of something like:
2281   //     cmp A, B
2282   //     C = seteq
2283   //     cmp D, E
2284   //     F = setle
2285   //     or C, F
2286   //     jnz foo
2287   // Emit:
2288   //     cmp A, B
2289   //     je foo
2290   //     cmp D, E
2291   //     jle foo
2292   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2293     Instruction::BinaryOps Opcode = BOp->getOpcode();
2294     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2295         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2296         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2297       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2298                            Opcode,
2299                            getEdgeProbability(BrMBB, Succ0MBB),
2300                            getEdgeProbability(BrMBB, Succ1MBB),
2301                            /*InvertCond=*/false);
2302       // If the compares in later blocks need to use values not currently
2303       // exported from this block, export them now.  This block should always
2304       // be the first entry.
2305       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2306 
2307       // Allow some cases to be rejected.
2308       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2309         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2310           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2311           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2312         }
2313 
2314         // Emit the branch for this block.
2315         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2316         SL->SwitchCases.erase(SL->SwitchCases.begin());
2317         return;
2318       }
2319 
2320       // Okay, we decided not to do this, remove any inserted MBB's and clear
2321       // SwitchCases.
2322       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2323         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2324 
2325       SL->SwitchCases.clear();
2326     }
2327   }
2328 
2329   // Create a CaseBlock record representing this branch.
2330   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2331                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2332 
2333   // Use visitSwitchCase to actually insert the fast branch sequence for this
2334   // cond branch.
2335   visitSwitchCase(CB, BrMBB);
2336 }
2337 
2338 /// visitSwitchCase - Emits the necessary code to represent a single node in
2339 /// the binary search tree resulting from lowering a switch instruction.
2340 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2341                                           MachineBasicBlock *SwitchBB) {
2342   SDValue Cond;
2343   SDValue CondLHS = getValue(CB.CmpLHS);
2344   SDLoc dl = CB.DL;
2345 
2346   if (CB.CC == ISD::SETTRUE) {
2347     // Branch or fall through to TrueBB.
2348     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2349     SwitchBB->normalizeSuccProbs();
2350     if (CB.TrueBB != NextBlock(SwitchBB)) {
2351       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2352                               DAG.getBasicBlock(CB.TrueBB)));
2353     }
2354     return;
2355   }
2356 
2357   auto &TLI = DAG.getTargetLoweringInfo();
2358   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2359 
2360   // Build the setcc now.
2361   if (!CB.CmpMHS) {
2362     // Fold "(X == true)" to X and "(X == false)" to !X to
2363     // handle common cases produced by branch lowering.
2364     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2365         CB.CC == ISD::SETEQ)
2366       Cond = CondLHS;
2367     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2368              CB.CC == ISD::SETEQ) {
2369       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2370       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2371     } else {
2372       SDValue CondRHS = getValue(CB.CmpRHS);
2373 
2374       // If a pointer's DAG type is larger than its memory type then the DAG
2375       // values are zero-extended. This breaks signed comparisons so truncate
2376       // back to the underlying type before doing the compare.
2377       if (CondLHS.getValueType() != MemVT) {
2378         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2379         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2380       }
2381       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2382     }
2383   } else {
2384     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2385 
2386     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2387     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2388 
2389     SDValue CmpOp = getValue(CB.CmpMHS);
2390     EVT VT = CmpOp.getValueType();
2391 
2392     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2393       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2394                           ISD::SETLE);
2395     } else {
2396       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2397                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2398       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2399                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2400     }
2401   }
2402 
2403   // Update successor info
2404   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2405   // TrueBB and FalseBB are always different unless the incoming IR is
2406   // degenerate. This only happens when running llc on weird IR.
2407   if (CB.TrueBB != CB.FalseBB)
2408     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2409   SwitchBB->normalizeSuccProbs();
2410 
2411   // If the lhs block is the next block, invert the condition so that we can
2412   // fall through to the lhs instead of the rhs block.
2413   if (CB.TrueBB == NextBlock(SwitchBB)) {
2414     std::swap(CB.TrueBB, CB.FalseBB);
2415     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2416     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2417   }
2418 
2419   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2420                                MVT::Other, getControlRoot(), Cond,
2421                                DAG.getBasicBlock(CB.TrueBB));
2422 
2423   // Insert the false branch. Do this even if it's a fall through branch,
2424   // this makes it easier to do DAG optimizations which require inverting
2425   // the branch condition.
2426   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2427                        DAG.getBasicBlock(CB.FalseBB));
2428 
2429   DAG.setRoot(BrCond);
2430 }
2431 
2432 /// visitJumpTable - Emit JumpTable node in the current MBB
2433 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2434   // Emit the code for the jump table
2435   assert(JT.Reg != -1U && "Should lower JT Header first!");
2436   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2437   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2438                                      JT.Reg, PTy);
2439   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2440   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2441                                     MVT::Other, Index.getValue(1),
2442                                     Table, Index);
2443   DAG.setRoot(BrJumpTable);
2444 }
2445 
2446 /// visitJumpTableHeader - This function emits necessary code to produce index
2447 /// in the JumpTable from switch case.
2448 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2449                                                JumpTableHeader &JTH,
2450                                                MachineBasicBlock *SwitchBB) {
2451   SDLoc dl = getCurSDLoc();
2452 
2453   // Subtract the lowest switch case value from the value being switched on.
2454   SDValue SwitchOp = getValue(JTH.SValue);
2455   EVT VT = SwitchOp.getValueType();
2456   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2457                             DAG.getConstant(JTH.First, dl, VT));
2458 
2459   // The SDNode we just created, which holds the value being switched on minus
2460   // the smallest case value, needs to be copied to a virtual register so it
2461   // can be used as an index into the jump table in a subsequent basic block.
2462   // This value may be smaller or larger than the target's pointer type, and
2463   // therefore require extension or truncating.
2464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2465   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2466 
2467   unsigned JumpTableReg =
2468       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2469   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2470                                     JumpTableReg, SwitchOp);
2471   JT.Reg = JumpTableReg;
2472 
2473   if (!JTH.OmitRangeCheck) {
2474     // Emit the range check for the jump table, and branch to the default block
2475     // for the switch statement if the value being switched on exceeds the
2476     // largest case in the switch.
2477     SDValue CMP = DAG.getSetCC(
2478         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2479                                    Sub.getValueType()),
2480         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2481 
2482     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2483                                  MVT::Other, CopyTo, CMP,
2484                                  DAG.getBasicBlock(JT.Default));
2485 
2486     // Avoid emitting unnecessary branches to the next block.
2487     if (JT.MBB != NextBlock(SwitchBB))
2488       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2489                            DAG.getBasicBlock(JT.MBB));
2490 
2491     DAG.setRoot(BrCond);
2492   } else {
2493     // Avoid emitting unnecessary branches to the next block.
2494     if (JT.MBB != NextBlock(SwitchBB))
2495       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2496                               DAG.getBasicBlock(JT.MBB)));
2497     else
2498       DAG.setRoot(CopyTo);
2499   }
2500 }
2501 
2502 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2503 /// variable if there exists one.
2504 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2505                                  SDValue &Chain) {
2506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2508   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2511   MachineSDNode *Node =
2512       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2513   if (Global) {
2514     MachinePointerInfo MPInfo(Global);
2515     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2516                  MachineMemOperand::MODereferenceable;
2517     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2518         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2519     DAG.setNodeMemRefs(Node, {MemRef});
2520   }
2521   if (PtrTy != PtrMemTy)
2522     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2523   return SDValue(Node, 0);
2524 }
2525 
2526 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2527 /// tail spliced into a stack protector check success bb.
2528 ///
2529 /// For a high level explanation of how this fits into the stack protector
2530 /// generation see the comment on the declaration of class
2531 /// StackProtectorDescriptor.
2532 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2533                                                   MachineBasicBlock *ParentBB) {
2534 
2535   // First create the loads to the guard/stack slot for the comparison.
2536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2537   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2538   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2539 
2540   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2541   int FI = MFI.getStackProtectorIndex();
2542 
2543   SDValue Guard;
2544   SDLoc dl = getCurSDLoc();
2545   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2546   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2547   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2548 
2549   // Generate code to load the content of the guard slot.
2550   SDValue GuardVal = DAG.getLoad(
2551       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2552       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2553       MachineMemOperand::MOVolatile);
2554 
2555   if (TLI.useStackGuardXorFP())
2556     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2557 
2558   // Retrieve guard check function, nullptr if instrumentation is inlined.
2559   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2560     // The target provides a guard check function to validate the guard value.
2561     // Generate a call to that function with the content of the guard slot as
2562     // argument.
2563     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2564     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2565 
2566     TargetLowering::ArgListTy Args;
2567     TargetLowering::ArgListEntry Entry;
2568     Entry.Node = GuardVal;
2569     Entry.Ty = FnTy->getParamType(0);
2570     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2571       Entry.IsInReg = true;
2572     Args.push_back(Entry);
2573 
2574     TargetLowering::CallLoweringInfo CLI(DAG);
2575     CLI.setDebugLoc(getCurSDLoc())
2576         .setChain(DAG.getEntryNode())
2577         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2578                    getValue(GuardCheckFn), std::move(Args));
2579 
2580     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2581     DAG.setRoot(Result.second);
2582     return;
2583   }
2584 
2585   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2586   // Otherwise, emit a volatile load to retrieve the stack guard value.
2587   SDValue Chain = DAG.getEntryNode();
2588   if (TLI.useLoadStackGuardNode()) {
2589     Guard = getLoadStackGuard(DAG, dl, Chain);
2590   } else {
2591     const Value *IRGuard = TLI.getSDagStackGuard(M);
2592     SDValue GuardPtr = getValue(IRGuard);
2593 
2594     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2595                         MachinePointerInfo(IRGuard, 0), Align,
2596                         MachineMemOperand::MOVolatile);
2597   }
2598 
2599   // Perform the comparison via a getsetcc.
2600   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2601                                                         *DAG.getContext(),
2602                                                         Guard.getValueType()),
2603                              Guard, GuardVal, ISD::SETNE);
2604 
2605   // If the guard/stackslot do not equal, branch to failure MBB.
2606   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2607                                MVT::Other, GuardVal.getOperand(0),
2608                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2609   // Otherwise branch to success MBB.
2610   SDValue Br = DAG.getNode(ISD::BR, dl,
2611                            MVT::Other, BrCond,
2612                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2613 
2614   DAG.setRoot(Br);
2615 }
2616 
2617 /// Codegen the failure basic block for a stack protector check.
2618 ///
2619 /// A failure stack protector machine basic block consists simply of a call to
2620 /// __stack_chk_fail().
2621 ///
2622 /// For a high level explanation of how this fits into the stack protector
2623 /// generation see the comment on the declaration of class
2624 /// StackProtectorDescriptor.
2625 void
2626 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2628   TargetLowering::MakeLibCallOptions CallOptions;
2629   CallOptions.setDiscardResult(true);
2630   SDValue Chain =
2631       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2632                       None, CallOptions, getCurSDLoc()).second;
2633   // On PS4, the "return address" must still be within the calling function,
2634   // even if it's at the very end, so emit an explicit TRAP here.
2635   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2636   if (TM.getTargetTriple().isPS4CPU())
2637     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2638 
2639   DAG.setRoot(Chain);
2640 }
2641 
2642 /// visitBitTestHeader - This function emits necessary code to produce value
2643 /// suitable for "bit tests"
2644 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2645                                              MachineBasicBlock *SwitchBB) {
2646   SDLoc dl = getCurSDLoc();
2647 
2648   // Subtract the minimum value.
2649   SDValue SwitchOp = getValue(B.SValue);
2650   EVT VT = SwitchOp.getValueType();
2651   SDValue RangeSub =
2652       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2653 
2654   // Determine the type of the test operands.
2655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2656   bool UsePtrType = false;
2657   if (!TLI.isTypeLegal(VT)) {
2658     UsePtrType = true;
2659   } else {
2660     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2661       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2662         // Switch table case range are encoded into series of masks.
2663         // Just use pointer type, it's guaranteed to fit.
2664         UsePtrType = true;
2665         break;
2666       }
2667   }
2668   SDValue Sub = RangeSub;
2669   if (UsePtrType) {
2670     VT = TLI.getPointerTy(DAG.getDataLayout());
2671     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2672   }
2673 
2674   B.RegVT = VT.getSimpleVT();
2675   B.Reg = FuncInfo.CreateReg(B.RegVT);
2676   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2677 
2678   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2679 
2680   if (!B.OmitRangeCheck)
2681     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2682   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2683   SwitchBB->normalizeSuccProbs();
2684 
2685   SDValue Root = CopyTo;
2686   if (!B.OmitRangeCheck) {
2687     // Conditional branch to the default block.
2688     SDValue RangeCmp = DAG.getSetCC(dl,
2689         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2690                                RangeSub.getValueType()),
2691         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2692         ISD::SETUGT);
2693 
2694     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2695                        DAG.getBasicBlock(B.Default));
2696   }
2697 
2698   // Avoid emitting unnecessary branches to the next block.
2699   if (MBB != NextBlock(SwitchBB))
2700     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2701 
2702   DAG.setRoot(Root);
2703 }
2704 
2705 /// visitBitTestCase - this function produces one "bit test"
2706 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2707                                            MachineBasicBlock* NextMBB,
2708                                            BranchProbability BranchProbToNext,
2709                                            unsigned Reg,
2710                                            BitTestCase &B,
2711                                            MachineBasicBlock *SwitchBB) {
2712   SDLoc dl = getCurSDLoc();
2713   MVT VT = BB.RegVT;
2714   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2715   SDValue Cmp;
2716   unsigned PopCount = countPopulation(B.Mask);
2717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2718   if (PopCount == 1) {
2719     // Testing for a single bit; just compare the shift count with what it
2720     // would need to be to shift a 1 bit in that position.
2721     Cmp = DAG.getSetCC(
2722         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2723         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2724         ISD::SETEQ);
2725   } else if (PopCount == BB.Range) {
2726     // There is only one zero bit in the range, test for it directly.
2727     Cmp = DAG.getSetCC(
2728         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2729         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2730         ISD::SETNE);
2731   } else {
2732     // Make desired shift
2733     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2734                                     DAG.getConstant(1, dl, VT), ShiftOp);
2735 
2736     // Emit bit tests and jumps
2737     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2738                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2739     Cmp = DAG.getSetCC(
2740         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2741         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2742   }
2743 
2744   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2745   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2746   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2747   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2748   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2749   // one as they are relative probabilities (and thus work more like weights),
2750   // and hence we need to normalize them to let the sum of them become one.
2751   SwitchBB->normalizeSuccProbs();
2752 
2753   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2754                               MVT::Other, getControlRoot(),
2755                               Cmp, DAG.getBasicBlock(B.TargetBB));
2756 
2757   // Avoid emitting unnecessary branches to the next block.
2758   if (NextMBB != NextBlock(SwitchBB))
2759     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2760                         DAG.getBasicBlock(NextMBB));
2761 
2762   DAG.setRoot(BrAnd);
2763 }
2764 
2765 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2766   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2767 
2768   // Retrieve successors. Look through artificial IR level blocks like
2769   // catchswitch for successors.
2770   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2771   const BasicBlock *EHPadBB = I.getSuccessor(1);
2772 
2773   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2774   // have to do anything here to lower funclet bundles.
2775   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2776                                         LLVMContext::OB_funclet,
2777                                         LLVMContext::OB_cfguardtarget}) &&
2778          "Cannot lower invokes with arbitrary operand bundles yet!");
2779 
2780   const Value *Callee(I.getCalledValue());
2781   const Function *Fn = dyn_cast<Function>(Callee);
2782   if (isa<InlineAsm>(Callee))
2783     visitInlineAsm(&I);
2784   else if (Fn && Fn->isIntrinsic()) {
2785     switch (Fn->getIntrinsicID()) {
2786     default:
2787       llvm_unreachable("Cannot invoke this intrinsic");
2788     case Intrinsic::donothing:
2789       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2790       break;
2791     case Intrinsic::experimental_patchpoint_void:
2792     case Intrinsic::experimental_patchpoint_i64:
2793       visitPatchpoint(&I, EHPadBB);
2794       break;
2795     case Intrinsic::experimental_gc_statepoint:
2796       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2797       break;
2798     case Intrinsic::wasm_rethrow_in_catch: {
2799       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2800       // special because it can be invoked, so we manually lower it to a DAG
2801       // node here.
2802       SmallVector<SDValue, 8> Ops;
2803       Ops.push_back(getRoot()); // inchain
2804       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2805       Ops.push_back(
2806           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2807                                 TLI.getPointerTy(DAG.getDataLayout())));
2808       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2809       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2810       break;
2811     }
2812     }
2813   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2814     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2815     // Eventually we will support lowering the @llvm.experimental.deoptimize
2816     // intrinsic, and right now there are no plans to support other intrinsics
2817     // with deopt state.
2818     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2819   } else {
2820     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2821   }
2822 
2823   // If the value of the invoke is used outside of its defining block, make it
2824   // available as a virtual register.
2825   // We already took care of the exported value for the statepoint instruction
2826   // during call to the LowerStatepoint.
2827   if (!isStatepoint(I)) {
2828     CopyToExportRegsIfNeeded(&I);
2829   }
2830 
2831   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2832   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2833   BranchProbability EHPadBBProb =
2834       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2835           : BranchProbability::getZero();
2836   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2837 
2838   // Update successor info.
2839   addSuccessorWithProb(InvokeMBB, Return);
2840   for (auto &UnwindDest : UnwindDests) {
2841     UnwindDest.first->setIsEHPad();
2842     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2843   }
2844   InvokeMBB->normalizeSuccProbs();
2845 
2846   // Drop into normal successor.
2847   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2848                           DAG.getBasicBlock(Return)));
2849 }
2850 
2851 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2852   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2853 
2854   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2855   // have to do anything here to lower funclet bundles.
2856   assert(!I.hasOperandBundlesOtherThan(
2857              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2858          "Cannot lower callbrs with arbitrary operand bundles yet!");
2859 
2860   assert(isa<InlineAsm>(I.getCalledValue()) &&
2861          "Only know how to handle inlineasm callbr");
2862   visitInlineAsm(&I);
2863   CopyToExportRegsIfNeeded(&I);
2864 
2865   // Retrieve successors.
2866   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2867   Return->setInlineAsmBrDefaultTarget();
2868 
2869   // Update successor info.
2870   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2871   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2872     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2873     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2874     CallBrMBB->addInlineAsmBrIndirectTarget(Target);
2875   }
2876   CallBrMBB->normalizeSuccProbs();
2877 
2878   // Drop into default successor.
2879   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2880                           MVT::Other, getControlRoot(),
2881                           DAG.getBasicBlock(Return)));
2882 }
2883 
2884 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2885   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2886 }
2887 
2888 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2889   assert(FuncInfo.MBB->isEHPad() &&
2890          "Call to landingpad not in landing pad!");
2891 
2892   // If there aren't registers to copy the values into (e.g., during SjLj
2893   // exceptions), then don't bother to create these DAG nodes.
2894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2895   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2896   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2897       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2898     return;
2899 
2900   // If landingpad's return type is token type, we don't create DAG nodes
2901   // for its exception pointer and selector value. The extraction of exception
2902   // pointer or selector value from token type landingpads is not currently
2903   // supported.
2904   if (LP.getType()->isTokenTy())
2905     return;
2906 
2907   SmallVector<EVT, 2> ValueVTs;
2908   SDLoc dl = getCurSDLoc();
2909   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2910   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2911 
2912   // Get the two live-in registers as SDValues. The physregs have already been
2913   // copied into virtual registers.
2914   SDValue Ops[2];
2915   if (FuncInfo.ExceptionPointerVirtReg) {
2916     Ops[0] = DAG.getZExtOrTrunc(
2917         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2918                            FuncInfo.ExceptionPointerVirtReg,
2919                            TLI.getPointerTy(DAG.getDataLayout())),
2920         dl, ValueVTs[0]);
2921   } else {
2922     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2923   }
2924   Ops[1] = DAG.getZExtOrTrunc(
2925       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2926                          FuncInfo.ExceptionSelectorVirtReg,
2927                          TLI.getPointerTy(DAG.getDataLayout())),
2928       dl, ValueVTs[1]);
2929 
2930   // Merge into one.
2931   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2932                             DAG.getVTList(ValueVTs), Ops);
2933   setValue(&LP, Res);
2934 }
2935 
2936 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2937                                            MachineBasicBlock *Last) {
2938   // Update JTCases.
2939   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2940     if (SL->JTCases[i].first.HeaderBB == First)
2941       SL->JTCases[i].first.HeaderBB = Last;
2942 
2943   // Update BitTestCases.
2944   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2945     if (SL->BitTestCases[i].Parent == First)
2946       SL->BitTestCases[i].Parent = Last;
2947 }
2948 
2949 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2950   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2951 
2952   // Update machine-CFG edges with unique successors.
2953   SmallSet<BasicBlock*, 32> Done;
2954   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2955     BasicBlock *BB = I.getSuccessor(i);
2956     bool Inserted = Done.insert(BB).second;
2957     if (!Inserted)
2958         continue;
2959 
2960     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2961     addSuccessorWithProb(IndirectBrMBB, Succ);
2962   }
2963   IndirectBrMBB->normalizeSuccProbs();
2964 
2965   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2966                           MVT::Other, getControlRoot(),
2967                           getValue(I.getAddress())));
2968 }
2969 
2970 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2971   if (!DAG.getTarget().Options.TrapUnreachable)
2972     return;
2973 
2974   // We may be able to ignore unreachable behind a noreturn call.
2975   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2976     const BasicBlock &BB = *I.getParent();
2977     if (&I != &BB.front()) {
2978       BasicBlock::const_iterator PredI =
2979         std::prev(BasicBlock::const_iterator(&I));
2980       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2981         if (Call->doesNotReturn())
2982           return;
2983       }
2984     }
2985   }
2986 
2987   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2988 }
2989 
2990 void SelectionDAGBuilder::visitFSub(const User &I) {
2991   // -0.0 - X --> fneg
2992   Type *Ty = I.getType();
2993   if (isa<Constant>(I.getOperand(0)) &&
2994       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2995     SDValue Op2 = getValue(I.getOperand(1));
2996     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2997                              Op2.getValueType(), Op2));
2998     return;
2999   }
3000 
3001   visitBinary(I, ISD::FSUB);
3002 }
3003 
3004 /// Checks if the given instruction performs a vector reduction, in which case
3005 /// we have the freedom to alter the elements in the result as long as the
3006 /// reduction of them stays unchanged.
3007 static bool isVectorReductionOp(const User *I) {
3008   const Instruction *Inst = dyn_cast<Instruction>(I);
3009   if (!Inst || !Inst->getType()->isVectorTy())
3010     return false;
3011 
3012   auto OpCode = Inst->getOpcode();
3013   switch (OpCode) {
3014   case Instruction::Add:
3015   case Instruction::Mul:
3016   case Instruction::And:
3017   case Instruction::Or:
3018   case Instruction::Xor:
3019     break;
3020   case Instruction::FAdd:
3021   case Instruction::FMul:
3022     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3023       if (FPOp->getFastMathFlags().isFast())
3024         break;
3025     LLVM_FALLTHROUGH;
3026   default:
3027     return false;
3028   }
3029 
3030   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3031   // Ensure the reduction size is a power of 2.
3032   if (!isPowerOf2_32(ElemNum))
3033     return false;
3034 
3035   unsigned ElemNumToReduce = ElemNum;
3036 
3037   // Do DFS search on the def-use chain from the given instruction. We only
3038   // allow four kinds of operations during the search until we reach the
3039   // instruction that extracts the first element from the vector:
3040   //
3041   //   1. The reduction operation of the same opcode as the given instruction.
3042   //
3043   //   2. PHI node.
3044   //
3045   //   3. ShuffleVector instruction together with a reduction operation that
3046   //      does a partial reduction.
3047   //
3048   //   4. ExtractElement that extracts the first element from the vector, and we
3049   //      stop searching the def-use chain here.
3050   //
3051   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3052   // from 1-3 to the stack to continue the DFS. The given instruction is not
3053   // a reduction operation if we meet any other instructions other than those
3054   // listed above.
3055 
3056   SmallVector<const User *, 16> UsersToVisit{Inst};
3057   SmallPtrSet<const User *, 16> Visited;
3058   bool ReduxExtracted = false;
3059 
3060   while (!UsersToVisit.empty()) {
3061     auto User = UsersToVisit.back();
3062     UsersToVisit.pop_back();
3063     if (!Visited.insert(User).second)
3064       continue;
3065 
3066     for (const auto *U : User->users()) {
3067       auto Inst = dyn_cast<Instruction>(U);
3068       if (!Inst)
3069         return false;
3070 
3071       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3072         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3073           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3074             return false;
3075         UsersToVisit.push_back(U);
3076       } else if (const ShuffleVectorInst *ShufInst =
3077                      dyn_cast<ShuffleVectorInst>(U)) {
3078         // Detect the following pattern: A ShuffleVector instruction together
3079         // with a reduction that do partial reduction on the first and second
3080         // ElemNumToReduce / 2 elements, and store the result in
3081         // ElemNumToReduce / 2 elements in another vector.
3082 
3083         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3084         if (ResultElements < ElemNum)
3085           return false;
3086 
3087         if (ElemNumToReduce == 1)
3088           return false;
3089         if (!isa<UndefValue>(U->getOperand(1)))
3090           return false;
3091         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3092           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3093             return false;
3094         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3095           if (ShufInst->getMaskValue(i) != -1)
3096             return false;
3097 
3098         // There is only one user of this ShuffleVector instruction, which
3099         // must be a reduction operation.
3100         if (!U->hasOneUse())
3101           return false;
3102 
3103         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3104         if (!U2 || U2->getOpcode() != OpCode)
3105           return false;
3106 
3107         // Check operands of the reduction operation.
3108         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3109             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3110           UsersToVisit.push_back(U2);
3111           ElemNumToReduce /= 2;
3112         } else
3113           return false;
3114       } else if (isa<ExtractElementInst>(U)) {
3115         // At this moment we should have reduced all elements in the vector.
3116         if (ElemNumToReduce != 1)
3117           return false;
3118 
3119         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3120         if (!Val || !Val->isZero())
3121           return false;
3122 
3123         ReduxExtracted = true;
3124       } else
3125         return false;
3126     }
3127   }
3128   return ReduxExtracted;
3129 }
3130 
3131 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3132   SDNodeFlags Flags;
3133 
3134   SDValue Op = getValue(I.getOperand(0));
3135   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3136                                     Op, Flags);
3137   setValue(&I, UnNodeValue);
3138 }
3139 
3140 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3141   SDNodeFlags Flags;
3142   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3143     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3144     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3145   }
3146   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3147     Flags.setExact(ExactOp->isExact());
3148   }
3149   if (isVectorReductionOp(&I)) {
3150     Flags.setVectorReduction(true);
3151     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3152 
3153     // If no flags are set we will propagate the incoming flags, if any flags
3154     // are set, we will intersect them with the incoming flag and so we need to
3155     // copy the FMF flags here.
3156     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3157       Flags.copyFMF(*FPOp);
3158     }
3159   }
3160 
3161   SDValue Op1 = getValue(I.getOperand(0));
3162   SDValue Op2 = getValue(I.getOperand(1));
3163   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3164                                      Op1, Op2, Flags);
3165   setValue(&I, BinNodeValue);
3166 }
3167 
3168 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3169   SDValue Op1 = getValue(I.getOperand(0));
3170   SDValue Op2 = getValue(I.getOperand(1));
3171 
3172   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3173       Op1.getValueType(), DAG.getDataLayout());
3174 
3175   // Coerce the shift amount to the right type if we can.
3176   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3177     unsigned ShiftSize = ShiftTy.getSizeInBits();
3178     unsigned Op2Size = Op2.getValueSizeInBits();
3179     SDLoc DL = getCurSDLoc();
3180 
3181     // If the operand is smaller than the shift count type, promote it.
3182     if (ShiftSize > Op2Size)
3183       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3184 
3185     // If the operand is larger than the shift count type but the shift
3186     // count type has enough bits to represent any shift value, truncate
3187     // it now. This is a common case and it exposes the truncate to
3188     // optimization early.
3189     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3190       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3191     // Otherwise we'll need to temporarily settle for some other convenient
3192     // type.  Type legalization will make adjustments once the shiftee is split.
3193     else
3194       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3195   }
3196 
3197   bool nuw = false;
3198   bool nsw = false;
3199   bool exact = false;
3200 
3201   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3202 
3203     if (const OverflowingBinaryOperator *OFBinOp =
3204             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3205       nuw = OFBinOp->hasNoUnsignedWrap();
3206       nsw = OFBinOp->hasNoSignedWrap();
3207     }
3208     if (const PossiblyExactOperator *ExactOp =
3209             dyn_cast<const PossiblyExactOperator>(&I))
3210       exact = ExactOp->isExact();
3211   }
3212   SDNodeFlags Flags;
3213   Flags.setExact(exact);
3214   Flags.setNoSignedWrap(nsw);
3215   Flags.setNoUnsignedWrap(nuw);
3216   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3217                             Flags);
3218   setValue(&I, Res);
3219 }
3220 
3221 void SelectionDAGBuilder::visitSDiv(const User &I) {
3222   SDValue Op1 = getValue(I.getOperand(0));
3223   SDValue Op2 = getValue(I.getOperand(1));
3224 
3225   SDNodeFlags Flags;
3226   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3227                  cast<PossiblyExactOperator>(&I)->isExact());
3228   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3229                            Op2, Flags));
3230 }
3231 
3232 void SelectionDAGBuilder::visitICmp(const User &I) {
3233   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3234   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3235     predicate = IC->getPredicate();
3236   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3237     predicate = ICmpInst::Predicate(IC->getPredicate());
3238   SDValue Op1 = getValue(I.getOperand(0));
3239   SDValue Op2 = getValue(I.getOperand(1));
3240   ISD::CondCode Opcode = getICmpCondCode(predicate);
3241 
3242   auto &TLI = DAG.getTargetLoweringInfo();
3243   EVT MemVT =
3244       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3245 
3246   // If a pointer's DAG type is larger than its memory type then the DAG values
3247   // are zero-extended. This breaks signed comparisons so truncate back to the
3248   // underlying type before doing the compare.
3249   if (Op1.getValueType() != MemVT) {
3250     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3251     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3252   }
3253 
3254   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3255                                                         I.getType());
3256   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3257 }
3258 
3259 void SelectionDAGBuilder::visitFCmp(const User &I) {
3260   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3261   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3262     predicate = FC->getPredicate();
3263   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3264     predicate = FCmpInst::Predicate(FC->getPredicate());
3265   SDValue Op1 = getValue(I.getOperand(0));
3266   SDValue Op2 = getValue(I.getOperand(1));
3267 
3268   ISD::CondCode Condition = getFCmpCondCode(predicate);
3269   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3270   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3271     Condition = getFCmpCodeWithoutNaN(Condition);
3272 
3273   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3274                                                         I.getType());
3275   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3276 }
3277 
3278 // Check if the condition of the select has one use or two users that are both
3279 // selects with the same condition.
3280 static bool hasOnlySelectUsers(const Value *Cond) {
3281   return llvm::all_of(Cond->users(), [](const Value *V) {
3282     return isa<SelectInst>(V);
3283   });
3284 }
3285 
3286 void SelectionDAGBuilder::visitSelect(const User &I) {
3287   SmallVector<EVT, 4> ValueVTs;
3288   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3289                   ValueVTs);
3290   unsigned NumValues = ValueVTs.size();
3291   if (NumValues == 0) return;
3292 
3293   SmallVector<SDValue, 4> Values(NumValues);
3294   SDValue Cond     = getValue(I.getOperand(0));
3295   SDValue LHSVal   = getValue(I.getOperand(1));
3296   SDValue RHSVal   = getValue(I.getOperand(2));
3297   SmallVector<SDValue, 1> BaseOps(1, Cond);
3298   ISD::NodeType OpCode =
3299       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3300 
3301   bool IsUnaryAbs = false;
3302 
3303   // Min/max matching is only viable if all output VTs are the same.
3304   if (is_splat(ValueVTs)) {
3305     EVT VT = ValueVTs[0];
3306     LLVMContext &Ctx = *DAG.getContext();
3307     auto &TLI = DAG.getTargetLoweringInfo();
3308 
3309     // We care about the legality of the operation after it has been type
3310     // legalized.
3311     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3312       VT = TLI.getTypeToTransformTo(Ctx, VT);
3313 
3314     // If the vselect is legal, assume we want to leave this as a vector setcc +
3315     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3316     // min/max is legal on the scalar type.
3317     bool UseScalarMinMax = VT.isVector() &&
3318       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3319 
3320     Value *LHS, *RHS;
3321     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3322     ISD::NodeType Opc = ISD::DELETED_NODE;
3323     switch (SPR.Flavor) {
3324     case SPF_UMAX:    Opc = ISD::UMAX; break;
3325     case SPF_UMIN:    Opc = ISD::UMIN; break;
3326     case SPF_SMAX:    Opc = ISD::SMAX; break;
3327     case SPF_SMIN:    Opc = ISD::SMIN; break;
3328     case SPF_FMINNUM:
3329       switch (SPR.NaNBehavior) {
3330       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3331       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3332       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3333       case SPNB_RETURNS_ANY: {
3334         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3335           Opc = ISD::FMINNUM;
3336         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3337           Opc = ISD::FMINIMUM;
3338         else if (UseScalarMinMax)
3339           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3340             ISD::FMINNUM : ISD::FMINIMUM;
3341         break;
3342       }
3343       }
3344       break;
3345     case SPF_FMAXNUM:
3346       switch (SPR.NaNBehavior) {
3347       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3348       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3349       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3350       case SPNB_RETURNS_ANY:
3351 
3352         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3353           Opc = ISD::FMAXNUM;
3354         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3355           Opc = ISD::FMAXIMUM;
3356         else if (UseScalarMinMax)
3357           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3358             ISD::FMAXNUM : ISD::FMAXIMUM;
3359         break;
3360       }
3361       break;
3362     case SPF_ABS:
3363       IsUnaryAbs = true;
3364       Opc = ISD::ABS;
3365       break;
3366     case SPF_NABS:
3367       // TODO: we need to produce sub(0, abs(X)).
3368     default: break;
3369     }
3370 
3371     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3372         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3373          (UseScalarMinMax &&
3374           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3375         // If the underlying comparison instruction is used by any other
3376         // instruction, the consumed instructions won't be destroyed, so it is
3377         // not profitable to convert to a min/max.
3378         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3379       OpCode = Opc;
3380       LHSVal = getValue(LHS);
3381       RHSVal = getValue(RHS);
3382       BaseOps.clear();
3383     }
3384 
3385     if (IsUnaryAbs) {
3386       OpCode = Opc;
3387       LHSVal = getValue(LHS);
3388       BaseOps.clear();
3389     }
3390   }
3391 
3392   if (IsUnaryAbs) {
3393     for (unsigned i = 0; i != NumValues; ++i) {
3394       Values[i] =
3395           DAG.getNode(OpCode, getCurSDLoc(),
3396                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3397                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3398     }
3399   } else {
3400     for (unsigned i = 0; i != NumValues; ++i) {
3401       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3402       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3403       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3404       Values[i] = DAG.getNode(
3405           OpCode, getCurSDLoc(),
3406           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3407     }
3408   }
3409 
3410   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3411                            DAG.getVTList(ValueVTs), Values));
3412 }
3413 
3414 void SelectionDAGBuilder::visitTrunc(const User &I) {
3415   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3416   SDValue N = getValue(I.getOperand(0));
3417   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3418                                                         I.getType());
3419   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3420 }
3421 
3422 void SelectionDAGBuilder::visitZExt(const User &I) {
3423   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3424   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3425   SDValue N = getValue(I.getOperand(0));
3426   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3427                                                         I.getType());
3428   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3429 }
3430 
3431 void SelectionDAGBuilder::visitSExt(const User &I) {
3432   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3433   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3434   SDValue N = getValue(I.getOperand(0));
3435   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3436                                                         I.getType());
3437   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3441   // FPTrunc is never a no-op cast, no need to check
3442   SDValue N = getValue(I.getOperand(0));
3443   SDLoc dl = getCurSDLoc();
3444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3445   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3446   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3447                            DAG.getTargetConstant(
3448                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3449 }
3450 
3451 void SelectionDAGBuilder::visitFPExt(const User &I) {
3452   // FPExt is never a no-op cast, no need to check
3453   SDValue N = getValue(I.getOperand(0));
3454   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3455                                                         I.getType());
3456   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3457 }
3458 
3459 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3460   // FPToUI is never a no-op cast, no need to check
3461   SDValue N = getValue(I.getOperand(0));
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3465 }
3466 
3467 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3468   // FPToSI is never a no-op cast, no need to check
3469   SDValue N = getValue(I.getOperand(0));
3470   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3471                                                         I.getType());
3472   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3473 }
3474 
3475 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3476   // UIToFP is never a no-op cast, no need to check
3477   SDValue N = getValue(I.getOperand(0));
3478   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3479                                                         I.getType());
3480   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3481 }
3482 
3483 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3484   // SIToFP is never a no-op cast, no need to check
3485   SDValue N = getValue(I.getOperand(0));
3486   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3487                                                         I.getType());
3488   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3489 }
3490 
3491 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3492   // What to do depends on the size of the integer and the size of the pointer.
3493   // We can either truncate, zero extend, or no-op, accordingly.
3494   SDValue N = getValue(I.getOperand(0));
3495   auto &TLI = DAG.getTargetLoweringInfo();
3496   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3497                                                         I.getType());
3498   EVT PtrMemVT =
3499       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3500   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3501   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3502   setValue(&I, N);
3503 }
3504 
3505 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3506   // What to do depends on the size of the integer and the size of the pointer.
3507   // We can either truncate, zero extend, or no-op, accordingly.
3508   SDValue N = getValue(I.getOperand(0));
3509   auto &TLI = DAG.getTargetLoweringInfo();
3510   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3511   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3512   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3513   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3514   setValue(&I, N);
3515 }
3516 
3517 void SelectionDAGBuilder::visitBitCast(const User &I) {
3518   SDValue N = getValue(I.getOperand(0));
3519   SDLoc dl = getCurSDLoc();
3520   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3521                                                         I.getType());
3522 
3523   // BitCast assures us that source and destination are the same size so this is
3524   // either a BITCAST or a no-op.
3525   if (DestVT != N.getValueType())
3526     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3527                              DestVT, N)); // convert types.
3528   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3529   // might fold any kind of constant expression to an integer constant and that
3530   // is not what we are looking for. Only recognize a bitcast of a genuine
3531   // constant integer as an opaque constant.
3532   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3533     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3534                                  /*isOpaque*/true));
3535   else
3536     setValue(&I, N);            // noop cast.
3537 }
3538 
3539 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3541   const Value *SV = I.getOperand(0);
3542   SDValue N = getValue(SV);
3543   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3544 
3545   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3546   unsigned DestAS = I.getType()->getPointerAddressSpace();
3547 
3548   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3549     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3550 
3551   setValue(&I, N);
3552 }
3553 
3554 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3556   SDValue InVec = getValue(I.getOperand(0));
3557   SDValue InVal = getValue(I.getOperand(1));
3558   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3559                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3560   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3561                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3562                            InVec, InVal, InIdx));
3563 }
3564 
3565 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3567   SDValue InVec = getValue(I.getOperand(0));
3568   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3569                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3570   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3571                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3572                            InVec, InIdx));
3573 }
3574 
3575 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3576   SDValue Src1 = getValue(I.getOperand(0));
3577   SDValue Src2 = getValue(I.getOperand(1));
3578   Constant *MaskV = cast<Constant>(I.getOperand(2));
3579   SDLoc DL = getCurSDLoc();
3580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3581   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3582   EVT SrcVT = Src1.getValueType();
3583   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3584 
3585   if (MaskV->isNullValue() && VT.isScalableVector()) {
3586     // Canonical splat form of first element of first input vector.
3587     SDValue FirstElt =
3588         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3589                     DAG.getVectorIdxConstant(0, DL));
3590     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3591     return;
3592   }
3593 
3594   // For now, we only handle splats for scalable vectors.
3595   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3596   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3597   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3598 
3599   SmallVector<int, 8> Mask;
3600   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3601   unsigned MaskNumElts = Mask.size();
3602 
3603   if (SrcNumElts == MaskNumElts) {
3604     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3605     return;
3606   }
3607 
3608   // Normalize the shuffle vector since mask and vector length don't match.
3609   if (SrcNumElts < MaskNumElts) {
3610     // Mask is longer than the source vectors. We can use concatenate vector to
3611     // make the mask and vectors lengths match.
3612 
3613     if (MaskNumElts % SrcNumElts == 0) {
3614       // Mask length is a multiple of the source vector length.
3615       // Check if the shuffle is some kind of concatenation of the input
3616       // vectors.
3617       unsigned NumConcat = MaskNumElts / SrcNumElts;
3618       bool IsConcat = true;
3619       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3620       for (unsigned i = 0; i != MaskNumElts; ++i) {
3621         int Idx = Mask[i];
3622         if (Idx < 0)
3623           continue;
3624         // Ensure the indices in each SrcVT sized piece are sequential and that
3625         // the same source is used for the whole piece.
3626         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3627             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3628              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3629           IsConcat = false;
3630           break;
3631         }
3632         // Remember which source this index came from.
3633         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3634       }
3635 
3636       // The shuffle is concatenating multiple vectors together. Just emit
3637       // a CONCAT_VECTORS operation.
3638       if (IsConcat) {
3639         SmallVector<SDValue, 8> ConcatOps;
3640         for (auto Src : ConcatSrcs) {
3641           if (Src < 0)
3642             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3643           else if (Src == 0)
3644             ConcatOps.push_back(Src1);
3645           else
3646             ConcatOps.push_back(Src2);
3647         }
3648         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3649         return;
3650       }
3651     }
3652 
3653     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3654     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3655     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3656                                     PaddedMaskNumElts);
3657 
3658     // Pad both vectors with undefs to make them the same length as the mask.
3659     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3660 
3661     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3662     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3663     MOps1[0] = Src1;
3664     MOps2[0] = Src2;
3665 
3666     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3667     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3668 
3669     // Readjust mask for new input vector length.
3670     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3671     for (unsigned i = 0; i != MaskNumElts; ++i) {
3672       int Idx = Mask[i];
3673       if (Idx >= (int)SrcNumElts)
3674         Idx -= SrcNumElts - PaddedMaskNumElts;
3675       MappedOps[i] = Idx;
3676     }
3677 
3678     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3679 
3680     // If the concatenated vector was padded, extract a subvector with the
3681     // correct number of elements.
3682     if (MaskNumElts != PaddedMaskNumElts)
3683       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3684                            DAG.getVectorIdxConstant(0, DL));
3685 
3686     setValue(&I, Result);
3687     return;
3688   }
3689 
3690   if (SrcNumElts > MaskNumElts) {
3691     // Analyze the access pattern of the vector to see if we can extract
3692     // two subvectors and do the shuffle.
3693     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3694     bool CanExtract = true;
3695     for (int Idx : Mask) {
3696       unsigned Input = 0;
3697       if (Idx < 0)
3698         continue;
3699 
3700       if (Idx >= (int)SrcNumElts) {
3701         Input = 1;
3702         Idx -= SrcNumElts;
3703       }
3704 
3705       // If all the indices come from the same MaskNumElts sized portion of
3706       // the sources we can use extract. Also make sure the extract wouldn't
3707       // extract past the end of the source.
3708       int NewStartIdx = alignDown(Idx, MaskNumElts);
3709       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3710           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3711         CanExtract = false;
3712       // Make sure we always update StartIdx as we use it to track if all
3713       // elements are undef.
3714       StartIdx[Input] = NewStartIdx;
3715     }
3716 
3717     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3718       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3719       return;
3720     }
3721     if (CanExtract) {
3722       // Extract appropriate subvector and generate a vector shuffle
3723       for (unsigned Input = 0; Input < 2; ++Input) {
3724         SDValue &Src = Input == 0 ? Src1 : Src2;
3725         if (StartIdx[Input] < 0)
3726           Src = DAG.getUNDEF(VT);
3727         else {
3728           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3729                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3730         }
3731       }
3732 
3733       // Calculate new mask.
3734       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3735       for (int &Idx : MappedOps) {
3736         if (Idx >= (int)SrcNumElts)
3737           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3738         else if (Idx >= 0)
3739           Idx -= StartIdx[0];
3740       }
3741 
3742       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3743       return;
3744     }
3745   }
3746 
3747   // We can't use either concat vectors or extract subvectors so fall back to
3748   // replacing the shuffle with extract and build vector.
3749   // to insert and build vector.
3750   EVT EltVT = VT.getVectorElementType();
3751   SmallVector<SDValue,8> Ops;
3752   for (int Idx : Mask) {
3753     SDValue Res;
3754 
3755     if (Idx < 0) {
3756       Res = DAG.getUNDEF(EltVT);
3757     } else {
3758       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3759       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3760 
3761       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3762                         DAG.getVectorIdxConstant(Idx, DL));
3763     }
3764 
3765     Ops.push_back(Res);
3766   }
3767 
3768   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3769 }
3770 
3771 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3772   ArrayRef<unsigned> Indices;
3773   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3774     Indices = IV->getIndices();
3775   else
3776     Indices = cast<ConstantExpr>(&I)->getIndices();
3777 
3778   const Value *Op0 = I.getOperand(0);
3779   const Value *Op1 = I.getOperand(1);
3780   Type *AggTy = I.getType();
3781   Type *ValTy = Op1->getType();
3782   bool IntoUndef = isa<UndefValue>(Op0);
3783   bool FromUndef = isa<UndefValue>(Op1);
3784 
3785   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3786 
3787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3788   SmallVector<EVT, 4> AggValueVTs;
3789   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3790   SmallVector<EVT, 4> ValValueVTs;
3791   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3792 
3793   unsigned NumAggValues = AggValueVTs.size();
3794   unsigned NumValValues = ValValueVTs.size();
3795   SmallVector<SDValue, 4> Values(NumAggValues);
3796 
3797   // Ignore an insertvalue that produces an empty object
3798   if (!NumAggValues) {
3799     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3800     return;
3801   }
3802 
3803   SDValue Agg = getValue(Op0);
3804   unsigned i = 0;
3805   // Copy the beginning value(s) from the original aggregate.
3806   for (; i != LinearIndex; ++i)
3807     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3808                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3809   // Copy values from the inserted value(s).
3810   if (NumValValues) {
3811     SDValue Val = getValue(Op1);
3812     for (; i != LinearIndex + NumValValues; ++i)
3813       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3814                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3815   }
3816   // Copy remaining value(s) from the original aggregate.
3817   for (; i != NumAggValues; ++i)
3818     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3819                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3820 
3821   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3822                            DAG.getVTList(AggValueVTs), Values));
3823 }
3824 
3825 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3826   ArrayRef<unsigned> Indices;
3827   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3828     Indices = EV->getIndices();
3829   else
3830     Indices = cast<ConstantExpr>(&I)->getIndices();
3831 
3832   const Value *Op0 = I.getOperand(0);
3833   Type *AggTy = Op0->getType();
3834   Type *ValTy = I.getType();
3835   bool OutOfUndef = isa<UndefValue>(Op0);
3836 
3837   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3838 
3839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3840   SmallVector<EVT, 4> ValValueVTs;
3841   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3842 
3843   unsigned NumValValues = ValValueVTs.size();
3844 
3845   // Ignore a extractvalue that produces an empty object
3846   if (!NumValValues) {
3847     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3848     return;
3849   }
3850 
3851   SmallVector<SDValue, 4> Values(NumValValues);
3852 
3853   SDValue Agg = getValue(Op0);
3854   // Copy out the selected value(s).
3855   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3856     Values[i - LinearIndex] =
3857       OutOfUndef ?
3858         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3859         SDValue(Agg.getNode(), Agg.getResNo() + i);
3860 
3861   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3862                            DAG.getVTList(ValValueVTs), Values));
3863 }
3864 
3865 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3866   Value *Op0 = I.getOperand(0);
3867   // Note that the pointer operand may be a vector of pointers. Take the scalar
3868   // element which holds a pointer.
3869   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3870   SDValue N = getValue(Op0);
3871   SDLoc dl = getCurSDLoc();
3872   auto &TLI = DAG.getTargetLoweringInfo();
3873   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3874   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3875 
3876   // Normalize Vector GEP - all scalar operands should be converted to the
3877   // splat vector.
3878   bool IsVectorGEP = I.getType()->isVectorTy();
3879   ElementCount VectorElementCount = IsVectorGEP ?
3880     I.getType()->getVectorElementCount() : ElementCount(0, false);
3881 
3882   if (IsVectorGEP && !N.getValueType().isVector()) {
3883     LLVMContext &Context = *DAG.getContext();
3884     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3885     if (VectorElementCount.Scalable)
3886       N = DAG.getSplatVector(VT, dl, N);
3887     else
3888       N = DAG.getSplatBuildVector(VT, dl, N);
3889   }
3890 
3891   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3892        GTI != E; ++GTI) {
3893     const Value *Idx = GTI.getOperand();
3894     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3895       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3896       if (Field) {
3897         // N = N + Offset
3898         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3899 
3900         // In an inbounds GEP with an offset that is nonnegative even when
3901         // interpreted as signed, assume there is no unsigned overflow.
3902         SDNodeFlags Flags;
3903         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3904           Flags.setNoUnsignedWrap(true);
3905 
3906         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3907                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3908       }
3909     } else {
3910       // IdxSize is the width of the arithmetic according to IR semantics.
3911       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3912       // (and fix up the result later).
3913       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3914       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3915       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3916       // We intentionally mask away the high bits here; ElementSize may not
3917       // fit in IdxTy.
3918       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3919       bool ElementScalable = ElementSize.isScalable();
3920 
3921       // If this is a scalar constant or a splat vector of constants,
3922       // handle it quickly.
3923       const auto *C = dyn_cast<Constant>(Idx);
3924       if (C && isa<VectorType>(C->getType()))
3925         C = C->getSplatValue();
3926 
3927       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3928       if (CI && CI->isZero())
3929         continue;
3930       if (CI && !ElementScalable) {
3931         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3932         LLVMContext &Context = *DAG.getContext();
3933         SDValue OffsVal;
3934         if (IsVectorGEP)
3935           OffsVal = DAG.getConstant(
3936               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3937         else
3938           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3939 
3940         // In an inbounds GEP with an offset that is nonnegative even when
3941         // interpreted as signed, assume there is no unsigned overflow.
3942         SDNodeFlags Flags;
3943         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3944           Flags.setNoUnsignedWrap(true);
3945 
3946         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3947 
3948         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3949         continue;
3950       }
3951 
3952       // N = N + Idx * ElementMul;
3953       SDValue IdxN = getValue(Idx);
3954 
3955       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3956         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3957                                   VectorElementCount);
3958         if (VectorElementCount.Scalable)
3959           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3960         else
3961           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3962       }
3963 
3964       // If the index is smaller or larger than intptr_t, truncate or extend
3965       // it.
3966       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3967 
3968       if (ElementScalable) {
3969         EVT VScaleTy = N.getValueType().getScalarType();
3970         SDValue VScale = DAG.getNode(
3971             ISD::VSCALE, dl, VScaleTy,
3972             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3973         if (IsVectorGEP)
3974           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3975         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3976       } else {
3977         // If this is a multiply by a power of two, turn it into a shl
3978         // immediately.  This is a very common case.
3979         if (ElementMul != 1) {
3980           if (ElementMul.isPowerOf2()) {
3981             unsigned Amt = ElementMul.logBase2();
3982             IdxN = DAG.getNode(ISD::SHL, dl,
3983                                N.getValueType(), IdxN,
3984                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3985           } else {
3986             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3987                                             IdxN.getValueType());
3988             IdxN = DAG.getNode(ISD::MUL, dl,
3989                                N.getValueType(), IdxN, Scale);
3990           }
3991         }
3992       }
3993 
3994       N = DAG.getNode(ISD::ADD, dl,
3995                       N.getValueType(), N, IdxN);
3996     }
3997   }
3998 
3999   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4000     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4001 
4002   setValue(&I, N);
4003 }
4004 
4005 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4006   // If this is a fixed sized alloca in the entry block of the function,
4007   // allocate it statically on the stack.
4008   if (FuncInfo.StaticAllocaMap.count(&I))
4009     return;   // getValue will auto-populate this.
4010 
4011   SDLoc dl = getCurSDLoc();
4012   Type *Ty = I.getAllocatedType();
4013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4014   auto &DL = DAG.getDataLayout();
4015   uint64_t TySize = DL.getTypeAllocSize(Ty);
4016   unsigned Align =
4017       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
4018 
4019   SDValue AllocSize = getValue(I.getArraySize());
4020 
4021   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4022   if (AllocSize.getValueType() != IntPtr)
4023     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4024 
4025   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4026                           AllocSize,
4027                           DAG.getConstant(TySize, dl, IntPtr));
4028 
4029   // Handle alignment.  If the requested alignment is less than or equal to
4030   // the stack alignment, ignore it.  If the size is greater than or equal to
4031   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4032   unsigned StackAlign =
4033       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4034   if (Align <= StackAlign)
4035     Align = 0;
4036 
4037   // Round the size of the allocation up to the stack alignment size
4038   // by add SA-1 to the size. This doesn't overflow because we're computing
4039   // an address inside an alloca.
4040   SDNodeFlags Flags;
4041   Flags.setNoUnsignedWrap(true);
4042   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4043                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4044 
4045   // Mask out the low bits for alignment purposes.
4046   AllocSize =
4047       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4048                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4049 
4050   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4051   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4052   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4053   setValue(&I, DSA);
4054   DAG.setRoot(DSA.getValue(1));
4055 
4056   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4057 }
4058 
4059 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4060   if (I.isAtomic())
4061     return visitAtomicLoad(I);
4062 
4063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4064   const Value *SV = I.getOperand(0);
4065   if (TLI.supportSwiftError()) {
4066     // Swifterror values can come from either a function parameter with
4067     // swifterror attribute or an alloca with swifterror attribute.
4068     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4069       if (Arg->hasSwiftErrorAttr())
4070         return visitLoadFromSwiftError(I);
4071     }
4072 
4073     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4074       if (Alloca->isSwiftError())
4075         return visitLoadFromSwiftError(I);
4076     }
4077   }
4078 
4079   SDValue Ptr = getValue(SV);
4080 
4081   Type *Ty = I.getType();
4082   unsigned Alignment = I.getAlignment();
4083 
4084   AAMDNodes AAInfo;
4085   I.getAAMetadata(AAInfo);
4086   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4087 
4088   SmallVector<EVT, 4> ValueVTs, MemVTs;
4089   SmallVector<uint64_t, 4> Offsets;
4090   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4091   unsigned NumValues = ValueVTs.size();
4092   if (NumValues == 0)
4093     return;
4094 
4095   bool isVolatile = I.isVolatile();
4096 
4097   SDValue Root;
4098   bool ConstantMemory = false;
4099   if (isVolatile)
4100     // Serialize volatile loads with other side effects.
4101     Root = getRoot();
4102   else if (NumValues > MaxParallelChains)
4103     Root = getMemoryRoot();
4104   else if (AA &&
4105            AA->pointsToConstantMemory(MemoryLocation(
4106                SV,
4107                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4108                AAInfo))) {
4109     // Do not serialize (non-volatile) loads of constant memory with anything.
4110     Root = DAG.getEntryNode();
4111     ConstantMemory = true;
4112   } else {
4113     // Do not serialize non-volatile loads against each other.
4114     Root = DAG.getRoot();
4115   }
4116 
4117   SDLoc dl = getCurSDLoc();
4118 
4119   if (isVolatile)
4120     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4121 
4122   // An aggregate load cannot wrap around the address space, so offsets to its
4123   // parts don't wrap either.
4124   SDNodeFlags Flags;
4125   Flags.setNoUnsignedWrap(true);
4126 
4127   SmallVector<SDValue, 4> Values(NumValues);
4128   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4129   EVT PtrVT = Ptr.getValueType();
4130 
4131   MachineMemOperand::Flags MMOFlags
4132     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4133 
4134   unsigned ChainI = 0;
4135   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4136     // Serializing loads here may result in excessive register pressure, and
4137     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4138     // could recover a bit by hoisting nodes upward in the chain by recognizing
4139     // they are side-effect free or do not alias. The optimizer should really
4140     // avoid this case by converting large object/array copies to llvm.memcpy
4141     // (MaxParallelChains should always remain as failsafe).
4142     if (ChainI == MaxParallelChains) {
4143       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4144       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4145                                   makeArrayRef(Chains.data(), ChainI));
4146       Root = Chain;
4147       ChainI = 0;
4148     }
4149     SDValue A = DAG.getNode(ISD::ADD, dl,
4150                             PtrVT, Ptr,
4151                             DAG.getConstant(Offsets[i], dl, PtrVT),
4152                             Flags);
4153 
4154     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4155                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4156                             MMOFlags, AAInfo, Ranges);
4157     Chains[ChainI] = L.getValue(1);
4158 
4159     if (MemVTs[i] != ValueVTs[i])
4160       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4161 
4162     Values[i] = L;
4163   }
4164 
4165   if (!ConstantMemory) {
4166     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4167                                 makeArrayRef(Chains.data(), ChainI));
4168     if (isVolatile)
4169       DAG.setRoot(Chain);
4170     else
4171       PendingLoads.push_back(Chain);
4172   }
4173 
4174   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4175                            DAG.getVTList(ValueVTs), Values));
4176 }
4177 
4178 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4179   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4180          "call visitStoreToSwiftError when backend supports swifterror");
4181 
4182   SmallVector<EVT, 4> ValueVTs;
4183   SmallVector<uint64_t, 4> Offsets;
4184   const Value *SrcV = I.getOperand(0);
4185   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4186                   SrcV->getType(), ValueVTs, &Offsets);
4187   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4188          "expect a single EVT for swifterror");
4189 
4190   SDValue Src = getValue(SrcV);
4191   // Create a virtual register, then update the virtual register.
4192   Register VReg =
4193       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4194   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4195   // Chain can be getRoot or getControlRoot.
4196   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4197                                       SDValue(Src.getNode(), Src.getResNo()));
4198   DAG.setRoot(CopyNode);
4199 }
4200 
4201 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4202   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4203          "call visitLoadFromSwiftError when backend supports swifterror");
4204 
4205   assert(!I.isVolatile() &&
4206          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4207          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4208          "Support volatile, non temporal, invariant for load_from_swift_error");
4209 
4210   const Value *SV = I.getOperand(0);
4211   Type *Ty = I.getType();
4212   AAMDNodes AAInfo;
4213   I.getAAMetadata(AAInfo);
4214   assert(
4215       (!AA ||
4216        !AA->pointsToConstantMemory(MemoryLocation(
4217            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4218            AAInfo))) &&
4219       "load_from_swift_error should not be constant memory");
4220 
4221   SmallVector<EVT, 4> ValueVTs;
4222   SmallVector<uint64_t, 4> Offsets;
4223   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4224                   ValueVTs, &Offsets);
4225   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4226          "expect a single EVT for swifterror");
4227 
4228   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4229   SDValue L = DAG.getCopyFromReg(
4230       getRoot(), getCurSDLoc(),
4231       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4232 
4233   setValue(&I, L);
4234 }
4235 
4236 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4237   if (I.isAtomic())
4238     return visitAtomicStore(I);
4239 
4240   const Value *SrcV = I.getOperand(0);
4241   const Value *PtrV = I.getOperand(1);
4242 
4243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4244   if (TLI.supportSwiftError()) {
4245     // Swifterror values can come from either a function parameter with
4246     // swifterror attribute or an alloca with swifterror attribute.
4247     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4248       if (Arg->hasSwiftErrorAttr())
4249         return visitStoreToSwiftError(I);
4250     }
4251 
4252     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4253       if (Alloca->isSwiftError())
4254         return visitStoreToSwiftError(I);
4255     }
4256   }
4257 
4258   SmallVector<EVT, 4> ValueVTs, MemVTs;
4259   SmallVector<uint64_t, 4> Offsets;
4260   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4261                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4262   unsigned NumValues = ValueVTs.size();
4263   if (NumValues == 0)
4264     return;
4265 
4266   // Get the lowered operands. Note that we do this after
4267   // checking if NumResults is zero, because with zero results
4268   // the operands won't have values in the map.
4269   SDValue Src = getValue(SrcV);
4270   SDValue Ptr = getValue(PtrV);
4271 
4272   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4273   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4274   SDLoc dl = getCurSDLoc();
4275   unsigned Alignment = I.getAlignment();
4276   AAMDNodes AAInfo;
4277   I.getAAMetadata(AAInfo);
4278 
4279   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4280 
4281   // An aggregate load cannot wrap around the address space, so offsets to its
4282   // parts don't wrap either.
4283   SDNodeFlags Flags;
4284   Flags.setNoUnsignedWrap(true);
4285 
4286   unsigned ChainI = 0;
4287   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4288     // See visitLoad comments.
4289     if (ChainI == MaxParallelChains) {
4290       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4291                                   makeArrayRef(Chains.data(), ChainI));
4292       Root = Chain;
4293       ChainI = 0;
4294     }
4295     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4296     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4297     if (MemVTs[i] != ValueVTs[i])
4298       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4299     SDValue St =
4300         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4301                      Alignment, MMOFlags, AAInfo);
4302     Chains[ChainI] = St;
4303   }
4304 
4305   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4306                                   makeArrayRef(Chains.data(), ChainI));
4307   DAG.setRoot(StoreNode);
4308 }
4309 
4310 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4311                                            bool IsCompressing) {
4312   SDLoc sdl = getCurSDLoc();
4313 
4314   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4315                            unsigned& Alignment) {
4316     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4317     Src0 = I.getArgOperand(0);
4318     Ptr = I.getArgOperand(1);
4319     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4320     Mask = I.getArgOperand(3);
4321   };
4322   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4323                            unsigned& Alignment) {
4324     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4325     Src0 = I.getArgOperand(0);
4326     Ptr = I.getArgOperand(1);
4327     Mask = I.getArgOperand(2);
4328     Alignment = 0;
4329   };
4330 
4331   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4332   unsigned Alignment;
4333   if (IsCompressing)
4334     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4335   else
4336     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4337 
4338   SDValue Ptr = getValue(PtrOperand);
4339   SDValue Src0 = getValue(Src0Operand);
4340   SDValue Mask = getValue(MaskOperand);
4341   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4342 
4343   EVT VT = Src0.getValueType();
4344   if (!Alignment)
4345     Alignment = DAG.getEVTAlignment(VT);
4346 
4347   AAMDNodes AAInfo;
4348   I.getAAMetadata(AAInfo);
4349 
4350   MachineMemOperand *MMO =
4351     DAG.getMachineFunction().
4352     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4353                           MachineMemOperand::MOStore,
4354                           // TODO: Make MachineMemOperands aware of scalable
4355                           // vectors.
4356                           VT.getStoreSize().getKnownMinSize(),
4357                           Alignment, AAInfo);
4358   SDValue StoreNode =
4359       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4360                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4361   DAG.setRoot(StoreNode);
4362   setValue(&I, StoreNode);
4363 }
4364 
4365 // Get a uniform base for the Gather/Scatter intrinsic.
4366 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4367 // We try to represent it as a base pointer + vector of indices.
4368 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4369 // The first operand of the GEP may be a single pointer or a vector of pointers
4370 // Example:
4371 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4372 //  or
4373 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4374 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4375 //
4376 // When the first GEP operand is a single pointer - it is the uniform base we
4377 // are looking for. If first operand of the GEP is a splat vector - we
4378 // extract the splat value and use it as a uniform base.
4379 // In all other cases the function returns 'false'.
4380 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4381                            ISD::MemIndexType &IndexType, SDValue &Scale,
4382                            SelectionDAGBuilder *SDB) {
4383   SelectionDAG& DAG = SDB->DAG;
4384   LLVMContext &Context = *DAG.getContext();
4385 
4386   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4387   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4388   if (!GEP)
4389     return false;
4390 
4391   const Value *GEPPtr = GEP->getPointerOperand();
4392   if (!GEPPtr->getType()->isVectorTy())
4393     Ptr = GEPPtr;
4394   else if (!(Ptr = getSplatValue(GEPPtr)))
4395     return false;
4396 
4397   unsigned FinalIndex = GEP->getNumOperands() - 1;
4398   Value *IndexVal = GEP->getOperand(FinalIndex);
4399   gep_type_iterator GTI = gep_type_begin(*GEP);
4400 
4401   // Ensure all the other indices are 0.
4402   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4403     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4404     if (!C)
4405       return false;
4406     if (isa<VectorType>(C->getType()))
4407       C = C->getSplatValue();
4408     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4409     if (!CI || !CI->isZero())
4410       return false;
4411   }
4412 
4413   // The operands of the GEP may be defined in another basic block.
4414   // In this case we'll not find nodes for the operands.
4415   if (!SDB->findValue(Ptr))
4416     return false;
4417   Constant *C = dyn_cast<Constant>(IndexVal);
4418   if (!C && !SDB->findValue(IndexVal))
4419     return false;
4420 
4421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4422   const DataLayout &DL = DAG.getDataLayout();
4423   StructType *STy = GTI.getStructTypeOrNull();
4424 
4425   if (STy) {
4426     const StructLayout *SL = DL.getStructLayout(STy);
4427     unsigned Field = cast<Constant>(IndexVal)->getUniqueInteger().getZExtValue();
4428     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4429     Index = DAG.getConstant(SL->getElementOffset(Field),
4430                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4431   } else {
4432     Scale = DAG.getTargetConstant(
4433                 DL.getTypeAllocSize(GEP->getResultElementType()),
4434                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4435     Index = SDB->getValue(IndexVal);
4436   }
4437   Base = SDB->getValue(Ptr);
4438   IndexType = ISD::SIGNED_SCALED;
4439 
4440   if (STy || !Index.getValueType().isVector()) {
4441     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4442     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4443     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4444   }
4445   return true;
4446 }
4447 
4448 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4449   SDLoc sdl = getCurSDLoc();
4450 
4451   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4452   const Value *Ptr = I.getArgOperand(1);
4453   SDValue Src0 = getValue(I.getArgOperand(0));
4454   SDValue Mask = getValue(I.getArgOperand(3));
4455   EVT VT = Src0.getValueType();
4456   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4457   if (!Alignment)
4458     Alignment = DAG.getEVTAlignment(VT);
4459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4460 
4461   AAMDNodes AAInfo;
4462   I.getAAMetadata(AAInfo);
4463 
4464   SDValue Base;
4465   SDValue Index;
4466   ISD::MemIndexType IndexType;
4467   SDValue Scale;
4468   const Value *BasePtr = Ptr;
4469   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4470                                     this);
4471 
4472   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4473   MachineMemOperand *MMO = DAG.getMachineFunction().
4474     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4475                          MachineMemOperand::MOStore,
4476                          // TODO: Make MachineMemOperands aware of scalable
4477                          // vectors.
4478                          VT.getStoreSize().getKnownMinSize(),
4479                          Alignment, AAInfo);
4480   if (!UniformBase) {
4481     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4482     Index = getValue(Ptr);
4483     IndexType = ISD::SIGNED_SCALED;
4484     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4485   }
4486   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4487   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4488                                          Ops, MMO, IndexType);
4489   DAG.setRoot(Scatter);
4490   setValue(&I, Scatter);
4491 }
4492 
4493 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4494   SDLoc sdl = getCurSDLoc();
4495 
4496   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4497                            unsigned& Alignment) {
4498     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4499     Ptr = I.getArgOperand(0);
4500     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4501     Mask = I.getArgOperand(2);
4502     Src0 = I.getArgOperand(3);
4503   };
4504   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4505                            unsigned& Alignment) {
4506     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4507     Ptr = I.getArgOperand(0);
4508     Alignment = 0;
4509     Mask = I.getArgOperand(1);
4510     Src0 = I.getArgOperand(2);
4511   };
4512 
4513   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4514   unsigned Alignment;
4515   if (IsExpanding)
4516     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4517   else
4518     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4519 
4520   SDValue Ptr = getValue(PtrOperand);
4521   SDValue Src0 = getValue(Src0Operand);
4522   SDValue Mask = getValue(MaskOperand);
4523   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4524 
4525   EVT VT = Src0.getValueType();
4526   if (!Alignment)
4527     Alignment = DAG.getEVTAlignment(VT);
4528 
4529   AAMDNodes AAInfo;
4530   I.getAAMetadata(AAInfo);
4531   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4532 
4533   // Do not serialize masked loads of constant memory with anything.
4534   MemoryLocation ML;
4535   if (VT.isScalableVector())
4536     ML = MemoryLocation(PtrOperand);
4537   else
4538     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4539                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4540                            AAInfo);
4541   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4542 
4543   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4544 
4545   MachineMemOperand *MMO =
4546     DAG.getMachineFunction().
4547     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4548                           MachineMemOperand::MOLoad,
4549                           // TODO: Make MachineMemOperands aware of scalable
4550                           // vectors.
4551                           VT.getStoreSize().getKnownMinSize(),
4552                           Alignment, AAInfo, Ranges);
4553 
4554   SDValue Load =
4555       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4556                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4557   if (AddToChain)
4558     PendingLoads.push_back(Load.getValue(1));
4559   setValue(&I, Load);
4560 }
4561 
4562 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4563   SDLoc sdl = getCurSDLoc();
4564 
4565   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4566   const Value *Ptr = I.getArgOperand(0);
4567   SDValue Src0 = getValue(I.getArgOperand(3));
4568   SDValue Mask = getValue(I.getArgOperand(2));
4569 
4570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4571   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4572   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4573   if (!Alignment)
4574     Alignment = DAG.getEVTAlignment(VT);
4575 
4576   AAMDNodes AAInfo;
4577   I.getAAMetadata(AAInfo);
4578   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4579 
4580   SDValue Root = DAG.getRoot();
4581   SDValue Base;
4582   SDValue Index;
4583   ISD::MemIndexType IndexType;
4584   SDValue Scale;
4585   const Value *BasePtr = Ptr;
4586   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4587                                     this);
4588   bool ConstantMemory = false;
4589   if (UniformBase && AA &&
4590       AA->pointsToConstantMemory(
4591           MemoryLocation(BasePtr,
4592                          LocationSize::precise(
4593                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4594                          AAInfo))) {
4595     // Do not serialize (non-volatile) loads of constant memory with anything.
4596     Root = DAG.getEntryNode();
4597     ConstantMemory = true;
4598   }
4599 
4600   MachineMemOperand *MMO =
4601     DAG.getMachineFunction().
4602     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4603                          MachineMemOperand::MOLoad,
4604                          // TODO: Make MachineMemOperands aware of scalable
4605                          // vectors.
4606                          VT.getStoreSize().getKnownMinSize(),
4607                          Alignment, AAInfo, Ranges);
4608 
4609   if (!UniformBase) {
4610     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4611     Index = getValue(Ptr);
4612     IndexType = ISD::SIGNED_SCALED;
4613     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4614   }
4615   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4616   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4617                                        Ops, MMO, IndexType);
4618 
4619   SDValue OutChain = Gather.getValue(1);
4620   if (!ConstantMemory)
4621     PendingLoads.push_back(OutChain);
4622   setValue(&I, Gather);
4623 }
4624 
4625 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4626   SDLoc dl = getCurSDLoc();
4627   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4628   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4629   SyncScope::ID SSID = I.getSyncScopeID();
4630 
4631   SDValue InChain = getRoot();
4632 
4633   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4634   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4635 
4636   auto Alignment = DAG.getEVTAlignment(MemVT);
4637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4638   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4639 
4640   MachineFunction &MF = DAG.getMachineFunction();
4641   MachineMemOperand *MMO =
4642     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4643                             Flags, MemVT.getStoreSize(), Alignment,
4644                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4645                             FailureOrdering);
4646 
4647   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4648                                    dl, MemVT, VTs, InChain,
4649                                    getValue(I.getPointerOperand()),
4650                                    getValue(I.getCompareOperand()),
4651                                    getValue(I.getNewValOperand()), MMO);
4652 
4653   SDValue OutChain = L.getValue(2);
4654 
4655   setValue(&I, L);
4656   DAG.setRoot(OutChain);
4657 }
4658 
4659 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4660   SDLoc dl = getCurSDLoc();
4661   ISD::NodeType NT;
4662   switch (I.getOperation()) {
4663   default: llvm_unreachable("Unknown atomicrmw operation");
4664   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4665   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4666   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4667   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4668   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4669   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4670   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4671   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4672   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4673   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4674   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4675   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4676   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4677   }
4678   AtomicOrdering Ordering = I.getOrdering();
4679   SyncScope::ID SSID = I.getSyncScopeID();
4680 
4681   SDValue InChain = getRoot();
4682 
4683   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4684   auto Alignment = DAG.getEVTAlignment(MemVT);
4685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4686   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4687 
4688   MachineFunction &MF = DAG.getMachineFunction();
4689   MachineMemOperand *MMO =
4690     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4691                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4692                             nullptr, SSID, Ordering);
4693 
4694   SDValue L =
4695     DAG.getAtomic(NT, dl, MemVT, InChain,
4696                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4697                   MMO);
4698 
4699   SDValue OutChain = L.getValue(1);
4700 
4701   setValue(&I, L);
4702   DAG.setRoot(OutChain);
4703 }
4704 
4705 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4706   SDLoc dl = getCurSDLoc();
4707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4708   SDValue Ops[3];
4709   Ops[0] = getRoot();
4710   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4711                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4712   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4713                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4714   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4715 }
4716 
4717 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4718   SDLoc dl = getCurSDLoc();
4719   AtomicOrdering Order = I.getOrdering();
4720   SyncScope::ID SSID = I.getSyncScopeID();
4721 
4722   SDValue InChain = getRoot();
4723 
4724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4725   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4726   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4727 
4728   if (!TLI.supportsUnalignedAtomics() &&
4729       I.getAlignment() < MemVT.getSizeInBits() / 8)
4730     report_fatal_error("Cannot generate unaligned atomic load");
4731 
4732   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4733 
4734   MachineMemOperand *MMO =
4735       DAG.getMachineFunction().
4736       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4737                            Flags, MemVT.getStoreSize(),
4738                            I.getAlignment() ? I.getAlignment() :
4739                                               DAG.getEVTAlignment(MemVT),
4740                            AAMDNodes(), nullptr, SSID, Order);
4741 
4742   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4743 
4744   SDValue Ptr = getValue(I.getPointerOperand());
4745 
4746   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4747     // TODO: Once this is better exercised by tests, it should be merged with
4748     // the normal path for loads to prevent future divergence.
4749     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4750     if (MemVT != VT)
4751       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4752 
4753     setValue(&I, L);
4754     SDValue OutChain = L.getValue(1);
4755     if (!I.isUnordered())
4756       DAG.setRoot(OutChain);
4757     else
4758       PendingLoads.push_back(OutChain);
4759     return;
4760   }
4761 
4762   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4763                             Ptr, MMO);
4764 
4765   SDValue OutChain = L.getValue(1);
4766   if (MemVT != VT)
4767     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4768 
4769   setValue(&I, L);
4770   DAG.setRoot(OutChain);
4771 }
4772 
4773 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4774   SDLoc dl = getCurSDLoc();
4775 
4776   AtomicOrdering Ordering = I.getOrdering();
4777   SyncScope::ID SSID = I.getSyncScopeID();
4778 
4779   SDValue InChain = getRoot();
4780 
4781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4782   EVT MemVT =
4783       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4784 
4785   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4786     report_fatal_error("Cannot generate unaligned atomic store");
4787 
4788   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4789 
4790   MachineFunction &MF = DAG.getMachineFunction();
4791   MachineMemOperand *MMO =
4792     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4793                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4794                             nullptr, SSID, Ordering);
4795 
4796   SDValue Val = getValue(I.getValueOperand());
4797   if (Val.getValueType() != MemVT)
4798     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4799   SDValue Ptr = getValue(I.getPointerOperand());
4800 
4801   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4802     // TODO: Once this is better exercised by tests, it should be merged with
4803     // the normal path for stores to prevent future divergence.
4804     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4805     DAG.setRoot(S);
4806     return;
4807   }
4808   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4809                                    Ptr, Val, MMO);
4810 
4811 
4812   DAG.setRoot(OutChain);
4813 }
4814 
4815 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4816 /// node.
4817 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4818                                                unsigned Intrinsic) {
4819   // Ignore the callsite's attributes. A specific call site may be marked with
4820   // readnone, but the lowering code will expect the chain based on the
4821   // definition.
4822   const Function *F = I.getCalledFunction();
4823   bool HasChain = !F->doesNotAccessMemory();
4824   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4825 
4826   // Build the operand list.
4827   SmallVector<SDValue, 8> Ops;
4828   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4829     if (OnlyLoad) {
4830       // We don't need to serialize loads against other loads.
4831       Ops.push_back(DAG.getRoot());
4832     } else {
4833       Ops.push_back(getRoot());
4834     }
4835   }
4836 
4837   // Info is set by getTgtMemInstrinsic
4838   TargetLowering::IntrinsicInfo Info;
4839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4840   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4841                                                DAG.getMachineFunction(),
4842                                                Intrinsic);
4843 
4844   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4845   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4846       Info.opc == ISD::INTRINSIC_W_CHAIN)
4847     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4848                                         TLI.getPointerTy(DAG.getDataLayout())));
4849 
4850   // Add all operands of the call to the operand list.
4851   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4852     const Value *Arg = I.getArgOperand(i);
4853     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4854       Ops.push_back(getValue(Arg));
4855       continue;
4856     }
4857 
4858     // Use TargetConstant instead of a regular constant for immarg.
4859     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4860     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4861       assert(CI->getBitWidth() <= 64 &&
4862              "large intrinsic immediates not handled");
4863       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4864     } else {
4865       Ops.push_back(
4866           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4867     }
4868   }
4869 
4870   SmallVector<EVT, 4> ValueVTs;
4871   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4872 
4873   if (HasChain)
4874     ValueVTs.push_back(MVT::Other);
4875 
4876   SDVTList VTs = DAG.getVTList(ValueVTs);
4877 
4878   // Create the node.
4879   SDValue Result;
4880   if (IsTgtIntrinsic) {
4881     // This is target intrinsic that touches memory
4882     AAMDNodes AAInfo;
4883     I.getAAMetadata(AAInfo);
4884     Result = DAG.getMemIntrinsicNode(
4885         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4886         MachinePointerInfo(Info.ptrVal, Info.offset),
4887         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4888   } else if (!HasChain) {
4889     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4890   } else if (!I.getType()->isVoidTy()) {
4891     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4892   } else {
4893     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4894   }
4895 
4896   if (HasChain) {
4897     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4898     if (OnlyLoad)
4899       PendingLoads.push_back(Chain);
4900     else
4901       DAG.setRoot(Chain);
4902   }
4903 
4904   if (!I.getType()->isVoidTy()) {
4905     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4906       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4907       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4908     } else
4909       Result = lowerRangeToAssertZExt(DAG, I, Result);
4910 
4911     setValue(&I, Result);
4912   }
4913 }
4914 
4915 /// GetSignificand - Get the significand and build it into a floating-point
4916 /// number with exponent of 1:
4917 ///
4918 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4919 ///
4920 /// where Op is the hexadecimal representation of floating point value.
4921 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4922   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4923                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4924   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4925                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4926   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4927 }
4928 
4929 /// GetExponent - Get the exponent:
4930 ///
4931 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4932 ///
4933 /// where Op is the hexadecimal representation of floating point value.
4934 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4935                            const TargetLowering &TLI, const SDLoc &dl) {
4936   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4937                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4938   SDValue t1 = DAG.getNode(
4939       ISD::SRL, dl, MVT::i32, t0,
4940       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4941   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4942                            DAG.getConstant(127, dl, MVT::i32));
4943   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4944 }
4945 
4946 /// getF32Constant - Get 32-bit floating point constant.
4947 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4948                               const SDLoc &dl) {
4949   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4950                            MVT::f32);
4951 }
4952 
4953 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4954                                        SelectionDAG &DAG) {
4955   // TODO: What fast-math-flags should be set on the floating-point nodes?
4956 
4957   //   IntegerPartOfX = ((int32_t)(t0);
4958   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4959 
4960   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4961   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4962   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4963 
4964   //   IntegerPartOfX <<= 23;
4965   IntegerPartOfX = DAG.getNode(
4966       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4967       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4968                                   DAG.getDataLayout())));
4969 
4970   SDValue TwoToFractionalPartOfX;
4971   if (LimitFloatPrecision <= 6) {
4972     // For floating-point precision of 6:
4973     //
4974     //   TwoToFractionalPartOfX =
4975     //     0.997535578f +
4976     //       (0.735607626f + 0.252464424f * x) * x;
4977     //
4978     // error 0.0144103317, which is 6 bits
4979     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4980                              getF32Constant(DAG, 0x3e814304, dl));
4981     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4982                              getF32Constant(DAG, 0x3f3c50c8, dl));
4983     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4984     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4985                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4986   } else if (LimitFloatPrecision <= 12) {
4987     // For floating-point precision of 12:
4988     //
4989     //   TwoToFractionalPartOfX =
4990     //     0.999892986f +
4991     //       (0.696457318f +
4992     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4993     //
4994     // error 0.000107046256, which is 13 to 14 bits
4995     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4996                              getF32Constant(DAG, 0x3da235e3, dl));
4997     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4998                              getF32Constant(DAG, 0x3e65b8f3, dl));
4999     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5000     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5001                              getF32Constant(DAG, 0x3f324b07, dl));
5002     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5003     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5004                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5005   } else { // LimitFloatPrecision <= 18
5006     // For floating-point precision of 18:
5007     //
5008     //   TwoToFractionalPartOfX =
5009     //     0.999999982f +
5010     //       (0.693148872f +
5011     //         (0.240227044f +
5012     //           (0.554906021e-1f +
5013     //             (0.961591928e-2f +
5014     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5015     // error 2.47208000*10^(-7), which is better than 18 bits
5016     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5017                              getF32Constant(DAG, 0x3924b03e, dl));
5018     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5019                              getF32Constant(DAG, 0x3ab24b87, dl));
5020     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5021     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5022                              getF32Constant(DAG, 0x3c1d8c17, dl));
5023     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5024     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5025                              getF32Constant(DAG, 0x3d634a1d, dl));
5026     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5027     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5028                              getF32Constant(DAG, 0x3e75fe14, dl));
5029     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5030     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5031                               getF32Constant(DAG, 0x3f317234, dl));
5032     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5033     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5034                                          getF32Constant(DAG, 0x3f800000, dl));
5035   }
5036 
5037   // Add the exponent into the result in integer domain.
5038   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5039   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5040                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5041 }
5042 
5043 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5044 /// limited-precision mode.
5045 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5046                          const TargetLowering &TLI) {
5047   if (Op.getValueType() == MVT::f32 &&
5048       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5049 
5050     // Put the exponent in the right bit position for later addition to the
5051     // final result:
5052     //
5053     // t0 = Op * log2(e)
5054 
5055     // TODO: What fast-math-flags should be set here?
5056     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5057                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5058     return getLimitedPrecisionExp2(t0, dl, DAG);
5059   }
5060 
5061   // No special expansion.
5062   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5063 }
5064 
5065 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5066 /// limited-precision mode.
5067 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5068                          const TargetLowering &TLI) {
5069   // TODO: What fast-math-flags should be set on the floating-point nodes?
5070 
5071   if (Op.getValueType() == MVT::f32 &&
5072       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5073     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5074 
5075     // Scale the exponent by log(2).
5076     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5077     SDValue LogOfExponent =
5078         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5079                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5080 
5081     // Get the significand and build it into a floating-point number with
5082     // exponent of 1.
5083     SDValue X = GetSignificand(DAG, Op1, dl);
5084 
5085     SDValue LogOfMantissa;
5086     if (LimitFloatPrecision <= 6) {
5087       // For floating-point precision of 6:
5088       //
5089       //   LogofMantissa =
5090       //     -1.1609546f +
5091       //       (1.4034025f - 0.23903021f * x) * x;
5092       //
5093       // error 0.0034276066, which is better than 8 bits
5094       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5095                                getF32Constant(DAG, 0xbe74c456, dl));
5096       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5097                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5098       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5099       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5100                                   getF32Constant(DAG, 0x3f949a29, dl));
5101     } else if (LimitFloatPrecision <= 12) {
5102       // For floating-point precision of 12:
5103       //
5104       //   LogOfMantissa =
5105       //     -1.7417939f +
5106       //       (2.8212026f +
5107       //         (-1.4699568f +
5108       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5109       //
5110       // error 0.000061011436, which is 14 bits
5111       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5112                                getF32Constant(DAG, 0xbd67b6d6, dl));
5113       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5114                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5115       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5116       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5117                                getF32Constant(DAG, 0x3fbc278b, dl));
5118       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5119       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5120                                getF32Constant(DAG, 0x40348e95, dl));
5121       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5122       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5123                                   getF32Constant(DAG, 0x3fdef31a, dl));
5124     } else { // LimitFloatPrecision <= 18
5125       // For floating-point precision of 18:
5126       //
5127       //   LogOfMantissa =
5128       //     -2.1072184f +
5129       //       (4.2372794f +
5130       //         (-3.7029485f +
5131       //           (2.2781945f +
5132       //             (-0.87823314f +
5133       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5134       //
5135       // error 0.0000023660568, which is better than 18 bits
5136       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5137                                getF32Constant(DAG, 0xbc91e5ac, dl));
5138       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5139                                getF32Constant(DAG, 0x3e4350aa, dl));
5140       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5141       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5142                                getF32Constant(DAG, 0x3f60d3e3, dl));
5143       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5144       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5145                                getF32Constant(DAG, 0x4011cdf0, dl));
5146       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5147       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5148                                getF32Constant(DAG, 0x406cfd1c, dl));
5149       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5150       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5151                                getF32Constant(DAG, 0x408797cb, dl));
5152       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5153       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5154                                   getF32Constant(DAG, 0x4006dcab, dl));
5155     }
5156 
5157     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5158   }
5159 
5160   // No special expansion.
5161   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5162 }
5163 
5164 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5165 /// limited-precision mode.
5166 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5167                           const TargetLowering &TLI) {
5168   // TODO: What fast-math-flags should be set on the floating-point nodes?
5169 
5170   if (Op.getValueType() == MVT::f32 &&
5171       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5172     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5173 
5174     // Get the exponent.
5175     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5176 
5177     // Get the significand and build it into a floating-point number with
5178     // exponent of 1.
5179     SDValue X = GetSignificand(DAG, Op1, dl);
5180 
5181     // Different possible minimax approximations of significand in
5182     // floating-point for various degrees of accuracy over [1,2].
5183     SDValue Log2ofMantissa;
5184     if (LimitFloatPrecision <= 6) {
5185       // For floating-point precision of 6:
5186       //
5187       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5188       //
5189       // error 0.0049451742, which is more than 7 bits
5190       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5191                                getF32Constant(DAG, 0xbeb08fe0, dl));
5192       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5193                                getF32Constant(DAG, 0x40019463, dl));
5194       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5195       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5196                                    getF32Constant(DAG, 0x3fd6633d, dl));
5197     } else if (LimitFloatPrecision <= 12) {
5198       // For floating-point precision of 12:
5199       //
5200       //   Log2ofMantissa =
5201       //     -2.51285454f +
5202       //       (4.07009056f +
5203       //         (-2.12067489f +
5204       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5205       //
5206       // error 0.0000876136000, which is better than 13 bits
5207       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5208                                getF32Constant(DAG, 0xbda7262e, dl));
5209       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5210                                getF32Constant(DAG, 0x3f25280b, dl));
5211       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5212       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5213                                getF32Constant(DAG, 0x4007b923, dl));
5214       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5215       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5216                                getF32Constant(DAG, 0x40823e2f, dl));
5217       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5218       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5219                                    getF32Constant(DAG, 0x4020d29c, dl));
5220     } else { // LimitFloatPrecision <= 18
5221       // For floating-point precision of 18:
5222       //
5223       //   Log2ofMantissa =
5224       //     -3.0400495f +
5225       //       (6.1129976f +
5226       //         (-5.3420409f +
5227       //           (3.2865683f +
5228       //             (-1.2669343f +
5229       //               (0.27515199f -
5230       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5231       //
5232       // error 0.0000018516, which is better than 18 bits
5233       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5234                                getF32Constant(DAG, 0xbcd2769e, dl));
5235       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5236                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5237       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5238       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5239                                getF32Constant(DAG, 0x3fa22ae7, dl));
5240       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5241       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5242                                getF32Constant(DAG, 0x40525723, dl));
5243       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5244       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5245                                getF32Constant(DAG, 0x40aaf200, dl));
5246       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5247       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5248                                getF32Constant(DAG, 0x40c39dad, dl));
5249       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5250       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5251                                    getF32Constant(DAG, 0x4042902c, dl));
5252     }
5253 
5254     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5255   }
5256 
5257   // No special expansion.
5258   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5259 }
5260 
5261 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5262 /// limited-precision mode.
5263 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5264                            const TargetLowering &TLI) {
5265   // TODO: What fast-math-flags should be set on the floating-point nodes?
5266 
5267   if (Op.getValueType() == MVT::f32 &&
5268       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5269     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5270 
5271     // Scale the exponent by log10(2) [0.30102999f].
5272     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5273     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5274                                         getF32Constant(DAG, 0x3e9a209a, dl));
5275 
5276     // Get the significand and build it into a floating-point number with
5277     // exponent of 1.
5278     SDValue X = GetSignificand(DAG, Op1, dl);
5279 
5280     SDValue Log10ofMantissa;
5281     if (LimitFloatPrecision <= 6) {
5282       // For floating-point precision of 6:
5283       //
5284       //   Log10ofMantissa =
5285       //     -0.50419619f +
5286       //       (0.60948995f - 0.10380950f * x) * x;
5287       //
5288       // error 0.0014886165, which is 6 bits
5289       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5290                                getF32Constant(DAG, 0xbdd49a13, dl));
5291       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5292                                getF32Constant(DAG, 0x3f1c0789, dl));
5293       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5294       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5295                                     getF32Constant(DAG, 0x3f011300, dl));
5296     } else if (LimitFloatPrecision <= 12) {
5297       // For floating-point precision of 12:
5298       //
5299       //   Log10ofMantissa =
5300       //     -0.64831180f +
5301       //       (0.91751397f +
5302       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5303       //
5304       // error 0.00019228036, which is better than 12 bits
5305       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5306                                getF32Constant(DAG, 0x3d431f31, dl));
5307       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5308                                getF32Constant(DAG, 0x3ea21fb2, dl));
5309       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5310       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5311                                getF32Constant(DAG, 0x3f6ae232, dl));
5312       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5313       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5314                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5315     } else { // LimitFloatPrecision <= 18
5316       // For floating-point precision of 18:
5317       //
5318       //   Log10ofMantissa =
5319       //     -0.84299375f +
5320       //       (1.5327582f +
5321       //         (-1.0688956f +
5322       //           (0.49102474f +
5323       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5324       //
5325       // error 0.0000037995730, which is better than 18 bits
5326       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5327                                getF32Constant(DAG, 0x3c5d51ce, dl));
5328       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5329                                getF32Constant(DAG, 0x3e00685a, dl));
5330       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5331       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5332                                getF32Constant(DAG, 0x3efb6798, dl));
5333       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5334       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5335                                getF32Constant(DAG, 0x3f88d192, dl));
5336       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5337       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5338                                getF32Constant(DAG, 0x3fc4316c, dl));
5339       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5340       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5341                                     getF32Constant(DAG, 0x3f57ce70, dl));
5342     }
5343 
5344     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5345   }
5346 
5347   // No special expansion.
5348   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5349 }
5350 
5351 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5352 /// limited-precision mode.
5353 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5354                           const TargetLowering &TLI) {
5355   if (Op.getValueType() == MVT::f32 &&
5356       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5357     return getLimitedPrecisionExp2(Op, dl, DAG);
5358 
5359   // No special expansion.
5360   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5361 }
5362 
5363 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5364 /// limited-precision mode with x == 10.0f.
5365 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5366                          SelectionDAG &DAG, const TargetLowering &TLI) {
5367   bool IsExp10 = false;
5368   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5369       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5370     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5371       APFloat Ten(10.0f);
5372       IsExp10 = LHSC->isExactlyValue(Ten);
5373     }
5374   }
5375 
5376   // TODO: What fast-math-flags should be set on the FMUL node?
5377   if (IsExp10) {
5378     // Put the exponent in the right bit position for later addition to the
5379     // final result:
5380     //
5381     //   #define LOG2OF10 3.3219281f
5382     //   t0 = Op * LOG2OF10;
5383     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5384                              getF32Constant(DAG, 0x40549a78, dl));
5385     return getLimitedPrecisionExp2(t0, dl, DAG);
5386   }
5387 
5388   // No special expansion.
5389   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5390 }
5391 
5392 /// ExpandPowI - Expand a llvm.powi intrinsic.
5393 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5394                           SelectionDAG &DAG) {
5395   // If RHS is a constant, we can expand this out to a multiplication tree,
5396   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5397   // optimizing for size, we only want to do this if the expansion would produce
5398   // a small number of multiplies, otherwise we do the full expansion.
5399   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5400     // Get the exponent as a positive value.
5401     unsigned Val = RHSC->getSExtValue();
5402     if ((int)Val < 0) Val = -Val;
5403 
5404     // powi(x, 0) -> 1.0
5405     if (Val == 0)
5406       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5407 
5408     bool OptForSize = DAG.shouldOptForSize();
5409     if (!OptForSize ||
5410         // If optimizing for size, don't insert too many multiplies.
5411         // This inserts up to 5 multiplies.
5412         countPopulation(Val) + Log2_32(Val) < 7) {
5413       // We use the simple binary decomposition method to generate the multiply
5414       // sequence.  There are more optimal ways to do this (for example,
5415       // powi(x,15) generates one more multiply than it should), but this has
5416       // the benefit of being both really simple and much better than a libcall.
5417       SDValue Res;  // Logically starts equal to 1.0
5418       SDValue CurSquare = LHS;
5419       // TODO: Intrinsics should have fast-math-flags that propagate to these
5420       // nodes.
5421       while (Val) {
5422         if (Val & 1) {
5423           if (Res.getNode())
5424             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5425           else
5426             Res = CurSquare;  // 1.0*CurSquare.
5427         }
5428 
5429         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5430                                 CurSquare, CurSquare);
5431         Val >>= 1;
5432       }
5433 
5434       // If the original was negative, invert the result, producing 1/(x*x*x).
5435       if (RHSC->getSExtValue() < 0)
5436         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5437                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5438       return Res;
5439     }
5440   }
5441 
5442   // Otherwise, expand to a libcall.
5443   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5444 }
5445 
5446 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5447                             SDValue LHS, SDValue RHS, SDValue Scale,
5448                             SelectionDAG &DAG, const TargetLowering &TLI) {
5449   EVT VT = LHS.getValueType();
5450   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5451   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5452   LLVMContext &Ctx = *DAG.getContext();
5453 
5454   // If the type is legal but the operation isn't, this node might survive all
5455   // the way to operation legalization. If we end up there and we do not have
5456   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5457   // node.
5458 
5459   // Coax the legalizer into expanding the node during type legalization instead
5460   // by bumping the size by one bit. This will force it to Promote, enabling the
5461   // early expansion and avoiding the need to expand later.
5462 
5463   // We don't have to do this if Scale is 0; that can always be expanded, unless
5464   // it's a saturating signed operation. Those can experience true integer
5465   // division overflow, a case which we must avoid.
5466 
5467   // FIXME: We wouldn't have to do this (or any of the early
5468   // expansion/promotion) if it was possible to expand a libcall of an
5469   // illegal type during operation legalization. But it's not, so things
5470   // get a bit hacky.
5471   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5472   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5473       (TLI.isTypeLegal(VT) ||
5474        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5475     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5476         Opcode, VT, ScaleInt);
5477     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5478       EVT PromVT;
5479       if (VT.isScalarInteger())
5480         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5481       else if (VT.isVector()) {
5482         PromVT = VT.getVectorElementType();
5483         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5484         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5485       } else
5486         llvm_unreachable("Wrong VT for DIVFIX?");
5487       if (Signed) {
5488         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5489         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5490       } else {
5491         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5492         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5493       }
5494       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5495       // For saturating operations, we need to shift up the LHS to get the
5496       // proper saturation width, and then shift down again afterwards.
5497       if (Saturating)
5498         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5499                           DAG.getConstant(1, DL, ShiftTy));
5500       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5501       if (Saturating)
5502         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5503                           DAG.getConstant(1, DL, ShiftTy));
5504       return DAG.getZExtOrTrunc(Res, DL, VT);
5505     }
5506   }
5507 
5508   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5509 }
5510 
5511 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5512 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5513 static void
5514 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5515                      const SDValue &N) {
5516   switch (N.getOpcode()) {
5517   case ISD::CopyFromReg: {
5518     SDValue Op = N.getOperand(1);
5519     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5520                       Op.getValueType().getSizeInBits());
5521     return;
5522   }
5523   case ISD::BITCAST:
5524   case ISD::AssertZext:
5525   case ISD::AssertSext:
5526   case ISD::TRUNCATE:
5527     getUnderlyingArgRegs(Regs, N.getOperand(0));
5528     return;
5529   case ISD::BUILD_PAIR:
5530   case ISD::BUILD_VECTOR:
5531   case ISD::CONCAT_VECTORS:
5532     for (SDValue Op : N->op_values())
5533       getUnderlyingArgRegs(Regs, Op);
5534     return;
5535   default:
5536     return;
5537   }
5538 }
5539 
5540 /// If the DbgValueInst is a dbg_value of a function argument, create the
5541 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5542 /// instruction selection, they will be inserted to the entry BB.
5543 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5544     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5545     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5546   const Argument *Arg = dyn_cast<Argument>(V);
5547   if (!Arg)
5548     return false;
5549 
5550   if (!IsDbgDeclare) {
5551     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5552     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5553     // the entry block.
5554     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5555     if (!IsInEntryBlock)
5556       return false;
5557 
5558     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5559     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5560     // variable that also is a param.
5561     //
5562     // Although, if we are at the top of the entry block already, we can still
5563     // emit using ArgDbgValue. This might catch some situations when the
5564     // dbg.value refers to an argument that isn't used in the entry block, so
5565     // any CopyToReg node would be optimized out and the only way to express
5566     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5567     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5568     // we should only emit as ArgDbgValue if the Variable is an argument to the
5569     // current function, and the dbg.value intrinsic is found in the entry
5570     // block.
5571     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5572         !DL->getInlinedAt();
5573     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5574     if (!IsInPrologue && !VariableIsFunctionInputArg)
5575       return false;
5576 
5577     // Here we assume that a function argument on IR level only can be used to
5578     // describe one input parameter on source level. If we for example have
5579     // source code like this
5580     //
5581     //    struct A { long x, y; };
5582     //    void foo(struct A a, long b) {
5583     //      ...
5584     //      b = a.x;
5585     //      ...
5586     //    }
5587     //
5588     // and IR like this
5589     //
5590     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5591     //  entry:
5592     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5593     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5594     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5595     //    ...
5596     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5597     //    ...
5598     //
5599     // then the last dbg.value is describing a parameter "b" using a value that
5600     // is an argument. But since we already has used %a1 to describe a parameter
5601     // we should not handle that last dbg.value here (that would result in an
5602     // incorrect hoisting of the DBG_VALUE to the function entry).
5603     // Notice that we allow one dbg.value per IR level argument, to accommodate
5604     // for the situation with fragments above.
5605     if (VariableIsFunctionInputArg) {
5606       unsigned ArgNo = Arg->getArgNo();
5607       if (ArgNo >= FuncInfo.DescribedArgs.size())
5608         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5609       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5610         return false;
5611       FuncInfo.DescribedArgs.set(ArgNo);
5612     }
5613   }
5614 
5615   MachineFunction &MF = DAG.getMachineFunction();
5616   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5617 
5618   bool IsIndirect = false;
5619   Optional<MachineOperand> Op;
5620   // Some arguments' frame index is recorded during argument lowering.
5621   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5622   if (FI != std::numeric_limits<int>::max())
5623     Op = MachineOperand::CreateFI(FI);
5624 
5625   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5626   if (!Op && N.getNode()) {
5627     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5628     Register Reg;
5629     if (ArgRegsAndSizes.size() == 1)
5630       Reg = ArgRegsAndSizes.front().first;
5631 
5632     if (Reg && Reg.isVirtual()) {
5633       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5634       Register PR = RegInfo.getLiveInPhysReg(Reg);
5635       if (PR)
5636         Reg = PR;
5637     }
5638     if (Reg) {
5639       Op = MachineOperand::CreateReg(Reg, false);
5640       IsIndirect = IsDbgDeclare;
5641     }
5642   }
5643 
5644   if (!Op && N.getNode()) {
5645     // Check if frame index is available.
5646     SDValue LCandidate = peekThroughBitcasts(N);
5647     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5648       if (FrameIndexSDNode *FINode =
5649           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5650         Op = MachineOperand::CreateFI(FINode->getIndex());
5651   }
5652 
5653   if (!Op) {
5654     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5655     auto splitMultiRegDbgValue
5656       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5657       unsigned Offset = 0;
5658       for (auto RegAndSize : SplitRegs) {
5659         // If the expression is already a fragment, the current register
5660         // offset+size might extend beyond the fragment. In this case, only
5661         // the register bits that are inside the fragment are relevant.
5662         int RegFragmentSizeInBits = RegAndSize.second;
5663         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5664           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5665           // The register is entirely outside the expression fragment,
5666           // so is irrelevant for debug info.
5667           if (Offset >= ExprFragmentSizeInBits)
5668             break;
5669           // The register is partially outside the expression fragment, only
5670           // the low bits within the fragment are relevant for debug info.
5671           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5672             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5673           }
5674         }
5675 
5676         auto FragmentExpr = DIExpression::createFragmentExpression(
5677             Expr, Offset, RegFragmentSizeInBits);
5678         Offset += RegAndSize.second;
5679         // If a valid fragment expression cannot be created, the variable's
5680         // correct value cannot be determined and so it is set as Undef.
5681         if (!FragmentExpr) {
5682           SDDbgValue *SDV = DAG.getConstantDbgValue(
5683               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5684           DAG.AddDbgValue(SDV, nullptr, false);
5685           continue;
5686         }
5687         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5688         FuncInfo.ArgDbgValues.push_back(
5689           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5690                   RegAndSize.first, Variable, *FragmentExpr));
5691       }
5692     };
5693 
5694     // Check if ValueMap has reg number.
5695     DenseMap<const Value *, unsigned>::const_iterator
5696       VMI = FuncInfo.ValueMap.find(V);
5697     if (VMI != FuncInfo.ValueMap.end()) {
5698       const auto &TLI = DAG.getTargetLoweringInfo();
5699       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5700                        V->getType(), getABIRegCopyCC(V));
5701       if (RFV.occupiesMultipleRegs()) {
5702         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5703         return true;
5704       }
5705 
5706       Op = MachineOperand::CreateReg(VMI->second, false);
5707       IsIndirect = IsDbgDeclare;
5708     } else if (ArgRegsAndSizes.size() > 1) {
5709       // This was split due to the calling convention, and no virtual register
5710       // mapping exists for the value.
5711       splitMultiRegDbgValue(ArgRegsAndSizes);
5712       return true;
5713     }
5714   }
5715 
5716   if (!Op)
5717     return false;
5718 
5719   assert(Variable->isValidLocationForIntrinsic(DL) &&
5720          "Expected inlined-at fields to agree");
5721   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5722   FuncInfo.ArgDbgValues.push_back(
5723       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5724               *Op, Variable, Expr));
5725 
5726   return true;
5727 }
5728 
5729 /// Return the appropriate SDDbgValue based on N.
5730 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5731                                              DILocalVariable *Variable,
5732                                              DIExpression *Expr,
5733                                              const DebugLoc &dl,
5734                                              unsigned DbgSDNodeOrder) {
5735   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5736     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5737     // stack slot locations.
5738     //
5739     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5740     // debug values here after optimization:
5741     //
5742     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5743     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5744     //
5745     // Both describe the direct values of their associated variables.
5746     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5747                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5748   }
5749   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5750                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5751 }
5752 
5753 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5754   switch (Intrinsic) {
5755   case Intrinsic::smul_fix:
5756     return ISD::SMULFIX;
5757   case Intrinsic::umul_fix:
5758     return ISD::UMULFIX;
5759   case Intrinsic::smul_fix_sat:
5760     return ISD::SMULFIXSAT;
5761   case Intrinsic::umul_fix_sat:
5762     return ISD::UMULFIXSAT;
5763   case Intrinsic::sdiv_fix:
5764     return ISD::SDIVFIX;
5765   case Intrinsic::udiv_fix:
5766     return ISD::UDIVFIX;
5767   case Intrinsic::sdiv_fix_sat:
5768     return ISD::SDIVFIXSAT;
5769   case Intrinsic::udiv_fix_sat:
5770     return ISD::UDIVFIXSAT;
5771   default:
5772     llvm_unreachable("Unhandled fixed point intrinsic");
5773   }
5774 }
5775 
5776 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5777                                            const char *FunctionName) {
5778   assert(FunctionName && "FunctionName must not be nullptr");
5779   SDValue Callee = DAG.getExternalSymbol(
5780       FunctionName,
5781       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5782   LowerCallTo(&I, Callee, I.isTailCall());
5783 }
5784 
5785 /// Lower the call to the specified intrinsic function.
5786 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5787                                              unsigned Intrinsic) {
5788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5789   SDLoc sdl = getCurSDLoc();
5790   DebugLoc dl = getCurDebugLoc();
5791   SDValue Res;
5792 
5793   switch (Intrinsic) {
5794   default:
5795     // By default, turn this into a target intrinsic node.
5796     visitTargetIntrinsic(I, Intrinsic);
5797     return;
5798   case Intrinsic::vscale: {
5799     match(&I, m_VScale(DAG.getDataLayout()));
5800     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5801     setValue(&I,
5802              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5803     return;
5804   }
5805   case Intrinsic::vastart:  visitVAStart(I); return;
5806   case Intrinsic::vaend:    visitVAEnd(I); return;
5807   case Intrinsic::vacopy:   visitVACopy(I); return;
5808   case Intrinsic::returnaddress:
5809     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5810                              TLI.getPointerTy(DAG.getDataLayout()),
5811                              getValue(I.getArgOperand(0))));
5812     return;
5813   case Intrinsic::addressofreturnaddress:
5814     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5815                              TLI.getPointerTy(DAG.getDataLayout())));
5816     return;
5817   case Intrinsic::sponentry:
5818     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5819                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5820     return;
5821   case Intrinsic::frameaddress:
5822     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5823                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5824                              getValue(I.getArgOperand(0))));
5825     return;
5826   case Intrinsic::read_register: {
5827     Value *Reg = I.getArgOperand(0);
5828     SDValue Chain = getRoot();
5829     SDValue RegName =
5830         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5831     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5832     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5833       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5834     setValue(&I, Res);
5835     DAG.setRoot(Res.getValue(1));
5836     return;
5837   }
5838   case Intrinsic::write_register: {
5839     Value *Reg = I.getArgOperand(0);
5840     Value *RegValue = I.getArgOperand(1);
5841     SDValue Chain = getRoot();
5842     SDValue RegName =
5843         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5844     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5845                             RegName, getValue(RegValue)));
5846     return;
5847   }
5848   case Intrinsic::memcpy: {
5849     const auto &MCI = cast<MemCpyInst>(I);
5850     SDValue Op1 = getValue(I.getArgOperand(0));
5851     SDValue Op2 = getValue(I.getArgOperand(1));
5852     SDValue Op3 = getValue(I.getArgOperand(2));
5853     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5854     Align DstAlign = MCI.getDestAlign().valueOrOne();
5855     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5856     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5857     bool isVol = MCI.isVolatile();
5858     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5859     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5860     // node.
5861     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5862     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5863                                /* AlwaysInline */ false, isTC,
5864                                MachinePointerInfo(I.getArgOperand(0)),
5865                                MachinePointerInfo(I.getArgOperand(1)));
5866     updateDAGForMaybeTailCall(MC);
5867     return;
5868   }
5869   case Intrinsic::memcpy_inline: {
5870     const auto &MCI = cast<MemCpyInlineInst>(I);
5871     SDValue Dst = getValue(I.getArgOperand(0));
5872     SDValue Src = getValue(I.getArgOperand(1));
5873     SDValue Size = getValue(I.getArgOperand(2));
5874     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5875     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5876     Align DstAlign = MCI.getDestAlign().valueOrOne();
5877     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5878     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5879     bool isVol = MCI.isVolatile();
5880     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5881     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5882     // node.
5883     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5884                                /* AlwaysInline */ true, isTC,
5885                                MachinePointerInfo(I.getArgOperand(0)),
5886                                MachinePointerInfo(I.getArgOperand(1)));
5887     updateDAGForMaybeTailCall(MC);
5888     return;
5889   }
5890   case Intrinsic::memset: {
5891     const auto &MSI = cast<MemSetInst>(I);
5892     SDValue Op1 = getValue(I.getArgOperand(0));
5893     SDValue Op2 = getValue(I.getArgOperand(1));
5894     SDValue Op3 = getValue(I.getArgOperand(2));
5895     // @llvm.memset defines 0 and 1 to both mean no alignment.
5896     Align Alignment = MSI.getDestAlign().valueOrOne();
5897     bool isVol = MSI.isVolatile();
5898     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5899     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5900     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5901                                MachinePointerInfo(I.getArgOperand(0)));
5902     updateDAGForMaybeTailCall(MS);
5903     return;
5904   }
5905   case Intrinsic::memmove: {
5906     const auto &MMI = cast<MemMoveInst>(I);
5907     SDValue Op1 = getValue(I.getArgOperand(0));
5908     SDValue Op2 = getValue(I.getArgOperand(1));
5909     SDValue Op3 = getValue(I.getArgOperand(2));
5910     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5911     Align DstAlign = MMI.getDestAlign().valueOrOne();
5912     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5913     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5914     bool isVol = MMI.isVolatile();
5915     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5916     // FIXME: Support passing different dest/src alignments to the memmove DAG
5917     // node.
5918     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5919     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5920                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5921                                 MachinePointerInfo(I.getArgOperand(1)));
5922     updateDAGForMaybeTailCall(MM);
5923     return;
5924   }
5925   case Intrinsic::memcpy_element_unordered_atomic: {
5926     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5927     SDValue Dst = getValue(MI.getRawDest());
5928     SDValue Src = getValue(MI.getRawSource());
5929     SDValue Length = getValue(MI.getLength());
5930 
5931     unsigned DstAlign = MI.getDestAlignment();
5932     unsigned SrcAlign = MI.getSourceAlignment();
5933     Type *LengthTy = MI.getLength()->getType();
5934     unsigned ElemSz = MI.getElementSizeInBytes();
5935     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5936     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5937                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5938                                      MachinePointerInfo(MI.getRawDest()),
5939                                      MachinePointerInfo(MI.getRawSource()));
5940     updateDAGForMaybeTailCall(MC);
5941     return;
5942   }
5943   case Intrinsic::memmove_element_unordered_atomic: {
5944     auto &MI = cast<AtomicMemMoveInst>(I);
5945     SDValue Dst = getValue(MI.getRawDest());
5946     SDValue Src = getValue(MI.getRawSource());
5947     SDValue Length = getValue(MI.getLength());
5948 
5949     unsigned DstAlign = MI.getDestAlignment();
5950     unsigned SrcAlign = MI.getSourceAlignment();
5951     Type *LengthTy = MI.getLength()->getType();
5952     unsigned ElemSz = MI.getElementSizeInBytes();
5953     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5954     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5955                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5956                                       MachinePointerInfo(MI.getRawDest()),
5957                                       MachinePointerInfo(MI.getRawSource()));
5958     updateDAGForMaybeTailCall(MC);
5959     return;
5960   }
5961   case Intrinsic::memset_element_unordered_atomic: {
5962     auto &MI = cast<AtomicMemSetInst>(I);
5963     SDValue Dst = getValue(MI.getRawDest());
5964     SDValue Val = getValue(MI.getValue());
5965     SDValue Length = getValue(MI.getLength());
5966 
5967     unsigned DstAlign = MI.getDestAlignment();
5968     Type *LengthTy = MI.getLength()->getType();
5969     unsigned ElemSz = MI.getElementSizeInBytes();
5970     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5971     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5972                                      LengthTy, ElemSz, isTC,
5973                                      MachinePointerInfo(MI.getRawDest()));
5974     updateDAGForMaybeTailCall(MC);
5975     return;
5976   }
5977   case Intrinsic::dbg_addr:
5978   case Intrinsic::dbg_declare: {
5979     const auto &DI = cast<DbgVariableIntrinsic>(I);
5980     DILocalVariable *Variable = DI.getVariable();
5981     DIExpression *Expression = DI.getExpression();
5982     dropDanglingDebugInfo(Variable, Expression);
5983     assert(Variable && "Missing variable");
5984     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5985                       << "\n");
5986     // Check if address has undef value.
5987     const Value *Address = DI.getVariableLocation();
5988     if (!Address || isa<UndefValue>(Address) ||
5989         (Address->use_empty() && !isa<Argument>(Address))) {
5990       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5991                         << " (bad/undef/unused-arg address)\n");
5992       return;
5993     }
5994 
5995     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5996 
5997     // Check if this variable can be described by a frame index, typically
5998     // either as a static alloca or a byval parameter.
5999     int FI = std::numeric_limits<int>::max();
6000     if (const auto *AI =
6001             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6002       if (AI->isStaticAlloca()) {
6003         auto I = FuncInfo.StaticAllocaMap.find(AI);
6004         if (I != FuncInfo.StaticAllocaMap.end())
6005           FI = I->second;
6006       }
6007     } else if (const auto *Arg = dyn_cast<Argument>(
6008                    Address->stripInBoundsConstantOffsets())) {
6009       FI = FuncInfo.getArgumentFrameIndex(Arg);
6010     }
6011 
6012     // llvm.dbg.addr is control dependent and always generates indirect
6013     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6014     // the MachineFunction variable table.
6015     if (FI != std::numeric_limits<int>::max()) {
6016       if (Intrinsic == Intrinsic::dbg_addr) {
6017         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6018             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
6019         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
6020       } else {
6021         LLVM_DEBUG(dbgs() << "Skipping " << DI
6022                           << " (variable info stashed in MF side table)\n");
6023       }
6024       return;
6025     }
6026 
6027     SDValue &N = NodeMap[Address];
6028     if (!N.getNode() && isa<Argument>(Address))
6029       // Check unused arguments map.
6030       N = UnusedArgNodeMap[Address];
6031     SDDbgValue *SDV;
6032     if (N.getNode()) {
6033       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6034         Address = BCI->getOperand(0);
6035       // Parameters are handled specially.
6036       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6037       if (isParameter && FINode) {
6038         // Byval parameter. We have a frame index at this point.
6039         SDV =
6040             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6041                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6042       } else if (isa<Argument>(Address)) {
6043         // Address is an argument, so try to emit its dbg value using
6044         // virtual register info from the FuncInfo.ValueMap.
6045         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6046         return;
6047       } else {
6048         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6049                               true, dl, SDNodeOrder);
6050       }
6051       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
6052     } else {
6053       // If Address is an argument then try to emit its dbg value using
6054       // virtual register info from the FuncInfo.ValueMap.
6055       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6056                                     N)) {
6057         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6058                           << " (could not emit func-arg dbg_value)\n");
6059       }
6060     }
6061     return;
6062   }
6063   case Intrinsic::dbg_label: {
6064     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6065     DILabel *Label = DI.getLabel();
6066     assert(Label && "Missing label");
6067 
6068     SDDbgLabel *SDV;
6069     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6070     DAG.AddDbgLabel(SDV);
6071     return;
6072   }
6073   case Intrinsic::dbg_value: {
6074     const DbgValueInst &DI = cast<DbgValueInst>(I);
6075     assert(DI.getVariable() && "Missing variable");
6076 
6077     DILocalVariable *Variable = DI.getVariable();
6078     DIExpression *Expression = DI.getExpression();
6079     dropDanglingDebugInfo(Variable, Expression);
6080     const Value *V = DI.getValue();
6081     if (!V)
6082       return;
6083 
6084     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6085         SDNodeOrder))
6086       return;
6087 
6088     // TODO: Dangling debug info will eventually either be resolved or produce
6089     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6090     // between the original dbg.value location and its resolved DBG_VALUE, which
6091     // we should ideally fill with an extra Undef DBG_VALUE.
6092 
6093     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6094     return;
6095   }
6096 
6097   case Intrinsic::eh_typeid_for: {
6098     // Find the type id for the given typeinfo.
6099     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6100     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6101     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6102     setValue(&I, Res);
6103     return;
6104   }
6105 
6106   case Intrinsic::eh_return_i32:
6107   case Intrinsic::eh_return_i64:
6108     DAG.getMachineFunction().setCallsEHReturn(true);
6109     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6110                             MVT::Other,
6111                             getControlRoot(),
6112                             getValue(I.getArgOperand(0)),
6113                             getValue(I.getArgOperand(1))));
6114     return;
6115   case Intrinsic::eh_unwind_init:
6116     DAG.getMachineFunction().setCallsUnwindInit(true);
6117     return;
6118   case Intrinsic::eh_dwarf_cfa:
6119     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6120                              TLI.getPointerTy(DAG.getDataLayout()),
6121                              getValue(I.getArgOperand(0))));
6122     return;
6123   case Intrinsic::eh_sjlj_callsite: {
6124     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6125     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6126     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6127     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6128 
6129     MMI.setCurrentCallSite(CI->getZExtValue());
6130     return;
6131   }
6132   case Intrinsic::eh_sjlj_functioncontext: {
6133     // Get and store the index of the function context.
6134     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6135     AllocaInst *FnCtx =
6136       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6137     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6138     MFI.setFunctionContextIndex(FI);
6139     return;
6140   }
6141   case Intrinsic::eh_sjlj_setjmp: {
6142     SDValue Ops[2];
6143     Ops[0] = getRoot();
6144     Ops[1] = getValue(I.getArgOperand(0));
6145     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6146                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6147     setValue(&I, Op.getValue(0));
6148     DAG.setRoot(Op.getValue(1));
6149     return;
6150   }
6151   case Intrinsic::eh_sjlj_longjmp:
6152     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6153                             getRoot(), getValue(I.getArgOperand(0))));
6154     return;
6155   case Intrinsic::eh_sjlj_setup_dispatch:
6156     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6157                             getRoot()));
6158     return;
6159   case Intrinsic::masked_gather:
6160     visitMaskedGather(I);
6161     return;
6162   case Intrinsic::masked_load:
6163     visitMaskedLoad(I);
6164     return;
6165   case Intrinsic::masked_scatter:
6166     visitMaskedScatter(I);
6167     return;
6168   case Intrinsic::masked_store:
6169     visitMaskedStore(I);
6170     return;
6171   case Intrinsic::masked_expandload:
6172     visitMaskedLoad(I, true /* IsExpanding */);
6173     return;
6174   case Intrinsic::masked_compressstore:
6175     visitMaskedStore(I, true /* IsCompressing */);
6176     return;
6177   case Intrinsic::powi:
6178     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6179                             getValue(I.getArgOperand(1)), DAG));
6180     return;
6181   case Intrinsic::log:
6182     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6183     return;
6184   case Intrinsic::log2:
6185     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6186     return;
6187   case Intrinsic::log10:
6188     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6189     return;
6190   case Intrinsic::exp:
6191     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6192     return;
6193   case Intrinsic::exp2:
6194     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6195     return;
6196   case Intrinsic::pow:
6197     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6198                            getValue(I.getArgOperand(1)), DAG, TLI));
6199     return;
6200   case Intrinsic::sqrt:
6201   case Intrinsic::fabs:
6202   case Intrinsic::sin:
6203   case Intrinsic::cos:
6204   case Intrinsic::floor:
6205   case Intrinsic::ceil:
6206   case Intrinsic::trunc:
6207   case Intrinsic::rint:
6208   case Intrinsic::nearbyint:
6209   case Intrinsic::round:
6210   case Intrinsic::canonicalize: {
6211     unsigned Opcode;
6212     switch (Intrinsic) {
6213     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6214     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6215     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6216     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6217     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6218     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6219     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6220     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6221     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6222     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6223     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6224     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6225     }
6226 
6227     setValue(&I, DAG.getNode(Opcode, sdl,
6228                              getValue(I.getArgOperand(0)).getValueType(),
6229                              getValue(I.getArgOperand(0))));
6230     return;
6231   }
6232   case Intrinsic::lround:
6233   case Intrinsic::llround:
6234   case Intrinsic::lrint:
6235   case Intrinsic::llrint: {
6236     unsigned Opcode;
6237     switch (Intrinsic) {
6238     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6239     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6240     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6241     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6242     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6243     }
6244 
6245     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6246     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6247                              getValue(I.getArgOperand(0))));
6248     return;
6249   }
6250   case Intrinsic::minnum:
6251     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6252                              getValue(I.getArgOperand(0)).getValueType(),
6253                              getValue(I.getArgOperand(0)),
6254                              getValue(I.getArgOperand(1))));
6255     return;
6256   case Intrinsic::maxnum:
6257     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6258                              getValue(I.getArgOperand(0)).getValueType(),
6259                              getValue(I.getArgOperand(0)),
6260                              getValue(I.getArgOperand(1))));
6261     return;
6262   case Intrinsic::minimum:
6263     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6264                              getValue(I.getArgOperand(0)).getValueType(),
6265                              getValue(I.getArgOperand(0)),
6266                              getValue(I.getArgOperand(1))));
6267     return;
6268   case Intrinsic::maximum:
6269     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6270                              getValue(I.getArgOperand(0)).getValueType(),
6271                              getValue(I.getArgOperand(0)),
6272                              getValue(I.getArgOperand(1))));
6273     return;
6274   case Intrinsic::copysign:
6275     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6276                              getValue(I.getArgOperand(0)).getValueType(),
6277                              getValue(I.getArgOperand(0)),
6278                              getValue(I.getArgOperand(1))));
6279     return;
6280   case Intrinsic::fma:
6281     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6282                              getValue(I.getArgOperand(0)).getValueType(),
6283                              getValue(I.getArgOperand(0)),
6284                              getValue(I.getArgOperand(1)),
6285                              getValue(I.getArgOperand(2))));
6286     return;
6287 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6288   case Intrinsic::INTRINSIC:
6289 #include "llvm/IR/ConstrainedOps.def"
6290     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6291     return;
6292   case Intrinsic::fmuladd: {
6293     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6294     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6295         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6296       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6297                                getValue(I.getArgOperand(0)).getValueType(),
6298                                getValue(I.getArgOperand(0)),
6299                                getValue(I.getArgOperand(1)),
6300                                getValue(I.getArgOperand(2))));
6301     } else {
6302       // TODO: Intrinsic calls should have fast-math-flags.
6303       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6304                                 getValue(I.getArgOperand(0)).getValueType(),
6305                                 getValue(I.getArgOperand(0)),
6306                                 getValue(I.getArgOperand(1)));
6307       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6308                                 getValue(I.getArgOperand(0)).getValueType(),
6309                                 Mul,
6310                                 getValue(I.getArgOperand(2)));
6311       setValue(&I, Add);
6312     }
6313     return;
6314   }
6315   case Intrinsic::convert_to_fp16:
6316     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6317                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6318                                          getValue(I.getArgOperand(0)),
6319                                          DAG.getTargetConstant(0, sdl,
6320                                                                MVT::i32))));
6321     return;
6322   case Intrinsic::convert_from_fp16:
6323     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6324                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6325                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6326                                          getValue(I.getArgOperand(0)))));
6327     return;
6328   case Intrinsic::pcmarker: {
6329     SDValue Tmp = getValue(I.getArgOperand(0));
6330     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6331     return;
6332   }
6333   case Intrinsic::readcyclecounter: {
6334     SDValue Op = getRoot();
6335     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6336                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6337     setValue(&I, Res);
6338     DAG.setRoot(Res.getValue(1));
6339     return;
6340   }
6341   case Intrinsic::bitreverse:
6342     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6343                              getValue(I.getArgOperand(0)).getValueType(),
6344                              getValue(I.getArgOperand(0))));
6345     return;
6346   case Intrinsic::bswap:
6347     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6348                              getValue(I.getArgOperand(0)).getValueType(),
6349                              getValue(I.getArgOperand(0))));
6350     return;
6351   case Intrinsic::cttz: {
6352     SDValue Arg = getValue(I.getArgOperand(0));
6353     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6354     EVT Ty = Arg.getValueType();
6355     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6356                              sdl, Ty, Arg));
6357     return;
6358   }
6359   case Intrinsic::ctlz: {
6360     SDValue Arg = getValue(I.getArgOperand(0));
6361     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6362     EVT Ty = Arg.getValueType();
6363     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6364                              sdl, Ty, Arg));
6365     return;
6366   }
6367   case Intrinsic::ctpop: {
6368     SDValue Arg = getValue(I.getArgOperand(0));
6369     EVT Ty = Arg.getValueType();
6370     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6371     return;
6372   }
6373   case Intrinsic::fshl:
6374   case Intrinsic::fshr: {
6375     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6376     SDValue X = getValue(I.getArgOperand(0));
6377     SDValue Y = getValue(I.getArgOperand(1));
6378     SDValue Z = getValue(I.getArgOperand(2));
6379     EVT VT = X.getValueType();
6380     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6381     SDValue Zero = DAG.getConstant(0, sdl, VT);
6382     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6383 
6384     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6385     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6386       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6387       return;
6388     }
6389 
6390     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6391     // avoid the select that is necessary in the general case to filter out
6392     // the 0-shift possibility that leads to UB.
6393     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6394       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6395       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6396         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6397         return;
6398       }
6399 
6400       // Some targets only rotate one way. Try the opposite direction.
6401       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6402       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6403         // Negate the shift amount because it is safe to ignore the high bits.
6404         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6405         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6406         return;
6407       }
6408 
6409       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6410       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6411       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6412       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6413       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6414       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6415       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6416       return;
6417     }
6418 
6419     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6420     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6421     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6422     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6423     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6424     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6425 
6426     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6427     // and that is undefined. We must compare and select to avoid UB.
6428     EVT CCVT = MVT::i1;
6429     if (VT.isVector())
6430       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6431 
6432     // For fshl, 0-shift returns the 1st arg (X).
6433     // For fshr, 0-shift returns the 2nd arg (Y).
6434     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6435     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6436     return;
6437   }
6438   case Intrinsic::sadd_sat: {
6439     SDValue Op1 = getValue(I.getArgOperand(0));
6440     SDValue Op2 = getValue(I.getArgOperand(1));
6441     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6442     return;
6443   }
6444   case Intrinsic::uadd_sat: {
6445     SDValue Op1 = getValue(I.getArgOperand(0));
6446     SDValue Op2 = getValue(I.getArgOperand(1));
6447     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6448     return;
6449   }
6450   case Intrinsic::ssub_sat: {
6451     SDValue Op1 = getValue(I.getArgOperand(0));
6452     SDValue Op2 = getValue(I.getArgOperand(1));
6453     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6454     return;
6455   }
6456   case Intrinsic::usub_sat: {
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6460     return;
6461   }
6462   case Intrinsic::smul_fix:
6463   case Intrinsic::umul_fix:
6464   case Intrinsic::smul_fix_sat:
6465   case Intrinsic::umul_fix_sat: {
6466     SDValue Op1 = getValue(I.getArgOperand(0));
6467     SDValue Op2 = getValue(I.getArgOperand(1));
6468     SDValue Op3 = getValue(I.getArgOperand(2));
6469     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6470                              Op1.getValueType(), Op1, Op2, Op3));
6471     return;
6472   }
6473   case Intrinsic::sdiv_fix:
6474   case Intrinsic::udiv_fix:
6475   case Intrinsic::sdiv_fix_sat:
6476   case Intrinsic::udiv_fix_sat: {
6477     SDValue Op1 = getValue(I.getArgOperand(0));
6478     SDValue Op2 = getValue(I.getArgOperand(1));
6479     SDValue Op3 = getValue(I.getArgOperand(2));
6480     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6481                               Op1, Op2, Op3, DAG, TLI));
6482     return;
6483   }
6484   case Intrinsic::stacksave: {
6485     SDValue Op = getRoot();
6486     Res = DAG.getNode(
6487         ISD::STACKSAVE, sdl,
6488         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6489     setValue(&I, Res);
6490     DAG.setRoot(Res.getValue(1));
6491     return;
6492   }
6493   case Intrinsic::stackrestore:
6494     Res = getValue(I.getArgOperand(0));
6495     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6496     return;
6497   case Intrinsic::get_dynamic_area_offset: {
6498     SDValue Op = getRoot();
6499     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6500     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6501     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6502     // target.
6503     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6504       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6505                          " intrinsic!");
6506     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6507                       Op);
6508     DAG.setRoot(Op);
6509     setValue(&I, Res);
6510     return;
6511   }
6512   case Intrinsic::stackguard: {
6513     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6514     MachineFunction &MF = DAG.getMachineFunction();
6515     const Module &M = *MF.getFunction().getParent();
6516     SDValue Chain = getRoot();
6517     if (TLI.useLoadStackGuardNode()) {
6518       Res = getLoadStackGuard(DAG, sdl, Chain);
6519     } else {
6520       const Value *Global = TLI.getSDagStackGuard(M);
6521       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6522       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6523                         MachinePointerInfo(Global, 0), Align,
6524                         MachineMemOperand::MOVolatile);
6525     }
6526     if (TLI.useStackGuardXorFP())
6527       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6528     DAG.setRoot(Chain);
6529     setValue(&I, Res);
6530     return;
6531   }
6532   case Intrinsic::stackprotector: {
6533     // Emit code into the DAG to store the stack guard onto the stack.
6534     MachineFunction &MF = DAG.getMachineFunction();
6535     MachineFrameInfo &MFI = MF.getFrameInfo();
6536     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6537     SDValue Src, Chain = getRoot();
6538 
6539     if (TLI.useLoadStackGuardNode())
6540       Src = getLoadStackGuard(DAG, sdl, Chain);
6541     else
6542       Src = getValue(I.getArgOperand(0));   // The guard's value.
6543 
6544     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6545 
6546     int FI = FuncInfo.StaticAllocaMap[Slot];
6547     MFI.setStackProtectorIndex(FI);
6548 
6549     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6550 
6551     // Store the stack protector onto the stack.
6552     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6553                                                  DAG.getMachineFunction(), FI),
6554                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6555     setValue(&I, Res);
6556     DAG.setRoot(Res);
6557     return;
6558   }
6559   case Intrinsic::objectsize:
6560     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6561 
6562   case Intrinsic::is_constant:
6563     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6564 
6565   case Intrinsic::annotation:
6566   case Intrinsic::ptr_annotation:
6567   case Intrinsic::launder_invariant_group:
6568   case Intrinsic::strip_invariant_group:
6569     // Drop the intrinsic, but forward the value
6570     setValue(&I, getValue(I.getOperand(0)));
6571     return;
6572   case Intrinsic::assume:
6573   case Intrinsic::var_annotation:
6574   case Intrinsic::sideeffect:
6575     // Discard annotate attributes, assumptions, and artificial side-effects.
6576     return;
6577 
6578   case Intrinsic::codeview_annotation: {
6579     // Emit a label associated with this metadata.
6580     MachineFunction &MF = DAG.getMachineFunction();
6581     MCSymbol *Label =
6582         MF.getMMI().getContext().createTempSymbol("annotation", true);
6583     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6584     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6585     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6586     DAG.setRoot(Res);
6587     return;
6588   }
6589 
6590   case Intrinsic::init_trampoline: {
6591     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6592 
6593     SDValue Ops[6];
6594     Ops[0] = getRoot();
6595     Ops[1] = getValue(I.getArgOperand(0));
6596     Ops[2] = getValue(I.getArgOperand(1));
6597     Ops[3] = getValue(I.getArgOperand(2));
6598     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6599     Ops[5] = DAG.getSrcValue(F);
6600 
6601     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6602 
6603     DAG.setRoot(Res);
6604     return;
6605   }
6606   case Intrinsic::adjust_trampoline:
6607     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6608                              TLI.getPointerTy(DAG.getDataLayout()),
6609                              getValue(I.getArgOperand(0))));
6610     return;
6611   case Intrinsic::gcroot: {
6612     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6613            "only valid in functions with gc specified, enforced by Verifier");
6614     assert(GFI && "implied by previous");
6615     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6616     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6617 
6618     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6619     GFI->addStackRoot(FI->getIndex(), TypeMap);
6620     return;
6621   }
6622   case Intrinsic::gcread:
6623   case Intrinsic::gcwrite:
6624     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6625   case Intrinsic::flt_rounds:
6626     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6627     setValue(&I, Res);
6628     DAG.setRoot(Res.getValue(1));
6629     return;
6630 
6631   case Intrinsic::expect:
6632     // Just replace __builtin_expect(exp, c) with EXP.
6633     setValue(&I, getValue(I.getArgOperand(0)));
6634     return;
6635 
6636   case Intrinsic::debugtrap:
6637   case Intrinsic::trap: {
6638     StringRef TrapFuncName =
6639         I.getAttributes()
6640             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6641             .getValueAsString();
6642     if (TrapFuncName.empty()) {
6643       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6644         ISD::TRAP : ISD::DEBUGTRAP;
6645       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6646       return;
6647     }
6648     TargetLowering::ArgListTy Args;
6649 
6650     TargetLowering::CallLoweringInfo CLI(DAG);
6651     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6652         CallingConv::C, I.getType(),
6653         DAG.getExternalSymbol(TrapFuncName.data(),
6654                               TLI.getPointerTy(DAG.getDataLayout())),
6655         std::move(Args));
6656 
6657     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6658     DAG.setRoot(Result.second);
6659     return;
6660   }
6661 
6662   case Intrinsic::uadd_with_overflow:
6663   case Intrinsic::sadd_with_overflow:
6664   case Intrinsic::usub_with_overflow:
6665   case Intrinsic::ssub_with_overflow:
6666   case Intrinsic::umul_with_overflow:
6667   case Intrinsic::smul_with_overflow: {
6668     ISD::NodeType Op;
6669     switch (Intrinsic) {
6670     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6671     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6672     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6673     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6674     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6675     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6676     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6677     }
6678     SDValue Op1 = getValue(I.getArgOperand(0));
6679     SDValue Op2 = getValue(I.getArgOperand(1));
6680 
6681     EVT ResultVT = Op1.getValueType();
6682     EVT OverflowVT = MVT::i1;
6683     if (ResultVT.isVector())
6684       OverflowVT = EVT::getVectorVT(
6685           *Context, OverflowVT, ResultVT.getVectorNumElements());
6686 
6687     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6688     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6689     return;
6690   }
6691   case Intrinsic::prefetch: {
6692     SDValue Ops[5];
6693     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6694     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6695     Ops[0] = DAG.getRoot();
6696     Ops[1] = getValue(I.getArgOperand(0));
6697     Ops[2] = getValue(I.getArgOperand(1));
6698     Ops[3] = getValue(I.getArgOperand(2));
6699     Ops[4] = getValue(I.getArgOperand(3));
6700     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6701                                              DAG.getVTList(MVT::Other), Ops,
6702                                              EVT::getIntegerVT(*Context, 8),
6703                                              MachinePointerInfo(I.getArgOperand(0)),
6704                                              0, /* align */
6705                                              Flags);
6706 
6707     // Chain the prefetch in parallell with any pending loads, to stay out of
6708     // the way of later optimizations.
6709     PendingLoads.push_back(Result);
6710     Result = getRoot();
6711     DAG.setRoot(Result);
6712     return;
6713   }
6714   case Intrinsic::lifetime_start:
6715   case Intrinsic::lifetime_end: {
6716     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6717     // Stack coloring is not enabled in O0, discard region information.
6718     if (TM.getOptLevel() == CodeGenOpt::None)
6719       return;
6720 
6721     const int64_t ObjectSize =
6722         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6723     Value *const ObjectPtr = I.getArgOperand(1);
6724     SmallVector<const Value *, 4> Allocas;
6725     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6726 
6727     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6728            E = Allocas.end(); Object != E; ++Object) {
6729       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6730 
6731       // Could not find an Alloca.
6732       if (!LifetimeObject)
6733         continue;
6734 
6735       // First check that the Alloca is static, otherwise it won't have a
6736       // valid frame index.
6737       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6738       if (SI == FuncInfo.StaticAllocaMap.end())
6739         return;
6740 
6741       const int FrameIndex = SI->second;
6742       int64_t Offset;
6743       if (GetPointerBaseWithConstantOffset(
6744               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6745         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6746       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6747                                 Offset);
6748       DAG.setRoot(Res);
6749     }
6750     return;
6751   }
6752   case Intrinsic::invariant_start:
6753     // Discard region information.
6754     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6755     return;
6756   case Intrinsic::invariant_end:
6757     // Discard region information.
6758     return;
6759   case Intrinsic::clear_cache:
6760     /// FunctionName may be null.
6761     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6762       lowerCallToExternalSymbol(I, FunctionName);
6763     return;
6764   case Intrinsic::donothing:
6765     // ignore
6766     return;
6767   case Intrinsic::experimental_stackmap:
6768     visitStackmap(I);
6769     return;
6770   case Intrinsic::experimental_patchpoint_void:
6771   case Intrinsic::experimental_patchpoint_i64:
6772     visitPatchpoint(&I);
6773     return;
6774   case Intrinsic::experimental_gc_statepoint:
6775     LowerStatepoint(ImmutableStatepoint(&I));
6776     return;
6777   case Intrinsic::experimental_gc_result:
6778     visitGCResult(cast<GCResultInst>(I));
6779     return;
6780   case Intrinsic::experimental_gc_relocate:
6781     visitGCRelocate(cast<GCRelocateInst>(I));
6782     return;
6783   case Intrinsic::instrprof_increment:
6784     llvm_unreachable("instrprof failed to lower an increment");
6785   case Intrinsic::instrprof_value_profile:
6786     llvm_unreachable("instrprof failed to lower a value profiling call");
6787   case Intrinsic::localescape: {
6788     MachineFunction &MF = DAG.getMachineFunction();
6789     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6790 
6791     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6792     // is the same on all targets.
6793     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6794       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6795       if (isa<ConstantPointerNull>(Arg))
6796         continue; // Skip null pointers. They represent a hole in index space.
6797       AllocaInst *Slot = cast<AllocaInst>(Arg);
6798       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6799              "can only escape static allocas");
6800       int FI = FuncInfo.StaticAllocaMap[Slot];
6801       MCSymbol *FrameAllocSym =
6802           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6803               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6804       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6805               TII->get(TargetOpcode::LOCAL_ESCAPE))
6806           .addSym(FrameAllocSym)
6807           .addFrameIndex(FI);
6808     }
6809 
6810     return;
6811   }
6812 
6813   case Intrinsic::localrecover: {
6814     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6815     MachineFunction &MF = DAG.getMachineFunction();
6816     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6817 
6818     // Get the symbol that defines the frame offset.
6819     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6820     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6821     unsigned IdxVal =
6822         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6823     MCSymbol *FrameAllocSym =
6824         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6825             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6826 
6827     // Create a MCSymbol for the label to avoid any target lowering
6828     // that would make this PC relative.
6829     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6830     SDValue OffsetVal =
6831         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6832 
6833     // Add the offset to the FP.
6834     Value *FP = I.getArgOperand(1);
6835     SDValue FPVal = getValue(FP);
6836     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6837     setValue(&I, Add);
6838 
6839     return;
6840   }
6841 
6842   case Intrinsic::eh_exceptionpointer:
6843   case Intrinsic::eh_exceptioncode: {
6844     // Get the exception pointer vreg, copy from it, and resize it to fit.
6845     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6846     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6847     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6848     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6849     SDValue N =
6850         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6851     if (Intrinsic == Intrinsic::eh_exceptioncode)
6852       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6853     setValue(&I, N);
6854     return;
6855   }
6856   case Intrinsic::xray_customevent: {
6857     // Here we want to make sure that the intrinsic behaves as if it has a
6858     // specific calling convention, and only for x86_64.
6859     // FIXME: Support other platforms later.
6860     const auto &Triple = DAG.getTarget().getTargetTriple();
6861     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6862       return;
6863 
6864     SDLoc DL = getCurSDLoc();
6865     SmallVector<SDValue, 8> Ops;
6866 
6867     // We want to say that we always want the arguments in registers.
6868     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6869     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6870     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6871     SDValue Chain = getRoot();
6872     Ops.push_back(LogEntryVal);
6873     Ops.push_back(StrSizeVal);
6874     Ops.push_back(Chain);
6875 
6876     // We need to enforce the calling convention for the callsite, so that
6877     // argument ordering is enforced correctly, and that register allocation can
6878     // see that some registers may be assumed clobbered and have to preserve
6879     // them across calls to the intrinsic.
6880     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6881                                            DL, NodeTys, Ops);
6882     SDValue patchableNode = SDValue(MN, 0);
6883     DAG.setRoot(patchableNode);
6884     setValue(&I, patchableNode);
6885     return;
6886   }
6887   case Intrinsic::xray_typedevent: {
6888     // Here we want to make sure that the intrinsic behaves as if it has a
6889     // specific calling convention, and only for x86_64.
6890     // FIXME: Support other platforms later.
6891     const auto &Triple = DAG.getTarget().getTargetTriple();
6892     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6893       return;
6894 
6895     SDLoc DL = getCurSDLoc();
6896     SmallVector<SDValue, 8> Ops;
6897 
6898     // We want to say that we always want the arguments in registers.
6899     // It's unclear to me how manipulating the selection DAG here forces callers
6900     // to provide arguments in registers instead of on the stack.
6901     SDValue LogTypeId = getValue(I.getArgOperand(0));
6902     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6903     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6904     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6905     SDValue Chain = getRoot();
6906     Ops.push_back(LogTypeId);
6907     Ops.push_back(LogEntryVal);
6908     Ops.push_back(StrSizeVal);
6909     Ops.push_back(Chain);
6910 
6911     // We need to enforce the calling convention for the callsite, so that
6912     // argument ordering is enforced correctly, and that register allocation can
6913     // see that some registers may be assumed clobbered and have to preserve
6914     // them across calls to the intrinsic.
6915     MachineSDNode *MN = DAG.getMachineNode(
6916         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6917     SDValue patchableNode = SDValue(MN, 0);
6918     DAG.setRoot(patchableNode);
6919     setValue(&I, patchableNode);
6920     return;
6921   }
6922   case Intrinsic::experimental_deoptimize:
6923     LowerDeoptimizeCall(&I);
6924     return;
6925 
6926   case Intrinsic::experimental_vector_reduce_v2_fadd:
6927   case Intrinsic::experimental_vector_reduce_v2_fmul:
6928   case Intrinsic::experimental_vector_reduce_add:
6929   case Intrinsic::experimental_vector_reduce_mul:
6930   case Intrinsic::experimental_vector_reduce_and:
6931   case Intrinsic::experimental_vector_reduce_or:
6932   case Intrinsic::experimental_vector_reduce_xor:
6933   case Intrinsic::experimental_vector_reduce_smax:
6934   case Intrinsic::experimental_vector_reduce_smin:
6935   case Intrinsic::experimental_vector_reduce_umax:
6936   case Intrinsic::experimental_vector_reduce_umin:
6937   case Intrinsic::experimental_vector_reduce_fmax:
6938   case Intrinsic::experimental_vector_reduce_fmin:
6939     visitVectorReduce(I, Intrinsic);
6940     return;
6941 
6942   case Intrinsic::icall_branch_funnel: {
6943     SmallVector<SDValue, 16> Ops;
6944     Ops.push_back(getValue(I.getArgOperand(0)));
6945 
6946     int64_t Offset;
6947     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6948         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6949     if (!Base)
6950       report_fatal_error(
6951           "llvm.icall.branch.funnel operand must be a GlobalValue");
6952     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6953 
6954     struct BranchFunnelTarget {
6955       int64_t Offset;
6956       SDValue Target;
6957     };
6958     SmallVector<BranchFunnelTarget, 8> Targets;
6959 
6960     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6961       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6962           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6963       if (ElemBase != Base)
6964         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6965                            "to the same GlobalValue");
6966 
6967       SDValue Val = getValue(I.getArgOperand(Op + 1));
6968       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6969       if (!GA)
6970         report_fatal_error(
6971             "llvm.icall.branch.funnel operand must be a GlobalValue");
6972       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6973                                      GA->getGlobal(), getCurSDLoc(),
6974                                      Val.getValueType(), GA->getOffset())});
6975     }
6976     llvm::sort(Targets,
6977                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6978                  return T1.Offset < T2.Offset;
6979                });
6980 
6981     for (auto &T : Targets) {
6982       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6983       Ops.push_back(T.Target);
6984     }
6985 
6986     Ops.push_back(DAG.getRoot()); // Chain
6987     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6988                                  getCurSDLoc(), MVT::Other, Ops),
6989               0);
6990     DAG.setRoot(N);
6991     setValue(&I, N);
6992     HasTailCall = true;
6993     return;
6994   }
6995 
6996   case Intrinsic::wasm_landingpad_index:
6997     // Information this intrinsic contained has been transferred to
6998     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6999     // delete it now.
7000     return;
7001 
7002   case Intrinsic::aarch64_settag:
7003   case Intrinsic::aarch64_settag_zero: {
7004     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7005     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7006     SDValue Val = TSI.EmitTargetCodeForSetTag(
7007         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7008         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7009         ZeroMemory);
7010     DAG.setRoot(Val);
7011     setValue(&I, Val);
7012     return;
7013   }
7014   case Intrinsic::ptrmask: {
7015     SDValue Ptr = getValue(I.getOperand(0));
7016     SDValue Const = getValue(I.getOperand(1));
7017 
7018     EVT DestVT =
7019         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7020 
7021     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
7022                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
7023     return;
7024   }
7025   }
7026 }
7027 
7028 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7029     const ConstrainedFPIntrinsic &FPI) {
7030   SDLoc sdl = getCurSDLoc();
7031 
7032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7033   SmallVector<EVT, 4> ValueVTs;
7034   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7035   ValueVTs.push_back(MVT::Other); // Out chain
7036 
7037   // We do not need to serialize constrained FP intrinsics against
7038   // each other or against (nonvolatile) loads, so they can be
7039   // chained like loads.
7040   SDValue Chain = DAG.getRoot();
7041   SmallVector<SDValue, 4> Opers;
7042   Opers.push_back(Chain);
7043   if (FPI.isUnaryOp()) {
7044     Opers.push_back(getValue(FPI.getArgOperand(0)));
7045   } else if (FPI.isTernaryOp()) {
7046     Opers.push_back(getValue(FPI.getArgOperand(0)));
7047     Opers.push_back(getValue(FPI.getArgOperand(1)));
7048     Opers.push_back(getValue(FPI.getArgOperand(2)));
7049   } else {
7050     Opers.push_back(getValue(FPI.getArgOperand(0)));
7051     Opers.push_back(getValue(FPI.getArgOperand(1)));
7052   }
7053 
7054   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7055     assert(Result.getNode()->getNumValues() == 2);
7056 
7057     // Push node to the appropriate list so that future instructions can be
7058     // chained up correctly.
7059     SDValue OutChain = Result.getValue(1);
7060     switch (EB) {
7061     case fp::ExceptionBehavior::ebIgnore:
7062       // The only reason why ebIgnore nodes still need to be chained is that
7063       // they might depend on the current rounding mode, and therefore must
7064       // not be moved across instruction that may change that mode.
7065       LLVM_FALLTHROUGH;
7066     case fp::ExceptionBehavior::ebMayTrap:
7067       // These must not be moved across calls or instructions that may change
7068       // floating-point exception masks.
7069       PendingConstrainedFP.push_back(OutChain);
7070       break;
7071     case fp::ExceptionBehavior::ebStrict:
7072       // These must not be moved across calls or instructions that may change
7073       // floating-point exception masks or read floating-point exception flags.
7074       // In addition, they cannot be optimized out even if unused.
7075       PendingConstrainedFPStrict.push_back(OutChain);
7076       break;
7077     }
7078   };
7079 
7080   SDVTList VTs = DAG.getVTList(ValueVTs);
7081   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7082 
7083   unsigned Opcode;
7084   switch (FPI.getIntrinsicID()) {
7085   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7086 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7087   case Intrinsic::INTRINSIC:                                                   \
7088     Opcode = ISD::STRICT_##DAGN;                                               \
7089     break;
7090 #include "llvm/IR/ConstrainedOps.def"
7091   case Intrinsic::experimental_constrained_fmuladd: {
7092     Opcode = ISD::STRICT_FMA;
7093     // Break fmuladd into fmul and fadd.
7094     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7095         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7096                                         ValueVTs[0])) {
7097       Opers.pop_back();
7098       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers);
7099       pushOutChain(Mul, EB);
7100       Opcode = ISD::STRICT_FADD;
7101       Opers.clear();
7102       Opers.push_back(Mul.getValue(1));
7103       Opers.push_back(Mul.getValue(0));
7104       Opers.push_back(getValue(FPI.getArgOperand(2)));
7105     }
7106     break;
7107   }
7108   }
7109 
7110   // A few strict DAG nodes carry additional operands that are not
7111   // set up by the default code above.
7112   switch (Opcode) {
7113   default: break;
7114   case ISD::STRICT_FP_ROUND:
7115     Opers.push_back(
7116         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7117     break;
7118   case ISD::STRICT_FSETCC:
7119   case ISD::STRICT_FSETCCS: {
7120     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7121     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7122     break;
7123   }
7124   }
7125 
7126   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7127   pushOutChain(Result, EB);
7128 
7129   SDValue FPResult = Result.getValue(0);
7130   setValue(&FPI, FPResult);
7131 }
7132 
7133 std::pair<SDValue, SDValue>
7134 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7135                                     const BasicBlock *EHPadBB) {
7136   MachineFunction &MF = DAG.getMachineFunction();
7137   MachineModuleInfo &MMI = MF.getMMI();
7138   MCSymbol *BeginLabel = nullptr;
7139 
7140   if (EHPadBB) {
7141     // Insert a label before the invoke call to mark the try range.  This can be
7142     // used to detect deletion of the invoke via the MachineModuleInfo.
7143     BeginLabel = MMI.getContext().createTempSymbol();
7144 
7145     // For SjLj, keep track of which landing pads go with which invokes
7146     // so as to maintain the ordering of pads in the LSDA.
7147     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7148     if (CallSiteIndex) {
7149       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7150       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7151 
7152       // Now that the call site is handled, stop tracking it.
7153       MMI.setCurrentCallSite(0);
7154     }
7155 
7156     // Both PendingLoads and PendingExports must be flushed here;
7157     // this call might not return.
7158     (void)getRoot();
7159     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7160 
7161     CLI.setChain(getRoot());
7162   }
7163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7164   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7165 
7166   assert((CLI.IsTailCall || Result.second.getNode()) &&
7167          "Non-null chain expected with non-tail call!");
7168   assert((Result.second.getNode() || !Result.first.getNode()) &&
7169          "Null value expected with tail call!");
7170 
7171   if (!Result.second.getNode()) {
7172     // As a special case, a null chain means that a tail call has been emitted
7173     // and the DAG root is already updated.
7174     HasTailCall = true;
7175 
7176     // Since there's no actual continuation from this block, nothing can be
7177     // relying on us setting vregs for them.
7178     PendingExports.clear();
7179   } else {
7180     DAG.setRoot(Result.second);
7181   }
7182 
7183   if (EHPadBB) {
7184     // Insert a label at the end of the invoke call to mark the try range.  This
7185     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7186     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7187     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7188 
7189     // Inform MachineModuleInfo of range.
7190     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7191     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7192     // actually use outlined funclets and their LSDA info style.
7193     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7194       assert(CLI.CS);
7195       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7196       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7197                                 BeginLabel, EndLabel);
7198     } else if (!isScopedEHPersonality(Pers)) {
7199       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7200     }
7201   }
7202 
7203   return Result;
7204 }
7205 
7206 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7207                                       bool isTailCall,
7208                                       const BasicBlock *EHPadBB) {
7209   auto &DL = DAG.getDataLayout();
7210   FunctionType *FTy = CS.getFunctionType();
7211   Type *RetTy = CS.getType();
7212 
7213   TargetLowering::ArgListTy Args;
7214   Args.reserve(CS.arg_size());
7215 
7216   const Value *SwiftErrorVal = nullptr;
7217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7218 
7219   if (isTailCall) {
7220     // Avoid emitting tail calls in functions with the disable-tail-calls
7221     // attribute.
7222     auto *Caller = CS.getInstruction()->getParent()->getParent();
7223     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7224         "true")
7225       isTailCall = false;
7226 
7227     // We can't tail call inside a function with a swifterror argument. Lowering
7228     // does not support this yet. It would have to move into the swifterror
7229     // register before the call.
7230     if (TLI.supportSwiftError() &&
7231         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7232       isTailCall = false;
7233   }
7234 
7235   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7236        i != e; ++i) {
7237     TargetLowering::ArgListEntry Entry;
7238     const Value *V = *i;
7239 
7240     // Skip empty types
7241     if (V->getType()->isEmptyTy())
7242       continue;
7243 
7244     SDValue ArgNode = getValue(V);
7245     Entry.Node = ArgNode; Entry.Ty = V->getType();
7246 
7247     Entry.setAttributes(&CS, i - CS.arg_begin());
7248 
7249     // Use swifterror virtual register as input to the call.
7250     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7251       SwiftErrorVal = V;
7252       // We find the virtual register for the actual swifterror argument.
7253       // Instead of using the Value, we use the virtual register instead.
7254       Entry.Node = DAG.getRegister(
7255           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7256           EVT(TLI.getPointerTy(DL)));
7257     }
7258 
7259     Args.push_back(Entry);
7260 
7261     // If we have an explicit sret argument that is an Instruction, (i.e., it
7262     // might point to function-local memory), we can't meaningfully tail-call.
7263     if (Entry.IsSRet && isa<Instruction>(V))
7264       isTailCall = false;
7265   }
7266 
7267   // If call site has a cfguardtarget operand bundle, create and add an
7268   // additional ArgListEntry.
7269   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7270     TargetLowering::ArgListEntry Entry;
7271     Value *V = Bundle->Inputs[0];
7272     SDValue ArgNode = getValue(V);
7273     Entry.Node = ArgNode;
7274     Entry.Ty = V->getType();
7275     Entry.IsCFGuardTarget = true;
7276     Args.push_back(Entry);
7277   }
7278 
7279   // Check if target-independent constraints permit a tail call here.
7280   // Target-dependent constraints are checked within TLI->LowerCallTo.
7281   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7282     isTailCall = false;
7283 
7284   // Disable tail calls if there is an swifterror argument. Targets have not
7285   // been updated to support tail calls.
7286   if (TLI.supportSwiftError() && SwiftErrorVal)
7287     isTailCall = false;
7288 
7289   TargetLowering::CallLoweringInfo CLI(DAG);
7290   CLI.setDebugLoc(getCurSDLoc())
7291       .setChain(getRoot())
7292       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7293       .setTailCall(isTailCall)
7294       .setConvergent(CS.isConvergent());
7295   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7296 
7297   if (Result.first.getNode()) {
7298     const Instruction *Inst = CS.getInstruction();
7299     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7300     setValue(Inst, Result.first);
7301   }
7302 
7303   // The last element of CLI.InVals has the SDValue for swifterror return.
7304   // Here we copy it to a virtual register and update SwiftErrorMap for
7305   // book-keeping.
7306   if (SwiftErrorVal && TLI.supportSwiftError()) {
7307     // Get the last element of InVals.
7308     SDValue Src = CLI.InVals.back();
7309     Register VReg = SwiftError.getOrCreateVRegDefAt(
7310         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7311     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7312     DAG.setRoot(CopyNode);
7313   }
7314 }
7315 
7316 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7317                              SelectionDAGBuilder &Builder) {
7318   // Check to see if this load can be trivially constant folded, e.g. if the
7319   // input is from a string literal.
7320   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7321     // Cast pointer to the type we really want to load.
7322     Type *LoadTy =
7323         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7324     if (LoadVT.isVector())
7325       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7326 
7327     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7328                                          PointerType::getUnqual(LoadTy));
7329 
7330     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7331             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7332       return Builder.getValue(LoadCst);
7333   }
7334 
7335   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7336   // still constant memory, the input chain can be the entry node.
7337   SDValue Root;
7338   bool ConstantMemory = false;
7339 
7340   // Do not serialize (non-volatile) loads of constant memory with anything.
7341   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7342     Root = Builder.DAG.getEntryNode();
7343     ConstantMemory = true;
7344   } else {
7345     // Do not serialize non-volatile loads against each other.
7346     Root = Builder.DAG.getRoot();
7347   }
7348 
7349   SDValue Ptr = Builder.getValue(PtrVal);
7350   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7351                                         Ptr, MachinePointerInfo(PtrVal),
7352                                         /* Alignment = */ 1);
7353 
7354   if (!ConstantMemory)
7355     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7356   return LoadVal;
7357 }
7358 
7359 /// Record the value for an instruction that produces an integer result,
7360 /// converting the type where necessary.
7361 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7362                                                   SDValue Value,
7363                                                   bool IsSigned) {
7364   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7365                                                     I.getType(), true);
7366   if (IsSigned)
7367     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7368   else
7369     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7370   setValue(&I, Value);
7371 }
7372 
7373 /// See if we can lower a memcmp call into an optimized form. If so, return
7374 /// true and lower it. Otherwise return false, and it will be lowered like a
7375 /// normal call.
7376 /// The caller already checked that \p I calls the appropriate LibFunc with a
7377 /// correct prototype.
7378 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7379   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7380   const Value *Size = I.getArgOperand(2);
7381   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7382   if (CSize && CSize->getZExtValue() == 0) {
7383     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7384                                                           I.getType(), true);
7385     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7386     return true;
7387   }
7388 
7389   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7390   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7391       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7392       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7393   if (Res.first.getNode()) {
7394     processIntegerCallValue(I, Res.first, true);
7395     PendingLoads.push_back(Res.second);
7396     return true;
7397   }
7398 
7399   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7400   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7401   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7402     return false;
7403 
7404   // If the target has a fast compare for the given size, it will return a
7405   // preferred load type for that size. Require that the load VT is legal and
7406   // that the target supports unaligned loads of that type. Otherwise, return
7407   // INVALID.
7408   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7409     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7410     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7411     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7412       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7413       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7414       // TODO: Check alignment of src and dest ptrs.
7415       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7416       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7417       if (!TLI.isTypeLegal(LVT) ||
7418           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7419           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7420         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7421     }
7422 
7423     return LVT;
7424   };
7425 
7426   // This turns into unaligned loads. We only do this if the target natively
7427   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7428   // we'll only produce a small number of byte loads.
7429   MVT LoadVT;
7430   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7431   switch (NumBitsToCompare) {
7432   default:
7433     return false;
7434   case 16:
7435     LoadVT = MVT::i16;
7436     break;
7437   case 32:
7438     LoadVT = MVT::i32;
7439     break;
7440   case 64:
7441   case 128:
7442   case 256:
7443     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7444     break;
7445   }
7446 
7447   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7448     return false;
7449 
7450   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7451   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7452 
7453   // Bitcast to a wide integer type if the loads are vectors.
7454   if (LoadVT.isVector()) {
7455     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7456     LoadL = DAG.getBitcast(CmpVT, LoadL);
7457     LoadR = DAG.getBitcast(CmpVT, LoadR);
7458   }
7459 
7460   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7461   processIntegerCallValue(I, Cmp, false);
7462   return true;
7463 }
7464 
7465 /// See if we can lower a memchr call into an optimized form. If so, return
7466 /// true and lower it. Otherwise return false, and it will be lowered like a
7467 /// normal call.
7468 /// The caller already checked that \p I calls the appropriate LibFunc with a
7469 /// correct prototype.
7470 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7471   const Value *Src = I.getArgOperand(0);
7472   const Value *Char = I.getArgOperand(1);
7473   const Value *Length = I.getArgOperand(2);
7474 
7475   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7476   std::pair<SDValue, SDValue> Res =
7477     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7478                                 getValue(Src), getValue(Char), getValue(Length),
7479                                 MachinePointerInfo(Src));
7480   if (Res.first.getNode()) {
7481     setValue(&I, Res.first);
7482     PendingLoads.push_back(Res.second);
7483     return true;
7484   }
7485 
7486   return false;
7487 }
7488 
7489 /// See if we can lower a mempcpy call into an optimized form. If so, return
7490 /// true and lower it. Otherwise return false, and it will be lowered like a
7491 /// normal call.
7492 /// The caller already checked that \p I calls the appropriate LibFunc with a
7493 /// correct prototype.
7494 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7495   SDValue Dst = getValue(I.getArgOperand(0));
7496   SDValue Src = getValue(I.getArgOperand(1));
7497   SDValue Size = getValue(I.getArgOperand(2));
7498 
7499   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7500   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7501   // DAG::getMemcpy needs Alignment to be defined.
7502   Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign));
7503 
7504   bool isVol = false;
7505   SDLoc sdl = getCurSDLoc();
7506 
7507   // In the mempcpy context we need to pass in a false value for isTailCall
7508   // because the return pointer needs to be adjusted by the size of
7509   // the copied memory.
7510   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7511   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7512                              /*isTailCall=*/false,
7513                              MachinePointerInfo(I.getArgOperand(0)),
7514                              MachinePointerInfo(I.getArgOperand(1)));
7515   assert(MC.getNode() != nullptr &&
7516          "** memcpy should not be lowered as TailCall in mempcpy context **");
7517   DAG.setRoot(MC);
7518 
7519   // Check if Size needs to be truncated or extended.
7520   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7521 
7522   // Adjust return pointer to point just past the last dst byte.
7523   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7524                                     Dst, Size);
7525   setValue(&I, DstPlusSize);
7526   return true;
7527 }
7528 
7529 /// See if we can lower a strcpy call into an optimized form.  If so, return
7530 /// true and lower it, otherwise return false and it will be lowered like a
7531 /// normal call.
7532 /// The caller already checked that \p I calls the appropriate LibFunc with a
7533 /// correct prototype.
7534 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7535   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7536 
7537   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7538   std::pair<SDValue, SDValue> Res =
7539     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7540                                 getValue(Arg0), getValue(Arg1),
7541                                 MachinePointerInfo(Arg0),
7542                                 MachinePointerInfo(Arg1), isStpcpy);
7543   if (Res.first.getNode()) {
7544     setValue(&I, Res.first);
7545     DAG.setRoot(Res.second);
7546     return true;
7547   }
7548 
7549   return false;
7550 }
7551 
7552 /// See if we can lower a strcmp call into an optimized form.  If so, return
7553 /// true and lower it, otherwise return false and it will be lowered like a
7554 /// normal call.
7555 /// The caller already checked that \p I calls the appropriate LibFunc with a
7556 /// correct prototype.
7557 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7558   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7559 
7560   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7561   std::pair<SDValue, SDValue> Res =
7562     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7563                                 getValue(Arg0), getValue(Arg1),
7564                                 MachinePointerInfo(Arg0),
7565                                 MachinePointerInfo(Arg1));
7566   if (Res.first.getNode()) {
7567     processIntegerCallValue(I, Res.first, true);
7568     PendingLoads.push_back(Res.second);
7569     return true;
7570   }
7571 
7572   return false;
7573 }
7574 
7575 /// See if we can lower a strlen call into an optimized form.  If so, return
7576 /// true and lower it, otherwise return false and it will be lowered like a
7577 /// normal call.
7578 /// The caller already checked that \p I calls the appropriate LibFunc with a
7579 /// correct prototype.
7580 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7581   const Value *Arg0 = I.getArgOperand(0);
7582 
7583   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7584   std::pair<SDValue, SDValue> Res =
7585     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7586                                 getValue(Arg0), MachinePointerInfo(Arg0));
7587   if (Res.first.getNode()) {
7588     processIntegerCallValue(I, Res.first, false);
7589     PendingLoads.push_back(Res.second);
7590     return true;
7591   }
7592 
7593   return false;
7594 }
7595 
7596 /// See if we can lower a strnlen call into an optimized form.  If so, return
7597 /// true and lower it, otherwise return false and it will be lowered like a
7598 /// normal call.
7599 /// The caller already checked that \p I calls the appropriate LibFunc with a
7600 /// correct prototype.
7601 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7602   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7603 
7604   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7605   std::pair<SDValue, SDValue> Res =
7606     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7607                                  getValue(Arg0), getValue(Arg1),
7608                                  MachinePointerInfo(Arg0));
7609   if (Res.first.getNode()) {
7610     processIntegerCallValue(I, Res.first, false);
7611     PendingLoads.push_back(Res.second);
7612     return true;
7613   }
7614 
7615   return false;
7616 }
7617 
7618 /// See if we can lower a unary floating-point operation into an SDNode with
7619 /// the specified Opcode.  If so, return true and lower it, otherwise return
7620 /// false and it will be lowered like a normal call.
7621 /// The caller already checked that \p I calls the appropriate LibFunc with a
7622 /// correct prototype.
7623 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7624                                               unsigned Opcode) {
7625   // We already checked this call's prototype; verify it doesn't modify errno.
7626   if (!I.onlyReadsMemory())
7627     return false;
7628 
7629   SDValue Tmp = getValue(I.getArgOperand(0));
7630   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7631   return true;
7632 }
7633 
7634 /// See if we can lower a binary floating-point operation into an SDNode with
7635 /// the specified Opcode. If so, return true and lower it. Otherwise return
7636 /// false, and it will be lowered like a normal call.
7637 /// The caller already checked that \p I calls the appropriate LibFunc with a
7638 /// correct prototype.
7639 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7640                                                unsigned Opcode) {
7641   // We already checked this call's prototype; verify it doesn't modify errno.
7642   if (!I.onlyReadsMemory())
7643     return false;
7644 
7645   SDValue Tmp0 = getValue(I.getArgOperand(0));
7646   SDValue Tmp1 = getValue(I.getArgOperand(1));
7647   EVT VT = Tmp0.getValueType();
7648   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7649   return true;
7650 }
7651 
7652 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7653   // Handle inline assembly differently.
7654   if (isa<InlineAsm>(I.getCalledValue())) {
7655     visitInlineAsm(&I);
7656     return;
7657   }
7658 
7659   if (Function *F = I.getCalledFunction()) {
7660     if (F->isDeclaration()) {
7661       // Is this an LLVM intrinsic or a target-specific intrinsic?
7662       unsigned IID = F->getIntrinsicID();
7663       if (!IID)
7664         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7665           IID = II->getIntrinsicID(F);
7666 
7667       if (IID) {
7668         visitIntrinsicCall(I, IID);
7669         return;
7670       }
7671     }
7672 
7673     // Check for well-known libc/libm calls.  If the function is internal, it
7674     // can't be a library call.  Don't do the check if marked as nobuiltin for
7675     // some reason or the call site requires strict floating point semantics.
7676     LibFunc Func;
7677     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7678         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7679         LibInfo->hasOptimizedCodeGen(Func)) {
7680       switch (Func) {
7681       default: break;
7682       case LibFunc_copysign:
7683       case LibFunc_copysignf:
7684       case LibFunc_copysignl:
7685         // We already checked this call's prototype; verify it doesn't modify
7686         // errno.
7687         if (I.onlyReadsMemory()) {
7688           SDValue LHS = getValue(I.getArgOperand(0));
7689           SDValue RHS = getValue(I.getArgOperand(1));
7690           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7691                                    LHS.getValueType(), LHS, RHS));
7692           return;
7693         }
7694         break;
7695       case LibFunc_fabs:
7696       case LibFunc_fabsf:
7697       case LibFunc_fabsl:
7698         if (visitUnaryFloatCall(I, ISD::FABS))
7699           return;
7700         break;
7701       case LibFunc_fmin:
7702       case LibFunc_fminf:
7703       case LibFunc_fminl:
7704         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7705           return;
7706         break;
7707       case LibFunc_fmax:
7708       case LibFunc_fmaxf:
7709       case LibFunc_fmaxl:
7710         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7711           return;
7712         break;
7713       case LibFunc_sin:
7714       case LibFunc_sinf:
7715       case LibFunc_sinl:
7716         if (visitUnaryFloatCall(I, ISD::FSIN))
7717           return;
7718         break;
7719       case LibFunc_cos:
7720       case LibFunc_cosf:
7721       case LibFunc_cosl:
7722         if (visitUnaryFloatCall(I, ISD::FCOS))
7723           return;
7724         break;
7725       case LibFunc_sqrt:
7726       case LibFunc_sqrtf:
7727       case LibFunc_sqrtl:
7728       case LibFunc_sqrt_finite:
7729       case LibFunc_sqrtf_finite:
7730       case LibFunc_sqrtl_finite:
7731         if (visitUnaryFloatCall(I, ISD::FSQRT))
7732           return;
7733         break;
7734       case LibFunc_floor:
7735       case LibFunc_floorf:
7736       case LibFunc_floorl:
7737         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7738           return;
7739         break;
7740       case LibFunc_nearbyint:
7741       case LibFunc_nearbyintf:
7742       case LibFunc_nearbyintl:
7743         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7744           return;
7745         break;
7746       case LibFunc_ceil:
7747       case LibFunc_ceilf:
7748       case LibFunc_ceill:
7749         if (visitUnaryFloatCall(I, ISD::FCEIL))
7750           return;
7751         break;
7752       case LibFunc_rint:
7753       case LibFunc_rintf:
7754       case LibFunc_rintl:
7755         if (visitUnaryFloatCall(I, ISD::FRINT))
7756           return;
7757         break;
7758       case LibFunc_round:
7759       case LibFunc_roundf:
7760       case LibFunc_roundl:
7761         if (visitUnaryFloatCall(I, ISD::FROUND))
7762           return;
7763         break;
7764       case LibFunc_trunc:
7765       case LibFunc_truncf:
7766       case LibFunc_truncl:
7767         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7768           return;
7769         break;
7770       case LibFunc_log2:
7771       case LibFunc_log2f:
7772       case LibFunc_log2l:
7773         if (visitUnaryFloatCall(I, ISD::FLOG2))
7774           return;
7775         break;
7776       case LibFunc_exp2:
7777       case LibFunc_exp2f:
7778       case LibFunc_exp2l:
7779         if (visitUnaryFloatCall(I, ISD::FEXP2))
7780           return;
7781         break;
7782       case LibFunc_memcmp:
7783         if (visitMemCmpCall(I))
7784           return;
7785         break;
7786       case LibFunc_mempcpy:
7787         if (visitMemPCpyCall(I))
7788           return;
7789         break;
7790       case LibFunc_memchr:
7791         if (visitMemChrCall(I))
7792           return;
7793         break;
7794       case LibFunc_strcpy:
7795         if (visitStrCpyCall(I, false))
7796           return;
7797         break;
7798       case LibFunc_stpcpy:
7799         if (visitStrCpyCall(I, true))
7800           return;
7801         break;
7802       case LibFunc_strcmp:
7803         if (visitStrCmpCall(I))
7804           return;
7805         break;
7806       case LibFunc_strlen:
7807         if (visitStrLenCall(I))
7808           return;
7809         break;
7810       case LibFunc_strnlen:
7811         if (visitStrNLenCall(I))
7812           return;
7813         break;
7814       }
7815     }
7816   }
7817 
7818   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7819   // have to do anything here to lower funclet bundles.
7820   // CFGuardTarget bundles are lowered in LowerCallTo.
7821   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7822                                         LLVMContext::OB_funclet,
7823                                         LLVMContext::OB_cfguardtarget}) &&
7824          "Cannot lower calls with arbitrary operand bundles!");
7825 
7826   SDValue Callee = getValue(I.getCalledValue());
7827 
7828   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7829     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7830   else
7831     // Check if we can potentially perform a tail call. More detailed checking
7832     // is be done within LowerCallTo, after more information about the call is
7833     // known.
7834     LowerCallTo(&I, Callee, I.isTailCall());
7835 }
7836 
7837 namespace {
7838 
7839 /// AsmOperandInfo - This contains information for each constraint that we are
7840 /// lowering.
7841 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7842 public:
7843   /// CallOperand - If this is the result output operand or a clobber
7844   /// this is null, otherwise it is the incoming operand to the CallInst.
7845   /// This gets modified as the asm is processed.
7846   SDValue CallOperand;
7847 
7848   /// AssignedRegs - If this is a register or register class operand, this
7849   /// contains the set of register corresponding to the operand.
7850   RegsForValue AssignedRegs;
7851 
7852   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7853     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7854   }
7855 
7856   /// Whether or not this operand accesses memory
7857   bool hasMemory(const TargetLowering &TLI) const {
7858     // Indirect operand accesses access memory.
7859     if (isIndirect)
7860       return true;
7861 
7862     for (const auto &Code : Codes)
7863       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7864         return true;
7865 
7866     return false;
7867   }
7868 
7869   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7870   /// corresponds to.  If there is no Value* for this operand, it returns
7871   /// MVT::Other.
7872   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7873                            const DataLayout &DL) const {
7874     if (!CallOperandVal) return MVT::Other;
7875 
7876     if (isa<BasicBlock>(CallOperandVal))
7877       return TLI.getPointerTy(DL);
7878 
7879     llvm::Type *OpTy = CallOperandVal->getType();
7880 
7881     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7882     // If this is an indirect operand, the operand is a pointer to the
7883     // accessed type.
7884     if (isIndirect) {
7885       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7886       if (!PtrTy)
7887         report_fatal_error("Indirect operand for inline asm not a pointer!");
7888       OpTy = PtrTy->getElementType();
7889     }
7890 
7891     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7892     if (StructType *STy = dyn_cast<StructType>(OpTy))
7893       if (STy->getNumElements() == 1)
7894         OpTy = STy->getElementType(0);
7895 
7896     // If OpTy is not a single value, it may be a struct/union that we
7897     // can tile with integers.
7898     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7899       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7900       switch (BitSize) {
7901       default: break;
7902       case 1:
7903       case 8:
7904       case 16:
7905       case 32:
7906       case 64:
7907       case 128:
7908         OpTy = IntegerType::get(Context, BitSize);
7909         break;
7910       }
7911     }
7912 
7913     return TLI.getValueType(DL, OpTy, true);
7914   }
7915 };
7916 
7917 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7918 
7919 } // end anonymous namespace
7920 
7921 /// Make sure that the output operand \p OpInfo and its corresponding input
7922 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7923 /// out).
7924 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7925                                SDISelAsmOperandInfo &MatchingOpInfo,
7926                                SelectionDAG &DAG) {
7927   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7928     return;
7929 
7930   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7931   const auto &TLI = DAG.getTargetLoweringInfo();
7932 
7933   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7934       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7935                                        OpInfo.ConstraintVT);
7936   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7937       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7938                                        MatchingOpInfo.ConstraintVT);
7939   if ((OpInfo.ConstraintVT.isInteger() !=
7940        MatchingOpInfo.ConstraintVT.isInteger()) ||
7941       (MatchRC.second != InputRC.second)) {
7942     // FIXME: error out in a more elegant fashion
7943     report_fatal_error("Unsupported asm: input constraint"
7944                        " with a matching output constraint of"
7945                        " incompatible type!");
7946   }
7947   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7948 }
7949 
7950 /// Get a direct memory input to behave well as an indirect operand.
7951 /// This may introduce stores, hence the need for a \p Chain.
7952 /// \return The (possibly updated) chain.
7953 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7954                                         SDISelAsmOperandInfo &OpInfo,
7955                                         SelectionDAG &DAG) {
7956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7957 
7958   // If we don't have an indirect input, put it in the constpool if we can,
7959   // otherwise spill it to a stack slot.
7960   // TODO: This isn't quite right. We need to handle these according to
7961   // the addressing mode that the constraint wants. Also, this may take
7962   // an additional register for the computation and we don't want that
7963   // either.
7964 
7965   // If the operand is a float, integer, or vector constant, spill to a
7966   // constant pool entry to get its address.
7967   const Value *OpVal = OpInfo.CallOperandVal;
7968   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7969       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7970     OpInfo.CallOperand = DAG.getConstantPool(
7971         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7972     return Chain;
7973   }
7974 
7975   // Otherwise, create a stack slot and emit a store to it before the asm.
7976   Type *Ty = OpVal->getType();
7977   auto &DL = DAG.getDataLayout();
7978   uint64_t TySize = DL.getTypeAllocSize(Ty);
7979   unsigned Align = DL.getPrefTypeAlignment(Ty);
7980   MachineFunction &MF = DAG.getMachineFunction();
7981   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7982   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7983   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7984                             MachinePointerInfo::getFixedStack(MF, SSFI),
7985                             TLI.getMemValueType(DL, Ty));
7986   OpInfo.CallOperand = StackSlot;
7987 
7988   return Chain;
7989 }
7990 
7991 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7992 /// specified operand.  We prefer to assign virtual registers, to allow the
7993 /// register allocator to handle the assignment process.  However, if the asm
7994 /// uses features that we can't model on machineinstrs, we have SDISel do the
7995 /// allocation.  This produces generally horrible, but correct, code.
7996 ///
7997 ///   OpInfo describes the operand
7998 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7999 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8000                                  SDISelAsmOperandInfo &OpInfo,
8001                                  SDISelAsmOperandInfo &RefOpInfo) {
8002   LLVMContext &Context = *DAG.getContext();
8003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8004 
8005   MachineFunction &MF = DAG.getMachineFunction();
8006   SmallVector<unsigned, 4> Regs;
8007   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8008 
8009   // No work to do for memory operations.
8010   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8011     return;
8012 
8013   // If this is a constraint for a single physreg, or a constraint for a
8014   // register class, find it.
8015   unsigned AssignedReg;
8016   const TargetRegisterClass *RC;
8017   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8018       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8019   // RC is unset only on failure. Return immediately.
8020   if (!RC)
8021     return;
8022 
8023   // Get the actual register value type.  This is important, because the user
8024   // may have asked for (e.g.) the AX register in i32 type.  We need to
8025   // remember that AX is actually i16 to get the right extension.
8026   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8027 
8028   if (OpInfo.ConstraintVT != MVT::Other) {
8029     // If this is an FP operand in an integer register (or visa versa), or more
8030     // generally if the operand value disagrees with the register class we plan
8031     // to stick it in, fix the operand type.
8032     //
8033     // If this is an input value, the bitcast to the new type is done now.
8034     // Bitcast for output value is done at the end of visitInlineAsm().
8035     if ((OpInfo.Type == InlineAsm::isOutput ||
8036          OpInfo.Type == InlineAsm::isInput) &&
8037         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8038       // Try to convert to the first EVT that the reg class contains.  If the
8039       // types are identical size, use a bitcast to convert (e.g. two differing
8040       // vector types).  Note: output bitcast is done at the end of
8041       // visitInlineAsm().
8042       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8043         // Exclude indirect inputs while they are unsupported because the code
8044         // to perform the load is missing and thus OpInfo.CallOperand still
8045         // refers to the input address rather than the pointed-to value.
8046         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8047           OpInfo.CallOperand =
8048               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8049         OpInfo.ConstraintVT = RegVT;
8050         // If the operand is an FP value and we want it in integer registers,
8051         // use the corresponding integer type. This turns an f64 value into
8052         // i64, which can be passed with two i32 values on a 32-bit machine.
8053       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8054         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8055         if (OpInfo.Type == InlineAsm::isInput)
8056           OpInfo.CallOperand =
8057               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8058         OpInfo.ConstraintVT = VT;
8059       }
8060     }
8061   }
8062 
8063   // No need to allocate a matching input constraint since the constraint it's
8064   // matching to has already been allocated.
8065   if (OpInfo.isMatchingInputConstraint())
8066     return;
8067 
8068   EVT ValueVT = OpInfo.ConstraintVT;
8069   if (OpInfo.ConstraintVT == MVT::Other)
8070     ValueVT = RegVT;
8071 
8072   // Initialize NumRegs.
8073   unsigned NumRegs = 1;
8074   if (OpInfo.ConstraintVT != MVT::Other)
8075     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8076 
8077   // If this is a constraint for a specific physical register, like {r17},
8078   // assign it now.
8079 
8080   // If this associated to a specific register, initialize iterator to correct
8081   // place. If virtual, make sure we have enough registers
8082 
8083   // Initialize iterator if necessary
8084   TargetRegisterClass::iterator I = RC->begin();
8085   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8086 
8087   // Do not check for single registers.
8088   if (AssignedReg) {
8089       for (; *I != AssignedReg; ++I)
8090         assert(I != RC->end() && "AssignedReg should be member of RC");
8091   }
8092 
8093   for (; NumRegs; --NumRegs, ++I) {
8094     assert(I != RC->end() && "Ran out of registers to allocate!");
8095     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8096     Regs.push_back(R);
8097   }
8098 
8099   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8100 }
8101 
8102 static unsigned
8103 findMatchingInlineAsmOperand(unsigned OperandNo,
8104                              const std::vector<SDValue> &AsmNodeOperands) {
8105   // Scan until we find the definition we already emitted of this operand.
8106   unsigned CurOp = InlineAsm::Op_FirstOperand;
8107   for (; OperandNo; --OperandNo) {
8108     // Advance to the next operand.
8109     unsigned OpFlag =
8110         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8111     assert((InlineAsm::isRegDefKind(OpFlag) ||
8112             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8113             InlineAsm::isMemKind(OpFlag)) &&
8114            "Skipped past definitions?");
8115     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8116   }
8117   return CurOp;
8118 }
8119 
8120 namespace {
8121 
8122 class ExtraFlags {
8123   unsigned Flags = 0;
8124 
8125 public:
8126   explicit ExtraFlags(ImmutableCallSite CS) {
8127     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8128     if (IA->hasSideEffects())
8129       Flags |= InlineAsm::Extra_HasSideEffects;
8130     if (IA->isAlignStack())
8131       Flags |= InlineAsm::Extra_IsAlignStack;
8132     if (CS.isConvergent())
8133       Flags |= InlineAsm::Extra_IsConvergent;
8134     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8135   }
8136 
8137   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8138     // Ideally, we would only check against memory constraints.  However, the
8139     // meaning of an Other constraint can be target-specific and we can't easily
8140     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8141     // for Other constraints as well.
8142     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8143         OpInfo.ConstraintType == TargetLowering::C_Other) {
8144       if (OpInfo.Type == InlineAsm::isInput)
8145         Flags |= InlineAsm::Extra_MayLoad;
8146       else if (OpInfo.Type == InlineAsm::isOutput)
8147         Flags |= InlineAsm::Extra_MayStore;
8148       else if (OpInfo.Type == InlineAsm::isClobber)
8149         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8150     }
8151   }
8152 
8153   unsigned get() const { return Flags; }
8154 };
8155 
8156 } // end anonymous namespace
8157 
8158 /// visitInlineAsm - Handle a call to an InlineAsm object.
8159 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8160   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8161 
8162   /// ConstraintOperands - Information about all of the constraints.
8163   SDISelAsmOperandInfoVector ConstraintOperands;
8164 
8165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8166   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8167       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8168 
8169   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8170   // AsmDialect, MayLoad, MayStore).
8171   bool HasSideEffect = IA->hasSideEffects();
8172   ExtraFlags ExtraInfo(CS);
8173 
8174   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8175   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8176   unsigned NumMatchingOps = 0;
8177   for (auto &T : TargetConstraints) {
8178     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8179     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8180 
8181     // Compute the value type for each operand.
8182     if (OpInfo.Type == InlineAsm::isInput ||
8183         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8184       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8185 
8186       // Process the call argument. BasicBlocks are labels, currently appearing
8187       // only in asm's.
8188       const Instruction *I = CS.getInstruction();
8189       if (isa<CallBrInst>(I) &&
8190           ArgNo - 1 >= (cast<CallBrInst>(I)->getNumArgOperands() -
8191                         cast<CallBrInst>(I)->getNumIndirectDests() -
8192                         NumMatchingOps) &&
8193           (NumMatchingOps == 0 ||
8194            ArgNo - 1 < (cast<CallBrInst>(I)->getNumArgOperands() -
8195                         NumMatchingOps))) {
8196         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8197         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8198         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8199       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8200         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8201       } else {
8202         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8203       }
8204 
8205       OpInfo.ConstraintVT =
8206           OpInfo
8207               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8208               .getSimpleVT();
8209     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8210       // The return value of the call is this value.  As such, there is no
8211       // corresponding argument.
8212       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8213       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8214         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8215             DAG.getDataLayout(), STy->getElementType(ResNo));
8216       } else {
8217         assert(ResNo == 0 && "Asm only has one result!");
8218         OpInfo.ConstraintVT =
8219             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8220       }
8221       ++ResNo;
8222     } else {
8223       OpInfo.ConstraintVT = MVT::Other;
8224     }
8225 
8226     if (OpInfo.hasMatchingInput())
8227       ++NumMatchingOps;
8228 
8229     if (!HasSideEffect)
8230       HasSideEffect = OpInfo.hasMemory(TLI);
8231 
8232     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8233     // FIXME: Could we compute this on OpInfo rather than T?
8234 
8235     // Compute the constraint code and ConstraintType to use.
8236     TLI.ComputeConstraintToUse(T, SDValue());
8237 
8238     if (T.ConstraintType == TargetLowering::C_Immediate &&
8239         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8240       // We've delayed emitting a diagnostic like the "n" constraint because
8241       // inlining could cause an integer showing up.
8242       return emitInlineAsmError(
8243           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8244                   "integer constant expression");
8245 
8246     ExtraInfo.update(T);
8247   }
8248 
8249 
8250   // We won't need to flush pending loads if this asm doesn't touch
8251   // memory and is nonvolatile.
8252   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8253 
8254   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8255   if (IsCallBr) {
8256     // If this is a callbr we need to flush pending exports since inlineasm_br
8257     // is a terminator. We need to do this before nodes are glued to
8258     // the inlineasm_br node.
8259     Chain = getControlRoot();
8260   }
8261 
8262   // Second pass over the constraints: compute which constraint option to use.
8263   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8264     // If this is an output operand with a matching input operand, look up the
8265     // matching input. If their types mismatch, e.g. one is an integer, the
8266     // other is floating point, or their sizes are different, flag it as an
8267     // error.
8268     if (OpInfo.hasMatchingInput()) {
8269       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8270       patchMatchingInput(OpInfo, Input, DAG);
8271     }
8272 
8273     // Compute the constraint code and ConstraintType to use.
8274     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8275 
8276     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8277         OpInfo.Type == InlineAsm::isClobber)
8278       continue;
8279 
8280     // If this is a memory input, and if the operand is not indirect, do what we
8281     // need to provide an address for the memory input.
8282     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8283         !OpInfo.isIndirect) {
8284       assert((OpInfo.isMultipleAlternative ||
8285               (OpInfo.Type == InlineAsm::isInput)) &&
8286              "Can only indirectify direct input operands!");
8287 
8288       // Memory operands really want the address of the value.
8289       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8290 
8291       // There is no longer a Value* corresponding to this operand.
8292       OpInfo.CallOperandVal = nullptr;
8293 
8294       // It is now an indirect operand.
8295       OpInfo.isIndirect = true;
8296     }
8297 
8298   }
8299 
8300   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8301   std::vector<SDValue> AsmNodeOperands;
8302   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8303   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8304       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8305 
8306   // If we have a !srcloc metadata node associated with it, we want to attach
8307   // this to the ultimately generated inline asm machineinstr.  To do this, we
8308   // pass in the third operand as this (potentially null) inline asm MDNode.
8309   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8310   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8311 
8312   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8313   // bits as operand 3.
8314   AsmNodeOperands.push_back(DAG.getTargetConstant(
8315       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8316 
8317   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8318   // this, assign virtual and physical registers for inputs and otput.
8319   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8320     // Assign Registers.
8321     SDISelAsmOperandInfo &RefOpInfo =
8322         OpInfo.isMatchingInputConstraint()
8323             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8324             : OpInfo;
8325     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8326 
8327     switch (OpInfo.Type) {
8328     case InlineAsm::isOutput:
8329       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8330         unsigned ConstraintID =
8331             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8332         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8333                "Failed to convert memory constraint code to constraint id.");
8334 
8335         // Add information to the INLINEASM node to know about this output.
8336         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8337         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8338         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8339                                                         MVT::i32));
8340         AsmNodeOperands.push_back(OpInfo.CallOperand);
8341       } else {
8342         // Otherwise, this outputs to a register (directly for C_Register /
8343         // C_RegisterClass, and a target-defined fashion for
8344         // C_Immediate/C_Other). Find a register that we can use.
8345         if (OpInfo.AssignedRegs.Regs.empty()) {
8346           emitInlineAsmError(
8347               CS, "couldn't allocate output register for constraint '" +
8348                       Twine(OpInfo.ConstraintCode) + "'");
8349           return;
8350         }
8351 
8352         // Add information to the INLINEASM node to know that this register is
8353         // set.
8354         OpInfo.AssignedRegs.AddInlineAsmOperands(
8355             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8356                                   : InlineAsm::Kind_RegDef,
8357             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8358       }
8359       break;
8360 
8361     case InlineAsm::isInput: {
8362       SDValue InOperandVal = OpInfo.CallOperand;
8363 
8364       if (OpInfo.isMatchingInputConstraint()) {
8365         // If this is required to match an output register we have already set,
8366         // just use its register.
8367         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8368                                                   AsmNodeOperands);
8369         unsigned OpFlag =
8370           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8371         if (InlineAsm::isRegDefKind(OpFlag) ||
8372             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8373           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8374           if (OpInfo.isIndirect) {
8375             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8376             emitInlineAsmError(CS, "inline asm not supported yet:"
8377                                    " don't know how to handle tied "
8378                                    "indirect register inputs");
8379             return;
8380           }
8381 
8382           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8383           SmallVector<unsigned, 4> Regs;
8384 
8385           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8386             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8387             MachineRegisterInfo &RegInfo =
8388                 DAG.getMachineFunction().getRegInfo();
8389             for (unsigned i = 0; i != NumRegs; ++i)
8390               Regs.push_back(RegInfo.createVirtualRegister(RC));
8391           } else {
8392             emitInlineAsmError(CS, "inline asm error: This value type register "
8393                                    "class is not natively supported!");
8394             return;
8395           }
8396 
8397           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8398 
8399           SDLoc dl = getCurSDLoc();
8400           // Use the produced MatchedRegs object to
8401           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8402                                     CS.getInstruction());
8403           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8404                                            true, OpInfo.getMatchedOperand(), dl,
8405                                            DAG, AsmNodeOperands);
8406           break;
8407         }
8408 
8409         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8410         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8411                "Unexpected number of operands");
8412         // Add information to the INLINEASM node to know about this input.
8413         // See InlineAsm.h isUseOperandTiedToDef.
8414         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8415         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8416                                                     OpInfo.getMatchedOperand());
8417         AsmNodeOperands.push_back(DAG.getTargetConstant(
8418             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8419         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8420         break;
8421       }
8422 
8423       // Treat indirect 'X' constraint as memory.
8424       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8425           OpInfo.isIndirect)
8426         OpInfo.ConstraintType = TargetLowering::C_Memory;
8427 
8428       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8429           OpInfo.ConstraintType == TargetLowering::C_Other) {
8430         std::vector<SDValue> Ops;
8431         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8432                                           Ops, DAG);
8433         if (Ops.empty()) {
8434           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8435             if (isa<ConstantSDNode>(InOperandVal)) {
8436               emitInlineAsmError(CS, "value out of range for constraint '" +
8437                                  Twine(OpInfo.ConstraintCode) + "'");
8438               return;
8439             }
8440 
8441           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8442                                      Twine(OpInfo.ConstraintCode) + "'");
8443           return;
8444         }
8445 
8446         // Add information to the INLINEASM node to know about this input.
8447         unsigned ResOpType =
8448           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8449         AsmNodeOperands.push_back(DAG.getTargetConstant(
8450             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8451         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8452         break;
8453       }
8454 
8455       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8456         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8457         assert(InOperandVal.getValueType() ==
8458                    TLI.getPointerTy(DAG.getDataLayout()) &&
8459                "Memory operands expect pointer values");
8460 
8461         unsigned ConstraintID =
8462             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8463         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8464                "Failed to convert memory constraint code to constraint id.");
8465 
8466         // Add information to the INLINEASM node to know about this input.
8467         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8468         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8469         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8470                                                         getCurSDLoc(),
8471                                                         MVT::i32));
8472         AsmNodeOperands.push_back(InOperandVal);
8473         break;
8474       }
8475 
8476       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8477               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8478              "Unknown constraint type!");
8479 
8480       // TODO: Support this.
8481       if (OpInfo.isIndirect) {
8482         emitInlineAsmError(
8483             CS, "Don't know how to handle indirect register inputs yet "
8484                 "for constraint '" +
8485                     Twine(OpInfo.ConstraintCode) + "'");
8486         return;
8487       }
8488 
8489       // Copy the input into the appropriate registers.
8490       if (OpInfo.AssignedRegs.Regs.empty()) {
8491         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8492                                    Twine(OpInfo.ConstraintCode) + "'");
8493         return;
8494       }
8495 
8496       SDLoc dl = getCurSDLoc();
8497 
8498       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8499                                         Chain, &Flag, CS.getInstruction());
8500 
8501       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8502                                                dl, DAG, AsmNodeOperands);
8503       break;
8504     }
8505     case InlineAsm::isClobber:
8506       // Add the clobbered value to the operand list, so that the register
8507       // allocator is aware that the physreg got clobbered.
8508       if (!OpInfo.AssignedRegs.Regs.empty())
8509         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8510                                                  false, 0, getCurSDLoc(), DAG,
8511                                                  AsmNodeOperands);
8512       break;
8513     }
8514   }
8515 
8516   // Finish up input operands.  Set the input chain and add the flag last.
8517   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8518   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8519 
8520   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8521   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8522                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8523   Flag = Chain.getValue(1);
8524 
8525   // Do additional work to generate outputs.
8526 
8527   SmallVector<EVT, 1> ResultVTs;
8528   SmallVector<SDValue, 1> ResultValues;
8529   SmallVector<SDValue, 8> OutChains;
8530 
8531   llvm::Type *CSResultType = CS.getType();
8532   ArrayRef<Type *> ResultTypes;
8533   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8534     ResultTypes = StructResult->elements();
8535   else if (!CSResultType->isVoidTy())
8536     ResultTypes = makeArrayRef(CSResultType);
8537 
8538   auto CurResultType = ResultTypes.begin();
8539   auto handleRegAssign = [&](SDValue V) {
8540     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8541     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8542     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8543     ++CurResultType;
8544     // If the type of the inline asm call site return value is different but has
8545     // same size as the type of the asm output bitcast it.  One example of this
8546     // is for vectors with different width / number of elements.  This can
8547     // happen for register classes that can contain multiple different value
8548     // types.  The preg or vreg allocated may not have the same VT as was
8549     // expected.
8550     //
8551     // This can also happen for a return value that disagrees with the register
8552     // class it is put in, eg. a double in a general-purpose register on a
8553     // 32-bit machine.
8554     if (ResultVT != V.getValueType() &&
8555         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8556       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8557     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8558              V.getValueType().isInteger()) {
8559       // If a result value was tied to an input value, the computed result
8560       // may have a wider width than the expected result.  Extract the
8561       // relevant portion.
8562       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8563     }
8564     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8565     ResultVTs.push_back(ResultVT);
8566     ResultValues.push_back(V);
8567   };
8568 
8569   // Deal with output operands.
8570   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8571     if (OpInfo.Type == InlineAsm::isOutput) {
8572       SDValue Val;
8573       // Skip trivial output operands.
8574       if (OpInfo.AssignedRegs.Regs.empty())
8575         continue;
8576 
8577       switch (OpInfo.ConstraintType) {
8578       case TargetLowering::C_Register:
8579       case TargetLowering::C_RegisterClass:
8580         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8581             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8582         break;
8583       case TargetLowering::C_Immediate:
8584       case TargetLowering::C_Other:
8585         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8586                                               OpInfo, DAG);
8587         break;
8588       case TargetLowering::C_Memory:
8589         break; // Already handled.
8590       case TargetLowering::C_Unknown:
8591         assert(false && "Unexpected unknown constraint");
8592       }
8593 
8594       // Indirect output manifest as stores. Record output chains.
8595       if (OpInfo.isIndirect) {
8596         const Value *Ptr = OpInfo.CallOperandVal;
8597         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8598         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8599                                      MachinePointerInfo(Ptr));
8600         OutChains.push_back(Store);
8601       } else {
8602         // generate CopyFromRegs to associated registers.
8603         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8604         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8605           for (const SDValue &V : Val->op_values())
8606             handleRegAssign(V);
8607         } else
8608           handleRegAssign(Val);
8609       }
8610     }
8611   }
8612 
8613   // Set results.
8614   if (!ResultValues.empty()) {
8615     assert(CurResultType == ResultTypes.end() &&
8616            "Mismatch in number of ResultTypes");
8617     assert(ResultValues.size() == ResultTypes.size() &&
8618            "Mismatch in number of output operands in asm result");
8619 
8620     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8621                             DAG.getVTList(ResultVTs), ResultValues);
8622     setValue(CS.getInstruction(), V);
8623   }
8624 
8625   // Collect store chains.
8626   if (!OutChains.empty())
8627     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8628 
8629   // Only Update Root if inline assembly has a memory effect.
8630   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8631     DAG.setRoot(Chain);
8632 }
8633 
8634 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8635                                              const Twine &Message) {
8636   LLVMContext &Ctx = *DAG.getContext();
8637   Ctx.emitError(CS.getInstruction(), Message);
8638 
8639   // Make sure we leave the DAG in a valid state
8640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8641   SmallVector<EVT, 1> ValueVTs;
8642   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8643 
8644   if (ValueVTs.empty())
8645     return;
8646 
8647   SmallVector<SDValue, 1> Ops;
8648   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8649     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8650 
8651   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8652 }
8653 
8654 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8655   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8656                           MVT::Other, getRoot(),
8657                           getValue(I.getArgOperand(0)),
8658                           DAG.getSrcValue(I.getArgOperand(0))));
8659 }
8660 
8661 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8663   const DataLayout &DL = DAG.getDataLayout();
8664   SDValue V = DAG.getVAArg(
8665       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8666       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8667       DL.getABITypeAlignment(I.getType()));
8668   DAG.setRoot(V.getValue(1));
8669 
8670   if (I.getType()->isPointerTy())
8671     V = DAG.getPtrExtOrTrunc(
8672         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8673   setValue(&I, V);
8674 }
8675 
8676 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8677   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8678                           MVT::Other, getRoot(),
8679                           getValue(I.getArgOperand(0)),
8680                           DAG.getSrcValue(I.getArgOperand(0))));
8681 }
8682 
8683 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8684   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8685                           MVT::Other, getRoot(),
8686                           getValue(I.getArgOperand(0)),
8687                           getValue(I.getArgOperand(1)),
8688                           DAG.getSrcValue(I.getArgOperand(0)),
8689                           DAG.getSrcValue(I.getArgOperand(1))));
8690 }
8691 
8692 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8693                                                     const Instruction &I,
8694                                                     SDValue Op) {
8695   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8696   if (!Range)
8697     return Op;
8698 
8699   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8700   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8701     return Op;
8702 
8703   APInt Lo = CR.getUnsignedMin();
8704   if (!Lo.isMinValue())
8705     return Op;
8706 
8707   APInt Hi = CR.getUnsignedMax();
8708   unsigned Bits = std::max(Hi.getActiveBits(),
8709                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8710 
8711   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8712 
8713   SDLoc SL = getCurSDLoc();
8714 
8715   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8716                              DAG.getValueType(SmallVT));
8717   unsigned NumVals = Op.getNode()->getNumValues();
8718   if (NumVals == 1)
8719     return ZExt;
8720 
8721   SmallVector<SDValue, 4> Ops;
8722 
8723   Ops.push_back(ZExt);
8724   for (unsigned I = 1; I != NumVals; ++I)
8725     Ops.push_back(Op.getValue(I));
8726 
8727   return DAG.getMergeValues(Ops, SL);
8728 }
8729 
8730 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8731 /// the call being lowered.
8732 ///
8733 /// This is a helper for lowering intrinsics that follow a target calling
8734 /// convention or require stack pointer adjustment. Only a subset of the
8735 /// intrinsic's operands need to participate in the calling convention.
8736 void SelectionDAGBuilder::populateCallLoweringInfo(
8737     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8738     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8739     bool IsPatchPoint) {
8740   TargetLowering::ArgListTy Args;
8741   Args.reserve(NumArgs);
8742 
8743   // Populate the argument list.
8744   // Attributes for args start at offset 1, after the return attribute.
8745   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8746        ArgI != ArgE; ++ArgI) {
8747     const Value *V = Call->getOperand(ArgI);
8748 
8749     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8750 
8751     TargetLowering::ArgListEntry Entry;
8752     Entry.Node = getValue(V);
8753     Entry.Ty = V->getType();
8754     Entry.setAttributes(Call, ArgI);
8755     Args.push_back(Entry);
8756   }
8757 
8758   CLI.setDebugLoc(getCurSDLoc())
8759       .setChain(getRoot())
8760       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8761       .setDiscardResult(Call->use_empty())
8762       .setIsPatchPoint(IsPatchPoint);
8763 }
8764 
8765 /// Add a stack map intrinsic call's live variable operands to a stackmap
8766 /// or patchpoint target node's operand list.
8767 ///
8768 /// Constants are converted to TargetConstants purely as an optimization to
8769 /// avoid constant materialization and register allocation.
8770 ///
8771 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8772 /// generate addess computation nodes, and so FinalizeISel can convert the
8773 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8774 /// address materialization and register allocation, but may also be required
8775 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8776 /// alloca in the entry block, then the runtime may assume that the alloca's
8777 /// StackMap location can be read immediately after compilation and that the
8778 /// location is valid at any point during execution (this is similar to the
8779 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8780 /// only available in a register, then the runtime would need to trap when
8781 /// execution reaches the StackMap in order to read the alloca's location.
8782 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8783                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8784                                 SelectionDAGBuilder &Builder) {
8785   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8786     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8788       Ops.push_back(
8789         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8790       Ops.push_back(
8791         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8792     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8793       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8794       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8795           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8796     } else
8797       Ops.push_back(OpVal);
8798   }
8799 }
8800 
8801 /// Lower llvm.experimental.stackmap directly to its target opcode.
8802 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8803   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8804   //                                  [live variables...])
8805 
8806   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8807 
8808   SDValue Chain, InFlag, Callee, NullPtr;
8809   SmallVector<SDValue, 32> Ops;
8810 
8811   SDLoc DL = getCurSDLoc();
8812   Callee = getValue(CI.getCalledValue());
8813   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8814 
8815   // The stackmap intrinsic only records the live variables (the arguments
8816   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8817   // intrinsic, this won't be lowered to a function call. This means we don't
8818   // have to worry about calling conventions and target specific lowering code.
8819   // Instead we perform the call lowering right here.
8820   //
8821   // chain, flag = CALLSEQ_START(chain, 0, 0)
8822   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8823   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8824   //
8825   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8826   InFlag = Chain.getValue(1);
8827 
8828   // Add the <id> and <numBytes> constants.
8829   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8830   Ops.push_back(DAG.getTargetConstant(
8831                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8832   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8833   Ops.push_back(DAG.getTargetConstant(
8834                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8835                   MVT::i32));
8836 
8837   // Push live variables for the stack map.
8838   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8839 
8840   // We are not pushing any register mask info here on the operands list,
8841   // because the stackmap doesn't clobber anything.
8842 
8843   // Push the chain and the glue flag.
8844   Ops.push_back(Chain);
8845   Ops.push_back(InFlag);
8846 
8847   // Create the STACKMAP node.
8848   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8849   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8850   Chain = SDValue(SM, 0);
8851   InFlag = Chain.getValue(1);
8852 
8853   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8854 
8855   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8856 
8857   // Set the root to the target-lowered call chain.
8858   DAG.setRoot(Chain);
8859 
8860   // Inform the Frame Information that we have a stackmap in this function.
8861   FuncInfo.MF->getFrameInfo().setHasStackMap();
8862 }
8863 
8864 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8865 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8866                                           const BasicBlock *EHPadBB) {
8867   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8868   //                                                 i32 <numBytes>,
8869   //                                                 i8* <target>,
8870   //                                                 i32 <numArgs>,
8871   //                                                 [Args...],
8872   //                                                 [live variables...])
8873 
8874   CallingConv::ID CC = CS.getCallingConv();
8875   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8876   bool HasDef = !CS->getType()->isVoidTy();
8877   SDLoc dl = getCurSDLoc();
8878   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8879 
8880   // Handle immediate and symbolic callees.
8881   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8882     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8883                                    /*isTarget=*/true);
8884   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8885     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8886                                          SDLoc(SymbolicCallee),
8887                                          SymbolicCallee->getValueType(0));
8888 
8889   // Get the real number of arguments participating in the call <numArgs>
8890   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8891   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8892 
8893   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8894   // Intrinsics include all meta-operands up to but not including CC.
8895   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8896   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8897          "Not enough arguments provided to the patchpoint intrinsic");
8898 
8899   // For AnyRegCC the arguments are lowered later on manually.
8900   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8901   Type *ReturnTy =
8902     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8903 
8904   TargetLowering::CallLoweringInfo CLI(DAG);
8905   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8906                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8907   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8908 
8909   SDNode *CallEnd = Result.second.getNode();
8910   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8911     CallEnd = CallEnd->getOperand(0).getNode();
8912 
8913   /// Get a call instruction from the call sequence chain.
8914   /// Tail calls are not allowed.
8915   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8916          "Expected a callseq node.");
8917   SDNode *Call = CallEnd->getOperand(0).getNode();
8918   bool HasGlue = Call->getGluedNode();
8919 
8920   // Replace the target specific call node with the patchable intrinsic.
8921   SmallVector<SDValue, 8> Ops;
8922 
8923   // Add the <id> and <numBytes> constants.
8924   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8925   Ops.push_back(DAG.getTargetConstant(
8926                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8927   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8928   Ops.push_back(DAG.getTargetConstant(
8929                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8930                   MVT::i32));
8931 
8932   // Add the callee.
8933   Ops.push_back(Callee);
8934 
8935   // Adjust <numArgs> to account for any arguments that have been passed on the
8936   // stack instead.
8937   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8938   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8939   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8940   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8941 
8942   // Add the calling convention
8943   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8944 
8945   // Add the arguments we omitted previously. The register allocator should
8946   // place these in any free register.
8947   if (IsAnyRegCC)
8948     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8949       Ops.push_back(getValue(CS.getArgument(i)));
8950 
8951   // Push the arguments from the call instruction up to the register mask.
8952   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8953   Ops.append(Call->op_begin() + 2, e);
8954 
8955   // Push live variables for the stack map.
8956   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8957 
8958   // Push the register mask info.
8959   if (HasGlue)
8960     Ops.push_back(*(Call->op_end()-2));
8961   else
8962     Ops.push_back(*(Call->op_end()-1));
8963 
8964   // Push the chain (this is originally the first operand of the call, but
8965   // becomes now the last or second to last operand).
8966   Ops.push_back(*(Call->op_begin()));
8967 
8968   // Push the glue flag (last operand).
8969   if (HasGlue)
8970     Ops.push_back(*(Call->op_end()-1));
8971 
8972   SDVTList NodeTys;
8973   if (IsAnyRegCC && HasDef) {
8974     // Create the return types based on the intrinsic definition
8975     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8976     SmallVector<EVT, 3> ValueVTs;
8977     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8978     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8979 
8980     // There is always a chain and a glue type at the end
8981     ValueVTs.push_back(MVT::Other);
8982     ValueVTs.push_back(MVT::Glue);
8983     NodeTys = DAG.getVTList(ValueVTs);
8984   } else
8985     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8986 
8987   // Replace the target specific call node with a PATCHPOINT node.
8988   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8989                                          dl, NodeTys, Ops);
8990 
8991   // Update the NodeMap.
8992   if (HasDef) {
8993     if (IsAnyRegCC)
8994       setValue(CS.getInstruction(), SDValue(MN, 0));
8995     else
8996       setValue(CS.getInstruction(), Result.first);
8997   }
8998 
8999   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9000   // call sequence. Furthermore the location of the chain and glue can change
9001   // when the AnyReg calling convention is used and the intrinsic returns a
9002   // value.
9003   if (IsAnyRegCC && HasDef) {
9004     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9005     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9006     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9007   } else
9008     DAG.ReplaceAllUsesWith(Call, MN);
9009   DAG.DeleteNode(Call);
9010 
9011   // Inform the Frame Information that we have a patchpoint in this function.
9012   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9013 }
9014 
9015 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9016                                             unsigned Intrinsic) {
9017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9018   SDValue Op1 = getValue(I.getArgOperand(0));
9019   SDValue Op2;
9020   if (I.getNumArgOperands() > 1)
9021     Op2 = getValue(I.getArgOperand(1));
9022   SDLoc dl = getCurSDLoc();
9023   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9024   SDValue Res;
9025   FastMathFlags FMF;
9026   if (isa<FPMathOperator>(I))
9027     FMF = I.getFastMathFlags();
9028 
9029   switch (Intrinsic) {
9030   case Intrinsic::experimental_vector_reduce_v2_fadd:
9031     if (FMF.allowReassoc())
9032       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9033                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
9034     else
9035       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
9036     break;
9037   case Intrinsic::experimental_vector_reduce_v2_fmul:
9038     if (FMF.allowReassoc())
9039       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9040                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
9041     else
9042       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
9043     break;
9044   case Intrinsic::experimental_vector_reduce_add:
9045     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9046     break;
9047   case Intrinsic::experimental_vector_reduce_mul:
9048     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9049     break;
9050   case Intrinsic::experimental_vector_reduce_and:
9051     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9052     break;
9053   case Intrinsic::experimental_vector_reduce_or:
9054     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9055     break;
9056   case Intrinsic::experimental_vector_reduce_xor:
9057     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9058     break;
9059   case Intrinsic::experimental_vector_reduce_smax:
9060     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9061     break;
9062   case Intrinsic::experimental_vector_reduce_smin:
9063     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9064     break;
9065   case Intrinsic::experimental_vector_reduce_umax:
9066     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9067     break;
9068   case Intrinsic::experimental_vector_reduce_umin:
9069     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9070     break;
9071   case Intrinsic::experimental_vector_reduce_fmax:
9072     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9073     break;
9074   case Intrinsic::experimental_vector_reduce_fmin:
9075     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9076     break;
9077   default:
9078     llvm_unreachable("Unhandled vector reduce intrinsic");
9079   }
9080   setValue(&I, Res);
9081 }
9082 
9083 /// Returns an AttributeList representing the attributes applied to the return
9084 /// value of the given call.
9085 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9086   SmallVector<Attribute::AttrKind, 2> Attrs;
9087   if (CLI.RetSExt)
9088     Attrs.push_back(Attribute::SExt);
9089   if (CLI.RetZExt)
9090     Attrs.push_back(Attribute::ZExt);
9091   if (CLI.IsInReg)
9092     Attrs.push_back(Attribute::InReg);
9093 
9094   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9095                             Attrs);
9096 }
9097 
9098 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9099 /// implementation, which just calls LowerCall.
9100 /// FIXME: When all targets are
9101 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9102 std::pair<SDValue, SDValue>
9103 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9104   // Handle the incoming return values from the call.
9105   CLI.Ins.clear();
9106   Type *OrigRetTy = CLI.RetTy;
9107   SmallVector<EVT, 4> RetTys;
9108   SmallVector<uint64_t, 4> Offsets;
9109   auto &DL = CLI.DAG.getDataLayout();
9110   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9111 
9112   if (CLI.IsPostTypeLegalization) {
9113     // If we are lowering a libcall after legalization, split the return type.
9114     SmallVector<EVT, 4> OldRetTys;
9115     SmallVector<uint64_t, 4> OldOffsets;
9116     RetTys.swap(OldRetTys);
9117     Offsets.swap(OldOffsets);
9118 
9119     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9120       EVT RetVT = OldRetTys[i];
9121       uint64_t Offset = OldOffsets[i];
9122       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9123       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9124       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9125       RetTys.append(NumRegs, RegisterVT);
9126       for (unsigned j = 0; j != NumRegs; ++j)
9127         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9128     }
9129   }
9130 
9131   SmallVector<ISD::OutputArg, 4> Outs;
9132   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9133 
9134   bool CanLowerReturn =
9135       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9136                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9137 
9138   SDValue DemoteStackSlot;
9139   int DemoteStackIdx = -100;
9140   if (!CanLowerReturn) {
9141     // FIXME: equivalent assert?
9142     // assert(!CS.hasInAllocaArgument() &&
9143     //        "sret demotion is incompatible with inalloca");
9144     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9145     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9146     MachineFunction &MF = CLI.DAG.getMachineFunction();
9147     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9148     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9149                                               DL.getAllocaAddrSpace());
9150 
9151     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9152     ArgListEntry Entry;
9153     Entry.Node = DemoteStackSlot;
9154     Entry.Ty = StackSlotPtrType;
9155     Entry.IsSExt = false;
9156     Entry.IsZExt = false;
9157     Entry.IsInReg = false;
9158     Entry.IsSRet = true;
9159     Entry.IsNest = false;
9160     Entry.IsByVal = false;
9161     Entry.IsReturned = false;
9162     Entry.IsSwiftSelf = false;
9163     Entry.IsSwiftError = false;
9164     Entry.IsCFGuardTarget = false;
9165     Entry.Alignment = Align;
9166     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9167     CLI.NumFixedArgs += 1;
9168     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9169 
9170     // sret demotion isn't compatible with tail-calls, since the sret argument
9171     // points into the callers stack frame.
9172     CLI.IsTailCall = false;
9173   } else {
9174     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9175         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9176     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9177       ISD::ArgFlagsTy Flags;
9178       if (NeedsRegBlock) {
9179         Flags.setInConsecutiveRegs();
9180         if (I == RetTys.size() - 1)
9181           Flags.setInConsecutiveRegsLast();
9182       }
9183       EVT VT = RetTys[I];
9184       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9185                                                      CLI.CallConv, VT);
9186       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9187                                                        CLI.CallConv, VT);
9188       for (unsigned i = 0; i != NumRegs; ++i) {
9189         ISD::InputArg MyFlags;
9190         MyFlags.Flags = Flags;
9191         MyFlags.VT = RegisterVT;
9192         MyFlags.ArgVT = VT;
9193         MyFlags.Used = CLI.IsReturnValueUsed;
9194         if (CLI.RetTy->isPointerTy()) {
9195           MyFlags.Flags.setPointer();
9196           MyFlags.Flags.setPointerAddrSpace(
9197               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9198         }
9199         if (CLI.RetSExt)
9200           MyFlags.Flags.setSExt();
9201         if (CLI.RetZExt)
9202           MyFlags.Flags.setZExt();
9203         if (CLI.IsInReg)
9204           MyFlags.Flags.setInReg();
9205         CLI.Ins.push_back(MyFlags);
9206       }
9207     }
9208   }
9209 
9210   // We push in swifterror return as the last element of CLI.Ins.
9211   ArgListTy &Args = CLI.getArgs();
9212   if (supportSwiftError()) {
9213     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9214       if (Args[i].IsSwiftError) {
9215         ISD::InputArg MyFlags;
9216         MyFlags.VT = getPointerTy(DL);
9217         MyFlags.ArgVT = EVT(getPointerTy(DL));
9218         MyFlags.Flags.setSwiftError();
9219         CLI.Ins.push_back(MyFlags);
9220       }
9221     }
9222   }
9223 
9224   // Handle all of the outgoing arguments.
9225   CLI.Outs.clear();
9226   CLI.OutVals.clear();
9227   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9228     SmallVector<EVT, 4> ValueVTs;
9229     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9230     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9231     Type *FinalType = Args[i].Ty;
9232     if (Args[i].IsByVal)
9233       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9234     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9235         FinalType, CLI.CallConv, CLI.IsVarArg);
9236     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9237          ++Value) {
9238       EVT VT = ValueVTs[Value];
9239       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9240       SDValue Op = SDValue(Args[i].Node.getNode(),
9241                            Args[i].Node.getResNo() + Value);
9242       ISD::ArgFlagsTy Flags;
9243 
9244       // Certain targets (such as MIPS), may have a different ABI alignment
9245       // for a type depending on the context. Give the target a chance to
9246       // specify the alignment it wants.
9247       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9248 
9249       if (Args[i].Ty->isPointerTy()) {
9250         Flags.setPointer();
9251         Flags.setPointerAddrSpace(
9252             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9253       }
9254       if (Args[i].IsZExt)
9255         Flags.setZExt();
9256       if (Args[i].IsSExt)
9257         Flags.setSExt();
9258       if (Args[i].IsInReg) {
9259         // If we are using vectorcall calling convention, a structure that is
9260         // passed InReg - is surely an HVA
9261         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9262             isa<StructType>(FinalType)) {
9263           // The first value of a structure is marked
9264           if (0 == Value)
9265             Flags.setHvaStart();
9266           Flags.setHva();
9267         }
9268         // Set InReg Flag
9269         Flags.setInReg();
9270       }
9271       if (Args[i].IsSRet)
9272         Flags.setSRet();
9273       if (Args[i].IsSwiftSelf)
9274         Flags.setSwiftSelf();
9275       if (Args[i].IsSwiftError)
9276         Flags.setSwiftError();
9277       if (Args[i].IsCFGuardTarget)
9278         Flags.setCFGuardTarget();
9279       if (Args[i].IsByVal)
9280         Flags.setByVal();
9281       if (Args[i].IsInAlloca) {
9282         Flags.setInAlloca();
9283         // Set the byval flag for CCAssignFn callbacks that don't know about
9284         // inalloca.  This way we can know how many bytes we should've allocated
9285         // and how many bytes a callee cleanup function will pop.  If we port
9286         // inalloca to more targets, we'll have to add custom inalloca handling
9287         // in the various CC lowering callbacks.
9288         Flags.setByVal();
9289       }
9290       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9291         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9292         Type *ElementTy = Ty->getElementType();
9293 
9294         unsigned FrameSize = DL.getTypeAllocSize(
9295             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9296         Flags.setByValSize(FrameSize);
9297 
9298         // info is not there but there are cases it cannot get right.
9299         unsigned FrameAlign;
9300         if (Args[i].Alignment)
9301           FrameAlign = Args[i].Alignment;
9302         else
9303           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9304         Flags.setByValAlign(Align(FrameAlign));
9305       }
9306       if (Args[i].IsNest)
9307         Flags.setNest();
9308       if (NeedsRegBlock)
9309         Flags.setInConsecutiveRegs();
9310       Flags.setOrigAlign(OriginalAlignment);
9311 
9312       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9313                                                  CLI.CallConv, VT);
9314       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9315                                                         CLI.CallConv, VT);
9316       SmallVector<SDValue, 4> Parts(NumParts);
9317       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9318 
9319       if (Args[i].IsSExt)
9320         ExtendKind = ISD::SIGN_EXTEND;
9321       else if (Args[i].IsZExt)
9322         ExtendKind = ISD::ZERO_EXTEND;
9323 
9324       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9325       // for now.
9326       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9327           CanLowerReturn) {
9328         assert((CLI.RetTy == Args[i].Ty ||
9329                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9330                  CLI.RetTy->getPointerAddressSpace() ==
9331                      Args[i].Ty->getPointerAddressSpace())) &&
9332                RetTys.size() == NumValues && "unexpected use of 'returned'");
9333         // Before passing 'returned' to the target lowering code, ensure that
9334         // either the register MVT and the actual EVT are the same size or that
9335         // the return value and argument are extended in the same way; in these
9336         // cases it's safe to pass the argument register value unchanged as the
9337         // return register value (although it's at the target's option whether
9338         // to do so)
9339         // TODO: allow code generation to take advantage of partially preserved
9340         // registers rather than clobbering the entire register when the
9341         // parameter extension method is not compatible with the return
9342         // extension method
9343         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9344             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9345              CLI.RetZExt == Args[i].IsZExt))
9346           Flags.setReturned();
9347       }
9348 
9349       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9350                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9351 
9352       for (unsigned j = 0; j != NumParts; ++j) {
9353         // if it isn't first piece, alignment must be 1
9354         // For scalable vectors the scalable part is currently handled
9355         // by individual targets, so we just use the known minimum size here.
9356         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9357                     i < CLI.NumFixedArgs, i,
9358                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9359         if (NumParts > 1 && j == 0)
9360           MyFlags.Flags.setSplit();
9361         else if (j != 0) {
9362           MyFlags.Flags.setOrigAlign(Align(1));
9363           if (j == NumParts - 1)
9364             MyFlags.Flags.setSplitEnd();
9365         }
9366 
9367         CLI.Outs.push_back(MyFlags);
9368         CLI.OutVals.push_back(Parts[j]);
9369       }
9370 
9371       if (NeedsRegBlock && Value == NumValues - 1)
9372         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9373     }
9374   }
9375 
9376   SmallVector<SDValue, 4> InVals;
9377   CLI.Chain = LowerCall(CLI, InVals);
9378 
9379   // Update CLI.InVals to use outside of this function.
9380   CLI.InVals = InVals;
9381 
9382   // Verify that the target's LowerCall behaved as expected.
9383   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9384          "LowerCall didn't return a valid chain!");
9385   assert((!CLI.IsTailCall || InVals.empty()) &&
9386          "LowerCall emitted a return value for a tail call!");
9387   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9388          "LowerCall didn't emit the correct number of values!");
9389 
9390   // For a tail call, the return value is merely live-out and there aren't
9391   // any nodes in the DAG representing it. Return a special value to
9392   // indicate that a tail call has been emitted and no more Instructions
9393   // should be processed in the current block.
9394   if (CLI.IsTailCall) {
9395     CLI.DAG.setRoot(CLI.Chain);
9396     return std::make_pair(SDValue(), SDValue());
9397   }
9398 
9399 #ifndef NDEBUG
9400   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9401     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9402     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9403            "LowerCall emitted a value with the wrong type!");
9404   }
9405 #endif
9406 
9407   SmallVector<SDValue, 4> ReturnValues;
9408   if (!CanLowerReturn) {
9409     // The instruction result is the result of loading from the
9410     // hidden sret parameter.
9411     SmallVector<EVT, 1> PVTs;
9412     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9413 
9414     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9415     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9416     EVT PtrVT = PVTs[0];
9417 
9418     unsigned NumValues = RetTys.size();
9419     ReturnValues.resize(NumValues);
9420     SmallVector<SDValue, 4> Chains(NumValues);
9421 
9422     // An aggregate return value cannot wrap around the address space, so
9423     // offsets to its parts don't wrap either.
9424     SDNodeFlags Flags;
9425     Flags.setNoUnsignedWrap(true);
9426 
9427     for (unsigned i = 0; i < NumValues; ++i) {
9428       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9429                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9430                                                         PtrVT), Flags);
9431       SDValue L = CLI.DAG.getLoad(
9432           RetTys[i], CLI.DL, CLI.Chain, Add,
9433           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9434                                             DemoteStackIdx, Offsets[i]),
9435           /* Alignment = */ 1);
9436       ReturnValues[i] = L;
9437       Chains[i] = L.getValue(1);
9438     }
9439 
9440     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9441   } else {
9442     // Collect the legal value parts into potentially illegal values
9443     // that correspond to the original function's return values.
9444     Optional<ISD::NodeType> AssertOp;
9445     if (CLI.RetSExt)
9446       AssertOp = ISD::AssertSext;
9447     else if (CLI.RetZExt)
9448       AssertOp = ISD::AssertZext;
9449     unsigned CurReg = 0;
9450     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9451       EVT VT = RetTys[I];
9452       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9453                                                      CLI.CallConv, VT);
9454       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9455                                                        CLI.CallConv, VT);
9456 
9457       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9458                                               NumRegs, RegisterVT, VT, nullptr,
9459                                               CLI.CallConv, AssertOp));
9460       CurReg += NumRegs;
9461     }
9462 
9463     // For a function returning void, there is no return value. We can't create
9464     // such a node, so we just return a null return value in that case. In
9465     // that case, nothing will actually look at the value.
9466     if (ReturnValues.empty())
9467       return std::make_pair(SDValue(), CLI.Chain);
9468   }
9469 
9470   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9471                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9472   return std::make_pair(Res, CLI.Chain);
9473 }
9474 
9475 void TargetLowering::LowerOperationWrapper(SDNode *N,
9476                                            SmallVectorImpl<SDValue> &Results,
9477                                            SelectionDAG &DAG) const {
9478   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9479     Results.push_back(Res);
9480 }
9481 
9482 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9483   llvm_unreachable("LowerOperation not implemented for this target!");
9484 }
9485 
9486 void
9487 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9488   SDValue Op = getNonRegisterValue(V);
9489   assert((Op.getOpcode() != ISD::CopyFromReg ||
9490           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9491          "Copy from a reg to the same reg!");
9492   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9493 
9494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9495   // If this is an InlineAsm we have to match the registers required, not the
9496   // notional registers required by the type.
9497 
9498   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9499                    None); // This is not an ABI copy.
9500   SDValue Chain = DAG.getEntryNode();
9501 
9502   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9503                               FuncInfo.PreferredExtendType.end())
9504                                  ? ISD::ANY_EXTEND
9505                                  : FuncInfo.PreferredExtendType[V];
9506   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9507   PendingExports.push_back(Chain);
9508 }
9509 
9510 #include "llvm/CodeGen/SelectionDAGISel.h"
9511 
9512 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9513 /// entry block, return true.  This includes arguments used by switches, since
9514 /// the switch may expand into multiple basic blocks.
9515 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9516   // With FastISel active, we may be splitting blocks, so force creation
9517   // of virtual registers for all non-dead arguments.
9518   if (FastISel)
9519     return A->use_empty();
9520 
9521   const BasicBlock &Entry = A->getParent()->front();
9522   for (const User *U : A->users())
9523     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9524       return false;  // Use not in entry block.
9525 
9526   return true;
9527 }
9528 
9529 using ArgCopyElisionMapTy =
9530     DenseMap<const Argument *,
9531              std::pair<const AllocaInst *, const StoreInst *>>;
9532 
9533 /// Scan the entry block of the function in FuncInfo for arguments that look
9534 /// like copies into a local alloca. Record any copied arguments in
9535 /// ArgCopyElisionCandidates.
9536 static void
9537 findArgumentCopyElisionCandidates(const DataLayout &DL,
9538                                   FunctionLoweringInfo *FuncInfo,
9539                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9540   // Record the state of every static alloca used in the entry block. Argument
9541   // allocas are all used in the entry block, so we need approximately as many
9542   // entries as we have arguments.
9543   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9544   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9545   unsigned NumArgs = FuncInfo->Fn->arg_size();
9546   StaticAllocas.reserve(NumArgs * 2);
9547 
9548   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9549     if (!V)
9550       return nullptr;
9551     V = V->stripPointerCasts();
9552     const auto *AI = dyn_cast<AllocaInst>(V);
9553     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9554       return nullptr;
9555     auto Iter = StaticAllocas.insert({AI, Unknown});
9556     return &Iter.first->second;
9557   };
9558 
9559   // Look for stores of arguments to static allocas. Look through bitcasts and
9560   // GEPs to handle type coercions, as long as the alloca is fully initialized
9561   // by the store. Any non-store use of an alloca escapes it and any subsequent
9562   // unanalyzed store might write it.
9563   // FIXME: Handle structs initialized with multiple stores.
9564   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9565     // Look for stores, and handle non-store uses conservatively.
9566     const auto *SI = dyn_cast<StoreInst>(&I);
9567     if (!SI) {
9568       // We will look through cast uses, so ignore them completely.
9569       if (I.isCast())
9570         continue;
9571       // Ignore debug info intrinsics, they don't escape or store to allocas.
9572       if (isa<DbgInfoIntrinsic>(I))
9573         continue;
9574       // This is an unknown instruction. Assume it escapes or writes to all
9575       // static alloca operands.
9576       for (const Use &U : I.operands()) {
9577         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9578           *Info = StaticAllocaInfo::Clobbered;
9579       }
9580       continue;
9581     }
9582 
9583     // If the stored value is a static alloca, mark it as escaped.
9584     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9585       *Info = StaticAllocaInfo::Clobbered;
9586 
9587     // Check if the destination is a static alloca.
9588     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9589     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9590     if (!Info)
9591       continue;
9592     const AllocaInst *AI = cast<AllocaInst>(Dst);
9593 
9594     // Skip allocas that have been initialized or clobbered.
9595     if (*Info != StaticAllocaInfo::Unknown)
9596       continue;
9597 
9598     // Check if the stored value is an argument, and that this store fully
9599     // initializes the alloca. Don't elide copies from the same argument twice.
9600     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9601     const auto *Arg = dyn_cast<Argument>(Val);
9602     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9603         Arg->getType()->isEmptyTy() ||
9604         DL.getTypeStoreSize(Arg->getType()) !=
9605             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9606         ArgCopyElisionCandidates.count(Arg)) {
9607       *Info = StaticAllocaInfo::Clobbered;
9608       continue;
9609     }
9610 
9611     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9612                       << '\n');
9613 
9614     // Mark this alloca and store for argument copy elision.
9615     *Info = StaticAllocaInfo::Elidable;
9616     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9617 
9618     // Stop scanning if we've seen all arguments. This will happen early in -O0
9619     // builds, which is useful, because -O0 builds have large entry blocks and
9620     // many allocas.
9621     if (ArgCopyElisionCandidates.size() == NumArgs)
9622       break;
9623   }
9624 }
9625 
9626 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9627 /// ArgVal is a load from a suitable fixed stack object.
9628 static void tryToElideArgumentCopy(
9629     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9630     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9631     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9632     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9633     SDValue ArgVal, bool &ArgHasUses) {
9634   // Check if this is a load from a fixed stack object.
9635   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9636   if (!LNode)
9637     return;
9638   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9639   if (!FINode)
9640     return;
9641 
9642   // Check that the fixed stack object is the right size and alignment.
9643   // Look at the alignment that the user wrote on the alloca instead of looking
9644   // at the stack object.
9645   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9646   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9647   const AllocaInst *AI = ArgCopyIter->second.first;
9648   int FixedIndex = FINode->getIndex();
9649   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9650   int OldIndex = AllocaIndex;
9651   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9652   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9653     LLVM_DEBUG(
9654         dbgs() << "  argument copy elision failed due to bad fixed stack "
9655                   "object size\n");
9656     return;
9657   }
9658   unsigned RequiredAlignment = AI->getAlignment();
9659   if (!RequiredAlignment) {
9660     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9661         AI->getAllocatedType());
9662   }
9663   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9664     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9665                          "greater than stack argument alignment ("
9666                       << RequiredAlignment << " vs "
9667                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9668     return;
9669   }
9670 
9671   // Perform the elision. Delete the old stack object and replace its only use
9672   // in the variable info map. Mark the stack object as mutable.
9673   LLVM_DEBUG({
9674     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9675            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9676            << '\n';
9677   });
9678   MFI.RemoveStackObject(OldIndex);
9679   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9680   AllocaIndex = FixedIndex;
9681   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9682   Chains.push_back(ArgVal.getValue(1));
9683 
9684   // Avoid emitting code for the store implementing the copy.
9685   const StoreInst *SI = ArgCopyIter->second.second;
9686   ElidedArgCopyInstrs.insert(SI);
9687 
9688   // Check for uses of the argument again so that we can avoid exporting ArgVal
9689   // if it is't used by anything other than the store.
9690   for (const Value *U : Arg.users()) {
9691     if (U != SI) {
9692       ArgHasUses = true;
9693       break;
9694     }
9695   }
9696 }
9697 
9698 void SelectionDAGISel::LowerArguments(const Function &F) {
9699   SelectionDAG &DAG = SDB->DAG;
9700   SDLoc dl = SDB->getCurSDLoc();
9701   const DataLayout &DL = DAG.getDataLayout();
9702   SmallVector<ISD::InputArg, 16> Ins;
9703 
9704   if (!FuncInfo->CanLowerReturn) {
9705     // Put in an sret pointer parameter before all the other parameters.
9706     SmallVector<EVT, 1> ValueVTs;
9707     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9708                     F.getReturnType()->getPointerTo(
9709                         DAG.getDataLayout().getAllocaAddrSpace()),
9710                     ValueVTs);
9711 
9712     // NOTE: Assuming that a pointer will never break down to more than one VT
9713     // or one register.
9714     ISD::ArgFlagsTy Flags;
9715     Flags.setSRet();
9716     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9717     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9718                          ISD::InputArg::NoArgIndex, 0);
9719     Ins.push_back(RetArg);
9720   }
9721 
9722   // Look for stores of arguments to static allocas. Mark such arguments with a
9723   // flag to ask the target to give us the memory location of that argument if
9724   // available.
9725   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9726   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9727                                     ArgCopyElisionCandidates);
9728 
9729   // Set up the incoming argument description vector.
9730   for (const Argument &Arg : F.args()) {
9731     unsigned ArgNo = Arg.getArgNo();
9732     SmallVector<EVT, 4> ValueVTs;
9733     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9734     bool isArgValueUsed = !Arg.use_empty();
9735     unsigned PartBase = 0;
9736     Type *FinalType = Arg.getType();
9737     if (Arg.hasAttribute(Attribute::ByVal))
9738       FinalType = Arg.getParamByValType();
9739     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9740         FinalType, F.getCallingConv(), F.isVarArg());
9741     for (unsigned Value = 0, NumValues = ValueVTs.size();
9742          Value != NumValues; ++Value) {
9743       EVT VT = ValueVTs[Value];
9744       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9745       ISD::ArgFlagsTy Flags;
9746 
9747       // Certain targets (such as MIPS), may have a different ABI alignment
9748       // for a type depending on the context. Give the target a chance to
9749       // specify the alignment it wants.
9750       const Align OriginalAlignment(
9751           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9752 
9753       if (Arg.getType()->isPointerTy()) {
9754         Flags.setPointer();
9755         Flags.setPointerAddrSpace(
9756             cast<PointerType>(Arg.getType())->getAddressSpace());
9757       }
9758       if (Arg.hasAttribute(Attribute::ZExt))
9759         Flags.setZExt();
9760       if (Arg.hasAttribute(Attribute::SExt))
9761         Flags.setSExt();
9762       if (Arg.hasAttribute(Attribute::InReg)) {
9763         // If we are using vectorcall calling convention, a structure that is
9764         // passed InReg - is surely an HVA
9765         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9766             isa<StructType>(Arg.getType())) {
9767           // The first value of a structure is marked
9768           if (0 == Value)
9769             Flags.setHvaStart();
9770           Flags.setHva();
9771         }
9772         // Set InReg Flag
9773         Flags.setInReg();
9774       }
9775       if (Arg.hasAttribute(Attribute::StructRet))
9776         Flags.setSRet();
9777       if (Arg.hasAttribute(Attribute::SwiftSelf))
9778         Flags.setSwiftSelf();
9779       if (Arg.hasAttribute(Attribute::SwiftError))
9780         Flags.setSwiftError();
9781       if (Arg.hasAttribute(Attribute::ByVal))
9782         Flags.setByVal();
9783       if (Arg.hasAttribute(Attribute::InAlloca)) {
9784         Flags.setInAlloca();
9785         // Set the byval flag for CCAssignFn callbacks that don't know about
9786         // inalloca.  This way we can know how many bytes we should've allocated
9787         // and how many bytes a callee cleanup function will pop.  If we port
9788         // inalloca to more targets, we'll have to add custom inalloca handling
9789         // in the various CC lowering callbacks.
9790         Flags.setByVal();
9791       }
9792       if (F.getCallingConv() == CallingConv::X86_INTR) {
9793         // IA Interrupt passes frame (1st parameter) by value in the stack.
9794         if (ArgNo == 0)
9795           Flags.setByVal();
9796       }
9797       if (Flags.isByVal() || Flags.isInAlloca()) {
9798         Type *ElementTy = Arg.getParamByValType();
9799 
9800         // For ByVal, size and alignment should be passed from FE.  BE will
9801         // guess if this info is not there but there are cases it cannot get
9802         // right.
9803         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9804         Flags.setByValSize(FrameSize);
9805 
9806         unsigned FrameAlign;
9807         if (Arg.getParamAlignment())
9808           FrameAlign = Arg.getParamAlignment();
9809         else
9810           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9811         Flags.setByValAlign(Align(FrameAlign));
9812       }
9813       if (Arg.hasAttribute(Attribute::Nest))
9814         Flags.setNest();
9815       if (NeedsRegBlock)
9816         Flags.setInConsecutiveRegs();
9817       Flags.setOrigAlign(OriginalAlignment);
9818       if (ArgCopyElisionCandidates.count(&Arg))
9819         Flags.setCopyElisionCandidate();
9820       if (Arg.hasAttribute(Attribute::Returned))
9821         Flags.setReturned();
9822 
9823       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9824           *CurDAG->getContext(), F.getCallingConv(), VT);
9825       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9826           *CurDAG->getContext(), F.getCallingConv(), VT);
9827       for (unsigned i = 0; i != NumRegs; ++i) {
9828         // For scalable vectors, use the minimum size; individual targets
9829         // are responsible for handling scalable vector arguments and
9830         // return values.
9831         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9832                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9833         if (NumRegs > 1 && i == 0)
9834           MyFlags.Flags.setSplit();
9835         // if it isn't first piece, alignment must be 1
9836         else if (i > 0) {
9837           MyFlags.Flags.setOrigAlign(Align(1));
9838           if (i == NumRegs - 1)
9839             MyFlags.Flags.setSplitEnd();
9840         }
9841         Ins.push_back(MyFlags);
9842       }
9843       if (NeedsRegBlock && Value == NumValues - 1)
9844         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9845       PartBase += VT.getStoreSize().getKnownMinSize();
9846     }
9847   }
9848 
9849   // Call the target to set up the argument values.
9850   SmallVector<SDValue, 8> InVals;
9851   SDValue NewRoot = TLI->LowerFormalArguments(
9852       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9853 
9854   // Verify that the target's LowerFormalArguments behaved as expected.
9855   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9856          "LowerFormalArguments didn't return a valid chain!");
9857   assert(InVals.size() == Ins.size() &&
9858          "LowerFormalArguments didn't emit the correct number of values!");
9859   LLVM_DEBUG({
9860     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9861       assert(InVals[i].getNode() &&
9862              "LowerFormalArguments emitted a null value!");
9863       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9864              "LowerFormalArguments emitted a value with the wrong type!");
9865     }
9866   });
9867 
9868   // Update the DAG with the new chain value resulting from argument lowering.
9869   DAG.setRoot(NewRoot);
9870 
9871   // Set up the argument values.
9872   unsigned i = 0;
9873   if (!FuncInfo->CanLowerReturn) {
9874     // Create a virtual register for the sret pointer, and put in a copy
9875     // from the sret argument into it.
9876     SmallVector<EVT, 1> ValueVTs;
9877     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9878                     F.getReturnType()->getPointerTo(
9879                         DAG.getDataLayout().getAllocaAddrSpace()),
9880                     ValueVTs);
9881     MVT VT = ValueVTs[0].getSimpleVT();
9882     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9883     Optional<ISD::NodeType> AssertOp = None;
9884     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9885                                         nullptr, F.getCallingConv(), AssertOp);
9886 
9887     MachineFunction& MF = SDB->DAG.getMachineFunction();
9888     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9889     Register SRetReg =
9890         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9891     FuncInfo->DemoteRegister = SRetReg;
9892     NewRoot =
9893         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9894     DAG.setRoot(NewRoot);
9895 
9896     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9897     ++i;
9898   }
9899 
9900   SmallVector<SDValue, 4> Chains;
9901   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9902   for (const Argument &Arg : F.args()) {
9903     SmallVector<SDValue, 4> ArgValues;
9904     SmallVector<EVT, 4> ValueVTs;
9905     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9906     unsigned NumValues = ValueVTs.size();
9907     if (NumValues == 0)
9908       continue;
9909 
9910     bool ArgHasUses = !Arg.use_empty();
9911 
9912     // Elide the copying store if the target loaded this argument from a
9913     // suitable fixed stack object.
9914     if (Ins[i].Flags.isCopyElisionCandidate()) {
9915       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9916                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9917                              InVals[i], ArgHasUses);
9918     }
9919 
9920     // If this argument is unused then remember its value. It is used to generate
9921     // debugging information.
9922     bool isSwiftErrorArg =
9923         TLI->supportSwiftError() &&
9924         Arg.hasAttribute(Attribute::SwiftError);
9925     if (!ArgHasUses && !isSwiftErrorArg) {
9926       SDB->setUnusedArgValue(&Arg, InVals[i]);
9927 
9928       // Also remember any frame index for use in FastISel.
9929       if (FrameIndexSDNode *FI =
9930           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9931         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9932     }
9933 
9934     for (unsigned Val = 0; Val != NumValues; ++Val) {
9935       EVT VT = ValueVTs[Val];
9936       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9937                                                       F.getCallingConv(), VT);
9938       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9939           *CurDAG->getContext(), F.getCallingConv(), VT);
9940 
9941       // Even an apparent 'unused' swifterror argument needs to be returned. So
9942       // we do generate a copy for it that can be used on return from the
9943       // function.
9944       if (ArgHasUses || isSwiftErrorArg) {
9945         Optional<ISD::NodeType> AssertOp;
9946         if (Arg.hasAttribute(Attribute::SExt))
9947           AssertOp = ISD::AssertSext;
9948         else if (Arg.hasAttribute(Attribute::ZExt))
9949           AssertOp = ISD::AssertZext;
9950 
9951         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9952                                              PartVT, VT, nullptr,
9953                                              F.getCallingConv(), AssertOp));
9954       }
9955 
9956       i += NumParts;
9957     }
9958 
9959     // We don't need to do anything else for unused arguments.
9960     if (ArgValues.empty())
9961       continue;
9962 
9963     // Note down frame index.
9964     if (FrameIndexSDNode *FI =
9965         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9966       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9967 
9968     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9969                                      SDB->getCurSDLoc());
9970 
9971     SDB->setValue(&Arg, Res);
9972     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9973       // We want to associate the argument with the frame index, among
9974       // involved operands, that correspond to the lowest address. The
9975       // getCopyFromParts function, called earlier, is swapping the order of
9976       // the operands to BUILD_PAIR depending on endianness. The result of
9977       // that swapping is that the least significant bits of the argument will
9978       // be in the first operand of the BUILD_PAIR node, and the most
9979       // significant bits will be in the second operand.
9980       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9981       if (LoadSDNode *LNode =
9982           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9983         if (FrameIndexSDNode *FI =
9984             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9985           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9986     }
9987 
9988     // Analyses past this point are naive and don't expect an assertion.
9989     if (Res.getOpcode() == ISD::AssertZext)
9990       Res = Res.getOperand(0);
9991 
9992     // Update the SwiftErrorVRegDefMap.
9993     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9994       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9995       if (Register::isVirtualRegister(Reg))
9996         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9997                                    Reg);
9998     }
9999 
10000     // If this argument is live outside of the entry block, insert a copy from
10001     // wherever we got it to the vreg that other BB's will reference it as.
10002     if (Res.getOpcode() == ISD::CopyFromReg) {
10003       // If we can, though, try to skip creating an unnecessary vreg.
10004       // FIXME: This isn't very clean... it would be nice to make this more
10005       // general.
10006       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10007       if (Register::isVirtualRegister(Reg)) {
10008         FuncInfo->ValueMap[&Arg] = Reg;
10009         continue;
10010       }
10011     }
10012     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10013       FuncInfo->InitializeRegForValue(&Arg);
10014       SDB->CopyToExportRegsIfNeeded(&Arg);
10015     }
10016   }
10017 
10018   if (!Chains.empty()) {
10019     Chains.push_back(NewRoot);
10020     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10021   }
10022 
10023   DAG.setRoot(NewRoot);
10024 
10025   assert(i == InVals.size() && "Argument register count mismatch!");
10026 
10027   // If any argument copy elisions occurred and we have debug info, update the
10028   // stale frame indices used in the dbg.declare variable info table.
10029   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10030   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10031     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10032       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10033       if (I != ArgCopyElisionFrameIndexMap.end())
10034         VI.Slot = I->second;
10035     }
10036   }
10037 
10038   // Finally, if the target has anything special to do, allow it to do so.
10039   emitFunctionEntryCode();
10040 }
10041 
10042 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10043 /// ensure constants are generated when needed.  Remember the virtual registers
10044 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10045 /// directly add them, because expansion might result in multiple MBB's for one
10046 /// BB.  As such, the start of the BB might correspond to a different MBB than
10047 /// the end.
10048 void
10049 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10050   const Instruction *TI = LLVMBB->getTerminator();
10051 
10052   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10053 
10054   // Check PHI nodes in successors that expect a value to be available from this
10055   // block.
10056   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10057     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10058     if (!isa<PHINode>(SuccBB->begin())) continue;
10059     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10060 
10061     // If this terminator has multiple identical successors (common for
10062     // switches), only handle each succ once.
10063     if (!SuccsHandled.insert(SuccMBB).second)
10064       continue;
10065 
10066     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10067 
10068     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10069     // nodes and Machine PHI nodes, but the incoming operands have not been
10070     // emitted yet.
10071     for (const PHINode &PN : SuccBB->phis()) {
10072       // Ignore dead phi's.
10073       if (PN.use_empty())
10074         continue;
10075 
10076       // Skip empty types
10077       if (PN.getType()->isEmptyTy())
10078         continue;
10079 
10080       unsigned Reg;
10081       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10082 
10083       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10084         unsigned &RegOut = ConstantsOut[C];
10085         if (RegOut == 0) {
10086           RegOut = FuncInfo.CreateRegs(C);
10087           CopyValueToVirtualRegister(C, RegOut);
10088         }
10089         Reg = RegOut;
10090       } else {
10091         DenseMap<const Value *, unsigned>::iterator I =
10092           FuncInfo.ValueMap.find(PHIOp);
10093         if (I != FuncInfo.ValueMap.end())
10094           Reg = I->second;
10095         else {
10096           assert(isa<AllocaInst>(PHIOp) &&
10097                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10098                  "Didn't codegen value into a register!??");
10099           Reg = FuncInfo.CreateRegs(PHIOp);
10100           CopyValueToVirtualRegister(PHIOp, Reg);
10101         }
10102       }
10103 
10104       // Remember that this register needs to added to the machine PHI node as
10105       // the input for this MBB.
10106       SmallVector<EVT, 4> ValueVTs;
10107       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10108       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10109       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10110         EVT VT = ValueVTs[vti];
10111         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10112         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10113           FuncInfo.PHINodesToUpdate.push_back(
10114               std::make_pair(&*MBBI++, Reg + i));
10115         Reg += NumRegisters;
10116       }
10117     }
10118   }
10119 
10120   ConstantsOut.clear();
10121 }
10122 
10123 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10124 /// is 0.
10125 MachineBasicBlock *
10126 SelectionDAGBuilder::StackProtectorDescriptor::
10127 AddSuccessorMBB(const BasicBlock *BB,
10128                 MachineBasicBlock *ParentMBB,
10129                 bool IsLikely,
10130                 MachineBasicBlock *SuccMBB) {
10131   // If SuccBB has not been created yet, create it.
10132   if (!SuccMBB) {
10133     MachineFunction *MF = ParentMBB->getParent();
10134     MachineFunction::iterator BBI(ParentMBB);
10135     SuccMBB = MF->CreateMachineBasicBlock(BB);
10136     MF->insert(++BBI, SuccMBB);
10137   }
10138   // Add it as a successor of ParentMBB.
10139   ParentMBB->addSuccessor(
10140       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10141   return SuccMBB;
10142 }
10143 
10144 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10145   MachineFunction::iterator I(MBB);
10146   if (++I == FuncInfo.MF->end())
10147     return nullptr;
10148   return &*I;
10149 }
10150 
10151 /// During lowering new call nodes can be created (such as memset, etc.).
10152 /// Those will become new roots of the current DAG, but complications arise
10153 /// when they are tail calls. In such cases, the call lowering will update
10154 /// the root, but the builder still needs to know that a tail call has been
10155 /// lowered in order to avoid generating an additional return.
10156 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10157   // If the node is null, we do have a tail call.
10158   if (MaybeTC.getNode() != nullptr)
10159     DAG.setRoot(MaybeTC);
10160   else
10161     HasTailCall = true;
10162 }
10163 
10164 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10165                                         MachineBasicBlock *SwitchMBB,
10166                                         MachineBasicBlock *DefaultMBB) {
10167   MachineFunction *CurMF = FuncInfo.MF;
10168   MachineBasicBlock *NextMBB = nullptr;
10169   MachineFunction::iterator BBI(W.MBB);
10170   if (++BBI != FuncInfo.MF->end())
10171     NextMBB = &*BBI;
10172 
10173   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10174 
10175   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10176 
10177   if (Size == 2 && W.MBB == SwitchMBB) {
10178     // If any two of the cases has the same destination, and if one value
10179     // is the same as the other, but has one bit unset that the other has set,
10180     // use bit manipulation to do two compares at once.  For example:
10181     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10182     // TODO: This could be extended to merge any 2 cases in switches with 3
10183     // cases.
10184     // TODO: Handle cases where W.CaseBB != SwitchBB.
10185     CaseCluster &Small = *W.FirstCluster;
10186     CaseCluster &Big = *W.LastCluster;
10187 
10188     if (Small.Low == Small.High && Big.Low == Big.High &&
10189         Small.MBB == Big.MBB) {
10190       const APInt &SmallValue = Small.Low->getValue();
10191       const APInt &BigValue = Big.Low->getValue();
10192 
10193       // Check that there is only one bit different.
10194       APInt CommonBit = BigValue ^ SmallValue;
10195       if (CommonBit.isPowerOf2()) {
10196         SDValue CondLHS = getValue(Cond);
10197         EVT VT = CondLHS.getValueType();
10198         SDLoc DL = getCurSDLoc();
10199 
10200         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10201                                  DAG.getConstant(CommonBit, DL, VT));
10202         SDValue Cond = DAG.getSetCC(
10203             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10204             ISD::SETEQ);
10205 
10206         // Update successor info.
10207         // Both Small and Big will jump to Small.BB, so we sum up the
10208         // probabilities.
10209         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10210         if (BPI)
10211           addSuccessorWithProb(
10212               SwitchMBB, DefaultMBB,
10213               // The default destination is the first successor in IR.
10214               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10215         else
10216           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10217 
10218         // Insert the true branch.
10219         SDValue BrCond =
10220             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10221                         DAG.getBasicBlock(Small.MBB));
10222         // Insert the false branch.
10223         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10224                              DAG.getBasicBlock(DefaultMBB));
10225 
10226         DAG.setRoot(BrCond);
10227         return;
10228       }
10229     }
10230   }
10231 
10232   if (TM.getOptLevel() != CodeGenOpt::None) {
10233     // Here, we order cases by probability so the most likely case will be
10234     // checked first. However, two clusters can have the same probability in
10235     // which case their relative ordering is non-deterministic. So we use Low
10236     // as a tie-breaker as clusters are guaranteed to never overlap.
10237     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10238                [](const CaseCluster &a, const CaseCluster &b) {
10239       return a.Prob != b.Prob ?
10240              a.Prob > b.Prob :
10241              a.Low->getValue().slt(b.Low->getValue());
10242     });
10243 
10244     // Rearrange the case blocks so that the last one falls through if possible
10245     // without changing the order of probabilities.
10246     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10247       --I;
10248       if (I->Prob > W.LastCluster->Prob)
10249         break;
10250       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10251         std::swap(*I, *W.LastCluster);
10252         break;
10253       }
10254     }
10255   }
10256 
10257   // Compute total probability.
10258   BranchProbability DefaultProb = W.DefaultProb;
10259   BranchProbability UnhandledProbs = DefaultProb;
10260   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10261     UnhandledProbs += I->Prob;
10262 
10263   MachineBasicBlock *CurMBB = W.MBB;
10264   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10265     bool FallthroughUnreachable = false;
10266     MachineBasicBlock *Fallthrough;
10267     if (I == W.LastCluster) {
10268       // For the last cluster, fall through to the default destination.
10269       Fallthrough = DefaultMBB;
10270       FallthroughUnreachable = isa<UnreachableInst>(
10271           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10272     } else {
10273       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10274       CurMF->insert(BBI, Fallthrough);
10275       // Put Cond in a virtual register to make it available from the new blocks.
10276       ExportFromCurrentBlock(Cond);
10277     }
10278     UnhandledProbs -= I->Prob;
10279 
10280     switch (I->Kind) {
10281       case CC_JumpTable: {
10282         // FIXME: Optimize away range check based on pivot comparisons.
10283         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10284         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10285 
10286         // The jump block hasn't been inserted yet; insert it here.
10287         MachineBasicBlock *JumpMBB = JT->MBB;
10288         CurMF->insert(BBI, JumpMBB);
10289 
10290         auto JumpProb = I->Prob;
10291         auto FallthroughProb = UnhandledProbs;
10292 
10293         // If the default statement is a target of the jump table, we evenly
10294         // distribute the default probability to successors of CurMBB. Also
10295         // update the probability on the edge from JumpMBB to Fallthrough.
10296         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10297                                               SE = JumpMBB->succ_end();
10298              SI != SE; ++SI) {
10299           if (*SI == DefaultMBB) {
10300             JumpProb += DefaultProb / 2;
10301             FallthroughProb -= DefaultProb / 2;
10302             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10303             JumpMBB->normalizeSuccProbs();
10304             break;
10305           }
10306         }
10307 
10308         if (FallthroughUnreachable) {
10309           // Skip the range check if the fallthrough block is unreachable.
10310           JTH->OmitRangeCheck = true;
10311         }
10312 
10313         if (!JTH->OmitRangeCheck)
10314           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10315         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10316         CurMBB->normalizeSuccProbs();
10317 
10318         // The jump table header will be inserted in our current block, do the
10319         // range check, and fall through to our fallthrough block.
10320         JTH->HeaderBB = CurMBB;
10321         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10322 
10323         // If we're in the right place, emit the jump table header right now.
10324         if (CurMBB == SwitchMBB) {
10325           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10326           JTH->Emitted = true;
10327         }
10328         break;
10329       }
10330       case CC_BitTests: {
10331         // FIXME: Optimize away range check based on pivot comparisons.
10332         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10333 
10334         // The bit test blocks haven't been inserted yet; insert them here.
10335         for (BitTestCase &BTC : BTB->Cases)
10336           CurMF->insert(BBI, BTC.ThisBB);
10337 
10338         // Fill in fields of the BitTestBlock.
10339         BTB->Parent = CurMBB;
10340         BTB->Default = Fallthrough;
10341 
10342         BTB->DefaultProb = UnhandledProbs;
10343         // If the cases in bit test don't form a contiguous range, we evenly
10344         // distribute the probability on the edge to Fallthrough to two
10345         // successors of CurMBB.
10346         if (!BTB->ContiguousRange) {
10347           BTB->Prob += DefaultProb / 2;
10348           BTB->DefaultProb -= DefaultProb / 2;
10349         }
10350 
10351         if (FallthroughUnreachable) {
10352           // Skip the range check if the fallthrough block is unreachable.
10353           BTB->OmitRangeCheck = true;
10354         }
10355 
10356         // If we're in the right place, emit the bit test header right now.
10357         if (CurMBB == SwitchMBB) {
10358           visitBitTestHeader(*BTB, SwitchMBB);
10359           BTB->Emitted = true;
10360         }
10361         break;
10362       }
10363       case CC_Range: {
10364         const Value *RHS, *LHS, *MHS;
10365         ISD::CondCode CC;
10366         if (I->Low == I->High) {
10367           // Check Cond == I->Low.
10368           CC = ISD::SETEQ;
10369           LHS = Cond;
10370           RHS=I->Low;
10371           MHS = nullptr;
10372         } else {
10373           // Check I->Low <= Cond <= I->High.
10374           CC = ISD::SETLE;
10375           LHS = I->Low;
10376           MHS = Cond;
10377           RHS = I->High;
10378         }
10379 
10380         // If Fallthrough is unreachable, fold away the comparison.
10381         if (FallthroughUnreachable)
10382           CC = ISD::SETTRUE;
10383 
10384         // The false probability is the sum of all unhandled cases.
10385         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10386                      getCurSDLoc(), I->Prob, UnhandledProbs);
10387 
10388         if (CurMBB == SwitchMBB)
10389           visitSwitchCase(CB, SwitchMBB);
10390         else
10391           SL->SwitchCases.push_back(CB);
10392 
10393         break;
10394       }
10395     }
10396     CurMBB = Fallthrough;
10397   }
10398 }
10399 
10400 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10401                                               CaseClusterIt First,
10402                                               CaseClusterIt Last) {
10403   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10404     if (X.Prob != CC.Prob)
10405       return X.Prob > CC.Prob;
10406 
10407     // Ties are broken by comparing the case value.
10408     return X.Low->getValue().slt(CC.Low->getValue());
10409   });
10410 }
10411 
10412 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10413                                         const SwitchWorkListItem &W,
10414                                         Value *Cond,
10415                                         MachineBasicBlock *SwitchMBB) {
10416   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10417          "Clusters not sorted?");
10418 
10419   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10420 
10421   // Balance the tree based on branch probabilities to create a near-optimal (in
10422   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10423   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10424   CaseClusterIt LastLeft = W.FirstCluster;
10425   CaseClusterIt FirstRight = W.LastCluster;
10426   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10427   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10428 
10429   // Move LastLeft and FirstRight towards each other from opposite directions to
10430   // find a partitioning of the clusters which balances the probability on both
10431   // sides. If LeftProb and RightProb are equal, alternate which side is
10432   // taken to ensure 0-probability nodes are distributed evenly.
10433   unsigned I = 0;
10434   while (LastLeft + 1 < FirstRight) {
10435     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10436       LeftProb += (++LastLeft)->Prob;
10437     else
10438       RightProb += (--FirstRight)->Prob;
10439     I++;
10440   }
10441 
10442   while (true) {
10443     // Our binary search tree differs from a typical BST in that ours can have up
10444     // to three values in each leaf. The pivot selection above doesn't take that
10445     // into account, which means the tree might require more nodes and be less
10446     // efficient. We compensate for this here.
10447 
10448     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10449     unsigned NumRight = W.LastCluster - FirstRight + 1;
10450 
10451     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10452       // If one side has less than 3 clusters, and the other has more than 3,
10453       // consider taking a cluster from the other side.
10454 
10455       if (NumLeft < NumRight) {
10456         // Consider moving the first cluster on the right to the left side.
10457         CaseCluster &CC = *FirstRight;
10458         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10459         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10460         if (LeftSideRank <= RightSideRank) {
10461           // Moving the cluster to the left does not demote it.
10462           ++LastLeft;
10463           ++FirstRight;
10464           continue;
10465         }
10466       } else {
10467         assert(NumRight < NumLeft);
10468         // Consider moving the last element on the left to the right side.
10469         CaseCluster &CC = *LastLeft;
10470         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10471         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10472         if (RightSideRank <= LeftSideRank) {
10473           // Moving the cluster to the right does not demot it.
10474           --LastLeft;
10475           --FirstRight;
10476           continue;
10477         }
10478       }
10479     }
10480     break;
10481   }
10482 
10483   assert(LastLeft + 1 == FirstRight);
10484   assert(LastLeft >= W.FirstCluster);
10485   assert(FirstRight <= W.LastCluster);
10486 
10487   // Use the first element on the right as pivot since we will make less-than
10488   // comparisons against it.
10489   CaseClusterIt PivotCluster = FirstRight;
10490   assert(PivotCluster > W.FirstCluster);
10491   assert(PivotCluster <= W.LastCluster);
10492 
10493   CaseClusterIt FirstLeft = W.FirstCluster;
10494   CaseClusterIt LastRight = W.LastCluster;
10495 
10496   const ConstantInt *Pivot = PivotCluster->Low;
10497 
10498   // New blocks will be inserted immediately after the current one.
10499   MachineFunction::iterator BBI(W.MBB);
10500   ++BBI;
10501 
10502   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10503   // we can branch to its destination directly if it's squeezed exactly in
10504   // between the known lower bound and Pivot - 1.
10505   MachineBasicBlock *LeftMBB;
10506   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10507       FirstLeft->Low == W.GE &&
10508       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10509     LeftMBB = FirstLeft->MBB;
10510   } else {
10511     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10512     FuncInfo.MF->insert(BBI, LeftMBB);
10513     WorkList.push_back(
10514         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10515     // Put Cond in a virtual register to make it available from the new blocks.
10516     ExportFromCurrentBlock(Cond);
10517   }
10518 
10519   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10520   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10521   // directly if RHS.High equals the current upper bound.
10522   MachineBasicBlock *RightMBB;
10523   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10524       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10525     RightMBB = FirstRight->MBB;
10526   } else {
10527     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10528     FuncInfo.MF->insert(BBI, RightMBB);
10529     WorkList.push_back(
10530         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10531     // Put Cond in a virtual register to make it available from the new blocks.
10532     ExportFromCurrentBlock(Cond);
10533   }
10534 
10535   // Create the CaseBlock record that will be used to lower the branch.
10536   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10537                getCurSDLoc(), LeftProb, RightProb);
10538 
10539   if (W.MBB == SwitchMBB)
10540     visitSwitchCase(CB, SwitchMBB);
10541   else
10542     SL->SwitchCases.push_back(CB);
10543 }
10544 
10545 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10546 // from the swith statement.
10547 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10548                                             BranchProbability PeeledCaseProb) {
10549   if (PeeledCaseProb == BranchProbability::getOne())
10550     return BranchProbability::getZero();
10551   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10552 
10553   uint32_t Numerator = CaseProb.getNumerator();
10554   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10555   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10556 }
10557 
10558 // Try to peel the top probability case if it exceeds the threshold.
10559 // Return current MachineBasicBlock for the switch statement if the peeling
10560 // does not occur.
10561 // If the peeling is performed, return the newly created MachineBasicBlock
10562 // for the peeled switch statement. Also update Clusters to remove the peeled
10563 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10564 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10565     const SwitchInst &SI, CaseClusterVector &Clusters,
10566     BranchProbability &PeeledCaseProb) {
10567   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10568   // Don't perform if there is only one cluster or optimizing for size.
10569   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10570       TM.getOptLevel() == CodeGenOpt::None ||
10571       SwitchMBB->getParent()->getFunction().hasMinSize())
10572     return SwitchMBB;
10573 
10574   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10575   unsigned PeeledCaseIndex = 0;
10576   bool SwitchPeeled = false;
10577   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10578     CaseCluster &CC = Clusters[Index];
10579     if (CC.Prob < TopCaseProb)
10580       continue;
10581     TopCaseProb = CC.Prob;
10582     PeeledCaseIndex = Index;
10583     SwitchPeeled = true;
10584   }
10585   if (!SwitchPeeled)
10586     return SwitchMBB;
10587 
10588   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10589                     << TopCaseProb << "\n");
10590 
10591   // Record the MBB for the peeled switch statement.
10592   MachineFunction::iterator BBI(SwitchMBB);
10593   ++BBI;
10594   MachineBasicBlock *PeeledSwitchMBB =
10595       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10596   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10597 
10598   ExportFromCurrentBlock(SI.getCondition());
10599   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10600   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10601                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10602   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10603 
10604   Clusters.erase(PeeledCaseIt);
10605   for (CaseCluster &CC : Clusters) {
10606     LLVM_DEBUG(
10607         dbgs() << "Scale the probablity for one cluster, before scaling: "
10608                << CC.Prob << "\n");
10609     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10610     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10611   }
10612   PeeledCaseProb = TopCaseProb;
10613   return PeeledSwitchMBB;
10614 }
10615 
10616 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10617   // Extract cases from the switch.
10618   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10619   CaseClusterVector Clusters;
10620   Clusters.reserve(SI.getNumCases());
10621   for (auto I : SI.cases()) {
10622     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10623     const ConstantInt *CaseVal = I.getCaseValue();
10624     BranchProbability Prob =
10625         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10626             : BranchProbability(1, SI.getNumCases() + 1);
10627     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10628   }
10629 
10630   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10631 
10632   // Cluster adjacent cases with the same destination. We do this at all
10633   // optimization levels because it's cheap to do and will make codegen faster
10634   // if there are many clusters.
10635   sortAndRangeify(Clusters);
10636 
10637   // The branch probablity of the peeled case.
10638   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10639   MachineBasicBlock *PeeledSwitchMBB =
10640       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10641 
10642   // If there is only the default destination, jump there directly.
10643   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10644   if (Clusters.empty()) {
10645     assert(PeeledSwitchMBB == SwitchMBB);
10646     SwitchMBB->addSuccessor(DefaultMBB);
10647     if (DefaultMBB != NextBlock(SwitchMBB)) {
10648       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10649                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10650     }
10651     return;
10652   }
10653 
10654   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10655   SL->findBitTestClusters(Clusters, &SI);
10656 
10657   LLVM_DEBUG({
10658     dbgs() << "Case clusters: ";
10659     for (const CaseCluster &C : Clusters) {
10660       if (C.Kind == CC_JumpTable)
10661         dbgs() << "JT:";
10662       if (C.Kind == CC_BitTests)
10663         dbgs() << "BT:";
10664 
10665       C.Low->getValue().print(dbgs(), true);
10666       if (C.Low != C.High) {
10667         dbgs() << '-';
10668         C.High->getValue().print(dbgs(), true);
10669       }
10670       dbgs() << ' ';
10671     }
10672     dbgs() << '\n';
10673   });
10674 
10675   assert(!Clusters.empty());
10676   SwitchWorkList WorkList;
10677   CaseClusterIt First = Clusters.begin();
10678   CaseClusterIt Last = Clusters.end() - 1;
10679   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10680   // Scale the branchprobability for DefaultMBB if the peel occurs and
10681   // DefaultMBB is not replaced.
10682   if (PeeledCaseProb != BranchProbability::getZero() &&
10683       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10684     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10685   WorkList.push_back(
10686       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10687 
10688   while (!WorkList.empty()) {
10689     SwitchWorkListItem W = WorkList.back();
10690     WorkList.pop_back();
10691     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10692 
10693     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10694         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10695       // For optimized builds, lower large range as a balanced binary tree.
10696       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10697       continue;
10698     }
10699 
10700     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10701   }
10702 }
10703 
10704 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10705   SDValue N = getValue(I.getOperand(0));
10706   setValue(&I, N);
10707 }
10708