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/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/BlockFrequencyInfo.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/LLVMContext.h"
90 #include "llvm/IR/Metadata.h"
91 #include "llvm/IR/Module.h"
92 #include "llvm/IR/Operator.h"
93 #include "llvm/IR/PatternMatch.h"
94 #include "llvm/IR/Statepoint.h"
95 #include "llvm/IR/Type.h"
96 #include "llvm/IR/User.h"
97 #include "llvm/IR/Value.h"
98 #include "llvm/MC/MCContext.h"
99 #include "llvm/MC/MCSymbol.h"
100 #include "llvm/Support/AtomicOrdering.h"
101 #include "llvm/Support/BranchProbability.h"
102 #include "llvm/Support/Casting.h"
103 #include "llvm/Support/CodeGen.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Compiler.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/ErrorHandling.h"
108 #include "llvm/Support/MachineValueType.h"
109 #include "llvm/Support/MathExtras.h"
110 #include "llvm/Support/raw_ostream.h"
111 #include "llvm/Target/TargetIntrinsicInfo.h"
112 #include "llvm/Target/TargetMachine.h"
113 #include "llvm/Target/TargetOptions.h"
114 #include "llvm/Transforms/Utils/Local.h"
115 #include <algorithm>
116 #include <cassert>
117 #include <cstddef>
118 #include <cstdint>
119 #include <cstring>
120 #include <iterator>
121 #include <limits>
122 #include <numeric>
123 #include <tuple>
124 #include <utility>
125 #include <vector>
126 
127 using namespace llvm;
128 using namespace PatternMatch;
129 using namespace SwitchCG;
130 
131 #define DEBUG_TYPE "isel"
132 
133 /// LimitFloatPrecision - Generate low-precision inline sequences for
134 /// some float libcalls (6, 8 or 12 bits).
135 static unsigned LimitFloatPrecision;
136 
137 static cl::opt<unsigned, true>
138     LimitFPPrecision("limit-float-precision",
139                      cl::desc("Generate low-precision inline sequences "
140                               "for some float libcalls"),
141                      cl::location(LimitFloatPrecision), cl::Hidden,
142                      cl::init(0));
143 
144 static cl::opt<unsigned> SwitchPeelThreshold(
145     "switch-peel-threshold", cl::Hidden, cl::init(66),
146     cl::desc("Set the case probability threshold for peeling the case from a "
147              "switch statement. A value greater than 100 will void this "
148              "optimization"));
149 
150 // Limit the width of DAG chains. This is important in general to prevent
151 // DAG-based analysis from blowing up. For example, alias analysis and
152 // load clustering may not complete in reasonable time. It is difficult to
153 // recognize and avoid this situation within each individual analysis, and
154 // future analyses are likely to have the same behavior. Limiting DAG width is
155 // the safe approach and will be especially important with global DAGs.
156 //
157 // MaxParallelChains default is arbitrarily high to avoid affecting
158 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
159 // sequence over this should have been converted to llvm.memcpy by the
160 // frontend. It is easy to induce this behavior with .ll code such as:
161 // %buffer = alloca [4096 x i8]
162 // %data = load [4096 x i8]* %argPtr
163 // store [4096 x i8] %data, [4096 x i8]* %buffer
164 static const unsigned MaxParallelChains = 64;
165 
166 // Return the calling convention if the Value passed requires ABI mangling as it
167 // is a parameter to a function or a return value from a function which is not
168 // an intrinsic.
169 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
170   if (auto *R = dyn_cast<ReturnInst>(V))
171     return R->getParent()->getParent()->getCallingConv();
172 
173   if (auto *CI = dyn_cast<CallInst>(V)) {
174     const bool IsInlineAsm = CI->isInlineAsm();
175     const bool IsIndirectFunctionCall =
176         !IsInlineAsm && !CI->getCalledFunction();
177 
178     // It is possible that the call instruction is an inline asm statement or an
179     // indirect function call in which case the return value of
180     // getCalledFunction() would be nullptr.
181     const bool IsInstrinsicCall =
182         !IsInlineAsm && !IsIndirectFunctionCall &&
183         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
184 
185     if (!IsInlineAsm && !IsInstrinsicCall)
186       return CI->getCallingConv();
187   }
188 
189   return None;
190 }
191 
192 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
193                                       const SDValue *Parts, unsigned NumParts,
194                                       MVT PartVT, EVT ValueVT, const Value *V,
195                                       Optional<CallingConv::ID> CC);
196 
197 /// getCopyFromParts - Create a value that contains the specified legal parts
198 /// combined into the value they represent.  If the parts combine to a type
199 /// larger than ValueVT then AssertOp can be used to specify whether the extra
200 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
201 /// (ISD::AssertSext).
202 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
203                                 const SDValue *Parts, unsigned NumParts,
204                                 MVT PartVT, EVT ValueVT, const Value *V,
205                                 Optional<CallingConv::ID> CC = None,
206                                 Optional<ISD::NodeType> AssertOp = None) {
207   if (ValueVT.isVector())
208     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
209                                   CC);
210 
211   assert(NumParts > 0 && "No parts to assemble!");
212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
213   SDValue Val = Parts[0];
214 
215   if (NumParts > 1) {
216     // Assemble the value from multiple parts.
217     if (ValueVT.isInteger()) {
218       unsigned PartBits = PartVT.getSizeInBits();
219       unsigned ValueBits = ValueVT.getSizeInBits();
220 
221       // Assemble the power of 2 part.
222       unsigned RoundParts =
223           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
224       unsigned RoundBits = PartBits * RoundParts;
225       EVT RoundVT = RoundBits == ValueBits ?
226         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
227       SDValue Lo, Hi;
228 
229       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
230 
231       if (RoundParts > 2) {
232         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
233                               PartVT, HalfVT, V);
234         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
235                               RoundParts / 2, PartVT, HalfVT, V);
236       } else {
237         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
238         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
239       }
240 
241       if (DAG.getDataLayout().isBigEndian())
242         std::swap(Lo, Hi);
243 
244       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
245 
246       if (RoundParts < NumParts) {
247         // Assemble the trailing non-power-of-2 part.
248         unsigned OddParts = NumParts - RoundParts;
249         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
250         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
251                               OddVT, V, CC);
252 
253         // Combine the round and odd parts.
254         Lo = Val;
255         if (DAG.getDataLayout().isBigEndian())
256           std::swap(Lo, Hi);
257         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
258         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
259         Hi =
260             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
261                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
262                                         TLI.getPointerTy(DAG.getDataLayout())));
263         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
264         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
265       }
266     } else if (PartVT.isFloatingPoint()) {
267       // FP split into multiple FP parts (for ppcf128)
268       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
269              "Unexpected split");
270       SDValue Lo, Hi;
271       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
272       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
273       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
274         std::swap(Lo, Hi);
275       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
276     } else {
277       // FP split into integer parts (soft fp)
278       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
279              !PartVT.isVector() && "Unexpected split");
280       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
281       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
282     }
283   }
284 
285   // There is now one part, held in Val.  Correct it to match ValueVT.
286   // PartEVT is the type of the register class that holds the value.
287   // ValueVT is the type of the inline asm operation.
288   EVT PartEVT = Val.getValueType();
289 
290   if (PartEVT == ValueVT)
291     return Val;
292 
293   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
294       ValueVT.bitsLT(PartEVT)) {
295     // For an FP value in an integer part, we need to truncate to the right
296     // width first.
297     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
298     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
299   }
300 
301   // Handle types that have the same size.
302   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
303     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
304 
305   // Handle types with different sizes.
306   if (PartEVT.isInteger() && ValueVT.isInteger()) {
307     if (ValueVT.bitsLT(PartEVT)) {
308       // For a truncate, see if we have any information to
309       // indicate whether the truncated bits will always be
310       // zero or sign-extension.
311       if (AssertOp.hasValue())
312         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
313                           DAG.getValueType(ValueVT));
314       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
315     }
316     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
317   }
318 
319   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
320     // FP_ROUND's are always exact here.
321     if (ValueVT.bitsLT(Val.getValueType()))
322       return DAG.getNode(
323           ISD::FP_ROUND, DL, ValueVT, Val,
324           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
325 
326     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
327   }
328 
329   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
330   // then truncating.
331   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
332       ValueVT.bitsLT(PartEVT)) {
333     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
334     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
335   }
336 
337   report_fatal_error("Unknown mismatch in getCopyFromParts!");
338 }
339 
340 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
341                                               const Twine &ErrMsg) {
342   const Instruction *I = dyn_cast_or_null<Instruction>(V);
343   if (!V)
344     return Ctx.emitError(ErrMsg);
345 
346   const char *AsmError = ", possible invalid constraint for vector type";
347   if (const CallInst *CI = dyn_cast<CallInst>(I))
348     if (isa<InlineAsm>(CI->getCalledValue()))
349       return Ctx.emitError(I, ErrMsg + AsmError);
350 
351   return Ctx.emitError(I, ErrMsg);
352 }
353 
354 /// getCopyFromPartsVector - Create a value that contains the specified legal
355 /// parts combined into the value they represent.  If the parts combine to a
356 /// type larger than ValueVT then AssertOp can be used to specify whether the
357 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
358 /// ValueVT (ISD::AssertSext).
359 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
360                                       const SDValue *Parts, unsigned NumParts,
361                                       MVT PartVT, EVT ValueVT, const Value *V,
362                                       Optional<CallingConv::ID> CallConv) {
363   assert(ValueVT.isVector() && "Not a vector value");
364   assert(NumParts > 0 && "No parts to assemble!");
365   const bool IsABIRegCopy = CallConv.hasValue();
366 
367   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
368   SDValue Val = Parts[0];
369 
370   // Handle a multi-element vector.
371   if (NumParts > 1) {
372     EVT IntermediateVT;
373     MVT RegisterVT;
374     unsigned NumIntermediates;
375     unsigned NumRegs;
376 
377     if (IsABIRegCopy) {
378       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
379           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
380           NumIntermediates, RegisterVT);
381     } else {
382       NumRegs =
383           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
384                                      NumIntermediates, RegisterVT);
385     }
386 
387     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
388     NumParts = NumRegs; // Silence a compiler warning.
389     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
390     assert(RegisterVT.getSizeInBits() ==
391            Parts[0].getSimpleValueType().getSizeInBits() &&
392            "Part type sizes don't match!");
393 
394     // Assemble the parts into intermediate operands.
395     SmallVector<SDValue, 8> Ops(NumIntermediates);
396     if (NumIntermediates == NumParts) {
397       // If the register was not expanded, truncate or copy the value,
398       // as appropriate.
399       for (unsigned i = 0; i != NumParts; ++i)
400         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
401                                   PartVT, IntermediateVT, V);
402     } else if (NumParts > 0) {
403       // If the intermediate type was expanded, build the intermediate
404       // operands from the parts.
405       assert(NumParts % NumIntermediates == 0 &&
406              "Must expand into a divisible number of parts!");
407       unsigned Factor = NumParts / NumIntermediates;
408       for (unsigned i = 0; i != NumIntermediates; ++i)
409         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
410                                   PartVT, IntermediateVT, V);
411     }
412 
413     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
414     // intermediate operands.
415     EVT BuiltVectorTy =
416         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
417                          (IntermediateVT.isVector()
418                               ? IntermediateVT.getVectorNumElements() * NumParts
419                               : NumIntermediates));
420     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
421                                                 : ISD::BUILD_VECTOR,
422                       DL, BuiltVectorTy, Ops);
423   }
424 
425   // There is now one part, held in Val.  Correct it to match ValueVT.
426   EVT PartEVT = Val.getValueType();
427 
428   if (PartEVT == ValueVT)
429     return Val;
430 
431   if (PartEVT.isVector()) {
432     // If the element type of the source/dest vectors are the same, but the
433     // parts vector has more elements than the value vector, then we have a
434     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
435     // elements we want.
436     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
437       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
438              "Cannot narrow, it would be a lossy transformation");
439       return DAG.getNode(
440           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
441           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
442     }
443 
444     // Vector/Vector bitcast.
445     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
446       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
447 
448     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
449       "Cannot handle this kind of promotion");
450     // Promoted vector extract
451     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
452 
453   }
454 
455   // Trivial bitcast if the types are the same size and the destination
456   // vector type is legal.
457   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
458       TLI.isTypeLegal(ValueVT))
459     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
460 
461   if (ValueVT.getVectorNumElements() != 1) {
462      // Certain ABIs require that vectors are passed as integers. For vectors
463      // are the same size, this is an obvious bitcast.
464      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
465        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
466      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
467        // Bitcast Val back the original type and extract the corresponding
468        // vector we want.
469        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
470        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
471                                            ValueVT.getVectorElementType(), Elts);
472        Val = DAG.getBitcast(WiderVecType, Val);
473        return DAG.getNode(
474            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
475            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
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     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
487                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
488 
489   return DAG.getBuildVector(ValueVT, DL, Val);
490 }
491 
492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
493                                  SDValue Val, SDValue *Parts, unsigned NumParts,
494                                  MVT PartVT, const Value *V,
495                                  Optional<CallingConv::ID> CallConv);
496 
497 /// getCopyToParts - Create a series of nodes that contain the specified value
498 /// split into legal parts.  If the parts contain more bits than Val, then, for
499 /// integers, ExtendKind can be used to specify how to generate the extra bits.
500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
501                            SDValue *Parts, unsigned NumParts, MVT PartVT,
502                            const Value *V,
503                            Optional<CallingConv::ID> CallConv = None,
504                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
505   EVT ValueVT = Val.getValueType();
506 
507   // Handle the vector case separately.
508   if (ValueVT.isVector())
509     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
510                                 CallConv);
511 
512   unsigned PartBits = PartVT.getSizeInBits();
513   unsigned OrigNumParts = NumParts;
514   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
515          "Copying to an illegal type!");
516 
517   if (NumParts == 0)
518     return;
519 
520   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
521   EVT PartEVT = PartVT;
522   if (PartEVT == ValueVT) {
523     assert(NumParts == 1 && "No-op copy with multiple parts!");
524     Parts[0] = Val;
525     return;
526   }
527 
528   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
529     // If the parts cover more bits than the value has, promote the value.
530     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
531       assert(NumParts == 1 && "Do not know what to promote to!");
532       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
533     } else {
534       if (ValueVT.isFloatingPoint()) {
535         // FP values need to be bitcast, then extended if they are being put
536         // into a larger container.
537         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
538         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
539       }
540       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
541              ValueVT.isInteger() &&
542              "Unknown mismatch!");
543       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
544       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
545       if (PartVT == MVT::x86mmx)
546         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547     }
548   } else if (PartBits == ValueVT.getSizeInBits()) {
549     // Different types of the same size.
550     assert(NumParts == 1 && PartEVT != ValueVT);
551     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
553     // If the parts cover less bits than value has, truncate the value.
554     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
555            ValueVT.isInteger() &&
556            "Unknown mismatch!");
557     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
558     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
559     if (PartVT == MVT::x86mmx)
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561   }
562 
563   // The value may have changed - recompute ValueVT.
564   ValueVT = Val.getValueType();
565   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
566          "Failed to tile the value with PartVT!");
567 
568   if (NumParts == 1) {
569     if (PartEVT != ValueVT) {
570       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
571                                         "scalar-to-vector conversion failed");
572       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
573     }
574 
575     Parts[0] = Val;
576     return;
577   }
578 
579   // Expand the value into multiple parts.
580   if (NumParts & (NumParts - 1)) {
581     // The number of parts is not a power of 2.  Split off and copy the tail.
582     assert(PartVT.isInteger() && ValueVT.isInteger() &&
583            "Do not know what to expand to!");
584     unsigned RoundParts = 1 << Log2_32(NumParts);
585     unsigned RoundBits = RoundParts * PartBits;
586     unsigned OddParts = NumParts - RoundParts;
587     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
588       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
589 
590     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
591                    CallConv);
592 
593     if (DAG.getDataLayout().isBigEndian())
594       // The odd parts were reversed by getCopyToParts - unreverse them.
595       std::reverse(Parts + RoundParts, Parts + NumParts);
596 
597     NumParts = RoundParts;
598     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
599     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
600   }
601 
602   // The number of parts is a power of 2.  Repeatedly bisect the value using
603   // EXTRACT_ELEMENT.
604   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
605                          EVT::getIntegerVT(*DAG.getContext(),
606                                            ValueVT.getSizeInBits()),
607                          Val);
608 
609   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
610     for (unsigned i = 0; i < NumParts; i += StepSize) {
611       unsigned ThisBits = StepSize * PartBits / 2;
612       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
613       SDValue &Part0 = Parts[i];
614       SDValue &Part1 = Parts[i+StepSize/2];
615 
616       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
618       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
620 
621       if (ThisBits == PartBits && ThisVT != PartVT) {
622         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
623         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
624       }
625     }
626   }
627 
628   if (DAG.getDataLayout().isBigEndian())
629     std::reverse(Parts, Parts + OrigNumParts);
630 }
631 
632 static SDValue widenVectorToPartType(SelectionDAG &DAG,
633                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
634   if (!PartVT.isVector())
635     return SDValue();
636 
637   EVT ValueVT = Val.getValueType();
638   unsigned PartNumElts = PartVT.getVectorNumElements();
639   unsigned ValueNumElts = ValueVT.getVectorNumElements();
640   if (PartNumElts > ValueNumElts &&
641       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
642     EVT ElementVT = PartVT.getVectorElementType();
643     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
644     // undef elements.
645     SmallVector<SDValue, 16> Ops;
646     DAG.ExtractVectorElements(Val, Ops);
647     SDValue EltUndef = DAG.getUNDEF(ElementVT);
648     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
649       Ops.push_back(EltUndef);
650 
651     // FIXME: Use CONCAT for 2x -> 4x.
652     return DAG.getBuildVector(PartVT, DL, Ops);
653   }
654 
655   return SDValue();
656 }
657 
658 /// getCopyToPartsVector - Create a series of nodes that contain the specified
659 /// value split into legal parts.
660 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
661                                  SDValue Val, SDValue *Parts, unsigned NumParts,
662                                  MVT PartVT, const Value *V,
663                                  Optional<CallingConv::ID> CallConv) {
664   EVT ValueVT = Val.getValueType();
665   assert(ValueVT.isVector() && "Not a vector");
666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
667   const bool IsABIRegCopy = CallConv.hasValue();
668 
669   if (NumParts == 1) {
670     EVT PartEVT = PartVT;
671     if (PartEVT == ValueVT) {
672       // Nothing to do.
673     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
674       // Bitconvert vector->vector case.
675       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
676     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
677       Val = Widened;
678     } else if (PartVT.isVector() &&
679                PartEVT.getVectorElementType().bitsGE(
680                  ValueVT.getVectorElementType()) &&
681                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
682 
683       // Promoted vector extract
684       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
685     } else {
686       if (ValueVT.getVectorNumElements() == 1) {
687         Val = DAG.getNode(
688             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
689             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
690       } else {
691         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
692                "lossy conversion of vector to scalar type");
693         EVT IntermediateType =
694             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
695         Val = DAG.getBitcast(IntermediateType, Val);
696         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
697       }
698     }
699 
700     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
701     Parts[0] = Val;
702     return;
703   }
704 
705   // Handle a multi-element vector.
706   EVT IntermediateVT;
707   MVT RegisterVT;
708   unsigned NumIntermediates;
709   unsigned NumRegs;
710   if (IsABIRegCopy) {
711     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
712         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
713         NumIntermediates, RegisterVT);
714   } else {
715     NumRegs =
716         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
717                                    NumIntermediates, RegisterVT);
718   }
719 
720   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
721   NumParts = NumRegs; // Silence a compiler warning.
722   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
723 
724   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
725     IntermediateVT.getVectorNumElements() : 1;
726 
727   // Convert the vector to the appropriate type if necessary.
728   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
729 
730   EVT BuiltVectorTy = EVT::getVectorVT(
731       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
732   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
733   if (ValueVT != BuiltVectorTy) {
734     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
735       Val = Widened;
736 
737     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
738   }
739 
740   // Split the vector into intermediate operands.
741   SmallVector<SDValue, 8> Ops(NumIntermediates);
742   for (unsigned i = 0; i != NumIntermediates; ++i) {
743     if (IntermediateVT.isVector()) {
744       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
745                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
746     } else {
747       Ops[i] = DAG.getNode(
748           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
749           DAG.getConstant(i, DL, IdxVT));
750     }
751   }
752 
753   // Split the intermediate operands into legal parts.
754   if (NumParts == NumIntermediates) {
755     // If the register was not expanded, promote or copy the value,
756     // as appropriate.
757     for (unsigned i = 0; i != NumParts; ++i)
758       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
759   } else if (NumParts > 0) {
760     // If the intermediate type was expanded, split each the value into
761     // legal parts.
762     assert(NumIntermediates != 0 && "division by zero");
763     assert(NumParts % NumIntermediates == 0 &&
764            "Must expand into a divisible number of parts!");
765     unsigned Factor = NumParts / NumIntermediates;
766     for (unsigned i = 0; i != NumIntermediates; ++i)
767       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
768                      CallConv);
769   }
770 }
771 
772 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
773                            EVT valuevt, Optional<CallingConv::ID> CC)
774     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
775       RegCount(1, regs.size()), CallConv(CC) {}
776 
777 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
778                            const DataLayout &DL, unsigned Reg, Type *Ty,
779                            Optional<CallingConv::ID> CC) {
780   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
781 
782   CallConv = CC;
783 
784   for (EVT ValueVT : ValueVTs) {
785     unsigned NumRegs =
786         isABIMangled()
787             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
788             : TLI.getNumRegisters(Context, ValueVT);
789     MVT RegisterVT =
790         isABIMangled()
791             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
792             : TLI.getRegisterType(Context, ValueVT);
793     for (unsigned i = 0; i != NumRegs; ++i)
794       Regs.push_back(Reg + i);
795     RegVTs.push_back(RegisterVT);
796     RegCount.push_back(NumRegs);
797     Reg += NumRegs;
798   }
799 }
800 
801 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
802                                       FunctionLoweringInfo &FuncInfo,
803                                       const SDLoc &dl, SDValue &Chain,
804                                       SDValue *Flag, const Value *V) const {
805   // A Value with type {} or [0 x %t] needs no registers.
806   if (ValueVTs.empty())
807     return SDValue();
808 
809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
810 
811   // Assemble the legal parts into the final values.
812   SmallVector<SDValue, 4> Values(ValueVTs.size());
813   SmallVector<SDValue, 8> Parts;
814   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
815     // Copy the legal parts from the registers.
816     EVT ValueVT = ValueVTs[Value];
817     unsigned NumRegs = RegCount[Value];
818     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
819                                           *DAG.getContext(),
820                                           CallConv.getValue(), RegVTs[Value])
821                                     : RegVTs[Value];
822 
823     Parts.resize(NumRegs);
824     for (unsigned i = 0; i != NumRegs; ++i) {
825       SDValue P;
826       if (!Flag) {
827         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
828       } else {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
830         *Flag = P.getValue(2);
831       }
832 
833       Chain = P.getValue(1);
834       Parts[i] = P;
835 
836       // If the source register was virtual and if we know something about it,
837       // add an assert node.
838       if (!Register::isVirtualRegister(Regs[Part + i]) ||
839           !RegisterVT.isInteger())
840         continue;
841 
842       const FunctionLoweringInfo::LiveOutInfo *LOI =
843         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
844       if (!LOI)
845         continue;
846 
847       unsigned RegSize = RegisterVT.getScalarSizeInBits();
848       unsigned NumSignBits = LOI->NumSignBits;
849       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
850 
851       if (NumZeroBits == RegSize) {
852         // The current value is a zero.
853         // Explicitly express that as it would be easier for
854         // optimizations to kick in.
855         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
856         continue;
857       }
858 
859       // FIXME: We capture more information than the dag can represent.  For
860       // now, just use the tightest assertzext/assertsext possible.
861       bool isSExt;
862       EVT FromVT(MVT::Other);
863       if (NumZeroBits) {
864         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
865         isSExt = false;
866       } else if (NumSignBits > 1) {
867         FromVT =
868             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
869         isSExt = true;
870       } else {
871         continue;
872       }
873       // Add an assertion node.
874       assert(FromVT != MVT::Other);
875       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
876                              RegisterVT, P, DAG.getValueType(FromVT));
877     }
878 
879     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
880                                      RegisterVT, ValueVT, V, CallConv);
881     Part += NumRegs;
882     Parts.clear();
883   }
884 
885   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
886 }
887 
888 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
889                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
890                                  const Value *V,
891                                  ISD::NodeType PreferredExtendType) const {
892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
893   ISD::NodeType ExtendKind = PreferredExtendType;
894 
895   // Get the list of the values's legal parts.
896   unsigned NumRegs = Regs.size();
897   SmallVector<SDValue, 8> Parts(NumRegs);
898   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
899     unsigned NumParts = RegCount[Value];
900 
901     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
902                                           *DAG.getContext(),
903                                           CallConv.getValue(), RegVTs[Value])
904                                     : RegVTs[Value];
905 
906     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
907       ExtendKind = ISD::ZERO_EXTEND;
908 
909     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
910                    NumParts, RegisterVT, V, CallConv, ExtendKind);
911     Part += NumParts;
912   }
913 
914   // Copy the parts into the registers.
915   SmallVector<SDValue, 8> Chains(NumRegs);
916   for (unsigned i = 0; i != NumRegs; ++i) {
917     SDValue Part;
918     if (!Flag) {
919       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
920     } else {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
922       *Flag = Part.getValue(1);
923     }
924 
925     Chains[i] = Part.getValue(0);
926   }
927 
928   if (NumRegs == 1 || Flag)
929     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
930     // flagged to it. That is the CopyToReg nodes and the user are considered
931     // a single scheduling unit. If we create a TokenFactor and return it as
932     // chain, then the TokenFactor is both a predecessor (operand) of the
933     // user as well as a successor (the TF operands are flagged to the user).
934     // c1, f1 = CopyToReg
935     // c2, f2 = CopyToReg
936     // c3     = TokenFactor c1, c2
937     // ...
938     //        = op c3, ..., f2
939     Chain = Chains[NumRegs-1];
940   else
941     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
942 }
943 
944 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
945                                         unsigned MatchingIdx, const SDLoc &dl,
946                                         SelectionDAG &DAG,
947                                         std::vector<SDValue> &Ops) const {
948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
949 
950   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
951   if (HasMatching)
952     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
953   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
954     // Put the register class of the virtual registers in the flag word.  That
955     // way, later passes can recompute register class constraints for inline
956     // assembly as well as normal instructions.
957     // Don't do this for tied operands that can use the regclass information
958     // from the def.
959     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
960     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
961     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
962   }
963 
964   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
965   Ops.push_back(Res);
966 
967   if (Code == InlineAsm::Kind_Clobber) {
968     // Clobbers should always have a 1:1 mapping with registers, and may
969     // reference registers that have illegal (e.g. vector) types. Hence, we
970     // shouldn't try to apply any sort of splitting logic to them.
971     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
972            "No 1:1 mapping from clobbers to regs?");
973     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
974     (void)SP;
975     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
976       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
977       assert(
978           (Regs[I] != SP ||
979            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
980           "If we clobbered the stack pointer, MFI should know about it.");
981     }
982     return;
983   }
984 
985   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
986     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
987     MVT RegisterVT = RegVTs[Value];
988     for (unsigned i = 0; i != NumRegs; ++i) {
989       assert(Reg < Regs.size() && "Mismatch in # registers expected");
990       unsigned TheReg = Regs[Reg++];
991       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
992     }
993   }
994 }
995 
996 SmallVector<std::pair<unsigned, unsigned>, 4>
997 RegsForValue::getRegsAndSizes() const {
998   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
999   unsigned I = 0;
1000   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1001     unsigned RegCount = std::get<0>(CountAndVT);
1002     MVT RegisterVT = std::get<1>(CountAndVT);
1003     unsigned RegisterSize = RegisterVT.getSizeInBits();
1004     for (unsigned E = I + RegCount; I != E; ++I)
1005       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1006   }
1007   return OutVec;
1008 }
1009 
1010 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1011                                const TargetLibraryInfo *li) {
1012   AA = aa;
1013   GFI = gfi;
1014   LibInfo = li;
1015   DL = &DAG.getDataLayout();
1016   Context = DAG.getContext();
1017   LPadToCallSiteMap.clear();
1018   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1019 }
1020 
1021 void SelectionDAGBuilder::clear() {
1022   NodeMap.clear();
1023   UnusedArgNodeMap.clear();
1024   PendingLoads.clear();
1025   PendingExports.clear();
1026   CurInst = nullptr;
1027   HasTailCall = false;
1028   SDNodeOrder = LowestSDNodeOrder;
1029   StatepointLowering.clear();
1030 }
1031 
1032 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1033   DanglingDebugInfoMap.clear();
1034 }
1035 
1036 SDValue SelectionDAGBuilder::getRoot() {
1037   if (PendingLoads.empty())
1038     return DAG.getRoot();
1039 
1040   if (PendingLoads.size() == 1) {
1041     SDValue Root = PendingLoads[0];
1042     DAG.setRoot(Root);
1043     PendingLoads.clear();
1044     return Root;
1045   }
1046 
1047   // Otherwise, we have to make a token factor node.
1048   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1049   PendingLoads.clear();
1050   DAG.setRoot(Root);
1051   return Root;
1052 }
1053 
1054 SDValue SelectionDAGBuilder::getControlRoot() {
1055   SDValue Root = DAG.getRoot();
1056 
1057   if (PendingExports.empty())
1058     return Root;
1059 
1060   // Turn all of the CopyToReg chains into one factored node.
1061   if (Root.getOpcode() != ISD::EntryToken) {
1062     unsigned i = 0, e = PendingExports.size();
1063     for (; i != e; ++i) {
1064       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1065       if (PendingExports[i].getNode()->getOperand(0) == Root)
1066         break;  // Don't add the root if we already indirectly depend on it.
1067     }
1068 
1069     if (i == e)
1070       PendingExports.push_back(Root);
1071   }
1072 
1073   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1074                      PendingExports);
1075   PendingExports.clear();
1076   DAG.setRoot(Root);
1077   return Root;
1078 }
1079 
1080 void SelectionDAGBuilder::visit(const Instruction &I) {
1081   // Set up outgoing PHI node register values before emitting the terminator.
1082   if (I.isTerminator()) {
1083     HandlePHINodesInSuccessorBlocks(I.getParent());
1084   }
1085 
1086   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1087   if (!isa<DbgInfoIntrinsic>(I))
1088     ++SDNodeOrder;
1089 
1090   CurInst = &I;
1091 
1092   visit(I.getOpcode(), I);
1093 
1094   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1095     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1096     // maps to this instruction.
1097     // TODO: We could handle all flags (nsw, etc) here.
1098     // TODO: If an IR instruction maps to >1 node, only the final node will have
1099     //       flags set.
1100     if (SDNode *Node = getNodeForIRValue(&I)) {
1101       SDNodeFlags IncomingFlags;
1102       IncomingFlags.copyFMF(*FPMO);
1103       if (!Node->getFlags().isDefined())
1104         Node->setFlags(IncomingFlags);
1105       else
1106         Node->intersectFlagsWith(IncomingFlags);
1107     }
1108   }
1109 
1110   if (!I.isTerminator() && !HasTailCall &&
1111       !isStatepoint(&I)) // statepoints handle their exports internally
1112     CopyToExportRegsIfNeeded(&I);
1113 
1114   CurInst = nullptr;
1115 }
1116 
1117 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1118   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1119 }
1120 
1121 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1122   // Note: this doesn't use InstVisitor, because it has to work with
1123   // ConstantExpr's in addition to instructions.
1124   switch (Opcode) {
1125   default: llvm_unreachable("Unknown instruction type encountered!");
1126     // Build the switch statement using the Instruction.def file.
1127 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1128     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1129 #include "llvm/IR/Instruction.def"
1130   }
1131 }
1132 
1133 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1134                                                 const DIExpression *Expr) {
1135   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1136     const DbgValueInst *DI = DDI.getDI();
1137     DIVariable *DanglingVariable = DI->getVariable();
1138     DIExpression *DanglingExpr = DI->getExpression();
1139     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1140       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1141       return true;
1142     }
1143     return false;
1144   };
1145 
1146   for (auto &DDIMI : DanglingDebugInfoMap) {
1147     DanglingDebugInfoVector &DDIV = DDIMI.second;
1148 
1149     // If debug info is to be dropped, run it through final checks to see
1150     // whether it can be salvaged.
1151     for (auto &DDI : DDIV)
1152       if (isMatchingDbgValue(DDI))
1153         salvageUnresolvedDbgValue(DDI);
1154 
1155     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1156   }
1157 }
1158 
1159 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1160 // generate the debug data structures now that we've seen its definition.
1161 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1162                                                    SDValue Val) {
1163   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1164   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1165     return;
1166 
1167   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1168   for (auto &DDI : DDIV) {
1169     const DbgValueInst *DI = DDI.getDI();
1170     assert(DI && "Ill-formed DanglingDebugInfo");
1171     DebugLoc dl = DDI.getdl();
1172     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1173     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1174     DILocalVariable *Variable = DI->getVariable();
1175     DIExpression *Expr = DI->getExpression();
1176     assert(Variable->isValidLocationForIntrinsic(dl) &&
1177            "Expected inlined-at fields to agree");
1178     SDDbgValue *SDV;
1179     if (Val.getNode()) {
1180       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1181       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1182       // we couldn't resolve it directly when examining the DbgValue intrinsic
1183       // in the first place we should not be more successful here). Unless we
1184       // have some test case that prove this to be correct we should avoid
1185       // calling EmitFuncArgumentDbgValue here.
1186       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1187         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1188                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1189         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1190         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1191         // inserted after the definition of Val when emitting the instructions
1192         // after ISel. An alternative could be to teach
1193         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1194         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1195                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1196                    << ValSDNodeOrder << "\n");
1197         SDV = getDbgValue(Val, Variable, Expr, dl,
1198                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1199         DAG.AddDbgValue(SDV, Val.getNode(), false);
1200       } else
1201         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1202                           << "in EmitFuncArgumentDbgValue\n");
1203     } else {
1204       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1205       auto Undef =
1206           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1207       auto SDV =
1208           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1209       DAG.AddDbgValue(SDV, nullptr, false);
1210     }
1211   }
1212   DDIV.clear();
1213 }
1214 
1215 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1216   Value *V = DDI.getDI()->getValue();
1217   DILocalVariable *Var = DDI.getDI()->getVariable();
1218   DIExpression *Expr = DDI.getDI()->getExpression();
1219   DebugLoc DL = DDI.getdl();
1220   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1221   unsigned SDOrder = DDI.getSDNodeOrder();
1222 
1223   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1224   // that DW_OP_stack_value is desired.
1225   assert(isa<DbgValueInst>(DDI.getDI()));
1226   bool StackValue = true;
1227 
1228   // Can this Value can be encoded without any further work?
1229   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1230     return;
1231 
1232   // Attempt to salvage back through as many instructions as possible. Bail if
1233   // a non-instruction is seen, such as a constant expression or global
1234   // variable. FIXME: Further work could recover those too.
1235   while (isa<Instruction>(V)) {
1236     Instruction &VAsInst = *cast<Instruction>(V);
1237     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1238 
1239     // If we cannot salvage any further, and haven't yet found a suitable debug
1240     // expression, bail out.
1241     if (!NewExpr)
1242       break;
1243 
1244     // New value and expr now represent this debuginfo.
1245     V = VAsInst.getOperand(0);
1246     Expr = NewExpr;
1247 
1248     // Some kind of simplification occurred: check whether the operand of the
1249     // salvaged debug expression can be encoded in this DAG.
1250     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1251       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1252                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1253       return;
1254     }
1255   }
1256 
1257   // This was the final opportunity to salvage this debug information, and it
1258   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1259   // any earlier variable location.
1260   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1261   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1262   DAG.AddDbgValue(SDV, nullptr, false);
1263 
1264   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1265                     << "\n");
1266   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1267                     << "\n");
1268 }
1269 
1270 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1271                                            DIExpression *Expr, DebugLoc dl,
1272                                            DebugLoc InstDL, unsigned Order) {
1273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1274   SDDbgValue *SDV;
1275   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1276       isa<ConstantPointerNull>(V)) {
1277     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1278     DAG.AddDbgValue(SDV, nullptr, false);
1279     return true;
1280   }
1281 
1282   // If the Value is a frame index, we can create a FrameIndex debug value
1283   // without relying on the DAG at all.
1284   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1285     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1286     if (SI != FuncInfo.StaticAllocaMap.end()) {
1287       auto SDV =
1288           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1289                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1290       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1291       // is still available even if the SDNode gets optimized out.
1292       DAG.AddDbgValue(SDV, nullptr, false);
1293       return true;
1294     }
1295   }
1296 
1297   // Do not use getValue() in here; we don't want to generate code at
1298   // this point if it hasn't been done yet.
1299   SDValue N = NodeMap[V];
1300   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1301     N = UnusedArgNodeMap[V];
1302   if (N.getNode()) {
1303     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1304       return true;
1305     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1306     DAG.AddDbgValue(SDV, N.getNode(), false);
1307     return true;
1308   }
1309 
1310   // Special rules apply for the first dbg.values of parameter variables in a
1311   // function. Identify them by the fact they reference Argument Values, that
1312   // they're parameters, and they are parameters of the current function. We
1313   // need to let them dangle until they get an SDNode.
1314   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1315                        !InstDL.getInlinedAt();
1316   if (!IsParamOfFunc) {
1317     // The value is not used in this block yet (or it would have an SDNode).
1318     // We still want the value to appear for the user if possible -- if it has
1319     // an associated VReg, we can refer to that instead.
1320     auto VMI = FuncInfo.ValueMap.find(V);
1321     if (VMI != FuncInfo.ValueMap.end()) {
1322       unsigned Reg = VMI->second;
1323       // If this is a PHI node, it may be split up into several MI PHI nodes
1324       // (in FunctionLoweringInfo::set).
1325       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1326                        V->getType(), None);
1327       if (RFV.occupiesMultipleRegs()) {
1328         unsigned Offset = 0;
1329         unsigned BitsToDescribe = 0;
1330         if (auto VarSize = Var->getSizeInBits())
1331           BitsToDescribe = *VarSize;
1332         if (auto Fragment = Expr->getFragmentInfo())
1333           BitsToDescribe = Fragment->SizeInBits;
1334         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1335           unsigned RegisterSize = RegAndSize.second;
1336           // Bail out if all bits are described already.
1337           if (Offset >= BitsToDescribe)
1338             break;
1339           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1340               ? BitsToDescribe - Offset
1341               : RegisterSize;
1342           auto FragmentExpr = DIExpression::createFragmentExpression(
1343               Expr, Offset, FragmentSize);
1344           if (!FragmentExpr)
1345               continue;
1346           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1347                                     false, dl, SDNodeOrder);
1348           DAG.AddDbgValue(SDV, nullptr, false);
1349           Offset += RegisterSize;
1350         }
1351       } else {
1352         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1353         DAG.AddDbgValue(SDV, nullptr, false);
1354       }
1355       return true;
1356     }
1357   }
1358 
1359   return false;
1360 }
1361 
1362 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1363   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1364   for (auto &Pair : DanglingDebugInfoMap)
1365     for (auto &DDI : Pair.second)
1366       salvageUnresolvedDbgValue(DDI);
1367   clearDanglingDebugInfo();
1368 }
1369 
1370 /// getCopyFromRegs - If there was virtual register allocated for the value V
1371 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1372 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1373   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1374   SDValue Result;
1375 
1376   if (It != FuncInfo.ValueMap.end()) {
1377     unsigned InReg = It->second;
1378 
1379     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1380                      DAG.getDataLayout(), InReg, Ty,
1381                      None); // This is not an ABI copy.
1382     SDValue Chain = DAG.getEntryNode();
1383     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1384                                  V);
1385     resolveDanglingDebugInfo(V, Result);
1386   }
1387 
1388   return Result;
1389 }
1390 
1391 /// getValue - Return an SDValue for the given Value.
1392 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1393   // If we already have an SDValue for this value, use it. It's important
1394   // to do this first, so that we don't create a CopyFromReg if we already
1395   // have a regular SDValue.
1396   SDValue &N = NodeMap[V];
1397   if (N.getNode()) return N;
1398 
1399   // If there's a virtual register allocated and initialized for this
1400   // value, use it.
1401   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1402     return copyFromReg;
1403 
1404   // Otherwise create a new SDValue and remember it.
1405   SDValue Val = getValueImpl(V);
1406   NodeMap[V] = Val;
1407   resolveDanglingDebugInfo(V, Val);
1408   return Val;
1409 }
1410 
1411 // Return true if SDValue exists for the given Value
1412 bool SelectionDAGBuilder::findValue(const Value *V) const {
1413   return (NodeMap.find(V) != NodeMap.end()) ||
1414     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1415 }
1416 
1417 /// getNonRegisterValue - Return an SDValue for the given Value, but
1418 /// don't look in FuncInfo.ValueMap for a virtual register.
1419 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1420   // If we already have an SDValue for this value, use it.
1421   SDValue &N = NodeMap[V];
1422   if (N.getNode()) {
1423     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1424       // Remove the debug location from the node as the node is about to be used
1425       // in a location which may differ from the original debug location.  This
1426       // is relevant to Constant and ConstantFP nodes because they can appear
1427       // as constant expressions inside PHI nodes.
1428       N->setDebugLoc(DebugLoc());
1429     }
1430     return N;
1431   }
1432 
1433   // Otherwise create a new SDValue and remember it.
1434   SDValue Val = getValueImpl(V);
1435   NodeMap[V] = Val;
1436   resolveDanglingDebugInfo(V, Val);
1437   return Val;
1438 }
1439 
1440 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1441 /// Create an SDValue for the given value.
1442 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1444 
1445   if (const Constant *C = dyn_cast<Constant>(V)) {
1446     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1447 
1448     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1449       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1450 
1451     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1452       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1453 
1454     if (isa<ConstantPointerNull>(C)) {
1455       unsigned AS = V->getType()->getPointerAddressSpace();
1456       return DAG.getConstant(0, getCurSDLoc(),
1457                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1458     }
1459 
1460     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1461       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1462 
1463     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1464       return DAG.getUNDEF(VT);
1465 
1466     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1467       visit(CE->getOpcode(), *CE);
1468       SDValue N1 = NodeMap[V];
1469       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1470       return N1;
1471     }
1472 
1473     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1474       SmallVector<SDValue, 4> Constants;
1475       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1476            OI != OE; ++OI) {
1477         SDNode *Val = getValue(*OI).getNode();
1478         // If the operand is an empty aggregate, there are no values.
1479         if (!Val) continue;
1480         // Add each leaf value from the operand to the Constants list
1481         // to form a flattened list of all the values.
1482         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1483           Constants.push_back(SDValue(Val, i));
1484       }
1485 
1486       return DAG.getMergeValues(Constants, getCurSDLoc());
1487     }
1488 
1489     if (const ConstantDataSequential *CDS =
1490           dyn_cast<ConstantDataSequential>(C)) {
1491       SmallVector<SDValue, 4> Ops;
1492       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1493         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1494         // Add each leaf value from the operand to the Constants list
1495         // to form a flattened list of all the values.
1496         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1497           Ops.push_back(SDValue(Val, i));
1498       }
1499 
1500       if (isa<ArrayType>(CDS->getType()))
1501         return DAG.getMergeValues(Ops, getCurSDLoc());
1502       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1503     }
1504 
1505     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1506       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1507              "Unknown struct or array constant!");
1508 
1509       SmallVector<EVT, 4> ValueVTs;
1510       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1511       unsigned NumElts = ValueVTs.size();
1512       if (NumElts == 0)
1513         return SDValue(); // empty struct
1514       SmallVector<SDValue, 4> Constants(NumElts);
1515       for (unsigned i = 0; i != NumElts; ++i) {
1516         EVT EltVT = ValueVTs[i];
1517         if (isa<UndefValue>(C))
1518           Constants[i] = DAG.getUNDEF(EltVT);
1519         else if (EltVT.isFloatingPoint())
1520           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1521         else
1522           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1523       }
1524 
1525       return DAG.getMergeValues(Constants, getCurSDLoc());
1526     }
1527 
1528     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1529       return DAG.getBlockAddress(BA, VT);
1530 
1531     VectorType *VecTy = cast<VectorType>(V->getType());
1532     unsigned NumElements = VecTy->getNumElements();
1533 
1534     // Now that we know the number and type of the elements, get that number of
1535     // elements into the Ops array based on what kind of constant it is.
1536     SmallVector<SDValue, 16> Ops;
1537     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1538       for (unsigned i = 0; i != NumElements; ++i)
1539         Ops.push_back(getValue(CV->getOperand(i)));
1540     } else {
1541       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1542       EVT EltVT =
1543           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1544 
1545       SDValue Op;
1546       if (EltVT.isFloatingPoint())
1547         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1548       else
1549         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1550       Ops.assign(NumElements, Op);
1551     }
1552 
1553     // Create a BUILD_VECTOR node.
1554     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1555   }
1556 
1557   // If this is a static alloca, generate it as the frameindex instead of
1558   // computation.
1559   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1560     DenseMap<const AllocaInst*, int>::iterator SI =
1561       FuncInfo.StaticAllocaMap.find(AI);
1562     if (SI != FuncInfo.StaticAllocaMap.end())
1563       return DAG.getFrameIndex(SI->second,
1564                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1565   }
1566 
1567   // If this is an instruction which fast-isel has deferred, select it now.
1568   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1569     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1570 
1571     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1572                      Inst->getType(), getABIRegCopyCC(V));
1573     SDValue Chain = DAG.getEntryNode();
1574     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1575   }
1576 
1577   llvm_unreachable("Can't get register for value!");
1578 }
1579 
1580 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1581   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1582   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1583   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1584   bool IsSEH = isAsynchronousEHPersonality(Pers);
1585   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1586   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1587   if (!IsSEH)
1588     CatchPadMBB->setIsEHScopeEntry();
1589   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1590   if (IsMSVCCXX || IsCoreCLR)
1591     CatchPadMBB->setIsEHFuncletEntry();
1592   // Wasm does not need catchpads anymore
1593   if (!IsWasmCXX)
1594     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1595                             getControlRoot()));
1596 }
1597 
1598 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1599   // Update machine-CFG edge.
1600   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1601   FuncInfo.MBB->addSuccessor(TargetMBB);
1602 
1603   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1604   bool IsSEH = isAsynchronousEHPersonality(Pers);
1605   if (IsSEH) {
1606     // If this is not a fall-through branch or optimizations are switched off,
1607     // emit the branch.
1608     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1609         TM.getOptLevel() == CodeGenOpt::None)
1610       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1611                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1612     return;
1613   }
1614 
1615   // Figure out the funclet membership for the catchret's successor.
1616   // This will be used by the FuncletLayout pass to determine how to order the
1617   // BB's.
1618   // A 'catchret' returns to the outer scope's color.
1619   Value *ParentPad = I.getCatchSwitchParentPad();
1620   const BasicBlock *SuccessorColor;
1621   if (isa<ConstantTokenNone>(ParentPad))
1622     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1623   else
1624     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1625   assert(SuccessorColor && "No parent funclet for catchret!");
1626   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1627   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1628 
1629   // Create the terminator node.
1630   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1631                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1632                             DAG.getBasicBlock(SuccessorColorMBB));
1633   DAG.setRoot(Ret);
1634 }
1635 
1636 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1637   // Don't emit any special code for the cleanuppad instruction. It just marks
1638   // the start of an EH scope/funclet.
1639   FuncInfo.MBB->setIsEHScopeEntry();
1640   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1641   if (Pers != EHPersonality::Wasm_CXX) {
1642     FuncInfo.MBB->setIsEHFuncletEntry();
1643     FuncInfo.MBB->setIsCleanupFuncletEntry();
1644   }
1645 }
1646 
1647 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1648 // the control flow always stops at the single catch pad, as it does for a
1649 // cleanup pad. In case the exception caught is not of the types the catch pad
1650 // catches, it will be rethrown by a rethrow.
1651 static void findWasmUnwindDestinations(
1652     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1653     BranchProbability Prob,
1654     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1655         &UnwindDests) {
1656   while (EHPadBB) {
1657     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1658     if (isa<CleanupPadInst>(Pad)) {
1659       // Stop on cleanup pads.
1660       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1661       UnwindDests.back().first->setIsEHScopeEntry();
1662       break;
1663     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1664       // Add the catchpad handlers to the possible destinations. We don't
1665       // continue to the unwind destination of the catchswitch for wasm.
1666       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1667         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1668         UnwindDests.back().first->setIsEHScopeEntry();
1669       }
1670       break;
1671     } else {
1672       continue;
1673     }
1674   }
1675 }
1676 
1677 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1678 /// many places it could ultimately go. In the IR, we have a single unwind
1679 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1680 /// This function skips over imaginary basic blocks that hold catchswitch
1681 /// instructions, and finds all the "real" machine
1682 /// basic block destinations. As those destinations may not be successors of
1683 /// EHPadBB, here we also calculate the edge probability to those destinations.
1684 /// The passed-in Prob is the edge probability to EHPadBB.
1685 static void findUnwindDestinations(
1686     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1687     BranchProbability Prob,
1688     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1689         &UnwindDests) {
1690   EHPersonality Personality =
1691     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1692   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1693   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1694   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1695   bool IsSEH = isAsynchronousEHPersonality(Personality);
1696 
1697   if (IsWasmCXX) {
1698     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1699     assert(UnwindDests.size() <= 1 &&
1700            "There should be at most one unwind destination for wasm");
1701     return;
1702   }
1703 
1704   while (EHPadBB) {
1705     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1706     BasicBlock *NewEHPadBB = nullptr;
1707     if (isa<LandingPadInst>(Pad)) {
1708       // Stop on landingpads. They are not funclets.
1709       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1710       break;
1711     } else if (isa<CleanupPadInst>(Pad)) {
1712       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1713       // personalities.
1714       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1715       UnwindDests.back().first->setIsEHScopeEntry();
1716       UnwindDests.back().first->setIsEHFuncletEntry();
1717       break;
1718     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1719       // Add the catchpad handlers to the possible destinations.
1720       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1721         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1722         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1723         if (IsMSVCCXX || IsCoreCLR)
1724           UnwindDests.back().first->setIsEHFuncletEntry();
1725         if (!IsSEH)
1726           UnwindDests.back().first->setIsEHScopeEntry();
1727       }
1728       NewEHPadBB = CatchSwitch->getUnwindDest();
1729     } else {
1730       continue;
1731     }
1732 
1733     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1734     if (BPI && NewEHPadBB)
1735       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1736     EHPadBB = NewEHPadBB;
1737   }
1738 }
1739 
1740 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1741   // Update successor info.
1742   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1743   auto UnwindDest = I.getUnwindDest();
1744   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1745   BranchProbability UnwindDestProb =
1746       (BPI && UnwindDest)
1747           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1748           : BranchProbability::getZero();
1749   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1750   for (auto &UnwindDest : UnwindDests) {
1751     UnwindDest.first->setIsEHPad();
1752     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1753   }
1754   FuncInfo.MBB->normalizeSuccProbs();
1755 
1756   // Create the terminator node.
1757   SDValue Ret =
1758       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1759   DAG.setRoot(Ret);
1760 }
1761 
1762 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1763   report_fatal_error("visitCatchSwitch not yet implemented!");
1764 }
1765 
1766 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1768   auto &DL = DAG.getDataLayout();
1769   SDValue Chain = getControlRoot();
1770   SmallVector<ISD::OutputArg, 8> Outs;
1771   SmallVector<SDValue, 8> OutVals;
1772 
1773   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1774   // lower
1775   //
1776   //   %val = call <ty> @llvm.experimental.deoptimize()
1777   //   ret <ty> %val
1778   //
1779   // differently.
1780   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1781     LowerDeoptimizingReturn();
1782     return;
1783   }
1784 
1785   if (!FuncInfo.CanLowerReturn) {
1786     unsigned DemoteReg = FuncInfo.DemoteRegister;
1787     const Function *F = I.getParent()->getParent();
1788 
1789     // Emit a store of the return value through the virtual register.
1790     // Leave Outs empty so that LowerReturn won't try to load return
1791     // registers the usual way.
1792     SmallVector<EVT, 1> PtrValueVTs;
1793     ComputeValueVTs(TLI, DL,
1794                     F->getReturnType()->getPointerTo(
1795                         DAG.getDataLayout().getAllocaAddrSpace()),
1796                     PtrValueVTs);
1797 
1798     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1799                                         DemoteReg, PtrValueVTs[0]);
1800     SDValue RetOp = getValue(I.getOperand(0));
1801 
1802     SmallVector<EVT, 4> ValueVTs, MemVTs;
1803     SmallVector<uint64_t, 4> Offsets;
1804     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1805                     &Offsets);
1806     unsigned NumValues = ValueVTs.size();
1807 
1808     SmallVector<SDValue, 4> Chains(NumValues);
1809     for (unsigned i = 0; i != NumValues; ++i) {
1810       // An aggregate return value cannot wrap around the address space, so
1811       // offsets to its parts don't wrap either.
1812       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1813 
1814       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1815       if (MemVTs[i] != ValueVTs[i])
1816         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1817       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1818           // FIXME: better loc info would be nice.
1819           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1820     }
1821 
1822     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1823                         MVT::Other, Chains);
1824   } else if (I.getNumOperands() != 0) {
1825     SmallVector<EVT, 4> ValueVTs;
1826     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1827     unsigned NumValues = ValueVTs.size();
1828     if (NumValues) {
1829       SDValue RetOp = getValue(I.getOperand(0));
1830 
1831       const Function *F = I.getParent()->getParent();
1832 
1833       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1834           I.getOperand(0)->getType(), F->getCallingConv(),
1835           /*IsVarArg*/ false);
1836 
1837       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1838       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1839                                           Attribute::SExt))
1840         ExtendKind = ISD::SIGN_EXTEND;
1841       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1842                                                Attribute::ZExt))
1843         ExtendKind = ISD::ZERO_EXTEND;
1844 
1845       LLVMContext &Context = F->getContext();
1846       bool RetInReg = F->getAttributes().hasAttribute(
1847           AttributeList::ReturnIndex, Attribute::InReg);
1848 
1849       for (unsigned j = 0; j != NumValues; ++j) {
1850         EVT VT = ValueVTs[j];
1851 
1852         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1853           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1854 
1855         CallingConv::ID CC = F->getCallingConv();
1856 
1857         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1858         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1859         SmallVector<SDValue, 4> Parts(NumParts);
1860         getCopyToParts(DAG, getCurSDLoc(),
1861                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1862                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1863 
1864         // 'inreg' on function refers to return value
1865         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1866         if (RetInReg)
1867           Flags.setInReg();
1868 
1869         if (I.getOperand(0)->getType()->isPointerTy()) {
1870           Flags.setPointer();
1871           Flags.setPointerAddrSpace(
1872               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1873         }
1874 
1875         if (NeedsRegBlock) {
1876           Flags.setInConsecutiveRegs();
1877           if (j == NumValues - 1)
1878             Flags.setInConsecutiveRegsLast();
1879         }
1880 
1881         // Propagate extension type if any
1882         if (ExtendKind == ISD::SIGN_EXTEND)
1883           Flags.setSExt();
1884         else if (ExtendKind == ISD::ZERO_EXTEND)
1885           Flags.setZExt();
1886 
1887         for (unsigned i = 0; i < NumParts; ++i) {
1888           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1889                                         VT, /*isfixed=*/true, 0, 0));
1890           OutVals.push_back(Parts[i]);
1891         }
1892       }
1893     }
1894   }
1895 
1896   // Push in swifterror virtual register as the last element of Outs. This makes
1897   // sure swifterror virtual register will be returned in the swifterror
1898   // physical register.
1899   const Function *F = I.getParent()->getParent();
1900   if (TLI.supportSwiftError() &&
1901       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1902     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1903     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1904     Flags.setSwiftError();
1905     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1906                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1907                                   true /*isfixed*/, 1 /*origidx*/,
1908                                   0 /*partOffs*/));
1909     // Create SDNode for the swifterror virtual register.
1910     OutVals.push_back(
1911         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1912                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1913                         EVT(TLI.getPointerTy(DL))));
1914   }
1915 
1916   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1917   CallingConv::ID CallConv =
1918     DAG.getMachineFunction().getFunction().getCallingConv();
1919   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1920       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1921 
1922   // Verify that the target's LowerReturn behaved as expected.
1923   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1924          "LowerReturn didn't return a valid chain!");
1925 
1926   // Update the DAG with the new chain value resulting from return lowering.
1927   DAG.setRoot(Chain);
1928 }
1929 
1930 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1931 /// created for it, emit nodes to copy the value into the virtual
1932 /// registers.
1933 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1934   // Skip empty types
1935   if (V->getType()->isEmptyTy())
1936     return;
1937 
1938   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1939   if (VMI != FuncInfo.ValueMap.end()) {
1940     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1941     CopyValueToVirtualRegister(V, VMI->second);
1942   }
1943 }
1944 
1945 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1946 /// the current basic block, add it to ValueMap now so that we'll get a
1947 /// CopyTo/FromReg.
1948 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1949   // No need to export constants.
1950   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1951 
1952   // Already exported?
1953   if (FuncInfo.isExportedInst(V)) return;
1954 
1955   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1956   CopyValueToVirtualRegister(V, Reg);
1957 }
1958 
1959 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1960                                                      const BasicBlock *FromBB) {
1961   // The operands of the setcc have to be in this block.  We don't know
1962   // how to export them from some other block.
1963   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1964     // Can export from current BB.
1965     if (VI->getParent() == FromBB)
1966       return true;
1967 
1968     // Is already exported, noop.
1969     return FuncInfo.isExportedInst(V);
1970   }
1971 
1972   // If this is an argument, we can export it if the BB is the entry block or
1973   // if it is already exported.
1974   if (isa<Argument>(V)) {
1975     if (FromBB == &FromBB->getParent()->getEntryBlock())
1976       return true;
1977 
1978     // Otherwise, can only export this if it is already exported.
1979     return FuncInfo.isExportedInst(V);
1980   }
1981 
1982   // Otherwise, constants can always be exported.
1983   return true;
1984 }
1985 
1986 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1987 BranchProbability
1988 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1989                                         const MachineBasicBlock *Dst) const {
1990   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1991   const BasicBlock *SrcBB = Src->getBasicBlock();
1992   const BasicBlock *DstBB = Dst->getBasicBlock();
1993   if (!BPI) {
1994     // If BPI is not available, set the default probability as 1 / N, where N is
1995     // the number of successors.
1996     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1997     return BranchProbability(1, SuccSize);
1998   }
1999   return BPI->getEdgeProbability(SrcBB, DstBB);
2000 }
2001 
2002 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2003                                                MachineBasicBlock *Dst,
2004                                                BranchProbability Prob) {
2005   if (!FuncInfo.BPI)
2006     Src->addSuccessorWithoutProb(Dst);
2007   else {
2008     if (Prob.isUnknown())
2009       Prob = getEdgeProbability(Src, Dst);
2010     Src->addSuccessor(Dst, Prob);
2011   }
2012 }
2013 
2014 static bool InBlock(const Value *V, const BasicBlock *BB) {
2015   if (const Instruction *I = dyn_cast<Instruction>(V))
2016     return I->getParent() == BB;
2017   return true;
2018 }
2019 
2020 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2021 /// This function emits a branch and is used at the leaves of an OR or an
2022 /// AND operator tree.
2023 void
2024 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2025                                                   MachineBasicBlock *TBB,
2026                                                   MachineBasicBlock *FBB,
2027                                                   MachineBasicBlock *CurBB,
2028                                                   MachineBasicBlock *SwitchBB,
2029                                                   BranchProbability TProb,
2030                                                   BranchProbability FProb,
2031                                                   bool InvertCond) {
2032   const BasicBlock *BB = CurBB->getBasicBlock();
2033 
2034   // If the leaf of the tree is a comparison, merge the condition into
2035   // the caseblock.
2036   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2037     // The operands of the cmp have to be in this block.  We don't know
2038     // how to export them from some other block.  If this is the first block
2039     // of the sequence, no exporting is needed.
2040     if (CurBB == SwitchBB ||
2041         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2042          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2043       ISD::CondCode Condition;
2044       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2045         ICmpInst::Predicate Pred =
2046             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2047         Condition = getICmpCondCode(Pred);
2048       } else {
2049         const FCmpInst *FC = cast<FCmpInst>(Cond);
2050         FCmpInst::Predicate Pred =
2051             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2052         Condition = getFCmpCondCode(Pred);
2053         if (TM.Options.NoNaNsFPMath)
2054           Condition = getFCmpCodeWithoutNaN(Condition);
2055       }
2056 
2057       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2058                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2059       SL->SwitchCases.push_back(CB);
2060       return;
2061     }
2062   }
2063 
2064   // Create a CaseBlock record representing this branch.
2065   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2066   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2067                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2068   SL->SwitchCases.push_back(CB);
2069 }
2070 
2071 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2072                                                MachineBasicBlock *TBB,
2073                                                MachineBasicBlock *FBB,
2074                                                MachineBasicBlock *CurBB,
2075                                                MachineBasicBlock *SwitchBB,
2076                                                Instruction::BinaryOps Opc,
2077                                                BranchProbability TProb,
2078                                                BranchProbability FProb,
2079                                                bool InvertCond) {
2080   // Skip over not part of the tree and remember to invert op and operands at
2081   // next level.
2082   Value *NotCond;
2083   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2084       InBlock(NotCond, CurBB->getBasicBlock())) {
2085     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2086                          !InvertCond);
2087     return;
2088   }
2089 
2090   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2091   // Compute the effective opcode for Cond, taking into account whether it needs
2092   // to be inverted, e.g.
2093   //   and (not (or A, B)), C
2094   // gets lowered as
2095   //   and (and (not A, not B), C)
2096   unsigned BOpc = 0;
2097   if (BOp) {
2098     BOpc = BOp->getOpcode();
2099     if (InvertCond) {
2100       if (BOpc == Instruction::And)
2101         BOpc = Instruction::Or;
2102       else if (BOpc == Instruction::Or)
2103         BOpc = Instruction::And;
2104     }
2105   }
2106 
2107   // If this node is not part of the or/and tree, emit it as a branch.
2108   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2109       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2110       BOp->getParent() != CurBB->getBasicBlock() ||
2111       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2112       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2113     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2114                                  TProb, FProb, InvertCond);
2115     return;
2116   }
2117 
2118   //  Create TmpBB after CurBB.
2119   MachineFunction::iterator BBI(CurBB);
2120   MachineFunction &MF = DAG.getMachineFunction();
2121   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2122   CurBB->getParent()->insert(++BBI, TmpBB);
2123 
2124   if (Opc == Instruction::Or) {
2125     // Codegen X | Y as:
2126     // BB1:
2127     //   jmp_if_X TBB
2128     //   jmp TmpBB
2129     // TmpBB:
2130     //   jmp_if_Y TBB
2131     //   jmp FBB
2132     //
2133 
2134     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2135     // The requirement is that
2136     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2137     //     = TrueProb for original BB.
2138     // Assuming the original probabilities are A and B, one choice is to set
2139     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2140     // A/(1+B) and 2B/(1+B). This choice assumes that
2141     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2142     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2143     // TmpBB, but the math is more complicated.
2144 
2145     auto NewTrueProb = TProb / 2;
2146     auto NewFalseProb = TProb / 2 + FProb;
2147     // Emit the LHS condition.
2148     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2149                          NewTrueProb, NewFalseProb, InvertCond);
2150 
2151     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2152     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2153     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2154     // Emit the RHS condition into TmpBB.
2155     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2156                          Probs[0], Probs[1], InvertCond);
2157   } else {
2158     assert(Opc == Instruction::And && "Unknown merge op!");
2159     // Codegen X & Y as:
2160     // BB1:
2161     //   jmp_if_X TmpBB
2162     //   jmp FBB
2163     // TmpBB:
2164     //   jmp_if_Y TBB
2165     //   jmp FBB
2166     //
2167     //  This requires creation of TmpBB after CurBB.
2168 
2169     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2170     // The requirement is that
2171     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2172     //     = FalseProb for original BB.
2173     // Assuming the original probabilities are A and B, one choice is to set
2174     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2175     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2176     // TrueProb for BB1 * FalseProb for TmpBB.
2177 
2178     auto NewTrueProb = TProb + FProb / 2;
2179     auto NewFalseProb = FProb / 2;
2180     // Emit the LHS condition.
2181     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2182                          NewTrueProb, NewFalseProb, InvertCond);
2183 
2184     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2185     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2186     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2187     // Emit the RHS condition into TmpBB.
2188     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2189                          Probs[0], Probs[1], InvertCond);
2190   }
2191 }
2192 
2193 /// If the set of cases should be emitted as a series of branches, return true.
2194 /// If we should emit this as a bunch of and/or'd together conditions, return
2195 /// false.
2196 bool
2197 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2198   if (Cases.size() != 2) return true;
2199 
2200   // If this is two comparisons of the same values or'd or and'd together, they
2201   // will get folded into a single comparison, so don't emit two blocks.
2202   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2203        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2204       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2205        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2206     return false;
2207   }
2208 
2209   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2210   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2211   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2212       Cases[0].CC == Cases[1].CC &&
2213       isa<Constant>(Cases[0].CmpRHS) &&
2214       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2215     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2216       return false;
2217     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2218       return false;
2219   }
2220 
2221   return true;
2222 }
2223 
2224 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2225   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2226 
2227   // Update machine-CFG edges.
2228   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2229 
2230   if (I.isUnconditional()) {
2231     // Update machine-CFG edges.
2232     BrMBB->addSuccessor(Succ0MBB);
2233 
2234     // If this is not a fall-through branch or optimizations are switched off,
2235     // emit the branch.
2236     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2237       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2238                               MVT::Other, getControlRoot(),
2239                               DAG.getBasicBlock(Succ0MBB)));
2240 
2241     return;
2242   }
2243 
2244   // If this condition is one of the special cases we handle, do special stuff
2245   // now.
2246   const Value *CondVal = I.getCondition();
2247   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2248 
2249   // If this is a series of conditions that are or'd or and'd together, emit
2250   // this as a sequence of branches instead of setcc's with and/or operations.
2251   // As long as jumps are not expensive, this should improve performance.
2252   // For example, instead of something like:
2253   //     cmp A, B
2254   //     C = seteq
2255   //     cmp D, E
2256   //     F = setle
2257   //     or C, F
2258   //     jnz foo
2259   // Emit:
2260   //     cmp A, B
2261   //     je foo
2262   //     cmp D, E
2263   //     jle foo
2264   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2265     Instruction::BinaryOps Opcode = BOp->getOpcode();
2266     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2267         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2268         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2269       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2270                            Opcode,
2271                            getEdgeProbability(BrMBB, Succ0MBB),
2272                            getEdgeProbability(BrMBB, Succ1MBB),
2273                            /*InvertCond=*/false);
2274       // If the compares in later blocks need to use values not currently
2275       // exported from this block, export them now.  This block should always
2276       // be the first entry.
2277       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2278 
2279       // Allow some cases to be rejected.
2280       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2281         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2282           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2283           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2284         }
2285 
2286         // Emit the branch for this block.
2287         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2288         SL->SwitchCases.erase(SL->SwitchCases.begin());
2289         return;
2290       }
2291 
2292       // Okay, we decided not to do this, remove any inserted MBB's and clear
2293       // SwitchCases.
2294       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2295         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2296 
2297       SL->SwitchCases.clear();
2298     }
2299   }
2300 
2301   // Create a CaseBlock record representing this branch.
2302   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2303                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2304 
2305   // Use visitSwitchCase to actually insert the fast branch sequence for this
2306   // cond branch.
2307   visitSwitchCase(CB, BrMBB);
2308 }
2309 
2310 /// visitSwitchCase - Emits the necessary code to represent a single node in
2311 /// the binary search tree resulting from lowering a switch instruction.
2312 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2313                                           MachineBasicBlock *SwitchBB) {
2314   SDValue Cond;
2315   SDValue CondLHS = getValue(CB.CmpLHS);
2316   SDLoc dl = CB.DL;
2317 
2318   if (CB.CC == ISD::SETTRUE) {
2319     // Branch or fall through to TrueBB.
2320     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2321     SwitchBB->normalizeSuccProbs();
2322     if (CB.TrueBB != NextBlock(SwitchBB)) {
2323       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2324                               DAG.getBasicBlock(CB.TrueBB)));
2325     }
2326     return;
2327   }
2328 
2329   auto &TLI = DAG.getTargetLoweringInfo();
2330   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2331 
2332   // Build the setcc now.
2333   if (!CB.CmpMHS) {
2334     // Fold "(X == true)" to X and "(X == false)" to !X to
2335     // handle common cases produced by branch lowering.
2336     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2337         CB.CC == ISD::SETEQ)
2338       Cond = CondLHS;
2339     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2340              CB.CC == ISD::SETEQ) {
2341       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2342       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2343     } else {
2344       SDValue CondRHS = getValue(CB.CmpRHS);
2345 
2346       // If a pointer's DAG type is larger than its memory type then the DAG
2347       // values are zero-extended. This breaks signed comparisons so truncate
2348       // back to the underlying type before doing the compare.
2349       if (CondLHS.getValueType() != MemVT) {
2350         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2351         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2352       }
2353       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2354     }
2355   } else {
2356     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2357 
2358     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2359     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2360 
2361     SDValue CmpOp = getValue(CB.CmpMHS);
2362     EVT VT = CmpOp.getValueType();
2363 
2364     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2365       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2366                           ISD::SETLE);
2367     } else {
2368       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2369                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2370       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2371                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2372     }
2373   }
2374 
2375   // Update successor info
2376   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2377   // TrueBB and FalseBB are always different unless the incoming IR is
2378   // degenerate. This only happens when running llc on weird IR.
2379   if (CB.TrueBB != CB.FalseBB)
2380     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2381   SwitchBB->normalizeSuccProbs();
2382 
2383   // If the lhs block is the next block, invert the condition so that we can
2384   // fall through to the lhs instead of the rhs block.
2385   if (CB.TrueBB == NextBlock(SwitchBB)) {
2386     std::swap(CB.TrueBB, CB.FalseBB);
2387     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2388     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2389   }
2390 
2391   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2392                                MVT::Other, getControlRoot(), Cond,
2393                                DAG.getBasicBlock(CB.TrueBB));
2394 
2395   // Insert the false branch. Do this even if it's a fall through branch,
2396   // this makes it easier to do DAG optimizations which require inverting
2397   // the branch condition.
2398   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2399                        DAG.getBasicBlock(CB.FalseBB));
2400 
2401   DAG.setRoot(BrCond);
2402 }
2403 
2404 /// visitJumpTable - Emit JumpTable node in the current MBB
2405 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2406   // Emit the code for the jump table
2407   assert(JT.Reg != -1U && "Should lower JT Header first!");
2408   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2409   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2410                                      JT.Reg, PTy);
2411   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2412   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2413                                     MVT::Other, Index.getValue(1),
2414                                     Table, Index);
2415   DAG.setRoot(BrJumpTable);
2416 }
2417 
2418 /// visitJumpTableHeader - This function emits necessary code to produce index
2419 /// in the JumpTable from switch case.
2420 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2421                                                JumpTableHeader &JTH,
2422                                                MachineBasicBlock *SwitchBB) {
2423   SDLoc dl = getCurSDLoc();
2424 
2425   // Subtract the lowest switch case value from the value being switched on.
2426   SDValue SwitchOp = getValue(JTH.SValue);
2427   EVT VT = SwitchOp.getValueType();
2428   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2429                             DAG.getConstant(JTH.First, dl, VT));
2430 
2431   // The SDNode we just created, which holds the value being switched on minus
2432   // the smallest case value, needs to be copied to a virtual register so it
2433   // can be used as an index into the jump table in a subsequent basic block.
2434   // This value may be smaller or larger than the target's pointer type, and
2435   // therefore require extension or truncating.
2436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2437   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2438 
2439   unsigned JumpTableReg =
2440       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2441   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2442                                     JumpTableReg, SwitchOp);
2443   JT.Reg = JumpTableReg;
2444 
2445   if (!JTH.OmitRangeCheck) {
2446     // Emit the range check for the jump table, and branch to the default block
2447     // for the switch statement if the value being switched on exceeds the
2448     // largest case in the switch.
2449     SDValue CMP = DAG.getSetCC(
2450         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2451                                    Sub.getValueType()),
2452         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2453 
2454     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2455                                  MVT::Other, CopyTo, CMP,
2456                                  DAG.getBasicBlock(JT.Default));
2457 
2458     // Avoid emitting unnecessary branches to the next block.
2459     if (JT.MBB != NextBlock(SwitchBB))
2460       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2461                            DAG.getBasicBlock(JT.MBB));
2462 
2463     DAG.setRoot(BrCond);
2464   } else {
2465     // Avoid emitting unnecessary branches to the next block.
2466     if (JT.MBB != NextBlock(SwitchBB))
2467       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2468                               DAG.getBasicBlock(JT.MBB)));
2469     else
2470       DAG.setRoot(CopyTo);
2471   }
2472 }
2473 
2474 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2475 /// variable if there exists one.
2476 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2477                                  SDValue &Chain) {
2478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2479   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2480   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2481   MachineFunction &MF = DAG.getMachineFunction();
2482   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2483   MachineSDNode *Node =
2484       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2485   if (Global) {
2486     MachinePointerInfo MPInfo(Global);
2487     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2488                  MachineMemOperand::MODereferenceable;
2489     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2490         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2491     DAG.setNodeMemRefs(Node, {MemRef});
2492   }
2493   if (PtrTy != PtrMemTy)
2494     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2495   return SDValue(Node, 0);
2496 }
2497 
2498 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2499 /// tail spliced into a stack protector check success bb.
2500 ///
2501 /// For a high level explanation of how this fits into the stack protector
2502 /// generation see the comment on the declaration of class
2503 /// StackProtectorDescriptor.
2504 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2505                                                   MachineBasicBlock *ParentBB) {
2506 
2507   // First create the loads to the guard/stack slot for the comparison.
2508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2509   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2510   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2511 
2512   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2513   int FI = MFI.getStackProtectorIndex();
2514 
2515   SDValue Guard;
2516   SDLoc dl = getCurSDLoc();
2517   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2518   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2519   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2520 
2521   // Generate code to load the content of the guard slot.
2522   SDValue GuardVal = DAG.getLoad(
2523       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2524       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2525       MachineMemOperand::MOVolatile);
2526 
2527   if (TLI.useStackGuardXorFP())
2528     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2529 
2530   // Retrieve guard check function, nullptr if instrumentation is inlined.
2531   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2532     // The target provides a guard check function to validate the guard value.
2533     // Generate a call to that function with the content of the guard slot as
2534     // argument.
2535     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2536     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2537 
2538     TargetLowering::ArgListTy Args;
2539     TargetLowering::ArgListEntry Entry;
2540     Entry.Node = GuardVal;
2541     Entry.Ty = FnTy->getParamType(0);
2542     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2543       Entry.IsInReg = true;
2544     Args.push_back(Entry);
2545 
2546     TargetLowering::CallLoweringInfo CLI(DAG);
2547     CLI.setDebugLoc(getCurSDLoc())
2548         .setChain(DAG.getEntryNode())
2549         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2550                    getValue(GuardCheckFn), std::move(Args));
2551 
2552     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2553     DAG.setRoot(Result.second);
2554     return;
2555   }
2556 
2557   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2558   // Otherwise, emit a volatile load to retrieve the stack guard value.
2559   SDValue Chain = DAG.getEntryNode();
2560   if (TLI.useLoadStackGuardNode()) {
2561     Guard = getLoadStackGuard(DAG, dl, Chain);
2562   } else {
2563     const Value *IRGuard = TLI.getSDagStackGuard(M);
2564     SDValue GuardPtr = getValue(IRGuard);
2565 
2566     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2567                         MachinePointerInfo(IRGuard, 0), Align,
2568                         MachineMemOperand::MOVolatile);
2569   }
2570 
2571   // Perform the comparison via a subtract/getsetcc.
2572   EVT VT = Guard.getValueType();
2573   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2574 
2575   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2576                                                         *DAG.getContext(),
2577                                                         Sub.getValueType()),
2578                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2579 
2580   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2581   // branch to failure MBB.
2582   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2583                                MVT::Other, GuardVal.getOperand(0),
2584                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2585   // Otherwise branch to success MBB.
2586   SDValue Br = DAG.getNode(ISD::BR, dl,
2587                            MVT::Other, BrCond,
2588                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2589 
2590   DAG.setRoot(Br);
2591 }
2592 
2593 /// Codegen the failure basic block for a stack protector check.
2594 ///
2595 /// A failure stack protector machine basic block consists simply of a call to
2596 /// __stack_chk_fail().
2597 ///
2598 /// For a high level explanation of how this fits into the stack protector
2599 /// generation see the comment on the declaration of class
2600 /// StackProtectorDescriptor.
2601 void
2602 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2604   TargetLowering::MakeLibCallOptions CallOptions;
2605   CallOptions.setDiscardResult(true);
2606   SDValue Chain =
2607       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2608                       None, CallOptions, getCurSDLoc()).second;
2609   // On PS4, the "return address" must still be within the calling function,
2610   // even if it's at the very end, so emit an explicit TRAP here.
2611   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2612   if (TM.getTargetTriple().isPS4CPU())
2613     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2614 
2615   DAG.setRoot(Chain);
2616 }
2617 
2618 /// visitBitTestHeader - This function emits necessary code to produce value
2619 /// suitable for "bit tests"
2620 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2621                                              MachineBasicBlock *SwitchBB) {
2622   SDLoc dl = getCurSDLoc();
2623 
2624   // Subtract the minimum value.
2625   SDValue SwitchOp = getValue(B.SValue);
2626   EVT VT = SwitchOp.getValueType();
2627   SDValue RangeSub =
2628       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2629 
2630   // Determine the type of the test operands.
2631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2632   bool UsePtrType = false;
2633   if (!TLI.isTypeLegal(VT)) {
2634     UsePtrType = true;
2635   } else {
2636     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2637       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2638         // Switch table case range are encoded into series of masks.
2639         // Just use pointer type, it's guaranteed to fit.
2640         UsePtrType = true;
2641         break;
2642       }
2643   }
2644   SDValue Sub = RangeSub;
2645   if (UsePtrType) {
2646     VT = TLI.getPointerTy(DAG.getDataLayout());
2647     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2648   }
2649 
2650   B.RegVT = VT.getSimpleVT();
2651   B.Reg = FuncInfo.CreateReg(B.RegVT);
2652   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2653 
2654   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2655 
2656   if (!B.OmitRangeCheck)
2657     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2658   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2659   SwitchBB->normalizeSuccProbs();
2660 
2661   SDValue Root = CopyTo;
2662   if (!B.OmitRangeCheck) {
2663     // Conditional branch to the default block.
2664     SDValue RangeCmp = DAG.getSetCC(dl,
2665         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2666                                RangeSub.getValueType()),
2667         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2668         ISD::SETUGT);
2669 
2670     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2671                        DAG.getBasicBlock(B.Default));
2672   }
2673 
2674   // Avoid emitting unnecessary branches to the next block.
2675   if (MBB != NextBlock(SwitchBB))
2676     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2677 
2678   DAG.setRoot(Root);
2679 }
2680 
2681 /// visitBitTestCase - this function produces one "bit test"
2682 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2683                                            MachineBasicBlock* NextMBB,
2684                                            BranchProbability BranchProbToNext,
2685                                            unsigned Reg,
2686                                            BitTestCase &B,
2687                                            MachineBasicBlock *SwitchBB) {
2688   SDLoc dl = getCurSDLoc();
2689   MVT VT = BB.RegVT;
2690   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2691   SDValue Cmp;
2692   unsigned PopCount = countPopulation(B.Mask);
2693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2694   if (PopCount == 1) {
2695     // Testing for a single bit; just compare the shift count with what it
2696     // would need to be to shift a 1 bit in that position.
2697     Cmp = DAG.getSetCC(
2698         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2699         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2700         ISD::SETEQ);
2701   } else if (PopCount == BB.Range) {
2702     // There is only one zero bit in the range, test for it directly.
2703     Cmp = DAG.getSetCC(
2704         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2705         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2706         ISD::SETNE);
2707   } else {
2708     // Make desired shift
2709     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2710                                     DAG.getConstant(1, dl, VT), ShiftOp);
2711 
2712     // Emit bit tests and jumps
2713     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2714                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2715     Cmp = DAG.getSetCC(
2716         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2717         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2718   }
2719 
2720   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2721   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2722   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2723   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2724   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2725   // one as they are relative probabilities (and thus work more like weights),
2726   // and hence we need to normalize them to let the sum of them become one.
2727   SwitchBB->normalizeSuccProbs();
2728 
2729   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2730                               MVT::Other, getControlRoot(),
2731                               Cmp, DAG.getBasicBlock(B.TargetBB));
2732 
2733   // Avoid emitting unnecessary branches to the next block.
2734   if (NextMBB != NextBlock(SwitchBB))
2735     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2736                         DAG.getBasicBlock(NextMBB));
2737 
2738   DAG.setRoot(BrAnd);
2739 }
2740 
2741 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2742   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2743 
2744   // Retrieve successors. Look through artificial IR level blocks like
2745   // catchswitch for successors.
2746   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2747   const BasicBlock *EHPadBB = I.getSuccessor(1);
2748 
2749   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2750   // have to do anything here to lower funclet bundles.
2751   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2752                                         LLVMContext::OB_funclet,
2753                                         LLVMContext::OB_cfguardtarget}) &&
2754          "Cannot lower invokes with arbitrary operand bundles yet!");
2755 
2756   const Value *Callee(I.getCalledValue());
2757   const Function *Fn = dyn_cast<Function>(Callee);
2758   if (isa<InlineAsm>(Callee))
2759     visitInlineAsm(&I);
2760   else if (Fn && Fn->isIntrinsic()) {
2761     switch (Fn->getIntrinsicID()) {
2762     default:
2763       llvm_unreachable("Cannot invoke this intrinsic");
2764     case Intrinsic::donothing:
2765       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2766       break;
2767     case Intrinsic::experimental_patchpoint_void:
2768     case Intrinsic::experimental_patchpoint_i64:
2769       visitPatchpoint(&I, EHPadBB);
2770       break;
2771     case Intrinsic::experimental_gc_statepoint:
2772       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2773       break;
2774     case Intrinsic::wasm_rethrow_in_catch: {
2775       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2776       // special because it can be invoked, so we manually lower it to a DAG
2777       // node here.
2778       SmallVector<SDValue, 8> Ops;
2779       Ops.push_back(getRoot()); // inchain
2780       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2781       Ops.push_back(
2782           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2783                                 TLI.getPointerTy(DAG.getDataLayout())));
2784       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2785       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2786       break;
2787     }
2788     }
2789   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2790     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2791     // Eventually we will support lowering the @llvm.experimental.deoptimize
2792     // intrinsic, and right now there are no plans to support other intrinsics
2793     // with deopt state.
2794     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2795   } else {
2796     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2797   }
2798 
2799   // If the value of the invoke is used outside of its defining block, make it
2800   // available as a virtual register.
2801   // We already took care of the exported value for the statepoint instruction
2802   // during call to the LowerStatepoint.
2803   if (!isStatepoint(I)) {
2804     CopyToExportRegsIfNeeded(&I);
2805   }
2806 
2807   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2808   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2809   BranchProbability EHPadBBProb =
2810       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2811           : BranchProbability::getZero();
2812   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2813 
2814   // Update successor info.
2815   addSuccessorWithProb(InvokeMBB, Return);
2816   for (auto &UnwindDest : UnwindDests) {
2817     UnwindDest.first->setIsEHPad();
2818     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2819   }
2820   InvokeMBB->normalizeSuccProbs();
2821 
2822   // Drop into normal successor.
2823   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2824                           DAG.getBasicBlock(Return)));
2825 }
2826 
2827 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2828   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2829 
2830   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2831   // have to do anything here to lower funclet bundles.
2832   assert(!I.hasOperandBundlesOtherThan(
2833              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2834          "Cannot lower callbrs with arbitrary operand bundles yet!");
2835 
2836   assert(isa<InlineAsm>(I.getCalledValue()) &&
2837          "Only know how to handle inlineasm callbr");
2838   visitInlineAsm(&I);
2839 
2840   // Retrieve successors.
2841   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2842 
2843   // Update successor info.
2844   addSuccessorWithProb(CallBrMBB, Return);
2845   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2846     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2847     addSuccessorWithProb(CallBrMBB, Target);
2848   }
2849   CallBrMBB->normalizeSuccProbs();
2850 
2851   // Drop into default successor.
2852   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2853                           MVT::Other, getControlRoot(),
2854                           DAG.getBasicBlock(Return)));
2855 }
2856 
2857 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2858   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2859 }
2860 
2861 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2862   assert(FuncInfo.MBB->isEHPad() &&
2863          "Call to landingpad not in landing pad!");
2864 
2865   // If there aren't registers to copy the values into (e.g., during SjLj
2866   // exceptions), then don't bother to create these DAG nodes.
2867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2868   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2869   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2870       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2871     return;
2872 
2873   // If landingpad's return type is token type, we don't create DAG nodes
2874   // for its exception pointer and selector value. The extraction of exception
2875   // pointer or selector value from token type landingpads is not currently
2876   // supported.
2877   if (LP.getType()->isTokenTy())
2878     return;
2879 
2880   SmallVector<EVT, 2> ValueVTs;
2881   SDLoc dl = getCurSDLoc();
2882   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2883   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2884 
2885   // Get the two live-in registers as SDValues. The physregs have already been
2886   // copied into virtual registers.
2887   SDValue Ops[2];
2888   if (FuncInfo.ExceptionPointerVirtReg) {
2889     Ops[0] = DAG.getZExtOrTrunc(
2890         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2891                            FuncInfo.ExceptionPointerVirtReg,
2892                            TLI.getPointerTy(DAG.getDataLayout())),
2893         dl, ValueVTs[0]);
2894   } else {
2895     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2896   }
2897   Ops[1] = DAG.getZExtOrTrunc(
2898       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2899                          FuncInfo.ExceptionSelectorVirtReg,
2900                          TLI.getPointerTy(DAG.getDataLayout())),
2901       dl, ValueVTs[1]);
2902 
2903   // Merge into one.
2904   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2905                             DAG.getVTList(ValueVTs), Ops);
2906   setValue(&LP, Res);
2907 }
2908 
2909 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2910                                            MachineBasicBlock *Last) {
2911   // Update JTCases.
2912   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2913     if (SL->JTCases[i].first.HeaderBB == First)
2914       SL->JTCases[i].first.HeaderBB = Last;
2915 
2916   // Update BitTestCases.
2917   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2918     if (SL->BitTestCases[i].Parent == First)
2919       SL->BitTestCases[i].Parent = Last;
2920 }
2921 
2922 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2923   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2924 
2925   // Update machine-CFG edges with unique successors.
2926   SmallSet<BasicBlock*, 32> Done;
2927   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2928     BasicBlock *BB = I.getSuccessor(i);
2929     bool Inserted = Done.insert(BB).second;
2930     if (!Inserted)
2931         continue;
2932 
2933     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2934     addSuccessorWithProb(IndirectBrMBB, Succ);
2935   }
2936   IndirectBrMBB->normalizeSuccProbs();
2937 
2938   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2939                           MVT::Other, getControlRoot(),
2940                           getValue(I.getAddress())));
2941 }
2942 
2943 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2944   if (!DAG.getTarget().Options.TrapUnreachable)
2945     return;
2946 
2947   // We may be able to ignore unreachable behind a noreturn call.
2948   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2949     const BasicBlock &BB = *I.getParent();
2950     if (&I != &BB.front()) {
2951       BasicBlock::const_iterator PredI =
2952         std::prev(BasicBlock::const_iterator(&I));
2953       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2954         if (Call->doesNotReturn())
2955           return;
2956       }
2957     }
2958   }
2959 
2960   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2961 }
2962 
2963 void SelectionDAGBuilder::visitFSub(const User &I) {
2964   // -0.0 - X --> fneg
2965   Type *Ty = I.getType();
2966   if (isa<Constant>(I.getOperand(0)) &&
2967       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2968     SDValue Op2 = getValue(I.getOperand(1));
2969     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2970                              Op2.getValueType(), Op2));
2971     return;
2972   }
2973 
2974   visitBinary(I, ISD::FSUB);
2975 }
2976 
2977 /// Checks if the given instruction performs a vector reduction, in which case
2978 /// we have the freedom to alter the elements in the result as long as the
2979 /// reduction of them stays unchanged.
2980 static bool isVectorReductionOp(const User *I) {
2981   const Instruction *Inst = dyn_cast<Instruction>(I);
2982   if (!Inst || !Inst->getType()->isVectorTy())
2983     return false;
2984 
2985   auto OpCode = Inst->getOpcode();
2986   switch (OpCode) {
2987   case Instruction::Add:
2988   case Instruction::Mul:
2989   case Instruction::And:
2990   case Instruction::Or:
2991   case Instruction::Xor:
2992     break;
2993   case Instruction::FAdd:
2994   case Instruction::FMul:
2995     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2996       if (FPOp->getFastMathFlags().isFast())
2997         break;
2998     LLVM_FALLTHROUGH;
2999   default:
3000     return false;
3001   }
3002 
3003   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3004   // Ensure the reduction size is a power of 2.
3005   if (!isPowerOf2_32(ElemNum))
3006     return false;
3007 
3008   unsigned ElemNumToReduce = ElemNum;
3009 
3010   // Do DFS search on the def-use chain from the given instruction. We only
3011   // allow four kinds of operations during the search until we reach the
3012   // instruction that extracts the first element from the vector:
3013   //
3014   //   1. The reduction operation of the same opcode as the given instruction.
3015   //
3016   //   2. PHI node.
3017   //
3018   //   3. ShuffleVector instruction together with a reduction operation that
3019   //      does a partial reduction.
3020   //
3021   //   4. ExtractElement that extracts the first element from the vector, and we
3022   //      stop searching the def-use chain here.
3023   //
3024   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3025   // from 1-3 to the stack to continue the DFS. The given instruction is not
3026   // a reduction operation if we meet any other instructions other than those
3027   // listed above.
3028 
3029   SmallVector<const User *, 16> UsersToVisit{Inst};
3030   SmallPtrSet<const User *, 16> Visited;
3031   bool ReduxExtracted = false;
3032 
3033   while (!UsersToVisit.empty()) {
3034     auto User = UsersToVisit.back();
3035     UsersToVisit.pop_back();
3036     if (!Visited.insert(User).second)
3037       continue;
3038 
3039     for (const auto &U : User->users()) {
3040       auto Inst = dyn_cast<Instruction>(U);
3041       if (!Inst)
3042         return false;
3043 
3044       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3045         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3046           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3047             return false;
3048         UsersToVisit.push_back(U);
3049       } else if (const ShuffleVectorInst *ShufInst =
3050                      dyn_cast<ShuffleVectorInst>(U)) {
3051         // Detect the following pattern: A ShuffleVector instruction together
3052         // with a reduction that do partial reduction on the first and second
3053         // ElemNumToReduce / 2 elements, and store the result in
3054         // ElemNumToReduce / 2 elements in another vector.
3055 
3056         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3057         if (ResultElements < ElemNum)
3058           return false;
3059 
3060         if (ElemNumToReduce == 1)
3061           return false;
3062         if (!isa<UndefValue>(U->getOperand(1)))
3063           return false;
3064         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3065           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3066             return false;
3067         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3068           if (ShufInst->getMaskValue(i) != -1)
3069             return false;
3070 
3071         // There is only one user of this ShuffleVector instruction, which
3072         // must be a reduction operation.
3073         if (!U->hasOneUse())
3074           return false;
3075 
3076         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3077         if (!U2 || U2->getOpcode() != OpCode)
3078           return false;
3079 
3080         // Check operands of the reduction operation.
3081         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3082             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3083           UsersToVisit.push_back(U2);
3084           ElemNumToReduce /= 2;
3085         } else
3086           return false;
3087       } else if (isa<ExtractElementInst>(U)) {
3088         // At this moment we should have reduced all elements in the vector.
3089         if (ElemNumToReduce != 1)
3090           return false;
3091 
3092         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3093         if (!Val || !Val->isZero())
3094           return false;
3095 
3096         ReduxExtracted = true;
3097       } else
3098         return false;
3099     }
3100   }
3101   return ReduxExtracted;
3102 }
3103 
3104 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3105   SDNodeFlags Flags;
3106 
3107   SDValue Op = getValue(I.getOperand(0));
3108   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3109                                     Op, Flags);
3110   setValue(&I, UnNodeValue);
3111 }
3112 
3113 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3114   SDNodeFlags Flags;
3115   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3116     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3117     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3118   }
3119   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3120     Flags.setExact(ExactOp->isExact());
3121   }
3122   if (isVectorReductionOp(&I)) {
3123     Flags.setVectorReduction(true);
3124     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3125   }
3126 
3127   SDValue Op1 = getValue(I.getOperand(0));
3128   SDValue Op2 = getValue(I.getOperand(1));
3129   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3130                                      Op1, Op2, Flags);
3131   setValue(&I, BinNodeValue);
3132 }
3133 
3134 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3135   SDValue Op1 = getValue(I.getOperand(0));
3136   SDValue Op2 = getValue(I.getOperand(1));
3137 
3138   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3139       Op1.getValueType(), DAG.getDataLayout());
3140 
3141   // Coerce the shift amount to the right type if we can.
3142   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3143     unsigned ShiftSize = ShiftTy.getSizeInBits();
3144     unsigned Op2Size = Op2.getValueSizeInBits();
3145     SDLoc DL = getCurSDLoc();
3146 
3147     // If the operand is smaller than the shift count type, promote it.
3148     if (ShiftSize > Op2Size)
3149       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3150 
3151     // If the operand is larger than the shift count type but the shift
3152     // count type has enough bits to represent any shift value, truncate
3153     // it now. This is a common case and it exposes the truncate to
3154     // optimization early.
3155     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3156       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3157     // Otherwise we'll need to temporarily settle for some other convenient
3158     // type.  Type legalization will make adjustments once the shiftee is split.
3159     else
3160       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3161   }
3162 
3163   bool nuw = false;
3164   bool nsw = false;
3165   bool exact = false;
3166 
3167   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3168 
3169     if (const OverflowingBinaryOperator *OFBinOp =
3170             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3171       nuw = OFBinOp->hasNoUnsignedWrap();
3172       nsw = OFBinOp->hasNoSignedWrap();
3173     }
3174     if (const PossiblyExactOperator *ExactOp =
3175             dyn_cast<const PossiblyExactOperator>(&I))
3176       exact = ExactOp->isExact();
3177   }
3178   SDNodeFlags Flags;
3179   Flags.setExact(exact);
3180   Flags.setNoSignedWrap(nsw);
3181   Flags.setNoUnsignedWrap(nuw);
3182   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3183                             Flags);
3184   setValue(&I, Res);
3185 }
3186 
3187 void SelectionDAGBuilder::visitSDiv(const User &I) {
3188   SDValue Op1 = getValue(I.getOperand(0));
3189   SDValue Op2 = getValue(I.getOperand(1));
3190 
3191   SDNodeFlags Flags;
3192   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3193                  cast<PossiblyExactOperator>(&I)->isExact());
3194   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3195                            Op2, Flags));
3196 }
3197 
3198 void SelectionDAGBuilder::visitICmp(const User &I) {
3199   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3200   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3201     predicate = IC->getPredicate();
3202   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3203     predicate = ICmpInst::Predicate(IC->getPredicate());
3204   SDValue Op1 = getValue(I.getOperand(0));
3205   SDValue Op2 = getValue(I.getOperand(1));
3206   ISD::CondCode Opcode = getICmpCondCode(predicate);
3207 
3208   auto &TLI = DAG.getTargetLoweringInfo();
3209   EVT MemVT =
3210       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3211 
3212   // If a pointer's DAG type is larger than its memory type then the DAG values
3213   // are zero-extended. This breaks signed comparisons so truncate back to the
3214   // underlying type before doing the compare.
3215   if (Op1.getValueType() != MemVT) {
3216     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3217     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3218   }
3219 
3220   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3221                                                         I.getType());
3222   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3223 }
3224 
3225 void SelectionDAGBuilder::visitFCmp(const User &I) {
3226   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3227   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3228     predicate = FC->getPredicate();
3229   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3230     predicate = FCmpInst::Predicate(FC->getPredicate());
3231   SDValue Op1 = getValue(I.getOperand(0));
3232   SDValue Op2 = getValue(I.getOperand(1));
3233 
3234   ISD::CondCode Condition = getFCmpCondCode(predicate);
3235   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3236   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3237     Condition = getFCmpCodeWithoutNaN(Condition);
3238 
3239   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3240                                                         I.getType());
3241   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3242 }
3243 
3244 // Check if the condition of the select has one use or two users that are both
3245 // selects with the same condition.
3246 static bool hasOnlySelectUsers(const Value *Cond) {
3247   return llvm::all_of(Cond->users(), [](const Value *V) {
3248     return isa<SelectInst>(V);
3249   });
3250 }
3251 
3252 void SelectionDAGBuilder::visitSelect(const User &I) {
3253   SmallVector<EVT, 4> ValueVTs;
3254   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3255                   ValueVTs);
3256   unsigned NumValues = ValueVTs.size();
3257   if (NumValues == 0) return;
3258 
3259   SmallVector<SDValue, 4> Values(NumValues);
3260   SDValue Cond     = getValue(I.getOperand(0));
3261   SDValue LHSVal   = getValue(I.getOperand(1));
3262   SDValue RHSVal   = getValue(I.getOperand(2));
3263   auto BaseOps = {Cond};
3264   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3265     ISD::VSELECT : ISD::SELECT;
3266 
3267   bool IsUnaryAbs = false;
3268 
3269   // Min/max matching is only viable if all output VTs are the same.
3270   if (is_splat(ValueVTs)) {
3271     EVT VT = ValueVTs[0];
3272     LLVMContext &Ctx = *DAG.getContext();
3273     auto &TLI = DAG.getTargetLoweringInfo();
3274 
3275     // We care about the legality of the operation after it has been type
3276     // legalized.
3277     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3278       VT = TLI.getTypeToTransformTo(Ctx, VT);
3279 
3280     // If the vselect is legal, assume we want to leave this as a vector setcc +
3281     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3282     // min/max is legal on the scalar type.
3283     bool UseScalarMinMax = VT.isVector() &&
3284       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3285 
3286     Value *LHS, *RHS;
3287     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3288     ISD::NodeType Opc = ISD::DELETED_NODE;
3289     switch (SPR.Flavor) {
3290     case SPF_UMAX:    Opc = ISD::UMAX; break;
3291     case SPF_UMIN:    Opc = ISD::UMIN; break;
3292     case SPF_SMAX:    Opc = ISD::SMAX; break;
3293     case SPF_SMIN:    Opc = ISD::SMIN; break;
3294     case SPF_FMINNUM:
3295       switch (SPR.NaNBehavior) {
3296       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3297       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3298       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3299       case SPNB_RETURNS_ANY: {
3300         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3301           Opc = ISD::FMINNUM;
3302         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3303           Opc = ISD::FMINIMUM;
3304         else if (UseScalarMinMax)
3305           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3306             ISD::FMINNUM : ISD::FMINIMUM;
3307         break;
3308       }
3309       }
3310       break;
3311     case SPF_FMAXNUM:
3312       switch (SPR.NaNBehavior) {
3313       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3314       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3315       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3316       case SPNB_RETURNS_ANY:
3317 
3318         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3319           Opc = ISD::FMAXNUM;
3320         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3321           Opc = ISD::FMAXIMUM;
3322         else if (UseScalarMinMax)
3323           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3324             ISD::FMAXNUM : ISD::FMAXIMUM;
3325         break;
3326       }
3327       break;
3328     case SPF_ABS:
3329       IsUnaryAbs = true;
3330       Opc = ISD::ABS;
3331       break;
3332     case SPF_NABS:
3333       // TODO: we need to produce sub(0, abs(X)).
3334     default: break;
3335     }
3336 
3337     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3338         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3339          (UseScalarMinMax &&
3340           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3341         // If the underlying comparison instruction is used by any other
3342         // instruction, the consumed instructions won't be destroyed, so it is
3343         // not profitable to convert to a min/max.
3344         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3345       OpCode = Opc;
3346       LHSVal = getValue(LHS);
3347       RHSVal = getValue(RHS);
3348       BaseOps = {};
3349     }
3350 
3351     if (IsUnaryAbs) {
3352       OpCode = Opc;
3353       LHSVal = getValue(LHS);
3354       BaseOps = {};
3355     }
3356   }
3357 
3358   if (IsUnaryAbs) {
3359     for (unsigned i = 0; i != NumValues; ++i) {
3360       Values[i] =
3361           DAG.getNode(OpCode, getCurSDLoc(),
3362                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3363                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3364     }
3365   } else {
3366     for (unsigned i = 0; i != NumValues; ++i) {
3367       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3368       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3369       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3370       Values[i] = DAG.getNode(
3371           OpCode, getCurSDLoc(),
3372           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3373     }
3374   }
3375 
3376   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3377                            DAG.getVTList(ValueVTs), Values));
3378 }
3379 
3380 void SelectionDAGBuilder::visitTrunc(const User &I) {
3381   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3382   SDValue N = getValue(I.getOperand(0));
3383   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3384                                                         I.getType());
3385   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3386 }
3387 
3388 void SelectionDAGBuilder::visitZExt(const User &I) {
3389   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3390   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3391   SDValue N = getValue(I.getOperand(0));
3392   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3393                                                         I.getType());
3394   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3395 }
3396 
3397 void SelectionDAGBuilder::visitSExt(const User &I) {
3398   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3399   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3400   SDValue N = getValue(I.getOperand(0));
3401   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3402                                                         I.getType());
3403   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3404 }
3405 
3406 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3407   // FPTrunc is never a no-op cast, no need to check
3408   SDValue N = getValue(I.getOperand(0));
3409   SDLoc dl = getCurSDLoc();
3410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3411   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3412   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3413                            DAG.getTargetConstant(
3414                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3415 }
3416 
3417 void SelectionDAGBuilder::visitFPExt(const User &I) {
3418   // FPExt is never a no-op cast, no need to check
3419   SDValue N = getValue(I.getOperand(0));
3420   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3421                                                         I.getType());
3422   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3423 }
3424 
3425 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3426   // FPToUI is never a no-op cast, no need to check
3427   SDValue N = getValue(I.getOperand(0));
3428   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3429                                                         I.getType());
3430   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3431 }
3432 
3433 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3434   // FPToSI is never a no-op cast, no need to check
3435   SDValue N = getValue(I.getOperand(0));
3436   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3437                                                         I.getType());
3438   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3439 }
3440 
3441 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3442   // UIToFP is never a no-op cast, no need to check
3443   SDValue N = getValue(I.getOperand(0));
3444   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3445                                                         I.getType());
3446   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3447 }
3448 
3449 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3450   // SIToFP is never a no-op cast, no need to check
3451   SDValue N = getValue(I.getOperand(0));
3452   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3453                                                         I.getType());
3454   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3455 }
3456 
3457 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3458   // What to do depends on the size of the integer and the size of the pointer.
3459   // We can either truncate, zero extend, or no-op, accordingly.
3460   SDValue N = getValue(I.getOperand(0));
3461   auto &TLI = DAG.getTargetLoweringInfo();
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   EVT PtrMemVT =
3465       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3466   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3467   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3468   setValue(&I, N);
3469 }
3470 
3471 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3472   // What to do depends on the size of the integer and the size of the pointer.
3473   // We can either truncate, zero extend, or no-op, accordingly.
3474   SDValue N = getValue(I.getOperand(0));
3475   auto &TLI = DAG.getTargetLoweringInfo();
3476   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3477   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3478   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3479   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3480   setValue(&I, N);
3481 }
3482 
3483 void SelectionDAGBuilder::visitBitCast(const User &I) {
3484   SDValue N = getValue(I.getOperand(0));
3485   SDLoc dl = getCurSDLoc();
3486   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3487                                                         I.getType());
3488 
3489   // BitCast assures us that source and destination are the same size so this is
3490   // either a BITCAST or a no-op.
3491   if (DestVT != N.getValueType())
3492     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3493                              DestVT, N)); // convert types.
3494   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3495   // might fold any kind of constant expression to an integer constant and that
3496   // is not what we are looking for. Only recognize a bitcast of a genuine
3497   // constant integer as an opaque constant.
3498   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3499     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3500                                  /*isOpaque*/true));
3501   else
3502     setValue(&I, N);            // noop cast.
3503 }
3504 
3505 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3507   const Value *SV = I.getOperand(0);
3508   SDValue N = getValue(SV);
3509   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3510 
3511   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3512   unsigned DestAS = I.getType()->getPointerAddressSpace();
3513 
3514   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3515     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3516 
3517   setValue(&I, N);
3518 }
3519 
3520 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3522   SDValue InVec = getValue(I.getOperand(0));
3523   SDValue InVal = getValue(I.getOperand(1));
3524   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3525                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3526   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3527                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3528                            InVec, InVal, InIdx));
3529 }
3530 
3531 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3533   SDValue InVec = getValue(I.getOperand(0));
3534   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3535                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3536   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3537                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3538                            InVec, InIdx));
3539 }
3540 
3541 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3542   SDValue Src1 = getValue(I.getOperand(0));
3543   SDValue Src2 = getValue(I.getOperand(1));
3544   Constant *MaskV = cast<Constant>(I.getOperand(2));
3545   SDLoc DL = getCurSDLoc();
3546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3547   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3548   EVT SrcVT = Src1.getValueType();
3549   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3550 
3551   if (MaskV->isNullValue() && VT.isScalableVector()) {
3552     // Canonical splat form of first element of first input vector.
3553     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3554                                    SrcVT.getScalarType(), Src1,
3555                                    DAG.getConstant(0, DL,
3556                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3557     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3558     return;
3559   }
3560 
3561   // For now, we only handle splats for scalable vectors.
3562   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3563   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3564   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3565 
3566   SmallVector<int, 8> Mask;
3567   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3568   unsigned MaskNumElts = Mask.size();
3569 
3570   if (SrcNumElts == MaskNumElts) {
3571     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3572     return;
3573   }
3574 
3575   // Normalize the shuffle vector since mask and vector length don't match.
3576   if (SrcNumElts < MaskNumElts) {
3577     // Mask is longer than the source vectors. We can use concatenate vector to
3578     // make the mask and vectors lengths match.
3579 
3580     if (MaskNumElts % SrcNumElts == 0) {
3581       // Mask length is a multiple of the source vector length.
3582       // Check if the shuffle is some kind of concatenation of the input
3583       // vectors.
3584       unsigned NumConcat = MaskNumElts / SrcNumElts;
3585       bool IsConcat = true;
3586       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3587       for (unsigned i = 0; i != MaskNumElts; ++i) {
3588         int Idx = Mask[i];
3589         if (Idx < 0)
3590           continue;
3591         // Ensure the indices in each SrcVT sized piece are sequential and that
3592         // the same source is used for the whole piece.
3593         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3594             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3595              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3596           IsConcat = false;
3597           break;
3598         }
3599         // Remember which source this index came from.
3600         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3601       }
3602 
3603       // The shuffle is concatenating multiple vectors together. Just emit
3604       // a CONCAT_VECTORS operation.
3605       if (IsConcat) {
3606         SmallVector<SDValue, 8> ConcatOps;
3607         for (auto Src : ConcatSrcs) {
3608           if (Src < 0)
3609             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3610           else if (Src == 0)
3611             ConcatOps.push_back(Src1);
3612           else
3613             ConcatOps.push_back(Src2);
3614         }
3615         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3616         return;
3617       }
3618     }
3619 
3620     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3621     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3622     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3623                                     PaddedMaskNumElts);
3624 
3625     // Pad both vectors with undefs to make them the same length as the mask.
3626     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3627 
3628     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3629     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3630     MOps1[0] = Src1;
3631     MOps2[0] = Src2;
3632 
3633     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3634     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3635 
3636     // Readjust mask for new input vector length.
3637     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3638     for (unsigned i = 0; i != MaskNumElts; ++i) {
3639       int Idx = Mask[i];
3640       if (Idx >= (int)SrcNumElts)
3641         Idx -= SrcNumElts - PaddedMaskNumElts;
3642       MappedOps[i] = Idx;
3643     }
3644 
3645     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3646 
3647     // If the concatenated vector was padded, extract a subvector with the
3648     // correct number of elements.
3649     if (MaskNumElts != PaddedMaskNumElts)
3650       Result = DAG.getNode(
3651           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3652           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3653 
3654     setValue(&I, Result);
3655     return;
3656   }
3657 
3658   if (SrcNumElts > MaskNumElts) {
3659     // Analyze the access pattern of the vector to see if we can extract
3660     // two subvectors and do the shuffle.
3661     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3662     bool CanExtract = true;
3663     for (int Idx : Mask) {
3664       unsigned Input = 0;
3665       if (Idx < 0)
3666         continue;
3667 
3668       if (Idx >= (int)SrcNumElts) {
3669         Input = 1;
3670         Idx -= SrcNumElts;
3671       }
3672 
3673       // If all the indices come from the same MaskNumElts sized portion of
3674       // the sources we can use extract. Also make sure the extract wouldn't
3675       // extract past the end of the source.
3676       int NewStartIdx = alignDown(Idx, MaskNumElts);
3677       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3678           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3679         CanExtract = false;
3680       // Make sure we always update StartIdx as we use it to track if all
3681       // elements are undef.
3682       StartIdx[Input] = NewStartIdx;
3683     }
3684 
3685     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3686       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3687       return;
3688     }
3689     if (CanExtract) {
3690       // Extract appropriate subvector and generate a vector shuffle
3691       for (unsigned Input = 0; Input < 2; ++Input) {
3692         SDValue &Src = Input == 0 ? Src1 : Src2;
3693         if (StartIdx[Input] < 0)
3694           Src = DAG.getUNDEF(VT);
3695         else {
3696           Src = DAG.getNode(
3697               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3698               DAG.getConstant(StartIdx[Input], DL,
3699                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3700         }
3701       }
3702 
3703       // Calculate new mask.
3704       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3705       for (int &Idx : MappedOps) {
3706         if (Idx >= (int)SrcNumElts)
3707           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3708         else if (Idx >= 0)
3709           Idx -= StartIdx[0];
3710       }
3711 
3712       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3713       return;
3714     }
3715   }
3716 
3717   // We can't use either concat vectors or extract subvectors so fall back to
3718   // replacing the shuffle with extract and build vector.
3719   // to insert and build vector.
3720   EVT EltVT = VT.getVectorElementType();
3721   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3722   SmallVector<SDValue,8> Ops;
3723   for (int Idx : Mask) {
3724     SDValue Res;
3725 
3726     if (Idx < 0) {
3727       Res = DAG.getUNDEF(EltVT);
3728     } else {
3729       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3730       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3731 
3732       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3733                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3734     }
3735 
3736     Ops.push_back(Res);
3737   }
3738 
3739   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3740 }
3741 
3742 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3743   ArrayRef<unsigned> Indices;
3744   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3745     Indices = IV->getIndices();
3746   else
3747     Indices = cast<ConstantExpr>(&I)->getIndices();
3748 
3749   const Value *Op0 = I.getOperand(0);
3750   const Value *Op1 = I.getOperand(1);
3751   Type *AggTy = I.getType();
3752   Type *ValTy = Op1->getType();
3753   bool IntoUndef = isa<UndefValue>(Op0);
3754   bool FromUndef = isa<UndefValue>(Op1);
3755 
3756   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3757 
3758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3759   SmallVector<EVT, 4> AggValueVTs;
3760   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3761   SmallVector<EVT, 4> ValValueVTs;
3762   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3763 
3764   unsigned NumAggValues = AggValueVTs.size();
3765   unsigned NumValValues = ValValueVTs.size();
3766   SmallVector<SDValue, 4> Values(NumAggValues);
3767 
3768   // Ignore an insertvalue that produces an empty object
3769   if (!NumAggValues) {
3770     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3771     return;
3772   }
3773 
3774   SDValue Agg = getValue(Op0);
3775   unsigned i = 0;
3776   // Copy the beginning value(s) from the original aggregate.
3777   for (; i != LinearIndex; ++i)
3778     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3779                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3780   // Copy values from the inserted value(s).
3781   if (NumValValues) {
3782     SDValue Val = getValue(Op1);
3783     for (; i != LinearIndex + NumValValues; ++i)
3784       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3785                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3786   }
3787   // Copy remaining value(s) from the original aggregate.
3788   for (; i != NumAggValues; ++i)
3789     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3790                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3791 
3792   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3793                            DAG.getVTList(AggValueVTs), Values));
3794 }
3795 
3796 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3797   ArrayRef<unsigned> Indices;
3798   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3799     Indices = EV->getIndices();
3800   else
3801     Indices = cast<ConstantExpr>(&I)->getIndices();
3802 
3803   const Value *Op0 = I.getOperand(0);
3804   Type *AggTy = Op0->getType();
3805   Type *ValTy = I.getType();
3806   bool OutOfUndef = isa<UndefValue>(Op0);
3807 
3808   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3809 
3810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3811   SmallVector<EVT, 4> ValValueVTs;
3812   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3813 
3814   unsigned NumValValues = ValValueVTs.size();
3815 
3816   // Ignore a extractvalue that produces an empty object
3817   if (!NumValValues) {
3818     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3819     return;
3820   }
3821 
3822   SmallVector<SDValue, 4> Values(NumValValues);
3823 
3824   SDValue Agg = getValue(Op0);
3825   // Copy out the selected value(s).
3826   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3827     Values[i - LinearIndex] =
3828       OutOfUndef ?
3829         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3830         SDValue(Agg.getNode(), Agg.getResNo() + i);
3831 
3832   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3833                            DAG.getVTList(ValValueVTs), Values));
3834 }
3835 
3836 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3837   Value *Op0 = I.getOperand(0);
3838   // Note that the pointer operand may be a vector of pointers. Take the scalar
3839   // element which holds a pointer.
3840   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3841   SDValue N = getValue(Op0);
3842   SDLoc dl = getCurSDLoc();
3843   auto &TLI = DAG.getTargetLoweringInfo();
3844   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3845   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3846 
3847   // Normalize Vector GEP - all scalar operands should be converted to the
3848   // splat vector.
3849   unsigned VectorWidth = I.getType()->isVectorTy() ?
3850     I.getType()->getVectorNumElements() : 0;
3851 
3852   if (VectorWidth && !N.getValueType().isVector()) {
3853     LLVMContext &Context = *DAG.getContext();
3854     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3855     N = DAG.getSplatBuildVector(VT, dl, N);
3856   }
3857 
3858   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3859        GTI != E; ++GTI) {
3860     const Value *Idx = GTI.getOperand();
3861     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3862       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3863       if (Field) {
3864         // N = N + Offset
3865         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3866 
3867         // In an inbounds GEP with an offset that is nonnegative even when
3868         // interpreted as signed, assume there is no unsigned overflow.
3869         SDNodeFlags Flags;
3870         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3871           Flags.setNoUnsignedWrap(true);
3872 
3873         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3874                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3875       }
3876     } else {
3877       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3878       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3879       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3880 
3881       // If this is a scalar constant or a splat vector of constants,
3882       // handle it quickly.
3883       const auto *C = dyn_cast<Constant>(Idx);
3884       if (C && isa<VectorType>(C->getType()))
3885         C = C->getSplatValue();
3886 
3887       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3888         if (CI->isZero())
3889           continue;
3890         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3891         LLVMContext &Context = *DAG.getContext();
3892         SDValue OffsVal = VectorWidth ?
3893           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3894           DAG.getConstant(Offs, dl, IdxTy);
3895 
3896         // In an inbounds GEP with an offset that is nonnegative even when
3897         // interpreted as signed, assume there is no unsigned overflow.
3898         SDNodeFlags Flags;
3899         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3900           Flags.setNoUnsignedWrap(true);
3901 
3902         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3903 
3904         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3905         continue;
3906       }
3907 
3908       // N = N + Idx * ElementSize;
3909       SDValue IdxN = getValue(Idx);
3910 
3911       if (!IdxN.getValueType().isVector() && VectorWidth) {
3912         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3913         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3914       }
3915 
3916       // If the index is smaller or larger than intptr_t, truncate or extend
3917       // it.
3918       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3919 
3920       // If this is a multiply by a power of two, turn it into a shl
3921       // immediately.  This is a very common case.
3922       if (ElementSize != 1) {
3923         if (ElementSize.isPowerOf2()) {
3924           unsigned Amt = ElementSize.logBase2();
3925           IdxN = DAG.getNode(ISD::SHL, dl,
3926                              N.getValueType(), IdxN,
3927                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3928         } else {
3929           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3930                                           IdxN.getValueType());
3931           IdxN = DAG.getNode(ISD::MUL, dl,
3932                              N.getValueType(), IdxN, Scale);
3933         }
3934       }
3935 
3936       N = DAG.getNode(ISD::ADD, dl,
3937                       N.getValueType(), N, IdxN);
3938     }
3939   }
3940 
3941   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3942     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3943 
3944   setValue(&I, N);
3945 }
3946 
3947 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3948   // If this is a fixed sized alloca in the entry block of the function,
3949   // allocate it statically on the stack.
3950   if (FuncInfo.StaticAllocaMap.count(&I))
3951     return;   // getValue will auto-populate this.
3952 
3953   SDLoc dl = getCurSDLoc();
3954   Type *Ty = I.getAllocatedType();
3955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3956   auto &DL = DAG.getDataLayout();
3957   uint64_t TySize = DL.getTypeAllocSize(Ty);
3958   unsigned Align =
3959       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3960 
3961   SDValue AllocSize = getValue(I.getArraySize());
3962 
3963   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3964   if (AllocSize.getValueType() != IntPtr)
3965     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3966 
3967   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3968                           AllocSize,
3969                           DAG.getConstant(TySize, dl, IntPtr));
3970 
3971   // Handle alignment.  If the requested alignment is less than or equal to
3972   // the stack alignment, ignore it.  If the size is greater than or equal to
3973   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3974   unsigned StackAlign =
3975       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3976   if (Align <= StackAlign)
3977     Align = 0;
3978 
3979   // Round the size of the allocation up to the stack alignment size
3980   // by add SA-1 to the size. This doesn't overflow because we're computing
3981   // an address inside an alloca.
3982   SDNodeFlags Flags;
3983   Flags.setNoUnsignedWrap(true);
3984   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3985                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3986 
3987   // Mask out the low bits for alignment purposes.
3988   AllocSize =
3989       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3990                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3991 
3992   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3993   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3994   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3995   setValue(&I, DSA);
3996   DAG.setRoot(DSA.getValue(1));
3997 
3998   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3999 }
4000 
4001 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4002   if (I.isAtomic())
4003     return visitAtomicLoad(I);
4004 
4005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4006   const Value *SV = I.getOperand(0);
4007   if (TLI.supportSwiftError()) {
4008     // Swifterror values can come from either a function parameter with
4009     // swifterror attribute or an alloca with swifterror attribute.
4010     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4011       if (Arg->hasSwiftErrorAttr())
4012         return visitLoadFromSwiftError(I);
4013     }
4014 
4015     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4016       if (Alloca->isSwiftError())
4017         return visitLoadFromSwiftError(I);
4018     }
4019   }
4020 
4021   SDValue Ptr = getValue(SV);
4022 
4023   Type *Ty = I.getType();
4024 
4025   bool isVolatile = I.isVolatile();
4026   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4027   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4028   bool isDereferenceable =
4029       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4030   unsigned Alignment = I.getAlignment();
4031 
4032   AAMDNodes AAInfo;
4033   I.getAAMetadata(AAInfo);
4034   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4035 
4036   SmallVector<EVT, 4> ValueVTs, MemVTs;
4037   SmallVector<uint64_t, 4> Offsets;
4038   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4039   unsigned NumValues = ValueVTs.size();
4040   if (NumValues == 0)
4041     return;
4042 
4043   SDValue Root;
4044   bool ConstantMemory = false;
4045   if (isVolatile || NumValues > MaxParallelChains)
4046     // Serialize volatile loads with other side effects.
4047     Root = getRoot();
4048   else if (AA &&
4049            AA->pointsToConstantMemory(MemoryLocation(
4050                SV,
4051                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4052                AAInfo))) {
4053     // Do not serialize (non-volatile) loads of constant memory with anything.
4054     Root = DAG.getEntryNode();
4055     ConstantMemory = true;
4056   } else {
4057     // Do not serialize non-volatile loads against each other.
4058     Root = DAG.getRoot();
4059   }
4060 
4061   SDLoc dl = getCurSDLoc();
4062 
4063   if (isVolatile)
4064     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4065 
4066   // An aggregate load cannot wrap around the address space, so offsets to its
4067   // parts don't wrap either.
4068   SDNodeFlags Flags;
4069   Flags.setNoUnsignedWrap(true);
4070 
4071   SmallVector<SDValue, 4> Values(NumValues);
4072   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4073   EVT PtrVT = Ptr.getValueType();
4074   unsigned ChainI = 0;
4075   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4076     // Serializing loads here may result in excessive register pressure, and
4077     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4078     // could recover a bit by hoisting nodes upward in the chain by recognizing
4079     // they are side-effect free or do not alias. The optimizer should really
4080     // avoid this case by converting large object/array copies to llvm.memcpy
4081     // (MaxParallelChains should always remain as failsafe).
4082     if (ChainI == MaxParallelChains) {
4083       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4084       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4085                                   makeArrayRef(Chains.data(), ChainI));
4086       Root = Chain;
4087       ChainI = 0;
4088     }
4089     SDValue A = DAG.getNode(ISD::ADD, dl,
4090                             PtrVT, Ptr,
4091                             DAG.getConstant(Offsets[i], dl, PtrVT),
4092                             Flags);
4093     auto MMOFlags = MachineMemOperand::MONone;
4094     if (isVolatile)
4095       MMOFlags |= MachineMemOperand::MOVolatile;
4096     if (isNonTemporal)
4097       MMOFlags |= MachineMemOperand::MONonTemporal;
4098     if (isInvariant)
4099       MMOFlags |= MachineMemOperand::MOInvariant;
4100     if (isDereferenceable)
4101       MMOFlags |= MachineMemOperand::MODereferenceable;
4102     MMOFlags |= TLI.getMMOFlags(I);
4103 
4104     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4105                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4106                             MMOFlags, AAInfo, Ranges);
4107     Chains[ChainI] = L.getValue(1);
4108 
4109     if (MemVTs[i] != ValueVTs[i])
4110       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4111 
4112     Values[i] = L;
4113   }
4114 
4115   if (!ConstantMemory) {
4116     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4117                                 makeArrayRef(Chains.data(), ChainI));
4118     if (isVolatile)
4119       DAG.setRoot(Chain);
4120     else
4121       PendingLoads.push_back(Chain);
4122   }
4123 
4124   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4125                            DAG.getVTList(ValueVTs), Values));
4126 }
4127 
4128 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4129   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4130          "call visitStoreToSwiftError when backend supports swifterror");
4131 
4132   SmallVector<EVT, 4> ValueVTs;
4133   SmallVector<uint64_t, 4> Offsets;
4134   const Value *SrcV = I.getOperand(0);
4135   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4136                   SrcV->getType(), ValueVTs, &Offsets);
4137   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4138          "expect a single EVT for swifterror");
4139 
4140   SDValue Src = getValue(SrcV);
4141   // Create a virtual register, then update the virtual register.
4142   Register VReg =
4143       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4144   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4145   // Chain can be getRoot or getControlRoot.
4146   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4147                                       SDValue(Src.getNode(), Src.getResNo()));
4148   DAG.setRoot(CopyNode);
4149 }
4150 
4151 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4152   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4153          "call visitLoadFromSwiftError when backend supports swifterror");
4154 
4155   assert(!I.isVolatile() &&
4156          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4157          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4158          "Support volatile, non temporal, invariant for load_from_swift_error");
4159 
4160   const Value *SV = I.getOperand(0);
4161   Type *Ty = I.getType();
4162   AAMDNodes AAInfo;
4163   I.getAAMetadata(AAInfo);
4164   assert(
4165       (!AA ||
4166        !AA->pointsToConstantMemory(MemoryLocation(
4167            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4168            AAInfo))) &&
4169       "load_from_swift_error should not be constant memory");
4170 
4171   SmallVector<EVT, 4> ValueVTs;
4172   SmallVector<uint64_t, 4> Offsets;
4173   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4174                   ValueVTs, &Offsets);
4175   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4176          "expect a single EVT for swifterror");
4177 
4178   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4179   SDValue L = DAG.getCopyFromReg(
4180       getRoot(), getCurSDLoc(),
4181       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4182 
4183   setValue(&I, L);
4184 }
4185 
4186 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4187   if (I.isAtomic())
4188     return visitAtomicStore(I);
4189 
4190   const Value *SrcV = I.getOperand(0);
4191   const Value *PtrV = I.getOperand(1);
4192 
4193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4194   if (TLI.supportSwiftError()) {
4195     // Swifterror values can come from either a function parameter with
4196     // swifterror attribute or an alloca with swifterror attribute.
4197     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4198       if (Arg->hasSwiftErrorAttr())
4199         return visitStoreToSwiftError(I);
4200     }
4201 
4202     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4203       if (Alloca->isSwiftError())
4204         return visitStoreToSwiftError(I);
4205     }
4206   }
4207 
4208   SmallVector<EVT, 4> ValueVTs, MemVTs;
4209   SmallVector<uint64_t, 4> Offsets;
4210   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4211                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4212   unsigned NumValues = ValueVTs.size();
4213   if (NumValues == 0)
4214     return;
4215 
4216   // Get the lowered operands. Note that we do this after
4217   // checking if NumResults is zero, because with zero results
4218   // the operands won't have values in the map.
4219   SDValue Src = getValue(SrcV);
4220   SDValue Ptr = getValue(PtrV);
4221 
4222   SDValue Root = getRoot();
4223   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4224   SDLoc dl = getCurSDLoc();
4225   EVT PtrVT = Ptr.getValueType();
4226   unsigned Alignment = I.getAlignment();
4227   AAMDNodes AAInfo;
4228   I.getAAMetadata(AAInfo);
4229 
4230   auto MMOFlags = MachineMemOperand::MONone;
4231   if (I.isVolatile())
4232     MMOFlags |= MachineMemOperand::MOVolatile;
4233   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4234     MMOFlags |= MachineMemOperand::MONonTemporal;
4235   MMOFlags |= TLI.getMMOFlags(I);
4236 
4237   // An aggregate load cannot wrap around the address space, so offsets to its
4238   // parts don't wrap either.
4239   SDNodeFlags Flags;
4240   Flags.setNoUnsignedWrap(true);
4241 
4242   unsigned ChainI = 0;
4243   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4244     // See visitLoad comments.
4245     if (ChainI == MaxParallelChains) {
4246       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4247                                   makeArrayRef(Chains.data(), ChainI));
4248       Root = Chain;
4249       ChainI = 0;
4250     }
4251     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4252                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4253     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4254     if (MemVTs[i] != ValueVTs[i])
4255       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4256     SDValue St =
4257         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4258                      Alignment, MMOFlags, AAInfo);
4259     Chains[ChainI] = St;
4260   }
4261 
4262   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4263                                   makeArrayRef(Chains.data(), ChainI));
4264   DAG.setRoot(StoreNode);
4265 }
4266 
4267 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4268                                            bool IsCompressing) {
4269   SDLoc sdl = getCurSDLoc();
4270 
4271   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4272                            unsigned& Alignment) {
4273     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4274     Src0 = I.getArgOperand(0);
4275     Ptr = I.getArgOperand(1);
4276     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4277     Mask = I.getArgOperand(3);
4278   };
4279   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4280                            unsigned& Alignment) {
4281     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4282     Src0 = I.getArgOperand(0);
4283     Ptr = I.getArgOperand(1);
4284     Mask = I.getArgOperand(2);
4285     Alignment = 0;
4286   };
4287 
4288   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4289   unsigned Alignment;
4290   if (IsCompressing)
4291     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4292   else
4293     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4294 
4295   SDValue Ptr = getValue(PtrOperand);
4296   SDValue Src0 = getValue(Src0Operand);
4297   SDValue Mask = getValue(MaskOperand);
4298   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4299 
4300   EVT VT = Src0.getValueType();
4301   if (!Alignment)
4302     Alignment = DAG.getEVTAlignment(VT);
4303 
4304   AAMDNodes AAInfo;
4305   I.getAAMetadata(AAInfo);
4306 
4307   MachineMemOperand *MMO =
4308     DAG.getMachineFunction().
4309     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4310                           MachineMemOperand::MOStore,
4311                           // TODO: Make MachineMemOperands aware of scalable
4312                           // vectors.
4313                           VT.getStoreSize().getKnownMinSize(),
4314                           Alignment, AAInfo);
4315   SDValue StoreNode =
4316       DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4317                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4318   DAG.setRoot(StoreNode);
4319   setValue(&I, StoreNode);
4320 }
4321 
4322 // Get a uniform base for the Gather/Scatter intrinsic.
4323 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4324 // We try to represent it as a base pointer + vector of indices.
4325 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4326 // The first operand of the GEP may be a single pointer or a vector of pointers
4327 // Example:
4328 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4329 //  or
4330 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4331 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4332 //
4333 // When the first GEP operand is a single pointer - it is the uniform base we
4334 // are looking for. If first operand of the GEP is a splat vector - we
4335 // extract the splat value and use it as a uniform base.
4336 // In all other cases the function returns 'false'.
4337 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4338                            ISD::MemIndexType &IndexType, SDValue &Scale,
4339                            SelectionDAGBuilder *SDB) {
4340   SelectionDAG& DAG = SDB->DAG;
4341   LLVMContext &Context = *DAG.getContext();
4342 
4343   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4344   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4345   if (!GEP)
4346     return false;
4347 
4348   const Value *GEPPtr = GEP->getPointerOperand();
4349   if (!GEPPtr->getType()->isVectorTy())
4350     Ptr = GEPPtr;
4351   else if (!(Ptr = getSplatValue(GEPPtr)))
4352     return false;
4353 
4354   unsigned FinalIndex = GEP->getNumOperands() - 1;
4355   Value *IndexVal = GEP->getOperand(FinalIndex);
4356 
4357   // Ensure all the other indices are 0.
4358   for (unsigned i = 1; i < FinalIndex; ++i) {
4359     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4360     if (!C)
4361       return false;
4362     if (isa<VectorType>(C->getType()))
4363       C = C->getSplatValue();
4364     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4365     if (!CI || !CI->isZero())
4366       return false;
4367   }
4368 
4369   // The operands of the GEP may be defined in another basic block.
4370   // In this case we'll not find nodes for the operands.
4371   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4372     return false;
4373 
4374   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4375   const DataLayout &DL = DAG.getDataLayout();
4376   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4377                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4378   Base = SDB->getValue(Ptr);
4379   Index = SDB->getValue(IndexVal);
4380   IndexType = ISD::SIGNED_SCALED;
4381 
4382   if (!Index.getValueType().isVector()) {
4383     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4384     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4385     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4386   }
4387   return true;
4388 }
4389 
4390 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4391   SDLoc sdl = getCurSDLoc();
4392 
4393   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4394   const Value *Ptr = I.getArgOperand(1);
4395   SDValue Src0 = getValue(I.getArgOperand(0));
4396   SDValue Mask = getValue(I.getArgOperand(3));
4397   EVT VT = Src0.getValueType();
4398   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4399   if (!Alignment)
4400     Alignment = DAG.getEVTAlignment(VT);
4401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4402 
4403   AAMDNodes AAInfo;
4404   I.getAAMetadata(AAInfo);
4405 
4406   SDValue Base;
4407   SDValue Index;
4408   ISD::MemIndexType IndexType;
4409   SDValue Scale;
4410   const Value *BasePtr = Ptr;
4411   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4412                                     this);
4413 
4414   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4415   MachineMemOperand *MMO = DAG.getMachineFunction().
4416     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4417                          MachineMemOperand::MOStore,
4418                          // TODO: Make MachineMemOperands aware of scalable
4419                          // vectors.
4420                          VT.getStoreSize().getKnownMinSize(),
4421                          Alignment, AAInfo);
4422   if (!UniformBase) {
4423     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4424     Index = getValue(Ptr);
4425     IndexType = ISD::SIGNED_SCALED;
4426     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4427   }
4428   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4429   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4430                                          Ops, MMO, IndexType);
4431   DAG.setRoot(Scatter);
4432   setValue(&I, Scatter);
4433 }
4434 
4435 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4436   SDLoc sdl = getCurSDLoc();
4437 
4438   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4439                            unsigned& Alignment) {
4440     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4441     Ptr = I.getArgOperand(0);
4442     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4443     Mask = I.getArgOperand(2);
4444     Src0 = I.getArgOperand(3);
4445   };
4446   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4447                            unsigned& Alignment) {
4448     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4449     Ptr = I.getArgOperand(0);
4450     Alignment = 0;
4451     Mask = I.getArgOperand(1);
4452     Src0 = I.getArgOperand(2);
4453   };
4454 
4455   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4456   unsigned Alignment;
4457   if (IsExpanding)
4458     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4459   else
4460     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4461 
4462   SDValue Ptr = getValue(PtrOperand);
4463   SDValue Src0 = getValue(Src0Operand);
4464   SDValue Mask = getValue(MaskOperand);
4465   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4466 
4467   EVT VT = Src0.getValueType();
4468   if (!Alignment)
4469     Alignment = DAG.getEVTAlignment(VT);
4470 
4471   AAMDNodes AAInfo;
4472   I.getAAMetadata(AAInfo);
4473   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4474 
4475   // Do not serialize masked loads of constant memory with anything.
4476   MemoryLocation ML;
4477   if (VT.isScalableVector())
4478     ML = MemoryLocation(PtrOperand);
4479   else
4480     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4481                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4482                            AAInfo);
4483   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4484 
4485   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4486 
4487   MachineMemOperand *MMO =
4488     DAG.getMachineFunction().
4489     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4490                           MachineMemOperand::MOLoad,
4491                           // TODO: Make MachineMemOperands aware of scalable
4492                           // vectors.
4493                           VT.getStoreSize().getKnownMinSize(),
4494                           Alignment, AAInfo, Ranges);
4495 
4496   SDValue Load =
4497       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4498                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4499   if (AddToChain)
4500     PendingLoads.push_back(Load.getValue(1));
4501   setValue(&I, Load);
4502 }
4503 
4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4505   SDLoc sdl = getCurSDLoc();
4506 
4507   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4508   const Value *Ptr = I.getArgOperand(0);
4509   SDValue Src0 = getValue(I.getArgOperand(3));
4510   SDValue Mask = getValue(I.getArgOperand(2));
4511 
4512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4513   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4514   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4515   if (!Alignment)
4516     Alignment = DAG.getEVTAlignment(VT);
4517 
4518   AAMDNodes AAInfo;
4519   I.getAAMetadata(AAInfo);
4520   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4521 
4522   SDValue Root = DAG.getRoot();
4523   SDValue Base;
4524   SDValue Index;
4525   ISD::MemIndexType IndexType;
4526   SDValue Scale;
4527   const Value *BasePtr = Ptr;
4528   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4529                                     this);
4530   bool ConstantMemory = false;
4531   if (UniformBase && AA &&
4532       AA->pointsToConstantMemory(
4533           MemoryLocation(BasePtr,
4534                          LocationSize::precise(
4535                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4536                          AAInfo))) {
4537     // Do not serialize (non-volatile) loads of constant memory with anything.
4538     Root = DAG.getEntryNode();
4539     ConstantMemory = true;
4540   }
4541 
4542   MachineMemOperand *MMO =
4543     DAG.getMachineFunction().
4544     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4545                          MachineMemOperand::MOLoad,
4546                          // TODO: Make MachineMemOperands aware of scalable
4547                          // vectors.
4548                          VT.getStoreSize().getKnownMinSize(),
4549                          Alignment, AAInfo, Ranges);
4550 
4551   if (!UniformBase) {
4552     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4553     Index = getValue(Ptr);
4554     IndexType = ISD::SIGNED_SCALED;
4555     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4556   }
4557   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4558   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4559                                        Ops, MMO, IndexType);
4560 
4561   SDValue OutChain = Gather.getValue(1);
4562   if (!ConstantMemory)
4563     PendingLoads.push_back(OutChain);
4564   setValue(&I, Gather);
4565 }
4566 
4567 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4568   SDLoc dl = getCurSDLoc();
4569   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4570   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4571   SyncScope::ID SSID = I.getSyncScopeID();
4572 
4573   SDValue InChain = getRoot();
4574 
4575   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4576   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4577 
4578   auto Alignment = DAG.getEVTAlignment(MemVT);
4579 
4580   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4581   if (I.isVolatile())
4582     Flags |= MachineMemOperand::MOVolatile;
4583   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4584 
4585   MachineFunction &MF = DAG.getMachineFunction();
4586   MachineMemOperand *MMO =
4587     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4588                             Flags, MemVT.getStoreSize(), Alignment,
4589                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4590                             FailureOrdering);
4591 
4592   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4593                                    dl, MemVT, VTs, InChain,
4594                                    getValue(I.getPointerOperand()),
4595                                    getValue(I.getCompareOperand()),
4596                                    getValue(I.getNewValOperand()), MMO);
4597 
4598   SDValue OutChain = L.getValue(2);
4599 
4600   setValue(&I, L);
4601   DAG.setRoot(OutChain);
4602 }
4603 
4604 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4605   SDLoc dl = getCurSDLoc();
4606   ISD::NodeType NT;
4607   switch (I.getOperation()) {
4608   default: llvm_unreachable("Unknown atomicrmw operation");
4609   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4610   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4611   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4612   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4613   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4614   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4615   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4616   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4617   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4618   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4619   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4620   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4621   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4622   }
4623   AtomicOrdering Ordering = I.getOrdering();
4624   SyncScope::ID SSID = I.getSyncScopeID();
4625 
4626   SDValue InChain = getRoot();
4627 
4628   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4629   auto Alignment = DAG.getEVTAlignment(MemVT);
4630 
4631   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4632   if (I.isVolatile())
4633     Flags |= MachineMemOperand::MOVolatile;
4634   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4635 
4636   MachineFunction &MF = DAG.getMachineFunction();
4637   MachineMemOperand *MMO =
4638     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4639                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4640                             nullptr, SSID, Ordering);
4641 
4642   SDValue L =
4643     DAG.getAtomic(NT, dl, MemVT, InChain,
4644                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4645                   MMO);
4646 
4647   SDValue OutChain = L.getValue(1);
4648 
4649   setValue(&I, L);
4650   DAG.setRoot(OutChain);
4651 }
4652 
4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4654   SDLoc dl = getCurSDLoc();
4655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4656   SDValue Ops[3];
4657   Ops[0] = getRoot();
4658   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4659                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4660   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4661                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4662   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4663 }
4664 
4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4666   SDLoc dl = getCurSDLoc();
4667   AtomicOrdering Order = I.getOrdering();
4668   SyncScope::ID SSID = I.getSyncScopeID();
4669 
4670   SDValue InChain = getRoot();
4671 
4672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4673   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4674   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4675 
4676   if (!TLI.supportsUnalignedAtomics() &&
4677       I.getAlignment() < MemVT.getSizeInBits() / 8)
4678     report_fatal_error("Cannot generate unaligned atomic load");
4679 
4680   auto Flags = MachineMemOperand::MOLoad;
4681   if (I.isVolatile())
4682     Flags |= MachineMemOperand::MOVolatile;
4683   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4684     Flags |= MachineMemOperand::MOInvariant;
4685   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4686                                DAG.getDataLayout()))
4687     Flags |= MachineMemOperand::MODereferenceable;
4688 
4689   Flags |= TLI.getMMOFlags(I);
4690 
4691   MachineMemOperand *MMO =
4692       DAG.getMachineFunction().
4693       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4694                            Flags, MemVT.getStoreSize(),
4695                            I.getAlignment() ? I.getAlignment() :
4696                                               DAG.getEVTAlignment(MemVT),
4697                            AAMDNodes(), nullptr, SSID, Order);
4698 
4699   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4700 
4701   SDValue Ptr = getValue(I.getPointerOperand());
4702 
4703   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4704     // TODO: Once this is better exercised by tests, it should be merged with
4705     // the normal path for loads to prevent future divergence.
4706     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4707     if (MemVT != VT)
4708       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4709 
4710     setValue(&I, L);
4711     SDValue OutChain = L.getValue(1);
4712     if (!I.isUnordered())
4713       DAG.setRoot(OutChain);
4714     else
4715       PendingLoads.push_back(OutChain);
4716     return;
4717   }
4718 
4719   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4720                             Ptr, MMO);
4721 
4722   SDValue OutChain = L.getValue(1);
4723   if (MemVT != VT)
4724     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4725 
4726   setValue(&I, L);
4727   DAG.setRoot(OutChain);
4728 }
4729 
4730 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4731   SDLoc dl = getCurSDLoc();
4732 
4733   AtomicOrdering Ordering = I.getOrdering();
4734   SyncScope::ID SSID = I.getSyncScopeID();
4735 
4736   SDValue InChain = getRoot();
4737 
4738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4739   EVT MemVT =
4740       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4741 
4742   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4743     report_fatal_error("Cannot generate unaligned atomic store");
4744 
4745   auto Flags = MachineMemOperand::MOStore;
4746   if (I.isVolatile())
4747     Flags |= MachineMemOperand::MOVolatile;
4748   Flags |= TLI.getMMOFlags(I);
4749 
4750   MachineFunction &MF = DAG.getMachineFunction();
4751   MachineMemOperand *MMO =
4752     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4753                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4754                             nullptr, SSID, Ordering);
4755 
4756   SDValue Val = getValue(I.getValueOperand());
4757   if (Val.getValueType() != MemVT)
4758     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4759   SDValue Ptr = getValue(I.getPointerOperand());
4760 
4761   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4762     // TODO: Once this is better exercised by tests, it should be merged with
4763     // the normal path for stores to prevent future divergence.
4764     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4765     DAG.setRoot(S);
4766     return;
4767   }
4768   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4769                                    Ptr, Val, MMO);
4770 
4771 
4772   DAG.setRoot(OutChain);
4773 }
4774 
4775 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4776 /// node.
4777 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4778                                                unsigned Intrinsic) {
4779   // Ignore the callsite's attributes. A specific call site may be marked with
4780   // readnone, but the lowering code will expect the chain based on the
4781   // definition.
4782   const Function *F = I.getCalledFunction();
4783   bool HasChain = !F->doesNotAccessMemory();
4784   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4785 
4786   // Build the operand list.
4787   SmallVector<SDValue, 8> Ops;
4788   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4789     if (OnlyLoad) {
4790       // We don't need to serialize loads against other loads.
4791       Ops.push_back(DAG.getRoot());
4792     } else {
4793       Ops.push_back(getRoot());
4794     }
4795   }
4796 
4797   // Info is set by getTgtMemInstrinsic
4798   TargetLowering::IntrinsicInfo Info;
4799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4800   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4801                                                DAG.getMachineFunction(),
4802                                                Intrinsic);
4803 
4804   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4805   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4806       Info.opc == ISD::INTRINSIC_W_CHAIN)
4807     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4808                                         TLI.getPointerTy(DAG.getDataLayout())));
4809 
4810   // Add all operands of the call to the operand list.
4811   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4812     const Value *Arg = I.getArgOperand(i);
4813     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4814       Ops.push_back(getValue(Arg));
4815       continue;
4816     }
4817 
4818     // Use TargetConstant instead of a regular constant for immarg.
4819     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4820     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4821       assert(CI->getBitWidth() <= 64 &&
4822              "large intrinsic immediates not handled");
4823       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4824     } else {
4825       Ops.push_back(
4826           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4827     }
4828   }
4829 
4830   SmallVector<EVT, 4> ValueVTs;
4831   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4832 
4833   if (HasChain)
4834     ValueVTs.push_back(MVT::Other);
4835 
4836   SDVTList VTs = DAG.getVTList(ValueVTs);
4837 
4838   // Create the node.
4839   SDValue Result;
4840   if (IsTgtIntrinsic) {
4841     // This is target intrinsic that touches memory
4842     AAMDNodes AAInfo;
4843     I.getAAMetadata(AAInfo);
4844     Result = DAG.getMemIntrinsicNode(
4845         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4846         MachinePointerInfo(Info.ptrVal, Info.offset),
4847         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4848   } else if (!HasChain) {
4849     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4850   } else if (!I.getType()->isVoidTy()) {
4851     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4852   } else {
4853     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4854   }
4855 
4856   if (HasChain) {
4857     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4858     if (OnlyLoad)
4859       PendingLoads.push_back(Chain);
4860     else
4861       DAG.setRoot(Chain);
4862   }
4863 
4864   if (!I.getType()->isVoidTy()) {
4865     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4866       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4867       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4868     } else
4869       Result = lowerRangeToAssertZExt(DAG, I, Result);
4870 
4871     setValue(&I, Result);
4872   }
4873 }
4874 
4875 /// GetSignificand - Get the significand and build it into a floating-point
4876 /// number with exponent of 1:
4877 ///
4878 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4879 ///
4880 /// where Op is the hexadecimal representation of floating point value.
4881 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4882   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4883                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4884   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4885                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4886   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4887 }
4888 
4889 /// GetExponent - Get the exponent:
4890 ///
4891 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4892 ///
4893 /// where Op is the hexadecimal representation of floating point value.
4894 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4895                            const TargetLowering &TLI, const SDLoc &dl) {
4896   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4897                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4898   SDValue t1 = DAG.getNode(
4899       ISD::SRL, dl, MVT::i32, t0,
4900       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4901   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4902                            DAG.getConstant(127, dl, MVT::i32));
4903   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4904 }
4905 
4906 /// getF32Constant - Get 32-bit floating point constant.
4907 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4908                               const SDLoc &dl) {
4909   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4910                            MVT::f32);
4911 }
4912 
4913 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4914                                        SelectionDAG &DAG) {
4915   // TODO: What fast-math-flags should be set on the floating-point nodes?
4916 
4917   //   IntegerPartOfX = ((int32_t)(t0);
4918   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4919 
4920   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4921   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4922   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4923 
4924   //   IntegerPartOfX <<= 23;
4925   IntegerPartOfX = DAG.getNode(
4926       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4927       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4928                                   DAG.getDataLayout())));
4929 
4930   SDValue TwoToFractionalPartOfX;
4931   if (LimitFloatPrecision <= 6) {
4932     // For floating-point precision of 6:
4933     //
4934     //   TwoToFractionalPartOfX =
4935     //     0.997535578f +
4936     //       (0.735607626f + 0.252464424f * x) * x;
4937     //
4938     // error 0.0144103317, which is 6 bits
4939     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4940                              getF32Constant(DAG, 0x3e814304, dl));
4941     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4942                              getF32Constant(DAG, 0x3f3c50c8, dl));
4943     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4944     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4945                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4946   } else if (LimitFloatPrecision <= 12) {
4947     // For floating-point precision of 12:
4948     //
4949     //   TwoToFractionalPartOfX =
4950     //     0.999892986f +
4951     //       (0.696457318f +
4952     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4953     //
4954     // error 0.000107046256, which is 13 to 14 bits
4955     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4956                              getF32Constant(DAG, 0x3da235e3, dl));
4957     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4958                              getF32Constant(DAG, 0x3e65b8f3, dl));
4959     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4960     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4961                              getF32Constant(DAG, 0x3f324b07, dl));
4962     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4963     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4964                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4965   } else { // LimitFloatPrecision <= 18
4966     // For floating-point precision of 18:
4967     //
4968     //   TwoToFractionalPartOfX =
4969     //     0.999999982f +
4970     //       (0.693148872f +
4971     //         (0.240227044f +
4972     //           (0.554906021e-1f +
4973     //             (0.961591928e-2f +
4974     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4975     // error 2.47208000*10^(-7), which is better than 18 bits
4976     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4977                              getF32Constant(DAG, 0x3924b03e, dl));
4978     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4979                              getF32Constant(DAG, 0x3ab24b87, dl));
4980     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4981     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4982                              getF32Constant(DAG, 0x3c1d8c17, dl));
4983     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4984     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4985                              getF32Constant(DAG, 0x3d634a1d, dl));
4986     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4987     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4988                              getF32Constant(DAG, 0x3e75fe14, dl));
4989     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4990     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4991                               getF32Constant(DAG, 0x3f317234, dl));
4992     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4993     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4994                                          getF32Constant(DAG, 0x3f800000, dl));
4995   }
4996 
4997   // Add the exponent into the result in integer domain.
4998   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4999   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5000                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5001 }
5002 
5003 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5004 /// limited-precision mode.
5005 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5006                          const TargetLowering &TLI) {
5007   if (Op.getValueType() == MVT::f32 &&
5008       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5009 
5010     // Put the exponent in the right bit position for later addition to the
5011     // final result:
5012     //
5013     // t0 = Op * log2(e)
5014 
5015     // TODO: What fast-math-flags should be set here?
5016     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5017                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5018     return getLimitedPrecisionExp2(t0, dl, DAG);
5019   }
5020 
5021   // No special expansion.
5022   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5023 }
5024 
5025 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5026 /// limited-precision mode.
5027 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5028                          const TargetLowering &TLI) {
5029   // TODO: What fast-math-flags should be set on the floating-point nodes?
5030 
5031   if (Op.getValueType() == MVT::f32 &&
5032       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5033     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5034 
5035     // Scale the exponent by log(2).
5036     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5037     SDValue LogOfExponent =
5038         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5039                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5040 
5041     // Get the significand and build it into a floating-point number with
5042     // exponent of 1.
5043     SDValue X = GetSignificand(DAG, Op1, dl);
5044 
5045     SDValue LogOfMantissa;
5046     if (LimitFloatPrecision <= 6) {
5047       // For floating-point precision of 6:
5048       //
5049       //   LogofMantissa =
5050       //     -1.1609546f +
5051       //       (1.4034025f - 0.23903021f * x) * x;
5052       //
5053       // error 0.0034276066, which is better than 8 bits
5054       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5055                                getF32Constant(DAG, 0xbe74c456, dl));
5056       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5057                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5058       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5059       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5060                                   getF32Constant(DAG, 0x3f949a29, dl));
5061     } else if (LimitFloatPrecision <= 12) {
5062       // For floating-point precision of 12:
5063       //
5064       //   LogOfMantissa =
5065       //     -1.7417939f +
5066       //       (2.8212026f +
5067       //         (-1.4699568f +
5068       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5069       //
5070       // error 0.000061011436, which is 14 bits
5071       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5072                                getF32Constant(DAG, 0xbd67b6d6, dl));
5073       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5074                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5075       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5076       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5077                                getF32Constant(DAG, 0x3fbc278b, dl));
5078       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5079       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5080                                getF32Constant(DAG, 0x40348e95, dl));
5081       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5082       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5083                                   getF32Constant(DAG, 0x3fdef31a, dl));
5084     } else { // LimitFloatPrecision <= 18
5085       // For floating-point precision of 18:
5086       //
5087       //   LogOfMantissa =
5088       //     -2.1072184f +
5089       //       (4.2372794f +
5090       //         (-3.7029485f +
5091       //           (2.2781945f +
5092       //             (-0.87823314f +
5093       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5094       //
5095       // error 0.0000023660568, which is better than 18 bits
5096       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5097                                getF32Constant(DAG, 0xbc91e5ac, dl));
5098       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5099                                getF32Constant(DAG, 0x3e4350aa, dl));
5100       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5101       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5102                                getF32Constant(DAG, 0x3f60d3e3, dl));
5103       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5104       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5105                                getF32Constant(DAG, 0x4011cdf0, dl));
5106       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5107       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5108                                getF32Constant(DAG, 0x406cfd1c, dl));
5109       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5110       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5111                                getF32Constant(DAG, 0x408797cb, dl));
5112       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5113       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5114                                   getF32Constant(DAG, 0x4006dcab, dl));
5115     }
5116 
5117     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5118   }
5119 
5120   // No special expansion.
5121   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5122 }
5123 
5124 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5125 /// limited-precision mode.
5126 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5127                           const TargetLowering &TLI) {
5128   // TODO: What fast-math-flags should be set on the floating-point nodes?
5129 
5130   if (Op.getValueType() == MVT::f32 &&
5131       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5132     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5133 
5134     // Get the exponent.
5135     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5136 
5137     // Get the significand and build it into a floating-point number with
5138     // exponent of 1.
5139     SDValue X = GetSignificand(DAG, Op1, dl);
5140 
5141     // Different possible minimax approximations of significand in
5142     // floating-point for various degrees of accuracy over [1,2].
5143     SDValue Log2ofMantissa;
5144     if (LimitFloatPrecision <= 6) {
5145       // For floating-point precision of 6:
5146       //
5147       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5148       //
5149       // error 0.0049451742, which is more than 7 bits
5150       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5151                                getF32Constant(DAG, 0xbeb08fe0, dl));
5152       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5153                                getF32Constant(DAG, 0x40019463, dl));
5154       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5155       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5156                                    getF32Constant(DAG, 0x3fd6633d, dl));
5157     } else if (LimitFloatPrecision <= 12) {
5158       // For floating-point precision of 12:
5159       //
5160       //   Log2ofMantissa =
5161       //     -2.51285454f +
5162       //       (4.07009056f +
5163       //         (-2.12067489f +
5164       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5165       //
5166       // error 0.0000876136000, which is better than 13 bits
5167       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5168                                getF32Constant(DAG, 0xbda7262e, dl));
5169       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5170                                getF32Constant(DAG, 0x3f25280b, dl));
5171       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5172       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5173                                getF32Constant(DAG, 0x4007b923, dl));
5174       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5175       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5176                                getF32Constant(DAG, 0x40823e2f, dl));
5177       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5178       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5179                                    getF32Constant(DAG, 0x4020d29c, dl));
5180     } else { // LimitFloatPrecision <= 18
5181       // For floating-point precision of 18:
5182       //
5183       //   Log2ofMantissa =
5184       //     -3.0400495f +
5185       //       (6.1129976f +
5186       //         (-5.3420409f +
5187       //           (3.2865683f +
5188       //             (-1.2669343f +
5189       //               (0.27515199f -
5190       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5191       //
5192       // error 0.0000018516, which is better than 18 bits
5193       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5194                                getF32Constant(DAG, 0xbcd2769e, dl));
5195       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5196                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5197       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5198       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5199                                getF32Constant(DAG, 0x3fa22ae7, dl));
5200       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5201       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5202                                getF32Constant(DAG, 0x40525723, dl));
5203       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5204       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5205                                getF32Constant(DAG, 0x40aaf200, dl));
5206       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5207       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5208                                getF32Constant(DAG, 0x40c39dad, dl));
5209       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5210       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5211                                    getF32Constant(DAG, 0x4042902c, dl));
5212     }
5213 
5214     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5215   }
5216 
5217   // No special expansion.
5218   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5219 }
5220 
5221 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5222 /// limited-precision mode.
5223 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5224                            const TargetLowering &TLI) {
5225   // TODO: What fast-math-flags should be set on the floating-point nodes?
5226 
5227   if (Op.getValueType() == MVT::f32 &&
5228       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5229     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5230 
5231     // Scale the exponent by log10(2) [0.30102999f].
5232     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5233     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5234                                         getF32Constant(DAG, 0x3e9a209a, dl));
5235 
5236     // Get the significand and build it into a floating-point number with
5237     // exponent of 1.
5238     SDValue X = GetSignificand(DAG, Op1, dl);
5239 
5240     SDValue Log10ofMantissa;
5241     if (LimitFloatPrecision <= 6) {
5242       // For floating-point precision of 6:
5243       //
5244       //   Log10ofMantissa =
5245       //     -0.50419619f +
5246       //       (0.60948995f - 0.10380950f * x) * x;
5247       //
5248       // error 0.0014886165, which is 6 bits
5249       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5250                                getF32Constant(DAG, 0xbdd49a13, dl));
5251       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5252                                getF32Constant(DAG, 0x3f1c0789, dl));
5253       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5254       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5255                                     getF32Constant(DAG, 0x3f011300, dl));
5256     } else if (LimitFloatPrecision <= 12) {
5257       // For floating-point precision of 12:
5258       //
5259       //   Log10ofMantissa =
5260       //     -0.64831180f +
5261       //       (0.91751397f +
5262       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5263       //
5264       // error 0.00019228036, which is better than 12 bits
5265       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5266                                getF32Constant(DAG, 0x3d431f31, dl));
5267       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5268                                getF32Constant(DAG, 0x3ea21fb2, dl));
5269       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5270       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5271                                getF32Constant(DAG, 0x3f6ae232, dl));
5272       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5273       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5274                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5275     } else { // LimitFloatPrecision <= 18
5276       // For floating-point precision of 18:
5277       //
5278       //   Log10ofMantissa =
5279       //     -0.84299375f +
5280       //       (1.5327582f +
5281       //         (-1.0688956f +
5282       //           (0.49102474f +
5283       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5284       //
5285       // error 0.0000037995730, which is better than 18 bits
5286       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5287                                getF32Constant(DAG, 0x3c5d51ce, dl));
5288       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5289                                getF32Constant(DAG, 0x3e00685a, dl));
5290       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5291       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5292                                getF32Constant(DAG, 0x3efb6798, dl));
5293       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5294       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5295                                getF32Constant(DAG, 0x3f88d192, dl));
5296       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5297       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5298                                getF32Constant(DAG, 0x3fc4316c, dl));
5299       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5300       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5301                                     getF32Constant(DAG, 0x3f57ce70, dl));
5302     }
5303 
5304     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5305   }
5306 
5307   // No special expansion.
5308   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5309 }
5310 
5311 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5312 /// limited-precision mode.
5313 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5314                           const TargetLowering &TLI) {
5315   if (Op.getValueType() == MVT::f32 &&
5316       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5317     return getLimitedPrecisionExp2(Op, dl, DAG);
5318 
5319   // No special expansion.
5320   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5321 }
5322 
5323 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5324 /// limited-precision mode with x == 10.0f.
5325 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5326                          SelectionDAG &DAG, const TargetLowering &TLI) {
5327   bool IsExp10 = false;
5328   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5329       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5330     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5331       APFloat Ten(10.0f);
5332       IsExp10 = LHSC->isExactlyValue(Ten);
5333     }
5334   }
5335 
5336   // TODO: What fast-math-flags should be set on the FMUL node?
5337   if (IsExp10) {
5338     // Put the exponent in the right bit position for later addition to the
5339     // final result:
5340     //
5341     //   #define LOG2OF10 3.3219281f
5342     //   t0 = Op * LOG2OF10;
5343     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5344                              getF32Constant(DAG, 0x40549a78, dl));
5345     return getLimitedPrecisionExp2(t0, dl, DAG);
5346   }
5347 
5348   // No special expansion.
5349   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5350 }
5351 
5352 /// ExpandPowI - Expand a llvm.powi intrinsic.
5353 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5354                           SelectionDAG &DAG) {
5355   // If RHS is a constant, we can expand this out to a multiplication tree,
5356   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5357   // optimizing for size, we only want to do this if the expansion would produce
5358   // a small number of multiplies, otherwise we do the full expansion.
5359   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5360     // Get the exponent as a positive value.
5361     unsigned Val = RHSC->getSExtValue();
5362     if ((int)Val < 0) Val = -Val;
5363 
5364     // powi(x, 0) -> 1.0
5365     if (Val == 0)
5366       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5367 
5368     bool OptForSize = DAG.shouldOptForSize();
5369     if (!OptForSize ||
5370         // If optimizing for size, don't insert too many multiplies.
5371         // This inserts up to 5 multiplies.
5372         countPopulation(Val) + Log2_32(Val) < 7) {
5373       // We use the simple binary decomposition method to generate the multiply
5374       // sequence.  There are more optimal ways to do this (for example,
5375       // powi(x,15) generates one more multiply than it should), but this has
5376       // the benefit of being both really simple and much better than a libcall.
5377       SDValue Res;  // Logically starts equal to 1.0
5378       SDValue CurSquare = LHS;
5379       // TODO: Intrinsics should have fast-math-flags that propagate to these
5380       // nodes.
5381       while (Val) {
5382         if (Val & 1) {
5383           if (Res.getNode())
5384             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5385           else
5386             Res = CurSquare;  // 1.0*CurSquare.
5387         }
5388 
5389         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5390                                 CurSquare, CurSquare);
5391         Val >>= 1;
5392       }
5393 
5394       // If the original was negative, invert the result, producing 1/(x*x*x).
5395       if (RHSC->getSExtValue() < 0)
5396         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5397                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5398       return Res;
5399     }
5400   }
5401 
5402   // Otherwise, expand to a libcall.
5403   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5404 }
5405 
5406 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5407 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5408 static void
5409 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5410                      const SDValue &N) {
5411   switch (N.getOpcode()) {
5412   case ISD::CopyFromReg: {
5413     SDValue Op = N.getOperand(1);
5414     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5415                       Op.getValueType().getSizeInBits());
5416     return;
5417   }
5418   case ISD::BITCAST:
5419   case ISD::AssertZext:
5420   case ISD::AssertSext:
5421   case ISD::TRUNCATE:
5422     getUnderlyingArgRegs(Regs, N.getOperand(0));
5423     return;
5424   case ISD::BUILD_PAIR:
5425   case ISD::BUILD_VECTOR:
5426   case ISD::CONCAT_VECTORS:
5427     for (SDValue Op : N->op_values())
5428       getUnderlyingArgRegs(Regs, Op);
5429     return;
5430   default:
5431     return;
5432   }
5433 }
5434 
5435 /// If the DbgValueInst is a dbg_value of a function argument, create the
5436 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5437 /// instruction selection, they will be inserted to the entry BB.
5438 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5439     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5440     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5441   const Argument *Arg = dyn_cast<Argument>(V);
5442   if (!Arg)
5443     return false;
5444 
5445   if (!IsDbgDeclare) {
5446     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5447     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5448     // the entry block.
5449     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5450     if (!IsInEntryBlock)
5451       return false;
5452 
5453     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5454     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5455     // variable that also is a param.
5456     //
5457     // Although, if we are at the top of the entry block already, we can still
5458     // emit using ArgDbgValue. This might catch some situations when the
5459     // dbg.value refers to an argument that isn't used in the entry block, so
5460     // any CopyToReg node would be optimized out and the only way to express
5461     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5462     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5463     // we should only emit as ArgDbgValue if the Variable is an argument to the
5464     // current function, and the dbg.value intrinsic is found in the entry
5465     // block.
5466     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5467         !DL->getInlinedAt();
5468     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5469     if (!IsInPrologue && !VariableIsFunctionInputArg)
5470       return false;
5471 
5472     // Here we assume that a function argument on IR level only can be used to
5473     // describe one input parameter on source level. If we for example have
5474     // source code like this
5475     //
5476     //    struct A { long x, y; };
5477     //    void foo(struct A a, long b) {
5478     //      ...
5479     //      b = a.x;
5480     //      ...
5481     //    }
5482     //
5483     // and IR like this
5484     //
5485     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5486     //  entry:
5487     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5488     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5489     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5490     //    ...
5491     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5492     //    ...
5493     //
5494     // then the last dbg.value is describing a parameter "b" using a value that
5495     // is an argument. But since we already has used %a1 to describe a parameter
5496     // we should not handle that last dbg.value here (that would result in an
5497     // incorrect hoisting of the DBG_VALUE to the function entry).
5498     // Notice that we allow one dbg.value per IR level argument, to accommodate
5499     // for the situation with fragments above.
5500     if (VariableIsFunctionInputArg) {
5501       unsigned ArgNo = Arg->getArgNo();
5502       if (ArgNo >= FuncInfo.DescribedArgs.size())
5503         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5504       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5505         return false;
5506       FuncInfo.DescribedArgs.set(ArgNo);
5507     }
5508   }
5509 
5510   MachineFunction &MF = DAG.getMachineFunction();
5511   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5512 
5513   Optional<MachineOperand> Op;
5514   // Some arguments' frame index is recorded during argument lowering.
5515   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5516   if (FI != std::numeric_limits<int>::max())
5517     Op = MachineOperand::CreateFI(FI);
5518 
5519   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5520   if (!Op && N.getNode()) {
5521     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5522     Register Reg;
5523     if (ArgRegsAndSizes.size() == 1)
5524       Reg = ArgRegsAndSizes.front().first;
5525 
5526     if (Reg && Reg.isVirtual()) {
5527       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5528       Register PR = RegInfo.getLiveInPhysReg(Reg);
5529       if (PR)
5530         Reg = PR;
5531     }
5532     if (Reg) {
5533       Op = MachineOperand::CreateReg(Reg, false);
5534     }
5535   }
5536 
5537   if (!Op && N.getNode()) {
5538     // Check if frame index is available.
5539     SDValue LCandidate = peekThroughBitcasts(N);
5540     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5541       if (FrameIndexSDNode *FINode =
5542           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5543         Op = MachineOperand::CreateFI(FINode->getIndex());
5544   }
5545 
5546   if (!Op) {
5547     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5548     auto splitMultiRegDbgValue
5549       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5550       unsigned Offset = 0;
5551       for (auto RegAndSize : SplitRegs) {
5552         auto FragmentExpr = DIExpression::createFragmentExpression(
5553           Expr, Offset, RegAndSize.second);
5554         if (!FragmentExpr)
5555           continue;
5556         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5557         FuncInfo.ArgDbgValues.push_back(
5558           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5559                   RegAndSize.first, Variable, *FragmentExpr));
5560         Offset += RegAndSize.second;
5561       }
5562     };
5563 
5564     // Check if ValueMap has reg number.
5565     DenseMap<const Value *, unsigned>::const_iterator
5566       VMI = FuncInfo.ValueMap.find(V);
5567     if (VMI != FuncInfo.ValueMap.end()) {
5568       const auto &TLI = DAG.getTargetLoweringInfo();
5569       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5570                        V->getType(), getABIRegCopyCC(V));
5571       if (RFV.occupiesMultipleRegs()) {
5572         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5573         return true;
5574       }
5575 
5576       Op = MachineOperand::CreateReg(VMI->second, false);
5577     } else if (ArgRegsAndSizes.size() > 1) {
5578       // This was split due to the calling convention, and no virtual register
5579       // mapping exists for the value.
5580       splitMultiRegDbgValue(ArgRegsAndSizes);
5581       return true;
5582     }
5583   }
5584 
5585   if (!Op)
5586     return false;
5587 
5588   assert(Variable->isValidLocationForIntrinsic(DL) &&
5589          "Expected inlined-at fields to agree");
5590 
5591   // If the argument arrives in a stack slot, then what the IR thought was a
5592   // normal Value is actually in memory, and we must add a deref to load it.
5593   if (Op->isFI()) {
5594     int FI = Op->getIndex();
5595     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5596     if (Expr->isImplicit()) {
5597       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5598       Expr = DIExpression::prependOpcodes(Expr, Ops);
5599     } else {
5600       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5601     }
5602   }
5603 
5604   // If this location was specified with a dbg.declare, then it and its
5605   // expression calculate the address of the variable. Append a deref to
5606   // force it to be a memory location.
5607   if (IsDbgDeclare)
5608     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5609 
5610   FuncInfo.ArgDbgValues.push_back(
5611       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5612               *Op, Variable, Expr));
5613 
5614   return true;
5615 }
5616 
5617 /// Return the appropriate SDDbgValue based on N.
5618 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5619                                              DILocalVariable *Variable,
5620                                              DIExpression *Expr,
5621                                              const DebugLoc &dl,
5622                                              unsigned DbgSDNodeOrder) {
5623   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5624     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5625     // stack slot locations.
5626     //
5627     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5628     // debug values here after optimization:
5629     //
5630     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5631     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5632     //
5633     // Both describe the direct values of their associated variables.
5634     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5635                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5636   }
5637   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5638                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5639 }
5640 
5641 // VisualStudio defines setjmp as _setjmp
5642 #if defined(_MSC_VER) && defined(setjmp) && \
5643                          !defined(setjmp_undefined_for_msvc)
5644 #  pragma push_macro("setjmp")
5645 #  undef setjmp
5646 #  define setjmp_undefined_for_msvc
5647 #endif
5648 
5649 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5650   switch (Intrinsic) {
5651   case Intrinsic::smul_fix:
5652     return ISD::SMULFIX;
5653   case Intrinsic::umul_fix:
5654     return ISD::UMULFIX;
5655   default:
5656     llvm_unreachable("Unhandled fixed point intrinsic");
5657   }
5658 }
5659 
5660 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5661                                            const char *FunctionName) {
5662   assert(FunctionName && "FunctionName must not be nullptr");
5663   SDValue Callee = DAG.getExternalSymbol(
5664       FunctionName,
5665       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5666   LowerCallTo(&I, Callee, I.isTailCall());
5667 }
5668 
5669 /// Lower the call to the specified intrinsic function.
5670 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5671                                              unsigned Intrinsic) {
5672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673   SDLoc sdl = getCurSDLoc();
5674   DebugLoc dl = getCurDebugLoc();
5675   SDValue Res;
5676 
5677   switch (Intrinsic) {
5678   default:
5679     // By default, turn this into a target intrinsic node.
5680     visitTargetIntrinsic(I, Intrinsic);
5681     return;
5682   case Intrinsic::vastart:  visitVAStart(I); return;
5683   case Intrinsic::vaend:    visitVAEnd(I); return;
5684   case Intrinsic::vacopy:   visitVACopy(I); return;
5685   case Intrinsic::returnaddress:
5686     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5687                              TLI.getPointerTy(DAG.getDataLayout()),
5688                              getValue(I.getArgOperand(0))));
5689     return;
5690   case Intrinsic::addressofreturnaddress:
5691     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5692                              TLI.getPointerTy(DAG.getDataLayout())));
5693     return;
5694   case Intrinsic::sponentry:
5695     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5696                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5697     return;
5698   case Intrinsic::frameaddress:
5699     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5700                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5701                              getValue(I.getArgOperand(0))));
5702     return;
5703   case Intrinsic::read_register: {
5704     Value *Reg = I.getArgOperand(0);
5705     SDValue Chain = getRoot();
5706     SDValue RegName =
5707         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5708     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5709     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5710       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5711     setValue(&I, Res);
5712     DAG.setRoot(Res.getValue(1));
5713     return;
5714   }
5715   case Intrinsic::write_register: {
5716     Value *Reg = I.getArgOperand(0);
5717     Value *RegValue = I.getArgOperand(1);
5718     SDValue Chain = getRoot();
5719     SDValue RegName =
5720         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5721     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5722                             RegName, getValue(RegValue)));
5723     return;
5724   }
5725   case Intrinsic::setjmp:
5726     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5727     return;
5728   case Intrinsic::longjmp:
5729     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5730     return;
5731   case Intrinsic::memcpy: {
5732     const auto &MCI = cast<MemCpyInst>(I);
5733     SDValue Op1 = getValue(I.getArgOperand(0));
5734     SDValue Op2 = getValue(I.getArgOperand(1));
5735     SDValue Op3 = getValue(I.getArgOperand(2));
5736     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5737     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5738     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5739     unsigned Align = MinAlign(DstAlign, SrcAlign);
5740     bool isVol = MCI.isVolatile();
5741     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5742     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5743     // node.
5744     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5745                                false, isTC,
5746                                MachinePointerInfo(I.getArgOperand(0)),
5747                                MachinePointerInfo(I.getArgOperand(1)));
5748     updateDAGForMaybeTailCall(MC);
5749     return;
5750   }
5751   case Intrinsic::memset: {
5752     const auto &MSI = cast<MemSetInst>(I);
5753     SDValue Op1 = getValue(I.getArgOperand(0));
5754     SDValue Op2 = getValue(I.getArgOperand(1));
5755     SDValue Op3 = getValue(I.getArgOperand(2));
5756     // @llvm.memset defines 0 and 1 to both mean no alignment.
5757     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5758     bool isVol = MSI.isVolatile();
5759     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5760     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5761                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5762     updateDAGForMaybeTailCall(MS);
5763     return;
5764   }
5765   case Intrinsic::memmove: {
5766     const auto &MMI = cast<MemMoveInst>(I);
5767     SDValue Op1 = getValue(I.getArgOperand(0));
5768     SDValue Op2 = getValue(I.getArgOperand(1));
5769     SDValue Op3 = getValue(I.getArgOperand(2));
5770     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5771     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5772     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5773     unsigned Align = MinAlign(DstAlign, SrcAlign);
5774     bool isVol = MMI.isVolatile();
5775     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5776     // FIXME: Support passing different dest/src alignments to the memmove DAG
5777     // node.
5778     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5779                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5780                                 MachinePointerInfo(I.getArgOperand(1)));
5781     updateDAGForMaybeTailCall(MM);
5782     return;
5783   }
5784   case Intrinsic::memcpy_element_unordered_atomic: {
5785     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5786     SDValue Dst = getValue(MI.getRawDest());
5787     SDValue Src = getValue(MI.getRawSource());
5788     SDValue Length = getValue(MI.getLength());
5789 
5790     unsigned DstAlign = MI.getDestAlignment();
5791     unsigned SrcAlign = MI.getSourceAlignment();
5792     Type *LengthTy = MI.getLength()->getType();
5793     unsigned ElemSz = MI.getElementSizeInBytes();
5794     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5795     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5796                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5797                                      MachinePointerInfo(MI.getRawDest()),
5798                                      MachinePointerInfo(MI.getRawSource()));
5799     updateDAGForMaybeTailCall(MC);
5800     return;
5801   }
5802   case Intrinsic::memmove_element_unordered_atomic: {
5803     auto &MI = cast<AtomicMemMoveInst>(I);
5804     SDValue Dst = getValue(MI.getRawDest());
5805     SDValue Src = getValue(MI.getRawSource());
5806     SDValue Length = getValue(MI.getLength());
5807 
5808     unsigned DstAlign = MI.getDestAlignment();
5809     unsigned SrcAlign = MI.getSourceAlignment();
5810     Type *LengthTy = MI.getLength()->getType();
5811     unsigned ElemSz = MI.getElementSizeInBytes();
5812     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5813     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5814                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5815                                       MachinePointerInfo(MI.getRawDest()),
5816                                       MachinePointerInfo(MI.getRawSource()));
5817     updateDAGForMaybeTailCall(MC);
5818     return;
5819   }
5820   case Intrinsic::memset_element_unordered_atomic: {
5821     auto &MI = cast<AtomicMemSetInst>(I);
5822     SDValue Dst = getValue(MI.getRawDest());
5823     SDValue Val = getValue(MI.getValue());
5824     SDValue Length = getValue(MI.getLength());
5825 
5826     unsigned DstAlign = MI.getDestAlignment();
5827     Type *LengthTy = MI.getLength()->getType();
5828     unsigned ElemSz = MI.getElementSizeInBytes();
5829     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5830     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5831                                      LengthTy, ElemSz, isTC,
5832                                      MachinePointerInfo(MI.getRawDest()));
5833     updateDAGForMaybeTailCall(MC);
5834     return;
5835   }
5836   case Intrinsic::dbg_addr:
5837   case Intrinsic::dbg_declare: {
5838     const auto &DI = cast<DbgVariableIntrinsic>(I);
5839     DILocalVariable *Variable = DI.getVariable();
5840     DIExpression *Expression = DI.getExpression();
5841     dropDanglingDebugInfo(Variable, Expression);
5842     assert(Variable && "Missing variable");
5843 
5844     // Check if address has undef value.
5845     const Value *Address = DI.getVariableLocation();
5846     if (!Address || isa<UndefValue>(Address) ||
5847         (Address->use_empty() && !isa<Argument>(Address))) {
5848       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5849       return;
5850     }
5851 
5852     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5853 
5854     // Check if this variable can be described by a frame index, typically
5855     // either as a static alloca or a byval parameter.
5856     int FI = std::numeric_limits<int>::max();
5857     if (const auto *AI =
5858             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5859       if (AI->isStaticAlloca()) {
5860         auto I = FuncInfo.StaticAllocaMap.find(AI);
5861         if (I != FuncInfo.StaticAllocaMap.end())
5862           FI = I->second;
5863       }
5864     } else if (const auto *Arg = dyn_cast<Argument>(
5865                    Address->stripInBoundsConstantOffsets())) {
5866       FI = FuncInfo.getArgumentFrameIndex(Arg);
5867     }
5868 
5869     // llvm.dbg.addr is control dependent and always generates indirect
5870     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5871     // the MachineFunction variable table.
5872     if (FI != std::numeric_limits<int>::max()) {
5873       if (Intrinsic == Intrinsic::dbg_addr) {
5874         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5875             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5876         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5877       }
5878       return;
5879     }
5880 
5881     SDValue &N = NodeMap[Address];
5882     if (!N.getNode() && isa<Argument>(Address))
5883       // Check unused arguments map.
5884       N = UnusedArgNodeMap[Address];
5885     SDDbgValue *SDV;
5886     if (N.getNode()) {
5887       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5888         Address = BCI->getOperand(0);
5889       // Parameters are handled specially.
5890       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5891       if (isParameter && FINode) {
5892         // Byval parameter. We have a frame index at this point.
5893         SDV =
5894             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5895                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5896       } else if (isa<Argument>(Address)) {
5897         // Address is an argument, so try to emit its dbg value using
5898         // virtual register info from the FuncInfo.ValueMap.
5899         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5900         return;
5901       } else {
5902         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5903                               true, dl, SDNodeOrder);
5904       }
5905       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5906     } else {
5907       // If Address is an argument then try to emit its dbg value using
5908       // virtual register info from the FuncInfo.ValueMap.
5909       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5910                                     N)) {
5911         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5912       }
5913     }
5914     return;
5915   }
5916   case Intrinsic::dbg_label: {
5917     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5918     DILabel *Label = DI.getLabel();
5919     assert(Label && "Missing label");
5920 
5921     SDDbgLabel *SDV;
5922     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5923     DAG.AddDbgLabel(SDV);
5924     return;
5925   }
5926   case Intrinsic::dbg_value: {
5927     const DbgValueInst &DI = cast<DbgValueInst>(I);
5928     assert(DI.getVariable() && "Missing variable");
5929 
5930     DILocalVariable *Variable = DI.getVariable();
5931     DIExpression *Expression = DI.getExpression();
5932     dropDanglingDebugInfo(Variable, Expression);
5933     const Value *V = DI.getValue();
5934     if (!V)
5935       return;
5936 
5937     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5938         SDNodeOrder))
5939       return;
5940 
5941     // TODO: Dangling debug info will eventually either be resolved or produce
5942     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5943     // between the original dbg.value location and its resolved DBG_VALUE, which
5944     // we should ideally fill with an extra Undef DBG_VALUE.
5945 
5946     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5947     return;
5948   }
5949 
5950   case Intrinsic::eh_typeid_for: {
5951     // Find the type id for the given typeinfo.
5952     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5953     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5954     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5955     setValue(&I, Res);
5956     return;
5957   }
5958 
5959   case Intrinsic::eh_return_i32:
5960   case Intrinsic::eh_return_i64:
5961     DAG.getMachineFunction().setCallsEHReturn(true);
5962     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5963                             MVT::Other,
5964                             getControlRoot(),
5965                             getValue(I.getArgOperand(0)),
5966                             getValue(I.getArgOperand(1))));
5967     return;
5968   case Intrinsic::eh_unwind_init:
5969     DAG.getMachineFunction().setCallsUnwindInit(true);
5970     return;
5971   case Intrinsic::eh_dwarf_cfa:
5972     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5973                              TLI.getPointerTy(DAG.getDataLayout()),
5974                              getValue(I.getArgOperand(0))));
5975     return;
5976   case Intrinsic::eh_sjlj_callsite: {
5977     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5978     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5979     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5980     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5981 
5982     MMI.setCurrentCallSite(CI->getZExtValue());
5983     return;
5984   }
5985   case Intrinsic::eh_sjlj_functioncontext: {
5986     // Get and store the index of the function context.
5987     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5988     AllocaInst *FnCtx =
5989       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5990     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5991     MFI.setFunctionContextIndex(FI);
5992     return;
5993   }
5994   case Intrinsic::eh_sjlj_setjmp: {
5995     SDValue Ops[2];
5996     Ops[0] = getRoot();
5997     Ops[1] = getValue(I.getArgOperand(0));
5998     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5999                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6000     setValue(&I, Op.getValue(0));
6001     DAG.setRoot(Op.getValue(1));
6002     return;
6003   }
6004   case Intrinsic::eh_sjlj_longjmp:
6005     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6006                             getRoot(), getValue(I.getArgOperand(0))));
6007     return;
6008   case Intrinsic::eh_sjlj_setup_dispatch:
6009     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6010                             getRoot()));
6011     return;
6012   case Intrinsic::masked_gather:
6013     visitMaskedGather(I);
6014     return;
6015   case Intrinsic::masked_load:
6016     visitMaskedLoad(I);
6017     return;
6018   case Intrinsic::masked_scatter:
6019     visitMaskedScatter(I);
6020     return;
6021   case Intrinsic::masked_store:
6022     visitMaskedStore(I);
6023     return;
6024   case Intrinsic::masked_expandload:
6025     visitMaskedLoad(I, true /* IsExpanding */);
6026     return;
6027   case Intrinsic::masked_compressstore:
6028     visitMaskedStore(I, true /* IsCompressing */);
6029     return;
6030   case Intrinsic::powi:
6031     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6032                             getValue(I.getArgOperand(1)), DAG));
6033     return;
6034   case Intrinsic::log:
6035     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6036     return;
6037   case Intrinsic::log2:
6038     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6039     return;
6040   case Intrinsic::log10:
6041     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6042     return;
6043   case Intrinsic::exp:
6044     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6045     return;
6046   case Intrinsic::exp2:
6047     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6048     return;
6049   case Intrinsic::pow:
6050     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6051                            getValue(I.getArgOperand(1)), DAG, TLI));
6052     return;
6053   case Intrinsic::sqrt:
6054   case Intrinsic::fabs:
6055   case Intrinsic::sin:
6056   case Intrinsic::cos:
6057   case Intrinsic::floor:
6058   case Intrinsic::ceil:
6059   case Intrinsic::trunc:
6060   case Intrinsic::rint:
6061   case Intrinsic::nearbyint:
6062   case Intrinsic::round:
6063   case Intrinsic::canonicalize: {
6064     unsigned Opcode;
6065     switch (Intrinsic) {
6066     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6067     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6068     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6069     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6070     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6071     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6072     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6073     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6074     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6075     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6076     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6077     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6078     }
6079 
6080     setValue(&I, DAG.getNode(Opcode, sdl,
6081                              getValue(I.getArgOperand(0)).getValueType(),
6082                              getValue(I.getArgOperand(0))));
6083     return;
6084   }
6085   case Intrinsic::lround:
6086   case Intrinsic::llround:
6087   case Intrinsic::lrint:
6088   case Intrinsic::llrint: {
6089     unsigned Opcode;
6090     switch (Intrinsic) {
6091     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6092     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6093     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6094     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6095     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6096     }
6097 
6098     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6099     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6100                              getValue(I.getArgOperand(0))));
6101     return;
6102   }
6103   case Intrinsic::minnum:
6104     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6105                              getValue(I.getArgOperand(0)).getValueType(),
6106                              getValue(I.getArgOperand(0)),
6107                              getValue(I.getArgOperand(1))));
6108     return;
6109   case Intrinsic::maxnum:
6110     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6111                              getValue(I.getArgOperand(0)).getValueType(),
6112                              getValue(I.getArgOperand(0)),
6113                              getValue(I.getArgOperand(1))));
6114     return;
6115   case Intrinsic::minimum:
6116     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6117                              getValue(I.getArgOperand(0)).getValueType(),
6118                              getValue(I.getArgOperand(0)),
6119                              getValue(I.getArgOperand(1))));
6120     return;
6121   case Intrinsic::maximum:
6122     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6123                              getValue(I.getArgOperand(0)).getValueType(),
6124                              getValue(I.getArgOperand(0)),
6125                              getValue(I.getArgOperand(1))));
6126     return;
6127   case Intrinsic::copysign:
6128     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6129                              getValue(I.getArgOperand(0)).getValueType(),
6130                              getValue(I.getArgOperand(0)),
6131                              getValue(I.getArgOperand(1))));
6132     return;
6133   case Intrinsic::fma:
6134     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0)),
6137                              getValue(I.getArgOperand(1)),
6138                              getValue(I.getArgOperand(2))));
6139     return;
6140 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6141   case Intrinsic::INTRINSIC:
6142 #include "llvm/IR/ConstrainedOps.def"
6143     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6144     return;
6145   case Intrinsic::fmuladd: {
6146     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6147     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6148         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6149       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6150                                getValue(I.getArgOperand(0)).getValueType(),
6151                                getValue(I.getArgOperand(0)),
6152                                getValue(I.getArgOperand(1)),
6153                                getValue(I.getArgOperand(2))));
6154     } else {
6155       // TODO: Intrinsic calls should have fast-math-flags.
6156       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6157                                 getValue(I.getArgOperand(0)).getValueType(),
6158                                 getValue(I.getArgOperand(0)),
6159                                 getValue(I.getArgOperand(1)));
6160       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6161                                 getValue(I.getArgOperand(0)).getValueType(),
6162                                 Mul,
6163                                 getValue(I.getArgOperand(2)));
6164       setValue(&I, Add);
6165     }
6166     return;
6167   }
6168   case Intrinsic::convert_to_fp16:
6169     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6170                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6171                                          getValue(I.getArgOperand(0)),
6172                                          DAG.getTargetConstant(0, sdl,
6173                                                                MVT::i32))));
6174     return;
6175   case Intrinsic::convert_from_fp16:
6176     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6177                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6178                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6179                                          getValue(I.getArgOperand(0)))));
6180     return;
6181   case Intrinsic::pcmarker: {
6182     SDValue Tmp = getValue(I.getArgOperand(0));
6183     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6184     return;
6185   }
6186   case Intrinsic::readcyclecounter: {
6187     SDValue Op = getRoot();
6188     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6189                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6190     setValue(&I, Res);
6191     DAG.setRoot(Res.getValue(1));
6192     return;
6193   }
6194   case Intrinsic::bitreverse:
6195     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6196                              getValue(I.getArgOperand(0)).getValueType(),
6197                              getValue(I.getArgOperand(0))));
6198     return;
6199   case Intrinsic::bswap:
6200     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6201                              getValue(I.getArgOperand(0)).getValueType(),
6202                              getValue(I.getArgOperand(0))));
6203     return;
6204   case Intrinsic::cttz: {
6205     SDValue Arg = getValue(I.getArgOperand(0));
6206     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6207     EVT Ty = Arg.getValueType();
6208     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6209                              sdl, Ty, Arg));
6210     return;
6211   }
6212   case Intrinsic::ctlz: {
6213     SDValue Arg = getValue(I.getArgOperand(0));
6214     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6215     EVT Ty = Arg.getValueType();
6216     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6217                              sdl, Ty, Arg));
6218     return;
6219   }
6220   case Intrinsic::ctpop: {
6221     SDValue Arg = getValue(I.getArgOperand(0));
6222     EVT Ty = Arg.getValueType();
6223     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6224     return;
6225   }
6226   case Intrinsic::fshl:
6227   case Intrinsic::fshr: {
6228     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6229     SDValue X = getValue(I.getArgOperand(0));
6230     SDValue Y = getValue(I.getArgOperand(1));
6231     SDValue Z = getValue(I.getArgOperand(2));
6232     EVT VT = X.getValueType();
6233     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6234     SDValue Zero = DAG.getConstant(0, sdl, VT);
6235     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6236 
6237     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6238     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6239       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6240       return;
6241     }
6242 
6243     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6244     // avoid the select that is necessary in the general case to filter out
6245     // the 0-shift possibility that leads to UB.
6246     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6247       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6248       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6249         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6250         return;
6251       }
6252 
6253       // Some targets only rotate one way. Try the opposite direction.
6254       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6255       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6256         // Negate the shift amount because it is safe to ignore the high bits.
6257         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6258         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6259         return;
6260       }
6261 
6262       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6263       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6264       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6265       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6266       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6267       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6268       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6269       return;
6270     }
6271 
6272     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6273     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6274     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6275     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6276     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6277     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6278 
6279     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6280     // and that is undefined. We must compare and select to avoid UB.
6281     EVT CCVT = MVT::i1;
6282     if (VT.isVector())
6283       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6284 
6285     // For fshl, 0-shift returns the 1st arg (X).
6286     // For fshr, 0-shift returns the 2nd arg (Y).
6287     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6288     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6289     return;
6290   }
6291   case Intrinsic::sadd_sat: {
6292     SDValue Op1 = getValue(I.getArgOperand(0));
6293     SDValue Op2 = getValue(I.getArgOperand(1));
6294     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6295     return;
6296   }
6297   case Intrinsic::uadd_sat: {
6298     SDValue Op1 = getValue(I.getArgOperand(0));
6299     SDValue Op2 = getValue(I.getArgOperand(1));
6300     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6301     return;
6302   }
6303   case Intrinsic::ssub_sat: {
6304     SDValue Op1 = getValue(I.getArgOperand(0));
6305     SDValue Op2 = getValue(I.getArgOperand(1));
6306     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6307     return;
6308   }
6309   case Intrinsic::usub_sat: {
6310     SDValue Op1 = getValue(I.getArgOperand(0));
6311     SDValue Op2 = getValue(I.getArgOperand(1));
6312     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6313     return;
6314   }
6315   case Intrinsic::smul_fix:
6316   case Intrinsic::umul_fix: {
6317     SDValue Op1 = getValue(I.getArgOperand(0));
6318     SDValue Op2 = getValue(I.getArgOperand(1));
6319     SDValue Op3 = getValue(I.getArgOperand(2));
6320     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6321                              Op1.getValueType(), Op1, Op2, Op3));
6322     return;
6323   }
6324   case Intrinsic::smul_fix_sat: {
6325     SDValue Op1 = getValue(I.getArgOperand(0));
6326     SDValue Op2 = getValue(I.getArgOperand(1));
6327     SDValue Op3 = getValue(I.getArgOperand(2));
6328     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6329                              Op3));
6330     return;
6331   }
6332   case Intrinsic::umul_fix_sat: {
6333     SDValue Op1 = getValue(I.getArgOperand(0));
6334     SDValue Op2 = getValue(I.getArgOperand(1));
6335     SDValue Op3 = getValue(I.getArgOperand(2));
6336     setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6337                              Op3));
6338     return;
6339   }
6340   case Intrinsic::stacksave: {
6341     SDValue Op = getRoot();
6342     Res = DAG.getNode(
6343         ISD::STACKSAVE, sdl,
6344         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6345     setValue(&I, Res);
6346     DAG.setRoot(Res.getValue(1));
6347     return;
6348   }
6349   case Intrinsic::stackrestore:
6350     Res = getValue(I.getArgOperand(0));
6351     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6352     return;
6353   case Intrinsic::get_dynamic_area_offset: {
6354     SDValue Op = getRoot();
6355     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6356     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6357     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6358     // target.
6359     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6360       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6361                          " intrinsic!");
6362     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6363                       Op);
6364     DAG.setRoot(Op);
6365     setValue(&I, Res);
6366     return;
6367   }
6368   case Intrinsic::stackguard: {
6369     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6370     MachineFunction &MF = DAG.getMachineFunction();
6371     const Module &M = *MF.getFunction().getParent();
6372     SDValue Chain = getRoot();
6373     if (TLI.useLoadStackGuardNode()) {
6374       Res = getLoadStackGuard(DAG, sdl, Chain);
6375     } else {
6376       const Value *Global = TLI.getSDagStackGuard(M);
6377       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6378       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6379                         MachinePointerInfo(Global, 0), Align,
6380                         MachineMemOperand::MOVolatile);
6381     }
6382     if (TLI.useStackGuardXorFP())
6383       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6384     DAG.setRoot(Chain);
6385     setValue(&I, Res);
6386     return;
6387   }
6388   case Intrinsic::stackprotector: {
6389     // Emit code into the DAG to store the stack guard onto the stack.
6390     MachineFunction &MF = DAG.getMachineFunction();
6391     MachineFrameInfo &MFI = MF.getFrameInfo();
6392     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6393     SDValue Src, Chain = getRoot();
6394 
6395     if (TLI.useLoadStackGuardNode())
6396       Src = getLoadStackGuard(DAG, sdl, Chain);
6397     else
6398       Src = getValue(I.getArgOperand(0));   // The guard's value.
6399 
6400     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6401 
6402     int FI = FuncInfo.StaticAllocaMap[Slot];
6403     MFI.setStackProtectorIndex(FI);
6404 
6405     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6406 
6407     // Store the stack protector onto the stack.
6408     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6409                                                  DAG.getMachineFunction(), FI),
6410                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6411     setValue(&I, Res);
6412     DAG.setRoot(Res);
6413     return;
6414   }
6415   case Intrinsic::objectsize:
6416     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6417 
6418   case Intrinsic::is_constant:
6419     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6420 
6421   case Intrinsic::annotation:
6422   case Intrinsic::ptr_annotation:
6423   case Intrinsic::launder_invariant_group:
6424   case Intrinsic::strip_invariant_group:
6425     // Drop the intrinsic, but forward the value
6426     setValue(&I, getValue(I.getOperand(0)));
6427     return;
6428   case Intrinsic::assume:
6429   case Intrinsic::var_annotation:
6430   case Intrinsic::sideeffect:
6431     // Discard annotate attributes, assumptions, and artificial side-effects.
6432     return;
6433 
6434   case Intrinsic::codeview_annotation: {
6435     // Emit a label associated with this metadata.
6436     MachineFunction &MF = DAG.getMachineFunction();
6437     MCSymbol *Label =
6438         MF.getMMI().getContext().createTempSymbol("annotation", true);
6439     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6440     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6441     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6442     DAG.setRoot(Res);
6443     return;
6444   }
6445 
6446   case Intrinsic::init_trampoline: {
6447     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6448 
6449     SDValue Ops[6];
6450     Ops[0] = getRoot();
6451     Ops[1] = getValue(I.getArgOperand(0));
6452     Ops[2] = getValue(I.getArgOperand(1));
6453     Ops[3] = getValue(I.getArgOperand(2));
6454     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6455     Ops[5] = DAG.getSrcValue(F);
6456 
6457     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6458 
6459     DAG.setRoot(Res);
6460     return;
6461   }
6462   case Intrinsic::adjust_trampoline:
6463     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6464                              TLI.getPointerTy(DAG.getDataLayout()),
6465                              getValue(I.getArgOperand(0))));
6466     return;
6467   case Intrinsic::gcroot: {
6468     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6469            "only valid in functions with gc specified, enforced by Verifier");
6470     assert(GFI && "implied by previous");
6471     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6472     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6473 
6474     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6475     GFI->addStackRoot(FI->getIndex(), TypeMap);
6476     return;
6477   }
6478   case Intrinsic::gcread:
6479   case Intrinsic::gcwrite:
6480     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6481   case Intrinsic::flt_rounds:
6482     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6483     return;
6484 
6485   case Intrinsic::expect:
6486     // Just replace __builtin_expect(exp, c) with EXP.
6487     setValue(&I, getValue(I.getArgOperand(0)));
6488     return;
6489 
6490   case Intrinsic::debugtrap:
6491   case Intrinsic::trap: {
6492     StringRef TrapFuncName =
6493         I.getAttributes()
6494             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6495             .getValueAsString();
6496     if (TrapFuncName.empty()) {
6497       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6498         ISD::TRAP : ISD::DEBUGTRAP;
6499       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6500       return;
6501     }
6502     TargetLowering::ArgListTy Args;
6503 
6504     TargetLowering::CallLoweringInfo CLI(DAG);
6505     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6506         CallingConv::C, I.getType(),
6507         DAG.getExternalSymbol(TrapFuncName.data(),
6508                               TLI.getPointerTy(DAG.getDataLayout())),
6509         std::move(Args));
6510 
6511     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6512     DAG.setRoot(Result.second);
6513     return;
6514   }
6515 
6516   case Intrinsic::uadd_with_overflow:
6517   case Intrinsic::sadd_with_overflow:
6518   case Intrinsic::usub_with_overflow:
6519   case Intrinsic::ssub_with_overflow:
6520   case Intrinsic::umul_with_overflow:
6521   case Intrinsic::smul_with_overflow: {
6522     ISD::NodeType Op;
6523     switch (Intrinsic) {
6524     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6525     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6526     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6527     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6528     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6529     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6530     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6531     }
6532     SDValue Op1 = getValue(I.getArgOperand(0));
6533     SDValue Op2 = getValue(I.getArgOperand(1));
6534 
6535     EVT ResultVT = Op1.getValueType();
6536     EVT OverflowVT = MVT::i1;
6537     if (ResultVT.isVector())
6538       OverflowVT = EVT::getVectorVT(
6539           *Context, OverflowVT, ResultVT.getVectorNumElements());
6540 
6541     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6542     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6543     return;
6544   }
6545   case Intrinsic::prefetch: {
6546     SDValue Ops[5];
6547     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6548     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6549     Ops[0] = DAG.getRoot();
6550     Ops[1] = getValue(I.getArgOperand(0));
6551     Ops[2] = getValue(I.getArgOperand(1));
6552     Ops[3] = getValue(I.getArgOperand(2));
6553     Ops[4] = getValue(I.getArgOperand(3));
6554     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6555                                              DAG.getVTList(MVT::Other), Ops,
6556                                              EVT::getIntegerVT(*Context, 8),
6557                                              MachinePointerInfo(I.getArgOperand(0)),
6558                                              0, /* align */
6559                                              Flags);
6560 
6561     // Chain the prefetch in parallell with any pending loads, to stay out of
6562     // the way of later optimizations.
6563     PendingLoads.push_back(Result);
6564     Result = getRoot();
6565     DAG.setRoot(Result);
6566     return;
6567   }
6568   case Intrinsic::lifetime_start:
6569   case Intrinsic::lifetime_end: {
6570     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6571     // Stack coloring is not enabled in O0, discard region information.
6572     if (TM.getOptLevel() == CodeGenOpt::None)
6573       return;
6574 
6575     const int64_t ObjectSize =
6576         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6577     Value *const ObjectPtr = I.getArgOperand(1);
6578     SmallVector<const Value *, 4> Allocas;
6579     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6580 
6581     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6582            E = Allocas.end(); Object != E; ++Object) {
6583       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6584 
6585       // Could not find an Alloca.
6586       if (!LifetimeObject)
6587         continue;
6588 
6589       // First check that the Alloca is static, otherwise it won't have a
6590       // valid frame index.
6591       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6592       if (SI == FuncInfo.StaticAllocaMap.end())
6593         return;
6594 
6595       const int FrameIndex = SI->second;
6596       int64_t Offset;
6597       if (GetPointerBaseWithConstantOffset(
6598               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6599         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6600       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6601                                 Offset);
6602       DAG.setRoot(Res);
6603     }
6604     return;
6605   }
6606   case Intrinsic::invariant_start:
6607     // Discard region information.
6608     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6609     return;
6610   case Intrinsic::invariant_end:
6611     // Discard region information.
6612     return;
6613   case Intrinsic::clear_cache:
6614     /// FunctionName may be null.
6615     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6616       lowerCallToExternalSymbol(I, FunctionName);
6617     return;
6618   case Intrinsic::donothing:
6619     // ignore
6620     return;
6621   case Intrinsic::experimental_stackmap:
6622     visitStackmap(I);
6623     return;
6624   case Intrinsic::experimental_patchpoint_void:
6625   case Intrinsic::experimental_patchpoint_i64:
6626     visitPatchpoint(&I);
6627     return;
6628   case Intrinsic::experimental_gc_statepoint:
6629     LowerStatepoint(ImmutableStatepoint(&I));
6630     return;
6631   case Intrinsic::experimental_gc_result:
6632     visitGCResult(cast<GCResultInst>(I));
6633     return;
6634   case Intrinsic::experimental_gc_relocate:
6635     visitGCRelocate(cast<GCRelocateInst>(I));
6636     return;
6637   case Intrinsic::instrprof_increment:
6638     llvm_unreachable("instrprof failed to lower an increment");
6639   case Intrinsic::instrprof_value_profile:
6640     llvm_unreachable("instrprof failed to lower a value profiling call");
6641   case Intrinsic::localescape: {
6642     MachineFunction &MF = DAG.getMachineFunction();
6643     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6644 
6645     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6646     // is the same on all targets.
6647     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6648       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6649       if (isa<ConstantPointerNull>(Arg))
6650         continue; // Skip null pointers. They represent a hole in index space.
6651       AllocaInst *Slot = cast<AllocaInst>(Arg);
6652       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6653              "can only escape static allocas");
6654       int FI = FuncInfo.StaticAllocaMap[Slot];
6655       MCSymbol *FrameAllocSym =
6656           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6657               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6658       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6659               TII->get(TargetOpcode::LOCAL_ESCAPE))
6660           .addSym(FrameAllocSym)
6661           .addFrameIndex(FI);
6662     }
6663 
6664     return;
6665   }
6666 
6667   case Intrinsic::localrecover: {
6668     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6669     MachineFunction &MF = DAG.getMachineFunction();
6670     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6671 
6672     // Get the symbol that defines the frame offset.
6673     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6674     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6675     unsigned IdxVal =
6676         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6677     MCSymbol *FrameAllocSym =
6678         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6679             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6680 
6681     // Create a MCSymbol for the label to avoid any target lowering
6682     // that would make this PC relative.
6683     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6684     SDValue OffsetVal =
6685         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6686 
6687     // Add the offset to the FP.
6688     Value *FP = I.getArgOperand(1);
6689     SDValue FPVal = getValue(FP);
6690     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6691     setValue(&I, Add);
6692 
6693     return;
6694   }
6695 
6696   case Intrinsic::eh_exceptionpointer:
6697   case Intrinsic::eh_exceptioncode: {
6698     // Get the exception pointer vreg, copy from it, and resize it to fit.
6699     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6700     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6701     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6702     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6703     SDValue N =
6704         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6705     if (Intrinsic == Intrinsic::eh_exceptioncode)
6706       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6707     setValue(&I, N);
6708     return;
6709   }
6710   case Intrinsic::xray_customevent: {
6711     // Here we want to make sure that the intrinsic behaves as if it has a
6712     // specific calling convention, and only for x86_64.
6713     // FIXME: Support other platforms later.
6714     const auto &Triple = DAG.getTarget().getTargetTriple();
6715     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6716       return;
6717 
6718     SDLoc DL = getCurSDLoc();
6719     SmallVector<SDValue, 8> Ops;
6720 
6721     // We want to say that we always want the arguments in registers.
6722     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6723     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6724     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6725     SDValue Chain = getRoot();
6726     Ops.push_back(LogEntryVal);
6727     Ops.push_back(StrSizeVal);
6728     Ops.push_back(Chain);
6729 
6730     // We need to enforce the calling convention for the callsite, so that
6731     // argument ordering is enforced correctly, and that register allocation can
6732     // see that some registers may be assumed clobbered and have to preserve
6733     // them across calls to the intrinsic.
6734     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6735                                            DL, NodeTys, Ops);
6736     SDValue patchableNode = SDValue(MN, 0);
6737     DAG.setRoot(patchableNode);
6738     setValue(&I, patchableNode);
6739     return;
6740   }
6741   case Intrinsic::xray_typedevent: {
6742     // Here we want to make sure that the intrinsic behaves as if it has a
6743     // specific calling convention, and only for x86_64.
6744     // FIXME: Support other platforms later.
6745     const auto &Triple = DAG.getTarget().getTargetTriple();
6746     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6747       return;
6748 
6749     SDLoc DL = getCurSDLoc();
6750     SmallVector<SDValue, 8> Ops;
6751 
6752     // We want to say that we always want the arguments in registers.
6753     // It's unclear to me how manipulating the selection DAG here forces callers
6754     // to provide arguments in registers instead of on the stack.
6755     SDValue LogTypeId = getValue(I.getArgOperand(0));
6756     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6757     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6758     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6759     SDValue Chain = getRoot();
6760     Ops.push_back(LogTypeId);
6761     Ops.push_back(LogEntryVal);
6762     Ops.push_back(StrSizeVal);
6763     Ops.push_back(Chain);
6764 
6765     // We need to enforce the calling convention for the callsite, so that
6766     // argument ordering is enforced correctly, and that register allocation can
6767     // see that some registers may be assumed clobbered and have to preserve
6768     // them across calls to the intrinsic.
6769     MachineSDNode *MN = DAG.getMachineNode(
6770         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6771     SDValue patchableNode = SDValue(MN, 0);
6772     DAG.setRoot(patchableNode);
6773     setValue(&I, patchableNode);
6774     return;
6775   }
6776   case Intrinsic::experimental_deoptimize:
6777     LowerDeoptimizeCall(&I);
6778     return;
6779 
6780   case Intrinsic::experimental_vector_reduce_v2_fadd:
6781   case Intrinsic::experimental_vector_reduce_v2_fmul:
6782   case Intrinsic::experimental_vector_reduce_add:
6783   case Intrinsic::experimental_vector_reduce_mul:
6784   case Intrinsic::experimental_vector_reduce_and:
6785   case Intrinsic::experimental_vector_reduce_or:
6786   case Intrinsic::experimental_vector_reduce_xor:
6787   case Intrinsic::experimental_vector_reduce_smax:
6788   case Intrinsic::experimental_vector_reduce_smin:
6789   case Intrinsic::experimental_vector_reduce_umax:
6790   case Intrinsic::experimental_vector_reduce_umin:
6791   case Intrinsic::experimental_vector_reduce_fmax:
6792   case Intrinsic::experimental_vector_reduce_fmin:
6793     visitVectorReduce(I, Intrinsic);
6794     return;
6795 
6796   case Intrinsic::icall_branch_funnel: {
6797     SmallVector<SDValue, 16> Ops;
6798     Ops.push_back(getValue(I.getArgOperand(0)));
6799 
6800     int64_t Offset;
6801     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6802         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6803     if (!Base)
6804       report_fatal_error(
6805           "llvm.icall.branch.funnel operand must be a GlobalValue");
6806     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6807 
6808     struct BranchFunnelTarget {
6809       int64_t Offset;
6810       SDValue Target;
6811     };
6812     SmallVector<BranchFunnelTarget, 8> Targets;
6813 
6814     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6815       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6816           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6817       if (ElemBase != Base)
6818         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6819                            "to the same GlobalValue");
6820 
6821       SDValue Val = getValue(I.getArgOperand(Op + 1));
6822       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6823       if (!GA)
6824         report_fatal_error(
6825             "llvm.icall.branch.funnel operand must be a GlobalValue");
6826       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6827                                      GA->getGlobal(), getCurSDLoc(),
6828                                      Val.getValueType(), GA->getOffset())});
6829     }
6830     llvm::sort(Targets,
6831                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6832                  return T1.Offset < T2.Offset;
6833                });
6834 
6835     for (auto &T : Targets) {
6836       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6837       Ops.push_back(T.Target);
6838     }
6839 
6840     Ops.push_back(DAG.getRoot()); // Chain
6841     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6842                                  getCurSDLoc(), MVT::Other, Ops),
6843               0);
6844     DAG.setRoot(N);
6845     setValue(&I, N);
6846     HasTailCall = true;
6847     return;
6848   }
6849 
6850   case Intrinsic::wasm_landingpad_index:
6851     // Information this intrinsic contained has been transferred to
6852     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6853     // delete it now.
6854     return;
6855 
6856   case Intrinsic::aarch64_settag:
6857   case Intrinsic::aarch64_settag_zero: {
6858     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6859     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6860     SDValue Val = TSI.EmitTargetCodeForSetTag(
6861         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6862         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6863         ZeroMemory);
6864     DAG.setRoot(Val);
6865     setValue(&I, Val);
6866     return;
6867   }
6868   case Intrinsic::ptrmask: {
6869     SDValue Ptr = getValue(I.getOperand(0));
6870     SDValue Const = getValue(I.getOperand(1));
6871 
6872     EVT DestVT =
6873         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6874 
6875     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6876                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6877     return;
6878   }
6879   }
6880 }
6881 
6882 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6883     const ConstrainedFPIntrinsic &FPI) {
6884   SDLoc sdl = getCurSDLoc();
6885 
6886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6887   SmallVector<EVT, 4> ValueVTs;
6888   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6889   ValueVTs.push_back(MVT::Other); // Out chain
6890 
6891   // We do not need to serialize constrained FP intrinsics against
6892   // each other or against (nonvolatile) loads, so they can be
6893   // chained like loads.
6894   SDValue Chain = DAG.getRoot();
6895   SmallVector<SDValue, 4> Opers;
6896   Opers.push_back(Chain);
6897   if (FPI.isUnaryOp()) {
6898     Opers.push_back(getValue(FPI.getArgOperand(0)));
6899   } else if (FPI.isTernaryOp()) {
6900     Opers.push_back(getValue(FPI.getArgOperand(0)));
6901     Opers.push_back(getValue(FPI.getArgOperand(1)));
6902     Opers.push_back(getValue(FPI.getArgOperand(2)));
6903   } else {
6904     Opers.push_back(getValue(FPI.getArgOperand(0)));
6905     Opers.push_back(getValue(FPI.getArgOperand(1)));
6906   }
6907 
6908   unsigned Opcode;
6909   switch (FPI.getIntrinsicID()) {
6910   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6911 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6912   case Intrinsic::INTRINSIC:                                                   \
6913     Opcode = ISD::STRICT_##DAGN;                                               \
6914     break;
6915 #include "llvm/IR/ConstrainedOps.def"
6916   }
6917 
6918   // A few strict DAG nodes carry additional operands that are not
6919   // set up by the default code above.
6920   switch (Opcode) {
6921   default: break;
6922   case ISD::STRICT_FP_ROUND:
6923     Opers.push_back(
6924         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6925     break;
6926   case ISD::STRICT_FSETCC:
6927   case ISD::STRICT_FSETCCS: {
6928     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6929     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6930     break;
6931   }
6932   }
6933 
6934   SDVTList VTs = DAG.getVTList(ValueVTs);
6935   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
6936 
6937   if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) {
6938     SDNodeFlags Flags;
6939     Flags.setFPExcept(true);
6940     Result->setFlags(Flags);
6941   }
6942 
6943   assert(Result.getNode()->getNumValues() == 2);
6944   // See above -- chain is handled like for loads here.
6945   SDValue OutChain = Result.getValue(1);
6946   PendingLoads.push_back(OutChain);
6947   SDValue FPResult = Result.getValue(0);
6948   setValue(&FPI, FPResult);
6949 }
6950 
6951 std::pair<SDValue, SDValue>
6952 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6953                                     const BasicBlock *EHPadBB) {
6954   MachineFunction &MF = DAG.getMachineFunction();
6955   MachineModuleInfo &MMI = MF.getMMI();
6956   MCSymbol *BeginLabel = nullptr;
6957 
6958   if (EHPadBB) {
6959     // Insert a label before the invoke call to mark the try range.  This can be
6960     // used to detect deletion of the invoke via the MachineModuleInfo.
6961     BeginLabel = MMI.getContext().createTempSymbol();
6962 
6963     // For SjLj, keep track of which landing pads go with which invokes
6964     // so as to maintain the ordering of pads in the LSDA.
6965     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6966     if (CallSiteIndex) {
6967       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6968       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6969 
6970       // Now that the call site is handled, stop tracking it.
6971       MMI.setCurrentCallSite(0);
6972     }
6973 
6974     // Both PendingLoads and PendingExports must be flushed here;
6975     // this call might not return.
6976     (void)getRoot();
6977     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6978 
6979     CLI.setChain(getRoot());
6980   }
6981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6982   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6983 
6984   assert((CLI.IsTailCall || Result.second.getNode()) &&
6985          "Non-null chain expected with non-tail call!");
6986   assert((Result.second.getNode() || !Result.first.getNode()) &&
6987          "Null value expected with tail call!");
6988 
6989   if (!Result.second.getNode()) {
6990     // As a special case, a null chain means that a tail call has been emitted
6991     // and the DAG root is already updated.
6992     HasTailCall = true;
6993 
6994     // Since there's no actual continuation from this block, nothing can be
6995     // relying on us setting vregs for them.
6996     PendingExports.clear();
6997   } else {
6998     DAG.setRoot(Result.second);
6999   }
7000 
7001   if (EHPadBB) {
7002     // Insert a label at the end of the invoke call to mark the try range.  This
7003     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7004     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7005     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7006 
7007     // Inform MachineModuleInfo of range.
7008     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7009     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7010     // actually use outlined funclets and their LSDA info style.
7011     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7012       assert(CLI.CS);
7013       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7014       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7015                                 BeginLabel, EndLabel);
7016     } else if (!isScopedEHPersonality(Pers)) {
7017       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7018     }
7019   }
7020 
7021   return Result;
7022 }
7023 
7024 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7025                                       bool isTailCall,
7026                                       const BasicBlock *EHPadBB) {
7027   auto &DL = DAG.getDataLayout();
7028   FunctionType *FTy = CS.getFunctionType();
7029   Type *RetTy = CS.getType();
7030 
7031   TargetLowering::ArgListTy Args;
7032   Args.reserve(CS.arg_size());
7033 
7034   const Value *SwiftErrorVal = nullptr;
7035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7036 
7037   // We can't tail call inside a function with a swifterror argument. Lowering
7038   // does not support this yet. It would have to move into the swifterror
7039   // register before the call.
7040   auto *Caller = CS.getInstruction()->getParent()->getParent();
7041   if (TLI.supportSwiftError() &&
7042       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7043     isTailCall = false;
7044 
7045   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7046        i != e; ++i) {
7047     TargetLowering::ArgListEntry Entry;
7048     const Value *V = *i;
7049 
7050     // Skip empty types
7051     if (V->getType()->isEmptyTy())
7052       continue;
7053 
7054     SDValue ArgNode = getValue(V);
7055     Entry.Node = ArgNode; Entry.Ty = V->getType();
7056 
7057     Entry.setAttributes(&CS, i - CS.arg_begin());
7058 
7059     // Use swifterror virtual register as input to the call.
7060     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7061       SwiftErrorVal = V;
7062       // We find the virtual register for the actual swifterror argument.
7063       // Instead of using the Value, we use the virtual register instead.
7064       Entry.Node = DAG.getRegister(
7065           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7066           EVT(TLI.getPointerTy(DL)));
7067     }
7068 
7069     Args.push_back(Entry);
7070 
7071     // If we have an explicit sret argument that is an Instruction, (i.e., it
7072     // might point to function-local memory), we can't meaningfully tail-call.
7073     if (Entry.IsSRet && isa<Instruction>(V))
7074       isTailCall = false;
7075   }
7076 
7077   // If call site has a cfguardtarget operand bundle, create and add an
7078   // additional ArgListEntry.
7079   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7080     TargetLowering::ArgListEntry Entry;
7081     Value *V = Bundle->Inputs[0];
7082     SDValue ArgNode = getValue(V);
7083     Entry.Node = ArgNode;
7084     Entry.Ty = V->getType();
7085     Entry.IsCFGuardTarget = true;
7086     Args.push_back(Entry);
7087   }
7088 
7089   // Check if target-independent constraints permit a tail call here.
7090   // Target-dependent constraints are checked within TLI->LowerCallTo.
7091   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7092     isTailCall = false;
7093 
7094   // Disable tail calls if there is an swifterror argument. Targets have not
7095   // been updated to support tail calls.
7096   if (TLI.supportSwiftError() && SwiftErrorVal)
7097     isTailCall = false;
7098 
7099   TargetLowering::CallLoweringInfo CLI(DAG);
7100   CLI.setDebugLoc(getCurSDLoc())
7101       .setChain(getRoot())
7102       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7103       .setTailCall(isTailCall)
7104       .setConvergent(CS.isConvergent());
7105   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7106 
7107   if (Result.first.getNode()) {
7108     const Instruction *Inst = CS.getInstruction();
7109     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7110     setValue(Inst, Result.first);
7111   }
7112 
7113   // The last element of CLI.InVals has the SDValue for swifterror return.
7114   // Here we copy it to a virtual register and update SwiftErrorMap for
7115   // book-keeping.
7116   if (SwiftErrorVal && TLI.supportSwiftError()) {
7117     // Get the last element of InVals.
7118     SDValue Src = CLI.InVals.back();
7119     Register VReg = SwiftError.getOrCreateVRegDefAt(
7120         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7121     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7122     DAG.setRoot(CopyNode);
7123   }
7124 }
7125 
7126 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7127                              SelectionDAGBuilder &Builder) {
7128   // Check to see if this load can be trivially constant folded, e.g. if the
7129   // input is from a string literal.
7130   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7131     // Cast pointer to the type we really want to load.
7132     Type *LoadTy =
7133         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7134     if (LoadVT.isVector())
7135       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7136 
7137     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7138                                          PointerType::getUnqual(LoadTy));
7139 
7140     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7141             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7142       return Builder.getValue(LoadCst);
7143   }
7144 
7145   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7146   // still constant memory, the input chain can be the entry node.
7147   SDValue Root;
7148   bool ConstantMemory = false;
7149 
7150   // Do not serialize (non-volatile) loads of constant memory with anything.
7151   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7152     Root = Builder.DAG.getEntryNode();
7153     ConstantMemory = true;
7154   } else {
7155     // Do not serialize non-volatile loads against each other.
7156     Root = Builder.DAG.getRoot();
7157   }
7158 
7159   SDValue Ptr = Builder.getValue(PtrVal);
7160   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7161                                         Ptr, MachinePointerInfo(PtrVal),
7162                                         /* Alignment = */ 1);
7163 
7164   if (!ConstantMemory)
7165     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7166   return LoadVal;
7167 }
7168 
7169 /// Record the value for an instruction that produces an integer result,
7170 /// converting the type where necessary.
7171 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7172                                                   SDValue Value,
7173                                                   bool IsSigned) {
7174   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7175                                                     I.getType(), true);
7176   if (IsSigned)
7177     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7178   else
7179     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7180   setValue(&I, Value);
7181 }
7182 
7183 /// See if we can lower a memcmp call into an optimized form. If so, return
7184 /// true and lower it. Otherwise return false, and it will be lowered like a
7185 /// normal call.
7186 /// The caller already checked that \p I calls the appropriate LibFunc with a
7187 /// correct prototype.
7188 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7189   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7190   const Value *Size = I.getArgOperand(2);
7191   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7192   if (CSize && CSize->getZExtValue() == 0) {
7193     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7194                                                           I.getType(), true);
7195     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7196     return true;
7197   }
7198 
7199   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7200   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7201       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7202       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7203   if (Res.first.getNode()) {
7204     processIntegerCallValue(I, Res.first, true);
7205     PendingLoads.push_back(Res.second);
7206     return true;
7207   }
7208 
7209   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7210   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7211   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7212     return false;
7213 
7214   // If the target has a fast compare for the given size, it will return a
7215   // preferred load type for that size. Require that the load VT is legal and
7216   // that the target supports unaligned loads of that type. Otherwise, return
7217   // INVALID.
7218   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7219     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7220     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7221     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7222       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7223       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7224       // TODO: Check alignment of src and dest ptrs.
7225       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7226       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7227       if (!TLI.isTypeLegal(LVT) ||
7228           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7229           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7230         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7231     }
7232 
7233     return LVT;
7234   };
7235 
7236   // This turns into unaligned loads. We only do this if the target natively
7237   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7238   // we'll only produce a small number of byte loads.
7239   MVT LoadVT;
7240   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7241   switch (NumBitsToCompare) {
7242   default:
7243     return false;
7244   case 16:
7245     LoadVT = MVT::i16;
7246     break;
7247   case 32:
7248     LoadVT = MVT::i32;
7249     break;
7250   case 64:
7251   case 128:
7252   case 256:
7253     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7254     break;
7255   }
7256 
7257   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7258     return false;
7259 
7260   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7261   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7262 
7263   // Bitcast to a wide integer type if the loads are vectors.
7264   if (LoadVT.isVector()) {
7265     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7266     LoadL = DAG.getBitcast(CmpVT, LoadL);
7267     LoadR = DAG.getBitcast(CmpVT, LoadR);
7268   }
7269 
7270   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7271   processIntegerCallValue(I, Cmp, false);
7272   return true;
7273 }
7274 
7275 /// See if we can lower a memchr call into an optimized form. If so, return
7276 /// true and lower it. Otherwise return false, and it will be lowered like a
7277 /// normal call.
7278 /// The caller already checked that \p I calls the appropriate LibFunc with a
7279 /// correct prototype.
7280 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7281   const Value *Src = I.getArgOperand(0);
7282   const Value *Char = I.getArgOperand(1);
7283   const Value *Length = I.getArgOperand(2);
7284 
7285   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7286   std::pair<SDValue, SDValue> Res =
7287     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7288                                 getValue(Src), getValue(Char), getValue(Length),
7289                                 MachinePointerInfo(Src));
7290   if (Res.first.getNode()) {
7291     setValue(&I, Res.first);
7292     PendingLoads.push_back(Res.second);
7293     return true;
7294   }
7295 
7296   return false;
7297 }
7298 
7299 /// See if we can lower a mempcpy call into an optimized form. If so, return
7300 /// true and lower it. Otherwise return false, and it will be lowered like a
7301 /// normal call.
7302 /// The caller already checked that \p I calls the appropriate LibFunc with a
7303 /// correct prototype.
7304 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7305   SDValue Dst = getValue(I.getArgOperand(0));
7306   SDValue Src = getValue(I.getArgOperand(1));
7307   SDValue Size = getValue(I.getArgOperand(2));
7308 
7309   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7310   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7311   unsigned Align = std::min(DstAlign, SrcAlign);
7312   if (Align == 0) // Alignment of one or both could not be inferred.
7313     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7314 
7315   bool isVol = false;
7316   SDLoc sdl = getCurSDLoc();
7317 
7318   // In the mempcpy context we need to pass in a false value for isTailCall
7319   // because the return pointer needs to be adjusted by the size of
7320   // the copied memory.
7321   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7322                              false, /*isTailCall=*/false,
7323                              MachinePointerInfo(I.getArgOperand(0)),
7324                              MachinePointerInfo(I.getArgOperand(1)));
7325   assert(MC.getNode() != nullptr &&
7326          "** memcpy should not be lowered as TailCall in mempcpy context **");
7327   DAG.setRoot(MC);
7328 
7329   // Check if Size needs to be truncated or extended.
7330   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7331 
7332   // Adjust return pointer to point just past the last dst byte.
7333   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7334                                     Dst, Size);
7335   setValue(&I, DstPlusSize);
7336   return true;
7337 }
7338 
7339 /// See if we can lower a strcpy call into an optimized form.  If so, return
7340 /// true and lower it, otherwise return false and it will be lowered like a
7341 /// normal call.
7342 /// The caller already checked that \p I calls the appropriate LibFunc with a
7343 /// correct prototype.
7344 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7345   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7346 
7347   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7348   std::pair<SDValue, SDValue> Res =
7349     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7350                                 getValue(Arg0), getValue(Arg1),
7351                                 MachinePointerInfo(Arg0),
7352                                 MachinePointerInfo(Arg1), isStpcpy);
7353   if (Res.first.getNode()) {
7354     setValue(&I, Res.first);
7355     DAG.setRoot(Res.second);
7356     return true;
7357   }
7358 
7359   return false;
7360 }
7361 
7362 /// See if we can lower a strcmp call into an optimized form.  If so, return
7363 /// true and lower it, otherwise return false and it will be lowered like a
7364 /// normal call.
7365 /// The caller already checked that \p I calls the appropriate LibFunc with a
7366 /// correct prototype.
7367 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7368   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7369 
7370   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7371   std::pair<SDValue, SDValue> Res =
7372     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7373                                 getValue(Arg0), getValue(Arg1),
7374                                 MachinePointerInfo(Arg0),
7375                                 MachinePointerInfo(Arg1));
7376   if (Res.first.getNode()) {
7377     processIntegerCallValue(I, Res.first, true);
7378     PendingLoads.push_back(Res.second);
7379     return true;
7380   }
7381 
7382   return false;
7383 }
7384 
7385 /// See if we can lower a strlen call into an optimized form.  If so, return
7386 /// true and lower it, otherwise return false and it will be lowered like a
7387 /// normal call.
7388 /// The caller already checked that \p I calls the appropriate LibFunc with a
7389 /// correct prototype.
7390 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7391   const Value *Arg0 = I.getArgOperand(0);
7392 
7393   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7394   std::pair<SDValue, SDValue> Res =
7395     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7396                                 getValue(Arg0), MachinePointerInfo(Arg0));
7397   if (Res.first.getNode()) {
7398     processIntegerCallValue(I, Res.first, false);
7399     PendingLoads.push_back(Res.second);
7400     return true;
7401   }
7402 
7403   return false;
7404 }
7405 
7406 /// See if we can lower a strnlen call into an optimized form.  If so, return
7407 /// true and lower it, otherwise return false and it will be lowered like a
7408 /// normal call.
7409 /// The caller already checked that \p I calls the appropriate LibFunc with a
7410 /// correct prototype.
7411 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7412   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7413 
7414   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7415   std::pair<SDValue, SDValue> Res =
7416     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7417                                  getValue(Arg0), getValue(Arg1),
7418                                  MachinePointerInfo(Arg0));
7419   if (Res.first.getNode()) {
7420     processIntegerCallValue(I, Res.first, false);
7421     PendingLoads.push_back(Res.second);
7422     return true;
7423   }
7424 
7425   return false;
7426 }
7427 
7428 /// See if we can lower a unary floating-point operation into an SDNode with
7429 /// the specified Opcode.  If so, return true and lower it, otherwise return
7430 /// false and it will be lowered like a normal call.
7431 /// The caller already checked that \p I calls the appropriate LibFunc with a
7432 /// correct prototype.
7433 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7434                                               unsigned Opcode) {
7435   // We already checked this call's prototype; verify it doesn't modify errno.
7436   if (!I.onlyReadsMemory())
7437     return false;
7438 
7439   SDValue Tmp = getValue(I.getArgOperand(0));
7440   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7441   return true;
7442 }
7443 
7444 /// See if we can lower a binary floating-point operation into an SDNode with
7445 /// the specified Opcode. If so, return true and lower it. Otherwise return
7446 /// false, and it will be lowered like a normal call.
7447 /// The caller already checked that \p I calls the appropriate LibFunc with a
7448 /// correct prototype.
7449 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7450                                                unsigned Opcode) {
7451   // We already checked this call's prototype; verify it doesn't modify errno.
7452   if (!I.onlyReadsMemory())
7453     return false;
7454 
7455   SDValue Tmp0 = getValue(I.getArgOperand(0));
7456   SDValue Tmp1 = getValue(I.getArgOperand(1));
7457   EVT VT = Tmp0.getValueType();
7458   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7459   return true;
7460 }
7461 
7462 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7463   // Handle inline assembly differently.
7464   if (isa<InlineAsm>(I.getCalledValue())) {
7465     visitInlineAsm(&I);
7466     return;
7467   }
7468 
7469   if (Function *F = I.getCalledFunction()) {
7470     if (F->isDeclaration()) {
7471       // Is this an LLVM intrinsic or a target-specific intrinsic?
7472       unsigned IID = F->getIntrinsicID();
7473       if (!IID)
7474         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7475           IID = II->getIntrinsicID(F);
7476 
7477       if (IID) {
7478         visitIntrinsicCall(I, IID);
7479         return;
7480       }
7481     }
7482 
7483     // Check for well-known libc/libm calls.  If the function is internal, it
7484     // can't be a library call.  Don't do the check if marked as nobuiltin for
7485     // some reason or the call site requires strict floating point semantics.
7486     LibFunc Func;
7487     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7488         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7489         LibInfo->hasOptimizedCodeGen(Func)) {
7490       switch (Func) {
7491       default: break;
7492       case LibFunc_copysign:
7493       case LibFunc_copysignf:
7494       case LibFunc_copysignl:
7495         // We already checked this call's prototype; verify it doesn't modify
7496         // errno.
7497         if (I.onlyReadsMemory()) {
7498           SDValue LHS = getValue(I.getArgOperand(0));
7499           SDValue RHS = getValue(I.getArgOperand(1));
7500           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7501                                    LHS.getValueType(), LHS, RHS));
7502           return;
7503         }
7504         break;
7505       case LibFunc_fabs:
7506       case LibFunc_fabsf:
7507       case LibFunc_fabsl:
7508         if (visitUnaryFloatCall(I, ISD::FABS))
7509           return;
7510         break;
7511       case LibFunc_fmin:
7512       case LibFunc_fminf:
7513       case LibFunc_fminl:
7514         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7515           return;
7516         break;
7517       case LibFunc_fmax:
7518       case LibFunc_fmaxf:
7519       case LibFunc_fmaxl:
7520         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7521           return;
7522         break;
7523       case LibFunc_sin:
7524       case LibFunc_sinf:
7525       case LibFunc_sinl:
7526         if (visitUnaryFloatCall(I, ISD::FSIN))
7527           return;
7528         break;
7529       case LibFunc_cos:
7530       case LibFunc_cosf:
7531       case LibFunc_cosl:
7532         if (visitUnaryFloatCall(I, ISD::FCOS))
7533           return;
7534         break;
7535       case LibFunc_sqrt:
7536       case LibFunc_sqrtf:
7537       case LibFunc_sqrtl:
7538       case LibFunc_sqrt_finite:
7539       case LibFunc_sqrtf_finite:
7540       case LibFunc_sqrtl_finite:
7541         if (visitUnaryFloatCall(I, ISD::FSQRT))
7542           return;
7543         break;
7544       case LibFunc_floor:
7545       case LibFunc_floorf:
7546       case LibFunc_floorl:
7547         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7548           return;
7549         break;
7550       case LibFunc_nearbyint:
7551       case LibFunc_nearbyintf:
7552       case LibFunc_nearbyintl:
7553         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7554           return;
7555         break;
7556       case LibFunc_ceil:
7557       case LibFunc_ceilf:
7558       case LibFunc_ceill:
7559         if (visitUnaryFloatCall(I, ISD::FCEIL))
7560           return;
7561         break;
7562       case LibFunc_rint:
7563       case LibFunc_rintf:
7564       case LibFunc_rintl:
7565         if (visitUnaryFloatCall(I, ISD::FRINT))
7566           return;
7567         break;
7568       case LibFunc_round:
7569       case LibFunc_roundf:
7570       case LibFunc_roundl:
7571         if (visitUnaryFloatCall(I, ISD::FROUND))
7572           return;
7573         break;
7574       case LibFunc_trunc:
7575       case LibFunc_truncf:
7576       case LibFunc_truncl:
7577         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7578           return;
7579         break;
7580       case LibFunc_log2:
7581       case LibFunc_log2f:
7582       case LibFunc_log2l:
7583         if (visitUnaryFloatCall(I, ISD::FLOG2))
7584           return;
7585         break;
7586       case LibFunc_exp2:
7587       case LibFunc_exp2f:
7588       case LibFunc_exp2l:
7589         if (visitUnaryFloatCall(I, ISD::FEXP2))
7590           return;
7591         break;
7592       case LibFunc_memcmp:
7593         if (visitMemCmpCall(I))
7594           return;
7595         break;
7596       case LibFunc_mempcpy:
7597         if (visitMemPCpyCall(I))
7598           return;
7599         break;
7600       case LibFunc_memchr:
7601         if (visitMemChrCall(I))
7602           return;
7603         break;
7604       case LibFunc_strcpy:
7605         if (visitStrCpyCall(I, false))
7606           return;
7607         break;
7608       case LibFunc_stpcpy:
7609         if (visitStrCpyCall(I, true))
7610           return;
7611         break;
7612       case LibFunc_strcmp:
7613         if (visitStrCmpCall(I))
7614           return;
7615         break;
7616       case LibFunc_strlen:
7617         if (visitStrLenCall(I))
7618           return;
7619         break;
7620       case LibFunc_strnlen:
7621         if (visitStrNLenCall(I))
7622           return;
7623         break;
7624       }
7625     }
7626   }
7627 
7628   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7629   // have to do anything here to lower funclet bundles.
7630   // CFGuardTarget bundles are lowered in LowerCallTo.
7631   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7632                                         LLVMContext::OB_funclet,
7633                                         LLVMContext::OB_cfguardtarget}) &&
7634          "Cannot lower calls with arbitrary operand bundles!");
7635 
7636   SDValue Callee = getValue(I.getCalledValue());
7637 
7638   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7639     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7640   else
7641     // Check if we can potentially perform a tail call. More detailed checking
7642     // is be done within LowerCallTo, after more information about the call is
7643     // known.
7644     LowerCallTo(&I, Callee, I.isTailCall());
7645 }
7646 
7647 namespace {
7648 
7649 /// AsmOperandInfo - This contains information for each constraint that we are
7650 /// lowering.
7651 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7652 public:
7653   /// CallOperand - If this is the result output operand or a clobber
7654   /// this is null, otherwise it is the incoming operand to the CallInst.
7655   /// This gets modified as the asm is processed.
7656   SDValue CallOperand;
7657 
7658   /// AssignedRegs - If this is a register or register class operand, this
7659   /// contains the set of register corresponding to the operand.
7660   RegsForValue AssignedRegs;
7661 
7662   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7663     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7664   }
7665 
7666   /// Whether or not this operand accesses memory
7667   bool hasMemory(const TargetLowering &TLI) const {
7668     // Indirect operand accesses access memory.
7669     if (isIndirect)
7670       return true;
7671 
7672     for (const auto &Code : Codes)
7673       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7674         return true;
7675 
7676     return false;
7677   }
7678 
7679   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7680   /// corresponds to.  If there is no Value* for this operand, it returns
7681   /// MVT::Other.
7682   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7683                            const DataLayout &DL) const {
7684     if (!CallOperandVal) return MVT::Other;
7685 
7686     if (isa<BasicBlock>(CallOperandVal))
7687       return TLI.getPointerTy(DL);
7688 
7689     llvm::Type *OpTy = CallOperandVal->getType();
7690 
7691     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7692     // If this is an indirect operand, the operand is a pointer to the
7693     // accessed type.
7694     if (isIndirect) {
7695       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7696       if (!PtrTy)
7697         report_fatal_error("Indirect operand for inline asm not a pointer!");
7698       OpTy = PtrTy->getElementType();
7699     }
7700 
7701     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7702     if (StructType *STy = dyn_cast<StructType>(OpTy))
7703       if (STy->getNumElements() == 1)
7704         OpTy = STy->getElementType(0);
7705 
7706     // If OpTy is not a single value, it may be a struct/union that we
7707     // can tile with integers.
7708     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7709       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7710       switch (BitSize) {
7711       default: break;
7712       case 1:
7713       case 8:
7714       case 16:
7715       case 32:
7716       case 64:
7717       case 128:
7718         OpTy = IntegerType::get(Context, BitSize);
7719         break;
7720       }
7721     }
7722 
7723     return TLI.getValueType(DL, OpTy, true);
7724   }
7725 };
7726 
7727 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7728 
7729 } // end anonymous namespace
7730 
7731 /// Make sure that the output operand \p OpInfo and its corresponding input
7732 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7733 /// out).
7734 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7735                                SDISelAsmOperandInfo &MatchingOpInfo,
7736                                SelectionDAG &DAG) {
7737   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7738     return;
7739 
7740   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7741   const auto &TLI = DAG.getTargetLoweringInfo();
7742 
7743   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7744       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7745                                        OpInfo.ConstraintVT);
7746   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7747       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7748                                        MatchingOpInfo.ConstraintVT);
7749   if ((OpInfo.ConstraintVT.isInteger() !=
7750        MatchingOpInfo.ConstraintVT.isInteger()) ||
7751       (MatchRC.second != InputRC.second)) {
7752     // FIXME: error out in a more elegant fashion
7753     report_fatal_error("Unsupported asm: input constraint"
7754                        " with a matching output constraint of"
7755                        " incompatible type!");
7756   }
7757   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7758 }
7759 
7760 /// Get a direct memory input to behave well as an indirect operand.
7761 /// This may introduce stores, hence the need for a \p Chain.
7762 /// \return The (possibly updated) chain.
7763 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7764                                         SDISelAsmOperandInfo &OpInfo,
7765                                         SelectionDAG &DAG) {
7766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7767 
7768   // If we don't have an indirect input, put it in the constpool if we can,
7769   // otherwise spill it to a stack slot.
7770   // TODO: This isn't quite right. We need to handle these according to
7771   // the addressing mode that the constraint wants. Also, this may take
7772   // an additional register for the computation and we don't want that
7773   // either.
7774 
7775   // If the operand is a float, integer, or vector constant, spill to a
7776   // constant pool entry to get its address.
7777   const Value *OpVal = OpInfo.CallOperandVal;
7778   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7779       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7780     OpInfo.CallOperand = DAG.getConstantPool(
7781         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7782     return Chain;
7783   }
7784 
7785   // Otherwise, create a stack slot and emit a store to it before the asm.
7786   Type *Ty = OpVal->getType();
7787   auto &DL = DAG.getDataLayout();
7788   uint64_t TySize = DL.getTypeAllocSize(Ty);
7789   unsigned Align = DL.getPrefTypeAlignment(Ty);
7790   MachineFunction &MF = DAG.getMachineFunction();
7791   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7792   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7793   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7794                             MachinePointerInfo::getFixedStack(MF, SSFI),
7795                             TLI.getMemValueType(DL, Ty));
7796   OpInfo.CallOperand = StackSlot;
7797 
7798   return Chain;
7799 }
7800 
7801 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7802 /// specified operand.  We prefer to assign virtual registers, to allow the
7803 /// register allocator to handle the assignment process.  However, if the asm
7804 /// uses features that we can't model on machineinstrs, we have SDISel do the
7805 /// allocation.  This produces generally horrible, but correct, code.
7806 ///
7807 ///   OpInfo describes the operand
7808 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7809 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7810                                  SDISelAsmOperandInfo &OpInfo,
7811                                  SDISelAsmOperandInfo &RefOpInfo) {
7812   LLVMContext &Context = *DAG.getContext();
7813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7814 
7815   MachineFunction &MF = DAG.getMachineFunction();
7816   SmallVector<unsigned, 4> Regs;
7817   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7818 
7819   // No work to do for memory operations.
7820   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7821     return;
7822 
7823   // If this is a constraint for a single physreg, or a constraint for a
7824   // register class, find it.
7825   unsigned AssignedReg;
7826   const TargetRegisterClass *RC;
7827   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7828       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7829   // RC is unset only on failure. Return immediately.
7830   if (!RC)
7831     return;
7832 
7833   // Get the actual register value type.  This is important, because the user
7834   // may have asked for (e.g.) the AX register in i32 type.  We need to
7835   // remember that AX is actually i16 to get the right extension.
7836   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7837 
7838   if (OpInfo.ConstraintVT != MVT::Other) {
7839     // If this is an FP operand in an integer register (or visa versa), or more
7840     // generally if the operand value disagrees with the register class we plan
7841     // to stick it in, fix the operand type.
7842     //
7843     // If this is an input value, the bitcast to the new type is done now.
7844     // Bitcast for output value is done at the end of visitInlineAsm().
7845     if ((OpInfo.Type == InlineAsm::isOutput ||
7846          OpInfo.Type == InlineAsm::isInput) &&
7847         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7848       // Try to convert to the first EVT that the reg class contains.  If the
7849       // types are identical size, use a bitcast to convert (e.g. two differing
7850       // vector types).  Note: output bitcast is done at the end of
7851       // visitInlineAsm().
7852       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7853         // Exclude indirect inputs while they are unsupported because the code
7854         // to perform the load is missing and thus OpInfo.CallOperand still
7855         // refers to the input address rather than the pointed-to value.
7856         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7857           OpInfo.CallOperand =
7858               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7859         OpInfo.ConstraintVT = RegVT;
7860         // If the operand is an FP value and we want it in integer registers,
7861         // use the corresponding integer type. This turns an f64 value into
7862         // i64, which can be passed with two i32 values on a 32-bit machine.
7863       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7864         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7865         if (OpInfo.Type == InlineAsm::isInput)
7866           OpInfo.CallOperand =
7867               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7868         OpInfo.ConstraintVT = VT;
7869       }
7870     }
7871   }
7872 
7873   // No need to allocate a matching input constraint since the constraint it's
7874   // matching to has already been allocated.
7875   if (OpInfo.isMatchingInputConstraint())
7876     return;
7877 
7878   EVT ValueVT = OpInfo.ConstraintVT;
7879   if (OpInfo.ConstraintVT == MVT::Other)
7880     ValueVT = RegVT;
7881 
7882   // Initialize NumRegs.
7883   unsigned NumRegs = 1;
7884   if (OpInfo.ConstraintVT != MVT::Other)
7885     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7886 
7887   // If this is a constraint for a specific physical register, like {r17},
7888   // assign it now.
7889 
7890   // If this associated to a specific register, initialize iterator to correct
7891   // place. If virtual, make sure we have enough registers
7892 
7893   // Initialize iterator if necessary
7894   TargetRegisterClass::iterator I = RC->begin();
7895   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7896 
7897   // Do not check for single registers.
7898   if (AssignedReg) {
7899       for (; *I != AssignedReg; ++I)
7900         assert(I != RC->end() && "AssignedReg should be member of RC");
7901   }
7902 
7903   for (; NumRegs; --NumRegs, ++I) {
7904     assert(I != RC->end() && "Ran out of registers to allocate!");
7905     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7906     Regs.push_back(R);
7907   }
7908 
7909   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7910 }
7911 
7912 static unsigned
7913 findMatchingInlineAsmOperand(unsigned OperandNo,
7914                              const std::vector<SDValue> &AsmNodeOperands) {
7915   // Scan until we find the definition we already emitted of this operand.
7916   unsigned CurOp = InlineAsm::Op_FirstOperand;
7917   for (; OperandNo; --OperandNo) {
7918     // Advance to the next operand.
7919     unsigned OpFlag =
7920         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7921     assert((InlineAsm::isRegDefKind(OpFlag) ||
7922             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7923             InlineAsm::isMemKind(OpFlag)) &&
7924            "Skipped past definitions?");
7925     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7926   }
7927   return CurOp;
7928 }
7929 
7930 namespace {
7931 
7932 class ExtraFlags {
7933   unsigned Flags = 0;
7934 
7935 public:
7936   explicit ExtraFlags(ImmutableCallSite CS) {
7937     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7938     if (IA->hasSideEffects())
7939       Flags |= InlineAsm::Extra_HasSideEffects;
7940     if (IA->isAlignStack())
7941       Flags |= InlineAsm::Extra_IsAlignStack;
7942     if (CS.isConvergent())
7943       Flags |= InlineAsm::Extra_IsConvergent;
7944     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7945   }
7946 
7947   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7948     // Ideally, we would only check against memory constraints.  However, the
7949     // meaning of an Other constraint can be target-specific and we can't easily
7950     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7951     // for Other constraints as well.
7952     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7953         OpInfo.ConstraintType == TargetLowering::C_Other) {
7954       if (OpInfo.Type == InlineAsm::isInput)
7955         Flags |= InlineAsm::Extra_MayLoad;
7956       else if (OpInfo.Type == InlineAsm::isOutput)
7957         Flags |= InlineAsm::Extra_MayStore;
7958       else if (OpInfo.Type == InlineAsm::isClobber)
7959         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7960     }
7961   }
7962 
7963   unsigned get() const { return Flags; }
7964 };
7965 
7966 } // end anonymous namespace
7967 
7968 /// visitInlineAsm - Handle a call to an InlineAsm object.
7969 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7970   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7971 
7972   /// ConstraintOperands - Information about all of the constraints.
7973   SDISelAsmOperandInfoVector ConstraintOperands;
7974 
7975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7976   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7977       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7978 
7979   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7980   // AsmDialect, MayLoad, MayStore).
7981   bool HasSideEffect = IA->hasSideEffects();
7982   ExtraFlags ExtraInfo(CS);
7983 
7984   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7985   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7986   for (auto &T : TargetConstraints) {
7987     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7988     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7989 
7990     // Compute the value type for each operand.
7991     if (OpInfo.Type == InlineAsm::isInput ||
7992         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7993       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7994 
7995       // Process the call argument. BasicBlocks are labels, currently appearing
7996       // only in asm's.
7997       const Instruction *I = CS.getInstruction();
7998       if (isa<CallBrInst>(I) &&
7999           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8000                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8001         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8002         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8003         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8004       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8005         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8006       } else {
8007         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8008       }
8009 
8010       OpInfo.ConstraintVT =
8011           OpInfo
8012               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8013               .getSimpleVT();
8014     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8015       // The return value of the call is this value.  As such, there is no
8016       // corresponding argument.
8017       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8018       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8019         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8020             DAG.getDataLayout(), STy->getElementType(ResNo));
8021       } else {
8022         assert(ResNo == 0 && "Asm only has one result!");
8023         OpInfo.ConstraintVT =
8024             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8025       }
8026       ++ResNo;
8027     } else {
8028       OpInfo.ConstraintVT = MVT::Other;
8029     }
8030 
8031     if (!HasSideEffect)
8032       HasSideEffect = OpInfo.hasMemory(TLI);
8033 
8034     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8035     // FIXME: Could we compute this on OpInfo rather than T?
8036 
8037     // Compute the constraint code and ConstraintType to use.
8038     TLI.ComputeConstraintToUse(T, SDValue());
8039 
8040     if (T.ConstraintType == TargetLowering::C_Immediate &&
8041         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8042       // We've delayed emitting a diagnostic like the "n" constraint because
8043       // inlining could cause an integer showing up.
8044       return emitInlineAsmError(
8045           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8046                   "integer constant expression");
8047 
8048     ExtraInfo.update(T);
8049   }
8050 
8051 
8052   // We won't need to flush pending loads if this asm doesn't touch
8053   // memory and is nonvolatile.
8054   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8055 
8056   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8057   if (IsCallBr) {
8058     // If this is a callbr we need to flush pending exports since inlineasm_br
8059     // is a terminator. We need to do this before nodes are glued to
8060     // the inlineasm_br node.
8061     Chain = getControlRoot();
8062   }
8063 
8064   // Second pass over the constraints: compute which constraint option to use.
8065   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8066     // If this is an output operand with a matching input operand, look up the
8067     // matching input. If their types mismatch, e.g. one is an integer, the
8068     // other is floating point, or their sizes are different, flag it as an
8069     // error.
8070     if (OpInfo.hasMatchingInput()) {
8071       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8072       patchMatchingInput(OpInfo, Input, DAG);
8073     }
8074 
8075     // Compute the constraint code and ConstraintType to use.
8076     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8077 
8078     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8079         OpInfo.Type == InlineAsm::isClobber)
8080       continue;
8081 
8082     // If this is a memory input, and if the operand is not indirect, do what we
8083     // need to provide an address for the memory input.
8084     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8085         !OpInfo.isIndirect) {
8086       assert((OpInfo.isMultipleAlternative ||
8087               (OpInfo.Type == InlineAsm::isInput)) &&
8088              "Can only indirectify direct input operands!");
8089 
8090       // Memory operands really want the address of the value.
8091       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8092 
8093       // There is no longer a Value* corresponding to this operand.
8094       OpInfo.CallOperandVal = nullptr;
8095 
8096       // It is now an indirect operand.
8097       OpInfo.isIndirect = true;
8098     }
8099 
8100   }
8101 
8102   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8103   std::vector<SDValue> AsmNodeOperands;
8104   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8105   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8106       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8107 
8108   // If we have a !srcloc metadata node associated with it, we want to attach
8109   // this to the ultimately generated inline asm machineinstr.  To do this, we
8110   // pass in the third operand as this (potentially null) inline asm MDNode.
8111   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8112   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8113 
8114   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8115   // bits as operand 3.
8116   AsmNodeOperands.push_back(DAG.getTargetConstant(
8117       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8118 
8119   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8120   // this, assign virtual and physical registers for inputs and otput.
8121   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8122     // Assign Registers.
8123     SDISelAsmOperandInfo &RefOpInfo =
8124         OpInfo.isMatchingInputConstraint()
8125             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8126             : OpInfo;
8127     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8128 
8129     switch (OpInfo.Type) {
8130     case InlineAsm::isOutput:
8131       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8132           ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8133             OpInfo.ConstraintType == TargetLowering::C_Other) &&
8134            OpInfo.isIndirect)) {
8135         unsigned ConstraintID =
8136             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8137         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8138                "Failed to convert memory constraint code to constraint id.");
8139 
8140         // Add information to the INLINEASM node to know about this output.
8141         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8142         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8143         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8144                                                         MVT::i32));
8145         AsmNodeOperands.push_back(OpInfo.CallOperand);
8146         break;
8147       } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8148                    OpInfo.ConstraintType == TargetLowering::C_Other) &&
8149                   !OpInfo.isIndirect) ||
8150                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8151                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8152         // Otherwise, this outputs to a register (directly for C_Register /
8153         // C_RegisterClass, and a target-defined fashion for
8154         // C_Immediate/C_Other). Find a register that we can use.
8155         if (OpInfo.AssignedRegs.Regs.empty()) {
8156           emitInlineAsmError(
8157               CS, "couldn't allocate output register for constraint '" +
8158                       Twine(OpInfo.ConstraintCode) + "'");
8159           return;
8160         }
8161 
8162         // Add information to the INLINEASM node to know that this register is
8163         // set.
8164         OpInfo.AssignedRegs.AddInlineAsmOperands(
8165             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8166                                   : InlineAsm::Kind_RegDef,
8167             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8168       }
8169       break;
8170 
8171     case InlineAsm::isInput: {
8172       SDValue InOperandVal = OpInfo.CallOperand;
8173 
8174       if (OpInfo.isMatchingInputConstraint()) {
8175         // If this is required to match an output register we have already set,
8176         // just use its register.
8177         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8178                                                   AsmNodeOperands);
8179         unsigned OpFlag =
8180           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8181         if (InlineAsm::isRegDefKind(OpFlag) ||
8182             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8183           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8184           if (OpInfo.isIndirect) {
8185             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8186             emitInlineAsmError(CS, "inline asm not supported yet:"
8187                                    " don't know how to handle tied "
8188                                    "indirect register inputs");
8189             return;
8190           }
8191 
8192           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8193           SmallVector<unsigned, 4> Regs;
8194 
8195           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8196             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8197             MachineRegisterInfo &RegInfo =
8198                 DAG.getMachineFunction().getRegInfo();
8199             for (unsigned i = 0; i != NumRegs; ++i)
8200               Regs.push_back(RegInfo.createVirtualRegister(RC));
8201           } else {
8202             emitInlineAsmError(CS, "inline asm error: This value type register "
8203                                    "class is not natively supported!");
8204             return;
8205           }
8206 
8207           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8208 
8209           SDLoc dl = getCurSDLoc();
8210           // Use the produced MatchedRegs object to
8211           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8212                                     CS.getInstruction());
8213           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8214                                            true, OpInfo.getMatchedOperand(), dl,
8215                                            DAG, AsmNodeOperands);
8216           break;
8217         }
8218 
8219         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8220         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8221                "Unexpected number of operands");
8222         // Add information to the INLINEASM node to know about this input.
8223         // See InlineAsm.h isUseOperandTiedToDef.
8224         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8225         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8226                                                     OpInfo.getMatchedOperand());
8227         AsmNodeOperands.push_back(DAG.getTargetConstant(
8228             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8229         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8230         break;
8231       }
8232 
8233       // Treat indirect 'X' constraint as memory.
8234       if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8235            OpInfo.ConstraintType == TargetLowering::C_Other) &&
8236           OpInfo.isIndirect)
8237         OpInfo.ConstraintType = TargetLowering::C_Memory;
8238 
8239       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8240           OpInfo.ConstraintType == TargetLowering::C_Other) {
8241         std::vector<SDValue> Ops;
8242         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8243                                           Ops, DAG);
8244         if (Ops.empty()) {
8245           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8246             if (isa<ConstantSDNode>(InOperandVal)) {
8247               emitInlineAsmError(CS, "value out of range for constraint '" +
8248                                  Twine(OpInfo.ConstraintCode) + "'");
8249               return;
8250             }
8251 
8252           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8253                                      Twine(OpInfo.ConstraintCode) + "'");
8254           return;
8255         }
8256 
8257         // Add information to the INLINEASM node to know about this input.
8258         unsigned ResOpType =
8259           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8260         AsmNodeOperands.push_back(DAG.getTargetConstant(
8261             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8262         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8263         break;
8264       }
8265 
8266       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8267         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8268         assert(InOperandVal.getValueType() ==
8269                    TLI.getPointerTy(DAG.getDataLayout()) &&
8270                "Memory operands expect pointer values");
8271 
8272         unsigned ConstraintID =
8273             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8274         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8275                "Failed to convert memory constraint code to constraint id.");
8276 
8277         // Add information to the INLINEASM node to know about this input.
8278         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8279         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8280         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8281                                                         getCurSDLoc(),
8282                                                         MVT::i32));
8283         AsmNodeOperands.push_back(InOperandVal);
8284         break;
8285       }
8286 
8287       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8288               OpInfo.ConstraintType == TargetLowering::C_Register ||
8289               OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8290              "Unknown constraint type!");
8291 
8292       // TODO: Support this.
8293       if (OpInfo.isIndirect) {
8294         emitInlineAsmError(
8295             CS, "Don't know how to handle indirect register inputs yet "
8296                 "for constraint '" +
8297                     Twine(OpInfo.ConstraintCode) + "'");
8298         return;
8299       }
8300 
8301       // Copy the input into the appropriate registers.
8302       if (OpInfo.AssignedRegs.Regs.empty()) {
8303         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8304                                    Twine(OpInfo.ConstraintCode) + "'");
8305         return;
8306       }
8307 
8308       SDLoc dl = getCurSDLoc();
8309 
8310       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8311                                         Chain, &Flag, CS.getInstruction());
8312 
8313       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8314                                                dl, DAG, AsmNodeOperands);
8315       break;
8316     }
8317     case InlineAsm::isClobber:
8318       // Add the clobbered value to the operand list, so that the register
8319       // allocator is aware that the physreg got clobbered.
8320       if (!OpInfo.AssignedRegs.Regs.empty())
8321         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8322                                                  false, 0, getCurSDLoc(), DAG,
8323                                                  AsmNodeOperands);
8324       break;
8325     }
8326   }
8327 
8328   // Finish up input operands.  Set the input chain and add the flag last.
8329   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8330   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8331 
8332   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8333   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8334                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8335   Flag = Chain.getValue(1);
8336 
8337   // Do additional work to generate outputs.
8338 
8339   SmallVector<EVT, 1> ResultVTs;
8340   SmallVector<SDValue, 1> ResultValues;
8341   SmallVector<SDValue, 8> OutChains;
8342 
8343   llvm::Type *CSResultType = CS.getType();
8344   ArrayRef<Type *> ResultTypes;
8345   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8346     ResultTypes = StructResult->elements();
8347   else if (!CSResultType->isVoidTy())
8348     ResultTypes = makeArrayRef(CSResultType);
8349 
8350   auto CurResultType = ResultTypes.begin();
8351   auto handleRegAssign = [&](SDValue V) {
8352     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8353     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8354     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8355     ++CurResultType;
8356     // If the type of the inline asm call site return value is different but has
8357     // same size as the type of the asm output bitcast it.  One example of this
8358     // is for vectors with different width / number of elements.  This can
8359     // happen for register classes that can contain multiple different value
8360     // types.  The preg or vreg allocated may not have the same VT as was
8361     // expected.
8362     //
8363     // This can also happen for a return value that disagrees with the register
8364     // class it is put in, eg. a double in a general-purpose register on a
8365     // 32-bit machine.
8366     if (ResultVT != V.getValueType() &&
8367         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8368       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8369     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8370              V.getValueType().isInteger()) {
8371       // If a result value was tied to an input value, the computed result
8372       // may have a wider width than the expected result.  Extract the
8373       // relevant portion.
8374       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8375     }
8376     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8377     ResultVTs.push_back(ResultVT);
8378     ResultValues.push_back(V);
8379   };
8380 
8381   // Deal with output operands.
8382   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8383     if (OpInfo.Type == InlineAsm::isOutput) {
8384       SDValue Val;
8385       // Skip trivial output operands.
8386       if (OpInfo.AssignedRegs.Regs.empty())
8387         continue;
8388 
8389       switch (OpInfo.ConstraintType) {
8390       case TargetLowering::C_Register:
8391       case TargetLowering::C_RegisterClass:
8392         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8393             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8394         break;
8395       case TargetLowering::C_Immediate:
8396       case TargetLowering::C_Other:
8397         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8398                                               OpInfo, DAG);
8399         break;
8400       case TargetLowering::C_Memory:
8401         break; // Already handled.
8402       case TargetLowering::C_Unknown:
8403         assert(false && "Unexpected unknown constraint");
8404       }
8405 
8406       // Indirect output manifest as stores. Record output chains.
8407       if (OpInfo.isIndirect) {
8408         const Value *Ptr = OpInfo.CallOperandVal;
8409         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8410         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8411                                      MachinePointerInfo(Ptr));
8412         OutChains.push_back(Store);
8413       } else {
8414         // generate CopyFromRegs to associated registers.
8415         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8416         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8417           for (const SDValue &V : Val->op_values())
8418             handleRegAssign(V);
8419         } else
8420           handleRegAssign(Val);
8421       }
8422     }
8423   }
8424 
8425   // Set results.
8426   if (!ResultValues.empty()) {
8427     assert(CurResultType == ResultTypes.end() &&
8428            "Mismatch in number of ResultTypes");
8429     assert(ResultValues.size() == ResultTypes.size() &&
8430            "Mismatch in number of output operands in asm result");
8431 
8432     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8433                             DAG.getVTList(ResultVTs), ResultValues);
8434     setValue(CS.getInstruction(), V);
8435   }
8436 
8437   // Collect store chains.
8438   if (!OutChains.empty())
8439     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8440 
8441   // Only Update Root if inline assembly has a memory effect.
8442   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8443     DAG.setRoot(Chain);
8444 }
8445 
8446 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8447                                              const Twine &Message) {
8448   LLVMContext &Ctx = *DAG.getContext();
8449   Ctx.emitError(CS.getInstruction(), Message);
8450 
8451   // Make sure we leave the DAG in a valid state
8452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8453   SmallVector<EVT, 1> ValueVTs;
8454   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8455 
8456   if (ValueVTs.empty())
8457     return;
8458 
8459   SmallVector<SDValue, 1> Ops;
8460   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8461     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8462 
8463   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8464 }
8465 
8466 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8467   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8468                           MVT::Other, getRoot(),
8469                           getValue(I.getArgOperand(0)),
8470                           DAG.getSrcValue(I.getArgOperand(0))));
8471 }
8472 
8473 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8475   const DataLayout &DL = DAG.getDataLayout();
8476   SDValue V = DAG.getVAArg(
8477       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8478       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8479       DL.getABITypeAlignment(I.getType()));
8480   DAG.setRoot(V.getValue(1));
8481 
8482   if (I.getType()->isPointerTy())
8483     V = DAG.getPtrExtOrTrunc(
8484         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8485   setValue(&I, V);
8486 }
8487 
8488 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8489   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8490                           MVT::Other, getRoot(),
8491                           getValue(I.getArgOperand(0)),
8492                           DAG.getSrcValue(I.getArgOperand(0))));
8493 }
8494 
8495 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8496   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8497                           MVT::Other, getRoot(),
8498                           getValue(I.getArgOperand(0)),
8499                           getValue(I.getArgOperand(1)),
8500                           DAG.getSrcValue(I.getArgOperand(0)),
8501                           DAG.getSrcValue(I.getArgOperand(1))));
8502 }
8503 
8504 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8505                                                     const Instruction &I,
8506                                                     SDValue Op) {
8507   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8508   if (!Range)
8509     return Op;
8510 
8511   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8512   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8513     return Op;
8514 
8515   APInt Lo = CR.getUnsignedMin();
8516   if (!Lo.isMinValue())
8517     return Op;
8518 
8519   APInt Hi = CR.getUnsignedMax();
8520   unsigned Bits = std::max(Hi.getActiveBits(),
8521                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8522 
8523   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8524 
8525   SDLoc SL = getCurSDLoc();
8526 
8527   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8528                              DAG.getValueType(SmallVT));
8529   unsigned NumVals = Op.getNode()->getNumValues();
8530   if (NumVals == 1)
8531     return ZExt;
8532 
8533   SmallVector<SDValue, 4> Ops;
8534 
8535   Ops.push_back(ZExt);
8536   for (unsigned I = 1; I != NumVals; ++I)
8537     Ops.push_back(Op.getValue(I));
8538 
8539   return DAG.getMergeValues(Ops, SL);
8540 }
8541 
8542 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8543 /// the call being lowered.
8544 ///
8545 /// This is a helper for lowering intrinsics that follow a target calling
8546 /// convention or require stack pointer adjustment. Only a subset of the
8547 /// intrinsic's operands need to participate in the calling convention.
8548 void SelectionDAGBuilder::populateCallLoweringInfo(
8549     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8550     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8551     bool IsPatchPoint) {
8552   TargetLowering::ArgListTy Args;
8553   Args.reserve(NumArgs);
8554 
8555   // Populate the argument list.
8556   // Attributes for args start at offset 1, after the return attribute.
8557   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8558        ArgI != ArgE; ++ArgI) {
8559     const Value *V = Call->getOperand(ArgI);
8560 
8561     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8562 
8563     TargetLowering::ArgListEntry Entry;
8564     Entry.Node = getValue(V);
8565     Entry.Ty = V->getType();
8566     Entry.setAttributes(Call, ArgI);
8567     Args.push_back(Entry);
8568   }
8569 
8570   CLI.setDebugLoc(getCurSDLoc())
8571       .setChain(getRoot())
8572       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8573       .setDiscardResult(Call->use_empty())
8574       .setIsPatchPoint(IsPatchPoint);
8575 }
8576 
8577 /// Add a stack map intrinsic call's live variable operands to a stackmap
8578 /// or patchpoint target node's operand list.
8579 ///
8580 /// Constants are converted to TargetConstants purely as an optimization to
8581 /// avoid constant materialization and register allocation.
8582 ///
8583 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8584 /// generate addess computation nodes, and so FinalizeISel can convert the
8585 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8586 /// address materialization and register allocation, but may also be required
8587 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8588 /// alloca in the entry block, then the runtime may assume that the alloca's
8589 /// StackMap location can be read immediately after compilation and that the
8590 /// location is valid at any point during execution (this is similar to the
8591 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8592 /// only available in a register, then the runtime would need to trap when
8593 /// execution reaches the StackMap in order to read the alloca's location.
8594 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8595                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8596                                 SelectionDAGBuilder &Builder) {
8597   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8598     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8599     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8600       Ops.push_back(
8601         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8602       Ops.push_back(
8603         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8604     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8605       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8606       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8607           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8608     } else
8609       Ops.push_back(OpVal);
8610   }
8611 }
8612 
8613 /// Lower llvm.experimental.stackmap directly to its target opcode.
8614 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8615   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8616   //                                  [live variables...])
8617 
8618   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8619 
8620   SDValue Chain, InFlag, Callee, NullPtr;
8621   SmallVector<SDValue, 32> Ops;
8622 
8623   SDLoc DL = getCurSDLoc();
8624   Callee = getValue(CI.getCalledValue());
8625   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8626 
8627   // The stackmap intrinsic only records the live variables (the arguments
8628   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8629   // intrinsic, this won't be lowered to a function call. This means we don't
8630   // have to worry about calling conventions and target specific lowering code.
8631   // Instead we perform the call lowering right here.
8632   //
8633   // chain, flag = CALLSEQ_START(chain, 0, 0)
8634   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8635   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8636   //
8637   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8638   InFlag = Chain.getValue(1);
8639 
8640   // Add the <id> and <numBytes> constants.
8641   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8642   Ops.push_back(DAG.getTargetConstant(
8643                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8644   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8645   Ops.push_back(DAG.getTargetConstant(
8646                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8647                   MVT::i32));
8648 
8649   // Push live variables for the stack map.
8650   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8651 
8652   // We are not pushing any register mask info here on the operands list,
8653   // because the stackmap doesn't clobber anything.
8654 
8655   // Push the chain and the glue flag.
8656   Ops.push_back(Chain);
8657   Ops.push_back(InFlag);
8658 
8659   // Create the STACKMAP node.
8660   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8661   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8662   Chain = SDValue(SM, 0);
8663   InFlag = Chain.getValue(1);
8664 
8665   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8666 
8667   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8668 
8669   // Set the root to the target-lowered call chain.
8670   DAG.setRoot(Chain);
8671 
8672   // Inform the Frame Information that we have a stackmap in this function.
8673   FuncInfo.MF->getFrameInfo().setHasStackMap();
8674 }
8675 
8676 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8677 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8678                                           const BasicBlock *EHPadBB) {
8679   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8680   //                                                 i32 <numBytes>,
8681   //                                                 i8* <target>,
8682   //                                                 i32 <numArgs>,
8683   //                                                 [Args...],
8684   //                                                 [live variables...])
8685 
8686   CallingConv::ID CC = CS.getCallingConv();
8687   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8688   bool HasDef = !CS->getType()->isVoidTy();
8689   SDLoc dl = getCurSDLoc();
8690   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8691 
8692   // Handle immediate and symbolic callees.
8693   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8694     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8695                                    /*isTarget=*/true);
8696   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8697     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8698                                          SDLoc(SymbolicCallee),
8699                                          SymbolicCallee->getValueType(0));
8700 
8701   // Get the real number of arguments participating in the call <numArgs>
8702   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8703   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8704 
8705   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8706   // Intrinsics include all meta-operands up to but not including CC.
8707   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8708   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8709          "Not enough arguments provided to the patchpoint intrinsic");
8710 
8711   // For AnyRegCC the arguments are lowered later on manually.
8712   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8713   Type *ReturnTy =
8714     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8715 
8716   TargetLowering::CallLoweringInfo CLI(DAG);
8717   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8718                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8719   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8720 
8721   SDNode *CallEnd = Result.second.getNode();
8722   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8723     CallEnd = CallEnd->getOperand(0).getNode();
8724 
8725   /// Get a call instruction from the call sequence chain.
8726   /// Tail calls are not allowed.
8727   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8728          "Expected a callseq node.");
8729   SDNode *Call = CallEnd->getOperand(0).getNode();
8730   bool HasGlue = Call->getGluedNode();
8731 
8732   // Replace the target specific call node with the patchable intrinsic.
8733   SmallVector<SDValue, 8> Ops;
8734 
8735   // Add the <id> and <numBytes> constants.
8736   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8737   Ops.push_back(DAG.getTargetConstant(
8738                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8739   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8740   Ops.push_back(DAG.getTargetConstant(
8741                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8742                   MVT::i32));
8743 
8744   // Add the callee.
8745   Ops.push_back(Callee);
8746 
8747   // Adjust <numArgs> to account for any arguments that have been passed on the
8748   // stack instead.
8749   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8750   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8751   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8752   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8753 
8754   // Add the calling convention
8755   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8756 
8757   // Add the arguments we omitted previously. The register allocator should
8758   // place these in any free register.
8759   if (IsAnyRegCC)
8760     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8761       Ops.push_back(getValue(CS.getArgument(i)));
8762 
8763   // Push the arguments from the call instruction up to the register mask.
8764   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8765   Ops.append(Call->op_begin() + 2, e);
8766 
8767   // Push live variables for the stack map.
8768   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8769 
8770   // Push the register mask info.
8771   if (HasGlue)
8772     Ops.push_back(*(Call->op_end()-2));
8773   else
8774     Ops.push_back(*(Call->op_end()-1));
8775 
8776   // Push the chain (this is originally the first operand of the call, but
8777   // becomes now the last or second to last operand).
8778   Ops.push_back(*(Call->op_begin()));
8779 
8780   // Push the glue flag (last operand).
8781   if (HasGlue)
8782     Ops.push_back(*(Call->op_end()-1));
8783 
8784   SDVTList NodeTys;
8785   if (IsAnyRegCC && HasDef) {
8786     // Create the return types based on the intrinsic definition
8787     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8788     SmallVector<EVT, 3> ValueVTs;
8789     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8790     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8791 
8792     // There is always a chain and a glue type at the end
8793     ValueVTs.push_back(MVT::Other);
8794     ValueVTs.push_back(MVT::Glue);
8795     NodeTys = DAG.getVTList(ValueVTs);
8796   } else
8797     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8798 
8799   // Replace the target specific call node with a PATCHPOINT node.
8800   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8801                                          dl, NodeTys, Ops);
8802 
8803   // Update the NodeMap.
8804   if (HasDef) {
8805     if (IsAnyRegCC)
8806       setValue(CS.getInstruction(), SDValue(MN, 0));
8807     else
8808       setValue(CS.getInstruction(), Result.first);
8809   }
8810 
8811   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8812   // call sequence. Furthermore the location of the chain and glue can change
8813   // when the AnyReg calling convention is used and the intrinsic returns a
8814   // value.
8815   if (IsAnyRegCC && HasDef) {
8816     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8817     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8818     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8819   } else
8820     DAG.ReplaceAllUsesWith(Call, MN);
8821   DAG.DeleteNode(Call);
8822 
8823   // Inform the Frame Information that we have a patchpoint in this function.
8824   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8825 }
8826 
8827 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8828                                             unsigned Intrinsic) {
8829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8830   SDValue Op1 = getValue(I.getArgOperand(0));
8831   SDValue Op2;
8832   if (I.getNumArgOperands() > 1)
8833     Op2 = getValue(I.getArgOperand(1));
8834   SDLoc dl = getCurSDLoc();
8835   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8836   SDValue Res;
8837   FastMathFlags FMF;
8838   if (isa<FPMathOperator>(I))
8839     FMF = I.getFastMathFlags();
8840 
8841   switch (Intrinsic) {
8842   case Intrinsic::experimental_vector_reduce_v2_fadd:
8843     if (FMF.allowReassoc())
8844       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8845                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8846     else
8847       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8848     break;
8849   case Intrinsic::experimental_vector_reduce_v2_fmul:
8850     if (FMF.allowReassoc())
8851       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8852                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8853     else
8854       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8855     break;
8856   case Intrinsic::experimental_vector_reduce_add:
8857     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8858     break;
8859   case Intrinsic::experimental_vector_reduce_mul:
8860     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8861     break;
8862   case Intrinsic::experimental_vector_reduce_and:
8863     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8864     break;
8865   case Intrinsic::experimental_vector_reduce_or:
8866     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8867     break;
8868   case Intrinsic::experimental_vector_reduce_xor:
8869     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8870     break;
8871   case Intrinsic::experimental_vector_reduce_smax:
8872     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8873     break;
8874   case Intrinsic::experimental_vector_reduce_smin:
8875     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8876     break;
8877   case Intrinsic::experimental_vector_reduce_umax:
8878     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8879     break;
8880   case Intrinsic::experimental_vector_reduce_umin:
8881     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8882     break;
8883   case Intrinsic::experimental_vector_reduce_fmax:
8884     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8885     break;
8886   case Intrinsic::experimental_vector_reduce_fmin:
8887     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8888     break;
8889   default:
8890     llvm_unreachable("Unhandled vector reduce intrinsic");
8891   }
8892   setValue(&I, Res);
8893 }
8894 
8895 /// Returns an AttributeList representing the attributes applied to the return
8896 /// value of the given call.
8897 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8898   SmallVector<Attribute::AttrKind, 2> Attrs;
8899   if (CLI.RetSExt)
8900     Attrs.push_back(Attribute::SExt);
8901   if (CLI.RetZExt)
8902     Attrs.push_back(Attribute::ZExt);
8903   if (CLI.IsInReg)
8904     Attrs.push_back(Attribute::InReg);
8905 
8906   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8907                             Attrs);
8908 }
8909 
8910 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8911 /// implementation, which just calls LowerCall.
8912 /// FIXME: When all targets are
8913 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8914 std::pair<SDValue, SDValue>
8915 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8916   // Handle the incoming return values from the call.
8917   CLI.Ins.clear();
8918   Type *OrigRetTy = CLI.RetTy;
8919   SmallVector<EVT, 4> RetTys;
8920   SmallVector<uint64_t, 4> Offsets;
8921   auto &DL = CLI.DAG.getDataLayout();
8922   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8923 
8924   if (CLI.IsPostTypeLegalization) {
8925     // If we are lowering a libcall after legalization, split the return type.
8926     SmallVector<EVT, 4> OldRetTys;
8927     SmallVector<uint64_t, 4> OldOffsets;
8928     RetTys.swap(OldRetTys);
8929     Offsets.swap(OldOffsets);
8930 
8931     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8932       EVT RetVT = OldRetTys[i];
8933       uint64_t Offset = OldOffsets[i];
8934       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8935       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8936       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8937       RetTys.append(NumRegs, RegisterVT);
8938       for (unsigned j = 0; j != NumRegs; ++j)
8939         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8940     }
8941   }
8942 
8943   SmallVector<ISD::OutputArg, 4> Outs;
8944   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8945 
8946   bool CanLowerReturn =
8947       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8948                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8949 
8950   SDValue DemoteStackSlot;
8951   int DemoteStackIdx = -100;
8952   if (!CanLowerReturn) {
8953     // FIXME: equivalent assert?
8954     // assert(!CS.hasInAllocaArgument() &&
8955     //        "sret demotion is incompatible with inalloca");
8956     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8957     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8958     MachineFunction &MF = CLI.DAG.getMachineFunction();
8959     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8960     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8961                                               DL.getAllocaAddrSpace());
8962 
8963     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8964     ArgListEntry Entry;
8965     Entry.Node = DemoteStackSlot;
8966     Entry.Ty = StackSlotPtrType;
8967     Entry.IsSExt = false;
8968     Entry.IsZExt = false;
8969     Entry.IsInReg = false;
8970     Entry.IsSRet = true;
8971     Entry.IsNest = false;
8972     Entry.IsByVal = false;
8973     Entry.IsReturned = false;
8974     Entry.IsSwiftSelf = false;
8975     Entry.IsSwiftError = false;
8976     Entry.IsCFGuardTarget = false;
8977     Entry.Alignment = Align;
8978     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8979     CLI.NumFixedArgs += 1;
8980     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8981 
8982     // sret demotion isn't compatible with tail-calls, since the sret argument
8983     // points into the callers stack frame.
8984     CLI.IsTailCall = false;
8985   } else {
8986     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8987         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8988     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8989       ISD::ArgFlagsTy Flags;
8990       if (NeedsRegBlock) {
8991         Flags.setInConsecutiveRegs();
8992         if (I == RetTys.size() - 1)
8993           Flags.setInConsecutiveRegsLast();
8994       }
8995       EVT VT = RetTys[I];
8996       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8997                                                      CLI.CallConv, VT);
8998       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8999                                                        CLI.CallConv, VT);
9000       for (unsigned i = 0; i != NumRegs; ++i) {
9001         ISD::InputArg MyFlags;
9002         MyFlags.Flags = Flags;
9003         MyFlags.VT = RegisterVT;
9004         MyFlags.ArgVT = VT;
9005         MyFlags.Used = CLI.IsReturnValueUsed;
9006         if (CLI.RetTy->isPointerTy()) {
9007           MyFlags.Flags.setPointer();
9008           MyFlags.Flags.setPointerAddrSpace(
9009               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9010         }
9011         if (CLI.RetSExt)
9012           MyFlags.Flags.setSExt();
9013         if (CLI.RetZExt)
9014           MyFlags.Flags.setZExt();
9015         if (CLI.IsInReg)
9016           MyFlags.Flags.setInReg();
9017         CLI.Ins.push_back(MyFlags);
9018       }
9019     }
9020   }
9021 
9022   // We push in swifterror return as the last element of CLI.Ins.
9023   ArgListTy &Args = CLI.getArgs();
9024   if (supportSwiftError()) {
9025     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9026       if (Args[i].IsSwiftError) {
9027         ISD::InputArg MyFlags;
9028         MyFlags.VT = getPointerTy(DL);
9029         MyFlags.ArgVT = EVT(getPointerTy(DL));
9030         MyFlags.Flags.setSwiftError();
9031         CLI.Ins.push_back(MyFlags);
9032       }
9033     }
9034   }
9035 
9036   // Handle all of the outgoing arguments.
9037   CLI.Outs.clear();
9038   CLI.OutVals.clear();
9039   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9040     SmallVector<EVT, 4> ValueVTs;
9041     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9042     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9043     Type *FinalType = Args[i].Ty;
9044     if (Args[i].IsByVal)
9045       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9046     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9047         FinalType, CLI.CallConv, CLI.IsVarArg);
9048     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9049          ++Value) {
9050       EVT VT = ValueVTs[Value];
9051       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9052       SDValue Op = SDValue(Args[i].Node.getNode(),
9053                            Args[i].Node.getResNo() + Value);
9054       ISD::ArgFlagsTy Flags;
9055 
9056       // Certain targets (such as MIPS), may have a different ABI alignment
9057       // for a type depending on the context. Give the target a chance to
9058       // specify the alignment it wants.
9059       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9060 
9061       if (Args[i].Ty->isPointerTy()) {
9062         Flags.setPointer();
9063         Flags.setPointerAddrSpace(
9064             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9065       }
9066       if (Args[i].IsZExt)
9067         Flags.setZExt();
9068       if (Args[i].IsSExt)
9069         Flags.setSExt();
9070       if (Args[i].IsInReg) {
9071         // If we are using vectorcall calling convention, a structure that is
9072         // passed InReg - is surely an HVA
9073         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9074             isa<StructType>(FinalType)) {
9075           // The first value of a structure is marked
9076           if (0 == Value)
9077             Flags.setHvaStart();
9078           Flags.setHva();
9079         }
9080         // Set InReg Flag
9081         Flags.setInReg();
9082       }
9083       if (Args[i].IsSRet)
9084         Flags.setSRet();
9085       if (Args[i].IsSwiftSelf)
9086         Flags.setSwiftSelf();
9087       if (Args[i].IsSwiftError)
9088         Flags.setSwiftError();
9089       if (Args[i].IsCFGuardTarget)
9090         Flags.setCFGuardTarget();
9091       if (Args[i].IsByVal)
9092         Flags.setByVal();
9093       if (Args[i].IsInAlloca) {
9094         Flags.setInAlloca();
9095         // Set the byval flag for CCAssignFn callbacks that don't know about
9096         // inalloca.  This way we can know how many bytes we should've allocated
9097         // and how many bytes a callee cleanup function will pop.  If we port
9098         // inalloca to more targets, we'll have to add custom inalloca handling
9099         // in the various CC lowering callbacks.
9100         Flags.setByVal();
9101       }
9102       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9103         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9104         Type *ElementTy = Ty->getElementType();
9105 
9106         unsigned FrameSize = DL.getTypeAllocSize(
9107             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9108         Flags.setByValSize(FrameSize);
9109 
9110         // info is not there but there are cases it cannot get right.
9111         unsigned FrameAlign;
9112         if (Args[i].Alignment)
9113           FrameAlign = Args[i].Alignment;
9114         else
9115           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9116         Flags.setByValAlign(Align(FrameAlign));
9117       }
9118       if (Args[i].IsNest)
9119         Flags.setNest();
9120       if (NeedsRegBlock)
9121         Flags.setInConsecutiveRegs();
9122       Flags.setOrigAlign(OriginalAlignment);
9123 
9124       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9125                                                  CLI.CallConv, VT);
9126       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9127                                                         CLI.CallConv, VT);
9128       SmallVector<SDValue, 4> Parts(NumParts);
9129       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9130 
9131       if (Args[i].IsSExt)
9132         ExtendKind = ISD::SIGN_EXTEND;
9133       else if (Args[i].IsZExt)
9134         ExtendKind = ISD::ZERO_EXTEND;
9135 
9136       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9137       // for now.
9138       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9139           CanLowerReturn) {
9140         assert((CLI.RetTy == Args[i].Ty ||
9141                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9142                  CLI.RetTy->getPointerAddressSpace() ==
9143                      Args[i].Ty->getPointerAddressSpace())) &&
9144                RetTys.size() == NumValues && "unexpected use of 'returned'");
9145         // Before passing 'returned' to the target lowering code, ensure that
9146         // either the register MVT and the actual EVT are the same size or that
9147         // the return value and argument are extended in the same way; in these
9148         // cases it's safe to pass the argument register value unchanged as the
9149         // return register value (although it's at the target's option whether
9150         // to do so)
9151         // TODO: allow code generation to take advantage of partially preserved
9152         // registers rather than clobbering the entire register when the
9153         // parameter extension method is not compatible with the return
9154         // extension method
9155         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9156             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9157              CLI.RetZExt == Args[i].IsZExt))
9158           Flags.setReturned();
9159       }
9160 
9161       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9162                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9163 
9164       for (unsigned j = 0; j != NumParts; ++j) {
9165         // if it isn't first piece, alignment must be 1
9166         // For scalable vectors the scalable part is currently handled
9167         // by individual targets, so we just use the known minimum size here.
9168         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9169                     i < CLI.NumFixedArgs, i,
9170                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9171         if (NumParts > 1 && j == 0)
9172           MyFlags.Flags.setSplit();
9173         else if (j != 0) {
9174           MyFlags.Flags.setOrigAlign(Align::None());
9175           if (j == NumParts - 1)
9176             MyFlags.Flags.setSplitEnd();
9177         }
9178 
9179         CLI.Outs.push_back(MyFlags);
9180         CLI.OutVals.push_back(Parts[j]);
9181       }
9182 
9183       if (NeedsRegBlock && Value == NumValues - 1)
9184         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9185     }
9186   }
9187 
9188   SmallVector<SDValue, 4> InVals;
9189   CLI.Chain = LowerCall(CLI, InVals);
9190 
9191   // Update CLI.InVals to use outside of this function.
9192   CLI.InVals = InVals;
9193 
9194   // Verify that the target's LowerCall behaved as expected.
9195   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9196          "LowerCall didn't return a valid chain!");
9197   assert((!CLI.IsTailCall || InVals.empty()) &&
9198          "LowerCall emitted a return value for a tail call!");
9199   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9200          "LowerCall didn't emit the correct number of values!");
9201 
9202   // For a tail call, the return value is merely live-out and there aren't
9203   // any nodes in the DAG representing it. Return a special value to
9204   // indicate that a tail call has been emitted and no more Instructions
9205   // should be processed in the current block.
9206   if (CLI.IsTailCall) {
9207     CLI.DAG.setRoot(CLI.Chain);
9208     return std::make_pair(SDValue(), SDValue());
9209   }
9210 
9211 #ifndef NDEBUG
9212   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9213     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9214     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9215            "LowerCall emitted a value with the wrong type!");
9216   }
9217 #endif
9218 
9219   SmallVector<SDValue, 4> ReturnValues;
9220   if (!CanLowerReturn) {
9221     // The instruction result is the result of loading from the
9222     // hidden sret parameter.
9223     SmallVector<EVT, 1> PVTs;
9224     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9225 
9226     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9227     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9228     EVT PtrVT = PVTs[0];
9229 
9230     unsigned NumValues = RetTys.size();
9231     ReturnValues.resize(NumValues);
9232     SmallVector<SDValue, 4> Chains(NumValues);
9233 
9234     // An aggregate return value cannot wrap around the address space, so
9235     // offsets to its parts don't wrap either.
9236     SDNodeFlags Flags;
9237     Flags.setNoUnsignedWrap(true);
9238 
9239     for (unsigned i = 0; i < NumValues; ++i) {
9240       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9241                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9242                                                         PtrVT), Flags);
9243       SDValue L = CLI.DAG.getLoad(
9244           RetTys[i], CLI.DL, CLI.Chain, Add,
9245           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9246                                             DemoteStackIdx, Offsets[i]),
9247           /* Alignment = */ 1);
9248       ReturnValues[i] = L;
9249       Chains[i] = L.getValue(1);
9250     }
9251 
9252     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9253   } else {
9254     // Collect the legal value parts into potentially illegal values
9255     // that correspond to the original function's return values.
9256     Optional<ISD::NodeType> AssertOp;
9257     if (CLI.RetSExt)
9258       AssertOp = ISD::AssertSext;
9259     else if (CLI.RetZExt)
9260       AssertOp = ISD::AssertZext;
9261     unsigned CurReg = 0;
9262     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9263       EVT VT = RetTys[I];
9264       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9265                                                      CLI.CallConv, VT);
9266       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9267                                                        CLI.CallConv, VT);
9268 
9269       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9270                                               NumRegs, RegisterVT, VT, nullptr,
9271                                               CLI.CallConv, AssertOp));
9272       CurReg += NumRegs;
9273     }
9274 
9275     // For a function returning void, there is no return value. We can't create
9276     // such a node, so we just return a null return value in that case. In
9277     // that case, nothing will actually look at the value.
9278     if (ReturnValues.empty())
9279       return std::make_pair(SDValue(), CLI.Chain);
9280   }
9281 
9282   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9283                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9284   return std::make_pair(Res, CLI.Chain);
9285 }
9286 
9287 void TargetLowering::LowerOperationWrapper(SDNode *N,
9288                                            SmallVectorImpl<SDValue> &Results,
9289                                            SelectionDAG &DAG) const {
9290   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9291     Results.push_back(Res);
9292 }
9293 
9294 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9295   llvm_unreachable("LowerOperation not implemented for this target!");
9296 }
9297 
9298 void
9299 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9300   SDValue Op = getNonRegisterValue(V);
9301   assert((Op.getOpcode() != ISD::CopyFromReg ||
9302           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9303          "Copy from a reg to the same reg!");
9304   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9305 
9306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9307   // If this is an InlineAsm we have to match the registers required, not the
9308   // notional registers required by the type.
9309 
9310   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9311                    None); // This is not an ABI copy.
9312   SDValue Chain = DAG.getEntryNode();
9313 
9314   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9315                               FuncInfo.PreferredExtendType.end())
9316                                  ? ISD::ANY_EXTEND
9317                                  : FuncInfo.PreferredExtendType[V];
9318   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9319   PendingExports.push_back(Chain);
9320 }
9321 
9322 #include "llvm/CodeGen/SelectionDAGISel.h"
9323 
9324 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9325 /// entry block, return true.  This includes arguments used by switches, since
9326 /// the switch may expand into multiple basic blocks.
9327 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9328   // With FastISel active, we may be splitting blocks, so force creation
9329   // of virtual registers for all non-dead arguments.
9330   if (FastISel)
9331     return A->use_empty();
9332 
9333   const BasicBlock &Entry = A->getParent()->front();
9334   for (const User *U : A->users())
9335     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9336       return false;  // Use not in entry block.
9337 
9338   return true;
9339 }
9340 
9341 using ArgCopyElisionMapTy =
9342     DenseMap<const Argument *,
9343              std::pair<const AllocaInst *, const StoreInst *>>;
9344 
9345 /// Scan the entry block of the function in FuncInfo for arguments that look
9346 /// like copies into a local alloca. Record any copied arguments in
9347 /// ArgCopyElisionCandidates.
9348 static void
9349 findArgumentCopyElisionCandidates(const DataLayout &DL,
9350                                   FunctionLoweringInfo *FuncInfo,
9351                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9352   // Record the state of every static alloca used in the entry block. Argument
9353   // allocas are all used in the entry block, so we need approximately as many
9354   // entries as we have arguments.
9355   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9356   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9357   unsigned NumArgs = FuncInfo->Fn->arg_size();
9358   StaticAllocas.reserve(NumArgs * 2);
9359 
9360   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9361     if (!V)
9362       return nullptr;
9363     V = V->stripPointerCasts();
9364     const auto *AI = dyn_cast<AllocaInst>(V);
9365     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9366       return nullptr;
9367     auto Iter = StaticAllocas.insert({AI, Unknown});
9368     return &Iter.first->second;
9369   };
9370 
9371   // Look for stores of arguments to static allocas. Look through bitcasts and
9372   // GEPs to handle type coercions, as long as the alloca is fully initialized
9373   // by the store. Any non-store use of an alloca escapes it and any subsequent
9374   // unanalyzed store might write it.
9375   // FIXME: Handle structs initialized with multiple stores.
9376   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9377     // Look for stores, and handle non-store uses conservatively.
9378     const auto *SI = dyn_cast<StoreInst>(&I);
9379     if (!SI) {
9380       // We will look through cast uses, so ignore them completely.
9381       if (I.isCast())
9382         continue;
9383       // Ignore debug info intrinsics, they don't escape or store to allocas.
9384       if (isa<DbgInfoIntrinsic>(I))
9385         continue;
9386       // This is an unknown instruction. Assume it escapes or writes to all
9387       // static alloca operands.
9388       for (const Use &U : I.operands()) {
9389         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9390           *Info = StaticAllocaInfo::Clobbered;
9391       }
9392       continue;
9393     }
9394 
9395     // If the stored value is a static alloca, mark it as escaped.
9396     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9397       *Info = StaticAllocaInfo::Clobbered;
9398 
9399     // Check if the destination is a static alloca.
9400     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9401     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9402     if (!Info)
9403       continue;
9404     const AllocaInst *AI = cast<AllocaInst>(Dst);
9405 
9406     // Skip allocas that have been initialized or clobbered.
9407     if (*Info != StaticAllocaInfo::Unknown)
9408       continue;
9409 
9410     // Check if the stored value is an argument, and that this store fully
9411     // initializes the alloca. Don't elide copies from the same argument twice.
9412     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9413     const auto *Arg = dyn_cast<Argument>(Val);
9414     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9415         Arg->getType()->isEmptyTy() ||
9416         DL.getTypeStoreSize(Arg->getType()) !=
9417             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9418         ArgCopyElisionCandidates.count(Arg)) {
9419       *Info = StaticAllocaInfo::Clobbered;
9420       continue;
9421     }
9422 
9423     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9424                       << '\n');
9425 
9426     // Mark this alloca and store for argument copy elision.
9427     *Info = StaticAllocaInfo::Elidable;
9428     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9429 
9430     // Stop scanning if we've seen all arguments. This will happen early in -O0
9431     // builds, which is useful, because -O0 builds have large entry blocks and
9432     // many allocas.
9433     if (ArgCopyElisionCandidates.size() == NumArgs)
9434       break;
9435   }
9436 }
9437 
9438 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9439 /// ArgVal is a load from a suitable fixed stack object.
9440 static void tryToElideArgumentCopy(
9441     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9442     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9443     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9444     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9445     SDValue ArgVal, bool &ArgHasUses) {
9446   // Check if this is a load from a fixed stack object.
9447   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9448   if (!LNode)
9449     return;
9450   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9451   if (!FINode)
9452     return;
9453 
9454   // Check that the fixed stack object is the right size and alignment.
9455   // Look at the alignment that the user wrote on the alloca instead of looking
9456   // at the stack object.
9457   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9458   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9459   const AllocaInst *AI = ArgCopyIter->second.first;
9460   int FixedIndex = FINode->getIndex();
9461   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9462   int OldIndex = AllocaIndex;
9463   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9464   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9465     LLVM_DEBUG(
9466         dbgs() << "  argument copy elision failed due to bad fixed stack "
9467                   "object size\n");
9468     return;
9469   }
9470   unsigned RequiredAlignment = AI->getAlignment();
9471   if (!RequiredAlignment) {
9472     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9473         AI->getAllocatedType());
9474   }
9475   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9476     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9477                          "greater than stack argument alignment ("
9478                       << RequiredAlignment << " vs "
9479                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9480     return;
9481   }
9482 
9483   // Perform the elision. Delete the old stack object and replace its only use
9484   // in the variable info map. Mark the stack object as mutable.
9485   LLVM_DEBUG({
9486     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9487            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9488            << '\n';
9489   });
9490   MFI.RemoveStackObject(OldIndex);
9491   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9492   AllocaIndex = FixedIndex;
9493   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9494   Chains.push_back(ArgVal.getValue(1));
9495 
9496   // Avoid emitting code for the store implementing the copy.
9497   const StoreInst *SI = ArgCopyIter->second.second;
9498   ElidedArgCopyInstrs.insert(SI);
9499 
9500   // Check for uses of the argument again so that we can avoid exporting ArgVal
9501   // if it is't used by anything other than the store.
9502   for (const Value *U : Arg.users()) {
9503     if (U != SI) {
9504       ArgHasUses = true;
9505       break;
9506     }
9507   }
9508 }
9509 
9510 void SelectionDAGISel::LowerArguments(const Function &F) {
9511   SelectionDAG &DAG = SDB->DAG;
9512   SDLoc dl = SDB->getCurSDLoc();
9513   const DataLayout &DL = DAG.getDataLayout();
9514   SmallVector<ISD::InputArg, 16> Ins;
9515 
9516   if (!FuncInfo->CanLowerReturn) {
9517     // Put in an sret pointer parameter before all the other parameters.
9518     SmallVector<EVT, 1> ValueVTs;
9519     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9520                     F.getReturnType()->getPointerTo(
9521                         DAG.getDataLayout().getAllocaAddrSpace()),
9522                     ValueVTs);
9523 
9524     // NOTE: Assuming that a pointer will never break down to more than one VT
9525     // or one register.
9526     ISD::ArgFlagsTy Flags;
9527     Flags.setSRet();
9528     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9529     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9530                          ISD::InputArg::NoArgIndex, 0);
9531     Ins.push_back(RetArg);
9532   }
9533 
9534   // Look for stores of arguments to static allocas. Mark such arguments with a
9535   // flag to ask the target to give us the memory location of that argument if
9536   // available.
9537   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9538   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9539 
9540   // Set up the incoming argument description vector.
9541   for (const Argument &Arg : F.args()) {
9542     unsigned ArgNo = Arg.getArgNo();
9543     SmallVector<EVT, 4> ValueVTs;
9544     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9545     bool isArgValueUsed = !Arg.use_empty();
9546     unsigned PartBase = 0;
9547     Type *FinalType = Arg.getType();
9548     if (Arg.hasAttribute(Attribute::ByVal))
9549       FinalType = Arg.getParamByValType();
9550     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9551         FinalType, F.getCallingConv(), F.isVarArg());
9552     for (unsigned Value = 0, NumValues = ValueVTs.size();
9553          Value != NumValues; ++Value) {
9554       EVT VT = ValueVTs[Value];
9555       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9556       ISD::ArgFlagsTy Flags;
9557 
9558       // Certain targets (such as MIPS), may have a different ABI alignment
9559       // for a type depending on the context. Give the target a chance to
9560       // specify the alignment it wants.
9561       const Align OriginalAlignment(
9562           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9563 
9564       if (Arg.getType()->isPointerTy()) {
9565         Flags.setPointer();
9566         Flags.setPointerAddrSpace(
9567             cast<PointerType>(Arg.getType())->getAddressSpace());
9568       }
9569       if (Arg.hasAttribute(Attribute::ZExt))
9570         Flags.setZExt();
9571       if (Arg.hasAttribute(Attribute::SExt))
9572         Flags.setSExt();
9573       if (Arg.hasAttribute(Attribute::InReg)) {
9574         // If we are using vectorcall calling convention, a structure that is
9575         // passed InReg - is surely an HVA
9576         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9577             isa<StructType>(Arg.getType())) {
9578           // The first value of a structure is marked
9579           if (0 == Value)
9580             Flags.setHvaStart();
9581           Flags.setHva();
9582         }
9583         // Set InReg Flag
9584         Flags.setInReg();
9585       }
9586       if (Arg.hasAttribute(Attribute::StructRet))
9587         Flags.setSRet();
9588       if (Arg.hasAttribute(Attribute::SwiftSelf))
9589         Flags.setSwiftSelf();
9590       if (Arg.hasAttribute(Attribute::SwiftError))
9591         Flags.setSwiftError();
9592       if (Arg.hasAttribute(Attribute::ByVal))
9593         Flags.setByVal();
9594       if (Arg.hasAttribute(Attribute::InAlloca)) {
9595         Flags.setInAlloca();
9596         // Set the byval flag for CCAssignFn callbacks that don't know about
9597         // inalloca.  This way we can know how many bytes we should've allocated
9598         // and how many bytes a callee cleanup function will pop.  If we port
9599         // inalloca to more targets, we'll have to add custom inalloca handling
9600         // in the various CC lowering callbacks.
9601         Flags.setByVal();
9602       }
9603       if (F.getCallingConv() == CallingConv::X86_INTR) {
9604         // IA Interrupt passes frame (1st parameter) by value in the stack.
9605         if (ArgNo == 0)
9606           Flags.setByVal();
9607       }
9608       if (Flags.isByVal() || Flags.isInAlloca()) {
9609         Type *ElementTy = Arg.getParamByValType();
9610 
9611         // For ByVal, size and alignment should be passed from FE.  BE will
9612         // guess if this info is not there but there are cases it cannot get
9613         // right.
9614         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9615         Flags.setByValSize(FrameSize);
9616 
9617         unsigned FrameAlign;
9618         if (Arg.getParamAlignment())
9619           FrameAlign = Arg.getParamAlignment();
9620         else
9621           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9622         Flags.setByValAlign(Align(FrameAlign));
9623       }
9624       if (Arg.hasAttribute(Attribute::Nest))
9625         Flags.setNest();
9626       if (NeedsRegBlock)
9627         Flags.setInConsecutiveRegs();
9628       Flags.setOrigAlign(OriginalAlignment);
9629       if (ArgCopyElisionCandidates.count(&Arg))
9630         Flags.setCopyElisionCandidate();
9631       if (Arg.hasAttribute(Attribute::Returned))
9632         Flags.setReturned();
9633 
9634       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9635           *CurDAG->getContext(), F.getCallingConv(), VT);
9636       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9637           *CurDAG->getContext(), F.getCallingConv(), VT);
9638       for (unsigned i = 0; i != NumRegs; ++i) {
9639         // For scalable vectors, use the minimum size; individual targets
9640         // are responsible for handling scalable vector arguments and
9641         // return values.
9642         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9643                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9644         if (NumRegs > 1 && i == 0)
9645           MyFlags.Flags.setSplit();
9646         // if it isn't first piece, alignment must be 1
9647         else if (i > 0) {
9648           MyFlags.Flags.setOrigAlign(Align::None());
9649           if (i == NumRegs - 1)
9650             MyFlags.Flags.setSplitEnd();
9651         }
9652         Ins.push_back(MyFlags);
9653       }
9654       if (NeedsRegBlock && Value == NumValues - 1)
9655         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9656       PartBase += VT.getStoreSize().getKnownMinSize();
9657     }
9658   }
9659 
9660   // Call the target to set up the argument values.
9661   SmallVector<SDValue, 8> InVals;
9662   SDValue NewRoot = TLI->LowerFormalArguments(
9663       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9664 
9665   // Verify that the target's LowerFormalArguments behaved as expected.
9666   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9667          "LowerFormalArguments didn't return a valid chain!");
9668   assert(InVals.size() == Ins.size() &&
9669          "LowerFormalArguments didn't emit the correct number of values!");
9670   LLVM_DEBUG({
9671     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9672       assert(InVals[i].getNode() &&
9673              "LowerFormalArguments emitted a null value!");
9674       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9675              "LowerFormalArguments emitted a value with the wrong type!");
9676     }
9677   });
9678 
9679   // Update the DAG with the new chain value resulting from argument lowering.
9680   DAG.setRoot(NewRoot);
9681 
9682   // Set up the argument values.
9683   unsigned i = 0;
9684   if (!FuncInfo->CanLowerReturn) {
9685     // Create a virtual register for the sret pointer, and put in a copy
9686     // from the sret argument into it.
9687     SmallVector<EVT, 1> ValueVTs;
9688     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9689                     F.getReturnType()->getPointerTo(
9690                         DAG.getDataLayout().getAllocaAddrSpace()),
9691                     ValueVTs);
9692     MVT VT = ValueVTs[0].getSimpleVT();
9693     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9694     Optional<ISD::NodeType> AssertOp = None;
9695     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9696                                         nullptr, F.getCallingConv(), AssertOp);
9697 
9698     MachineFunction& MF = SDB->DAG.getMachineFunction();
9699     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9700     Register SRetReg =
9701         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9702     FuncInfo->DemoteRegister = SRetReg;
9703     NewRoot =
9704         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9705     DAG.setRoot(NewRoot);
9706 
9707     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9708     ++i;
9709   }
9710 
9711   SmallVector<SDValue, 4> Chains;
9712   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9713   for (const Argument &Arg : F.args()) {
9714     SmallVector<SDValue, 4> ArgValues;
9715     SmallVector<EVT, 4> ValueVTs;
9716     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9717     unsigned NumValues = ValueVTs.size();
9718     if (NumValues == 0)
9719       continue;
9720 
9721     bool ArgHasUses = !Arg.use_empty();
9722 
9723     // Elide the copying store if the target loaded this argument from a
9724     // suitable fixed stack object.
9725     if (Ins[i].Flags.isCopyElisionCandidate()) {
9726       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9727                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9728                              InVals[i], ArgHasUses);
9729     }
9730 
9731     // If this argument is unused then remember its value. It is used to generate
9732     // debugging information.
9733     bool isSwiftErrorArg =
9734         TLI->supportSwiftError() &&
9735         Arg.hasAttribute(Attribute::SwiftError);
9736     if (!ArgHasUses && !isSwiftErrorArg) {
9737       SDB->setUnusedArgValue(&Arg, InVals[i]);
9738 
9739       // Also remember any frame index for use in FastISel.
9740       if (FrameIndexSDNode *FI =
9741           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9742         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9743     }
9744 
9745     for (unsigned Val = 0; Val != NumValues; ++Val) {
9746       EVT VT = ValueVTs[Val];
9747       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9748                                                       F.getCallingConv(), VT);
9749       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9750           *CurDAG->getContext(), F.getCallingConv(), VT);
9751 
9752       // Even an apparent 'unused' swifterror argument needs to be returned. So
9753       // we do generate a copy for it that can be used on return from the
9754       // function.
9755       if (ArgHasUses || isSwiftErrorArg) {
9756         Optional<ISD::NodeType> AssertOp;
9757         if (Arg.hasAttribute(Attribute::SExt))
9758           AssertOp = ISD::AssertSext;
9759         else if (Arg.hasAttribute(Attribute::ZExt))
9760           AssertOp = ISD::AssertZext;
9761 
9762         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9763                                              PartVT, VT, nullptr,
9764                                              F.getCallingConv(), AssertOp));
9765       }
9766 
9767       i += NumParts;
9768     }
9769 
9770     // We don't need to do anything else for unused arguments.
9771     if (ArgValues.empty())
9772       continue;
9773 
9774     // Note down frame index.
9775     if (FrameIndexSDNode *FI =
9776         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9777       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9778 
9779     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9780                                      SDB->getCurSDLoc());
9781 
9782     SDB->setValue(&Arg, Res);
9783     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9784       // We want to associate the argument with the frame index, among
9785       // involved operands, that correspond to the lowest address. The
9786       // getCopyFromParts function, called earlier, is swapping the order of
9787       // the operands to BUILD_PAIR depending on endianness. The result of
9788       // that swapping is that the least significant bits of the argument will
9789       // be in the first operand of the BUILD_PAIR node, and the most
9790       // significant bits will be in the second operand.
9791       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9792       if (LoadSDNode *LNode =
9793           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9794         if (FrameIndexSDNode *FI =
9795             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9796           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9797     }
9798 
9799     // Analyses past this point are naive and don't expect an assertion.
9800     if (Res.getOpcode() == ISD::AssertZext)
9801       Res = Res.getOperand(0);
9802 
9803     // Update the SwiftErrorVRegDefMap.
9804     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9805       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9806       if (Register::isVirtualRegister(Reg))
9807         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9808                                    Reg);
9809     }
9810 
9811     // If this argument is live outside of the entry block, insert a copy from
9812     // wherever we got it to the vreg that other BB's will reference it as.
9813     if (Res.getOpcode() == ISD::CopyFromReg) {
9814       // If we can, though, try to skip creating an unnecessary vreg.
9815       // FIXME: This isn't very clean... it would be nice to make this more
9816       // general.
9817       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9818       if (Register::isVirtualRegister(Reg)) {
9819         FuncInfo->ValueMap[&Arg] = Reg;
9820         continue;
9821       }
9822     }
9823     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9824       FuncInfo->InitializeRegForValue(&Arg);
9825       SDB->CopyToExportRegsIfNeeded(&Arg);
9826     }
9827   }
9828 
9829   if (!Chains.empty()) {
9830     Chains.push_back(NewRoot);
9831     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9832   }
9833 
9834   DAG.setRoot(NewRoot);
9835 
9836   assert(i == InVals.size() && "Argument register count mismatch!");
9837 
9838   // If any argument copy elisions occurred and we have debug info, update the
9839   // stale frame indices used in the dbg.declare variable info table.
9840   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9841   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9842     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9843       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9844       if (I != ArgCopyElisionFrameIndexMap.end())
9845         VI.Slot = I->second;
9846     }
9847   }
9848 
9849   // Finally, if the target has anything special to do, allow it to do so.
9850   EmitFunctionEntryCode();
9851 }
9852 
9853 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9854 /// ensure constants are generated when needed.  Remember the virtual registers
9855 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9856 /// directly add them, because expansion might result in multiple MBB's for one
9857 /// BB.  As such, the start of the BB might correspond to a different MBB than
9858 /// the end.
9859 void
9860 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9861   const Instruction *TI = LLVMBB->getTerminator();
9862 
9863   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9864 
9865   // Check PHI nodes in successors that expect a value to be available from this
9866   // block.
9867   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9868     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9869     if (!isa<PHINode>(SuccBB->begin())) continue;
9870     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9871 
9872     // If this terminator has multiple identical successors (common for
9873     // switches), only handle each succ once.
9874     if (!SuccsHandled.insert(SuccMBB).second)
9875       continue;
9876 
9877     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9878 
9879     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9880     // nodes and Machine PHI nodes, but the incoming operands have not been
9881     // emitted yet.
9882     for (const PHINode &PN : SuccBB->phis()) {
9883       // Ignore dead phi's.
9884       if (PN.use_empty())
9885         continue;
9886 
9887       // Skip empty types
9888       if (PN.getType()->isEmptyTy())
9889         continue;
9890 
9891       unsigned Reg;
9892       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9893 
9894       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9895         unsigned &RegOut = ConstantsOut[C];
9896         if (RegOut == 0) {
9897           RegOut = FuncInfo.CreateRegs(C);
9898           CopyValueToVirtualRegister(C, RegOut);
9899         }
9900         Reg = RegOut;
9901       } else {
9902         DenseMap<const Value *, unsigned>::iterator I =
9903           FuncInfo.ValueMap.find(PHIOp);
9904         if (I != FuncInfo.ValueMap.end())
9905           Reg = I->second;
9906         else {
9907           assert(isa<AllocaInst>(PHIOp) &&
9908                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9909                  "Didn't codegen value into a register!??");
9910           Reg = FuncInfo.CreateRegs(PHIOp);
9911           CopyValueToVirtualRegister(PHIOp, Reg);
9912         }
9913       }
9914 
9915       // Remember that this register needs to added to the machine PHI node as
9916       // the input for this MBB.
9917       SmallVector<EVT, 4> ValueVTs;
9918       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9919       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9920       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9921         EVT VT = ValueVTs[vti];
9922         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9923         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9924           FuncInfo.PHINodesToUpdate.push_back(
9925               std::make_pair(&*MBBI++, Reg + i));
9926         Reg += NumRegisters;
9927       }
9928     }
9929   }
9930 
9931   ConstantsOut.clear();
9932 }
9933 
9934 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9935 /// is 0.
9936 MachineBasicBlock *
9937 SelectionDAGBuilder::StackProtectorDescriptor::
9938 AddSuccessorMBB(const BasicBlock *BB,
9939                 MachineBasicBlock *ParentMBB,
9940                 bool IsLikely,
9941                 MachineBasicBlock *SuccMBB) {
9942   // If SuccBB has not been created yet, create it.
9943   if (!SuccMBB) {
9944     MachineFunction *MF = ParentMBB->getParent();
9945     MachineFunction::iterator BBI(ParentMBB);
9946     SuccMBB = MF->CreateMachineBasicBlock(BB);
9947     MF->insert(++BBI, SuccMBB);
9948   }
9949   // Add it as a successor of ParentMBB.
9950   ParentMBB->addSuccessor(
9951       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9952   return SuccMBB;
9953 }
9954 
9955 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9956   MachineFunction::iterator I(MBB);
9957   if (++I == FuncInfo.MF->end())
9958     return nullptr;
9959   return &*I;
9960 }
9961 
9962 /// During lowering new call nodes can be created (such as memset, etc.).
9963 /// Those will become new roots of the current DAG, but complications arise
9964 /// when they are tail calls. In such cases, the call lowering will update
9965 /// the root, but the builder still needs to know that a tail call has been
9966 /// lowered in order to avoid generating an additional return.
9967 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9968   // If the node is null, we do have a tail call.
9969   if (MaybeTC.getNode() != nullptr)
9970     DAG.setRoot(MaybeTC);
9971   else
9972     HasTailCall = true;
9973 }
9974 
9975 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9976                                         MachineBasicBlock *SwitchMBB,
9977                                         MachineBasicBlock *DefaultMBB) {
9978   MachineFunction *CurMF = FuncInfo.MF;
9979   MachineBasicBlock *NextMBB = nullptr;
9980   MachineFunction::iterator BBI(W.MBB);
9981   if (++BBI != FuncInfo.MF->end())
9982     NextMBB = &*BBI;
9983 
9984   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9985 
9986   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9987 
9988   if (Size == 2 && W.MBB == SwitchMBB) {
9989     // If any two of the cases has the same destination, and if one value
9990     // is the same as the other, but has one bit unset that the other has set,
9991     // use bit manipulation to do two compares at once.  For example:
9992     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9993     // TODO: This could be extended to merge any 2 cases in switches with 3
9994     // cases.
9995     // TODO: Handle cases where W.CaseBB != SwitchBB.
9996     CaseCluster &Small = *W.FirstCluster;
9997     CaseCluster &Big = *W.LastCluster;
9998 
9999     if (Small.Low == Small.High && Big.Low == Big.High &&
10000         Small.MBB == Big.MBB) {
10001       const APInt &SmallValue = Small.Low->getValue();
10002       const APInt &BigValue = Big.Low->getValue();
10003 
10004       // Check that there is only one bit different.
10005       APInt CommonBit = BigValue ^ SmallValue;
10006       if (CommonBit.isPowerOf2()) {
10007         SDValue CondLHS = getValue(Cond);
10008         EVT VT = CondLHS.getValueType();
10009         SDLoc DL = getCurSDLoc();
10010 
10011         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10012                                  DAG.getConstant(CommonBit, DL, VT));
10013         SDValue Cond = DAG.getSetCC(
10014             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10015             ISD::SETEQ);
10016 
10017         // Update successor info.
10018         // Both Small and Big will jump to Small.BB, so we sum up the
10019         // probabilities.
10020         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10021         if (BPI)
10022           addSuccessorWithProb(
10023               SwitchMBB, DefaultMBB,
10024               // The default destination is the first successor in IR.
10025               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10026         else
10027           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10028 
10029         // Insert the true branch.
10030         SDValue BrCond =
10031             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10032                         DAG.getBasicBlock(Small.MBB));
10033         // Insert the false branch.
10034         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10035                              DAG.getBasicBlock(DefaultMBB));
10036 
10037         DAG.setRoot(BrCond);
10038         return;
10039       }
10040     }
10041   }
10042 
10043   if (TM.getOptLevel() != CodeGenOpt::None) {
10044     // Here, we order cases by probability so the most likely case will be
10045     // checked first. However, two clusters can have the same probability in
10046     // which case their relative ordering is non-deterministic. So we use Low
10047     // as a tie-breaker as clusters are guaranteed to never overlap.
10048     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10049                [](const CaseCluster &a, const CaseCluster &b) {
10050       return a.Prob != b.Prob ?
10051              a.Prob > b.Prob :
10052              a.Low->getValue().slt(b.Low->getValue());
10053     });
10054 
10055     // Rearrange the case blocks so that the last one falls through if possible
10056     // without changing the order of probabilities.
10057     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10058       --I;
10059       if (I->Prob > W.LastCluster->Prob)
10060         break;
10061       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10062         std::swap(*I, *W.LastCluster);
10063         break;
10064       }
10065     }
10066   }
10067 
10068   // Compute total probability.
10069   BranchProbability DefaultProb = W.DefaultProb;
10070   BranchProbability UnhandledProbs = DefaultProb;
10071   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10072     UnhandledProbs += I->Prob;
10073 
10074   MachineBasicBlock *CurMBB = W.MBB;
10075   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10076     bool FallthroughUnreachable = false;
10077     MachineBasicBlock *Fallthrough;
10078     if (I == W.LastCluster) {
10079       // For the last cluster, fall through to the default destination.
10080       Fallthrough = DefaultMBB;
10081       FallthroughUnreachable = isa<UnreachableInst>(
10082           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10083     } else {
10084       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10085       CurMF->insert(BBI, Fallthrough);
10086       // Put Cond in a virtual register to make it available from the new blocks.
10087       ExportFromCurrentBlock(Cond);
10088     }
10089     UnhandledProbs -= I->Prob;
10090 
10091     switch (I->Kind) {
10092       case CC_JumpTable: {
10093         // FIXME: Optimize away range check based on pivot comparisons.
10094         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10095         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10096 
10097         // The jump block hasn't been inserted yet; insert it here.
10098         MachineBasicBlock *JumpMBB = JT->MBB;
10099         CurMF->insert(BBI, JumpMBB);
10100 
10101         auto JumpProb = I->Prob;
10102         auto FallthroughProb = UnhandledProbs;
10103 
10104         // If the default statement is a target of the jump table, we evenly
10105         // distribute the default probability to successors of CurMBB. Also
10106         // update the probability on the edge from JumpMBB to Fallthrough.
10107         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10108                                               SE = JumpMBB->succ_end();
10109              SI != SE; ++SI) {
10110           if (*SI == DefaultMBB) {
10111             JumpProb += DefaultProb / 2;
10112             FallthroughProb -= DefaultProb / 2;
10113             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10114             JumpMBB->normalizeSuccProbs();
10115             break;
10116           }
10117         }
10118 
10119         if (FallthroughUnreachable) {
10120           // Skip the range check if the fallthrough block is unreachable.
10121           JTH->OmitRangeCheck = true;
10122         }
10123 
10124         if (!JTH->OmitRangeCheck)
10125           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10126         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10127         CurMBB->normalizeSuccProbs();
10128 
10129         // The jump table header will be inserted in our current block, do the
10130         // range check, and fall through to our fallthrough block.
10131         JTH->HeaderBB = CurMBB;
10132         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10133 
10134         // If we're in the right place, emit the jump table header right now.
10135         if (CurMBB == SwitchMBB) {
10136           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10137           JTH->Emitted = true;
10138         }
10139         break;
10140       }
10141       case CC_BitTests: {
10142         // FIXME: Optimize away range check based on pivot comparisons.
10143         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10144 
10145         // The bit test blocks haven't been inserted yet; insert them here.
10146         for (BitTestCase &BTC : BTB->Cases)
10147           CurMF->insert(BBI, BTC.ThisBB);
10148 
10149         // Fill in fields of the BitTestBlock.
10150         BTB->Parent = CurMBB;
10151         BTB->Default = Fallthrough;
10152 
10153         BTB->DefaultProb = UnhandledProbs;
10154         // If the cases in bit test don't form a contiguous range, we evenly
10155         // distribute the probability on the edge to Fallthrough to two
10156         // successors of CurMBB.
10157         if (!BTB->ContiguousRange) {
10158           BTB->Prob += DefaultProb / 2;
10159           BTB->DefaultProb -= DefaultProb / 2;
10160         }
10161 
10162         if (FallthroughUnreachable) {
10163           // Skip the range check if the fallthrough block is unreachable.
10164           BTB->OmitRangeCheck = true;
10165         }
10166 
10167         // If we're in the right place, emit the bit test header right now.
10168         if (CurMBB == SwitchMBB) {
10169           visitBitTestHeader(*BTB, SwitchMBB);
10170           BTB->Emitted = true;
10171         }
10172         break;
10173       }
10174       case CC_Range: {
10175         const Value *RHS, *LHS, *MHS;
10176         ISD::CondCode CC;
10177         if (I->Low == I->High) {
10178           // Check Cond == I->Low.
10179           CC = ISD::SETEQ;
10180           LHS = Cond;
10181           RHS=I->Low;
10182           MHS = nullptr;
10183         } else {
10184           // Check I->Low <= Cond <= I->High.
10185           CC = ISD::SETLE;
10186           LHS = I->Low;
10187           MHS = Cond;
10188           RHS = I->High;
10189         }
10190 
10191         // If Fallthrough is unreachable, fold away the comparison.
10192         if (FallthroughUnreachable)
10193           CC = ISD::SETTRUE;
10194 
10195         // The false probability is the sum of all unhandled cases.
10196         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10197                      getCurSDLoc(), I->Prob, UnhandledProbs);
10198 
10199         if (CurMBB == SwitchMBB)
10200           visitSwitchCase(CB, SwitchMBB);
10201         else
10202           SL->SwitchCases.push_back(CB);
10203 
10204         break;
10205       }
10206     }
10207     CurMBB = Fallthrough;
10208   }
10209 }
10210 
10211 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10212                                               CaseClusterIt First,
10213                                               CaseClusterIt Last) {
10214   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10215     if (X.Prob != CC.Prob)
10216       return X.Prob > CC.Prob;
10217 
10218     // Ties are broken by comparing the case value.
10219     return X.Low->getValue().slt(CC.Low->getValue());
10220   });
10221 }
10222 
10223 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10224                                         const SwitchWorkListItem &W,
10225                                         Value *Cond,
10226                                         MachineBasicBlock *SwitchMBB) {
10227   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10228          "Clusters not sorted?");
10229 
10230   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10231 
10232   // Balance the tree based on branch probabilities to create a near-optimal (in
10233   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10234   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10235   CaseClusterIt LastLeft = W.FirstCluster;
10236   CaseClusterIt FirstRight = W.LastCluster;
10237   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10238   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10239 
10240   // Move LastLeft and FirstRight towards each other from opposite directions to
10241   // find a partitioning of the clusters which balances the probability on both
10242   // sides. If LeftProb and RightProb are equal, alternate which side is
10243   // taken to ensure 0-probability nodes are distributed evenly.
10244   unsigned I = 0;
10245   while (LastLeft + 1 < FirstRight) {
10246     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10247       LeftProb += (++LastLeft)->Prob;
10248     else
10249       RightProb += (--FirstRight)->Prob;
10250     I++;
10251   }
10252 
10253   while (true) {
10254     // Our binary search tree differs from a typical BST in that ours can have up
10255     // to three values in each leaf. The pivot selection above doesn't take that
10256     // into account, which means the tree might require more nodes and be less
10257     // efficient. We compensate for this here.
10258 
10259     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10260     unsigned NumRight = W.LastCluster - FirstRight + 1;
10261 
10262     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10263       // If one side has less than 3 clusters, and the other has more than 3,
10264       // consider taking a cluster from the other side.
10265 
10266       if (NumLeft < NumRight) {
10267         // Consider moving the first cluster on the right to the left side.
10268         CaseCluster &CC = *FirstRight;
10269         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10270         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10271         if (LeftSideRank <= RightSideRank) {
10272           // Moving the cluster to the left does not demote it.
10273           ++LastLeft;
10274           ++FirstRight;
10275           continue;
10276         }
10277       } else {
10278         assert(NumRight < NumLeft);
10279         // Consider moving the last element on the left to the right side.
10280         CaseCluster &CC = *LastLeft;
10281         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10282         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10283         if (RightSideRank <= LeftSideRank) {
10284           // Moving the cluster to the right does not demot it.
10285           --LastLeft;
10286           --FirstRight;
10287           continue;
10288         }
10289       }
10290     }
10291     break;
10292   }
10293 
10294   assert(LastLeft + 1 == FirstRight);
10295   assert(LastLeft >= W.FirstCluster);
10296   assert(FirstRight <= W.LastCluster);
10297 
10298   // Use the first element on the right as pivot since we will make less-than
10299   // comparisons against it.
10300   CaseClusterIt PivotCluster = FirstRight;
10301   assert(PivotCluster > W.FirstCluster);
10302   assert(PivotCluster <= W.LastCluster);
10303 
10304   CaseClusterIt FirstLeft = W.FirstCluster;
10305   CaseClusterIt LastRight = W.LastCluster;
10306 
10307   const ConstantInt *Pivot = PivotCluster->Low;
10308 
10309   // New blocks will be inserted immediately after the current one.
10310   MachineFunction::iterator BBI(W.MBB);
10311   ++BBI;
10312 
10313   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10314   // we can branch to its destination directly if it's squeezed exactly in
10315   // between the known lower bound and Pivot - 1.
10316   MachineBasicBlock *LeftMBB;
10317   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10318       FirstLeft->Low == W.GE &&
10319       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10320     LeftMBB = FirstLeft->MBB;
10321   } else {
10322     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10323     FuncInfo.MF->insert(BBI, LeftMBB);
10324     WorkList.push_back(
10325         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10326     // Put Cond in a virtual register to make it available from the new blocks.
10327     ExportFromCurrentBlock(Cond);
10328   }
10329 
10330   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10331   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10332   // directly if RHS.High equals the current upper bound.
10333   MachineBasicBlock *RightMBB;
10334   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10335       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10336     RightMBB = FirstRight->MBB;
10337   } else {
10338     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10339     FuncInfo.MF->insert(BBI, RightMBB);
10340     WorkList.push_back(
10341         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10342     // Put Cond in a virtual register to make it available from the new blocks.
10343     ExportFromCurrentBlock(Cond);
10344   }
10345 
10346   // Create the CaseBlock record that will be used to lower the branch.
10347   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10348                getCurSDLoc(), LeftProb, RightProb);
10349 
10350   if (W.MBB == SwitchMBB)
10351     visitSwitchCase(CB, SwitchMBB);
10352   else
10353     SL->SwitchCases.push_back(CB);
10354 }
10355 
10356 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10357 // from the swith statement.
10358 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10359                                             BranchProbability PeeledCaseProb) {
10360   if (PeeledCaseProb == BranchProbability::getOne())
10361     return BranchProbability::getZero();
10362   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10363 
10364   uint32_t Numerator = CaseProb.getNumerator();
10365   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10366   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10367 }
10368 
10369 // Try to peel the top probability case if it exceeds the threshold.
10370 // Return current MachineBasicBlock for the switch statement if the peeling
10371 // does not occur.
10372 // If the peeling is performed, return the newly created MachineBasicBlock
10373 // for the peeled switch statement. Also update Clusters to remove the peeled
10374 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10375 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10376     const SwitchInst &SI, CaseClusterVector &Clusters,
10377     BranchProbability &PeeledCaseProb) {
10378   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10379   // Don't perform if there is only one cluster or optimizing for size.
10380   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10381       TM.getOptLevel() == CodeGenOpt::None ||
10382       SwitchMBB->getParent()->getFunction().hasMinSize())
10383     return SwitchMBB;
10384 
10385   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10386   unsigned PeeledCaseIndex = 0;
10387   bool SwitchPeeled = false;
10388   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10389     CaseCluster &CC = Clusters[Index];
10390     if (CC.Prob < TopCaseProb)
10391       continue;
10392     TopCaseProb = CC.Prob;
10393     PeeledCaseIndex = Index;
10394     SwitchPeeled = true;
10395   }
10396   if (!SwitchPeeled)
10397     return SwitchMBB;
10398 
10399   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10400                     << TopCaseProb << "\n");
10401 
10402   // Record the MBB for the peeled switch statement.
10403   MachineFunction::iterator BBI(SwitchMBB);
10404   ++BBI;
10405   MachineBasicBlock *PeeledSwitchMBB =
10406       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10407   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10408 
10409   ExportFromCurrentBlock(SI.getCondition());
10410   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10411   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10412                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10413   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10414 
10415   Clusters.erase(PeeledCaseIt);
10416   for (CaseCluster &CC : Clusters) {
10417     LLVM_DEBUG(
10418         dbgs() << "Scale the probablity for one cluster, before scaling: "
10419                << CC.Prob << "\n");
10420     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10421     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10422   }
10423   PeeledCaseProb = TopCaseProb;
10424   return PeeledSwitchMBB;
10425 }
10426 
10427 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10428   // Extract cases from the switch.
10429   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10430   CaseClusterVector Clusters;
10431   Clusters.reserve(SI.getNumCases());
10432   for (auto I : SI.cases()) {
10433     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10434     const ConstantInt *CaseVal = I.getCaseValue();
10435     BranchProbability Prob =
10436         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10437             : BranchProbability(1, SI.getNumCases() + 1);
10438     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10439   }
10440 
10441   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10442 
10443   // Cluster adjacent cases with the same destination. We do this at all
10444   // optimization levels because it's cheap to do and will make codegen faster
10445   // if there are many clusters.
10446   sortAndRangeify(Clusters);
10447 
10448   // The branch probablity of the peeled case.
10449   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10450   MachineBasicBlock *PeeledSwitchMBB =
10451       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10452 
10453   // If there is only the default destination, jump there directly.
10454   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10455   if (Clusters.empty()) {
10456     assert(PeeledSwitchMBB == SwitchMBB);
10457     SwitchMBB->addSuccessor(DefaultMBB);
10458     if (DefaultMBB != NextBlock(SwitchMBB)) {
10459       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10460                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10461     }
10462     return;
10463   }
10464 
10465   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10466   SL->findBitTestClusters(Clusters, &SI);
10467 
10468   LLVM_DEBUG({
10469     dbgs() << "Case clusters: ";
10470     for (const CaseCluster &C : Clusters) {
10471       if (C.Kind == CC_JumpTable)
10472         dbgs() << "JT:";
10473       if (C.Kind == CC_BitTests)
10474         dbgs() << "BT:";
10475 
10476       C.Low->getValue().print(dbgs(), true);
10477       if (C.Low != C.High) {
10478         dbgs() << '-';
10479         C.High->getValue().print(dbgs(), true);
10480       }
10481       dbgs() << ' ';
10482     }
10483     dbgs() << '\n';
10484   });
10485 
10486   assert(!Clusters.empty());
10487   SwitchWorkList WorkList;
10488   CaseClusterIt First = Clusters.begin();
10489   CaseClusterIt Last = Clusters.end() - 1;
10490   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10491   // Scale the branchprobability for DefaultMBB if the peel occurs and
10492   // DefaultMBB is not replaced.
10493   if (PeeledCaseProb != BranchProbability::getZero() &&
10494       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10495     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10496   WorkList.push_back(
10497       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10498 
10499   while (!WorkList.empty()) {
10500     SwitchWorkListItem W = WorkList.back();
10501     WorkList.pop_back();
10502     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10503 
10504     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10505         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10506       // For optimized builds, lower large range as a balanced binary tree.
10507       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10508       continue;
10509     }
10510 
10511     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10512   }
10513 }
10514 
10515 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10516   SDValue N = getValue(I.getOperand(0));
10517   setValue(&I, N);
10518 }
10519