xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision daee549b1756a7aa0f1560d5460ae580897e4c1a)
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   if (Opcode == ISD::STRICT_FP_ROUND)
6919     Opers.push_back(
6920         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6921 
6922   SDVTList VTs = DAG.getVTList(ValueVTs);
6923   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
6924 
6925   if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) {
6926     SDNodeFlags Flags;
6927     Flags.setFPExcept(true);
6928     Result->setFlags(Flags);
6929   }
6930 
6931   assert(Result.getNode()->getNumValues() == 2);
6932   // See above -- chain is handled like for loads here.
6933   SDValue OutChain = Result.getValue(1);
6934   PendingLoads.push_back(OutChain);
6935   SDValue FPResult = Result.getValue(0);
6936   setValue(&FPI, FPResult);
6937 }
6938 
6939 std::pair<SDValue, SDValue>
6940 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6941                                     const BasicBlock *EHPadBB) {
6942   MachineFunction &MF = DAG.getMachineFunction();
6943   MachineModuleInfo &MMI = MF.getMMI();
6944   MCSymbol *BeginLabel = nullptr;
6945 
6946   if (EHPadBB) {
6947     // Insert a label before the invoke call to mark the try range.  This can be
6948     // used to detect deletion of the invoke via the MachineModuleInfo.
6949     BeginLabel = MMI.getContext().createTempSymbol();
6950 
6951     // For SjLj, keep track of which landing pads go with which invokes
6952     // so as to maintain the ordering of pads in the LSDA.
6953     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6954     if (CallSiteIndex) {
6955       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6956       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6957 
6958       // Now that the call site is handled, stop tracking it.
6959       MMI.setCurrentCallSite(0);
6960     }
6961 
6962     // Both PendingLoads and PendingExports must be flushed here;
6963     // this call might not return.
6964     (void)getRoot();
6965     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6966 
6967     CLI.setChain(getRoot());
6968   }
6969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6970   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6971 
6972   assert((CLI.IsTailCall || Result.second.getNode()) &&
6973          "Non-null chain expected with non-tail call!");
6974   assert((Result.second.getNode() || !Result.first.getNode()) &&
6975          "Null value expected with tail call!");
6976 
6977   if (!Result.second.getNode()) {
6978     // As a special case, a null chain means that a tail call has been emitted
6979     // and the DAG root is already updated.
6980     HasTailCall = true;
6981 
6982     // Since there's no actual continuation from this block, nothing can be
6983     // relying on us setting vregs for them.
6984     PendingExports.clear();
6985   } else {
6986     DAG.setRoot(Result.second);
6987   }
6988 
6989   if (EHPadBB) {
6990     // Insert a label at the end of the invoke call to mark the try range.  This
6991     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6992     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6993     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6994 
6995     // Inform MachineModuleInfo of range.
6996     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6997     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6998     // actually use outlined funclets and their LSDA info style.
6999     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7000       assert(CLI.CS);
7001       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7002       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7003                                 BeginLabel, EndLabel);
7004     } else if (!isScopedEHPersonality(Pers)) {
7005       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7006     }
7007   }
7008 
7009   return Result;
7010 }
7011 
7012 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7013                                       bool isTailCall,
7014                                       const BasicBlock *EHPadBB) {
7015   auto &DL = DAG.getDataLayout();
7016   FunctionType *FTy = CS.getFunctionType();
7017   Type *RetTy = CS.getType();
7018 
7019   TargetLowering::ArgListTy Args;
7020   Args.reserve(CS.arg_size());
7021 
7022   const Value *SwiftErrorVal = nullptr;
7023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7024 
7025   // We can't tail call inside a function with a swifterror argument. Lowering
7026   // does not support this yet. It would have to move into the swifterror
7027   // register before the call.
7028   auto *Caller = CS.getInstruction()->getParent()->getParent();
7029   if (TLI.supportSwiftError() &&
7030       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7031     isTailCall = false;
7032 
7033   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7034        i != e; ++i) {
7035     TargetLowering::ArgListEntry Entry;
7036     const Value *V = *i;
7037 
7038     // Skip empty types
7039     if (V->getType()->isEmptyTy())
7040       continue;
7041 
7042     SDValue ArgNode = getValue(V);
7043     Entry.Node = ArgNode; Entry.Ty = V->getType();
7044 
7045     Entry.setAttributes(&CS, i - CS.arg_begin());
7046 
7047     // Use swifterror virtual register as input to the call.
7048     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7049       SwiftErrorVal = V;
7050       // We find the virtual register for the actual swifterror argument.
7051       // Instead of using the Value, we use the virtual register instead.
7052       Entry.Node = DAG.getRegister(
7053           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7054           EVT(TLI.getPointerTy(DL)));
7055     }
7056 
7057     Args.push_back(Entry);
7058 
7059     // If we have an explicit sret argument that is an Instruction, (i.e., it
7060     // might point to function-local memory), we can't meaningfully tail-call.
7061     if (Entry.IsSRet && isa<Instruction>(V))
7062       isTailCall = false;
7063   }
7064 
7065   // If call site has a cfguardtarget operand bundle, create and add an
7066   // additional ArgListEntry.
7067   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7068     TargetLowering::ArgListEntry Entry;
7069     Value *V = Bundle->Inputs[0];
7070     SDValue ArgNode = getValue(V);
7071     Entry.Node = ArgNode;
7072     Entry.Ty = V->getType();
7073     Entry.IsCFGuardTarget = true;
7074     Args.push_back(Entry);
7075   }
7076 
7077   // Check if target-independent constraints permit a tail call here.
7078   // Target-dependent constraints are checked within TLI->LowerCallTo.
7079   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7080     isTailCall = false;
7081 
7082   // Disable tail calls if there is an swifterror argument. Targets have not
7083   // been updated to support tail calls.
7084   if (TLI.supportSwiftError() && SwiftErrorVal)
7085     isTailCall = false;
7086 
7087   TargetLowering::CallLoweringInfo CLI(DAG);
7088   CLI.setDebugLoc(getCurSDLoc())
7089       .setChain(getRoot())
7090       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7091       .setTailCall(isTailCall)
7092       .setConvergent(CS.isConvergent());
7093   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7094 
7095   if (Result.first.getNode()) {
7096     const Instruction *Inst = CS.getInstruction();
7097     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7098     setValue(Inst, Result.first);
7099   }
7100 
7101   // The last element of CLI.InVals has the SDValue for swifterror return.
7102   // Here we copy it to a virtual register and update SwiftErrorMap for
7103   // book-keeping.
7104   if (SwiftErrorVal && TLI.supportSwiftError()) {
7105     // Get the last element of InVals.
7106     SDValue Src = CLI.InVals.back();
7107     Register VReg = SwiftError.getOrCreateVRegDefAt(
7108         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7109     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7110     DAG.setRoot(CopyNode);
7111   }
7112 }
7113 
7114 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7115                              SelectionDAGBuilder &Builder) {
7116   // Check to see if this load can be trivially constant folded, e.g. if the
7117   // input is from a string literal.
7118   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7119     // Cast pointer to the type we really want to load.
7120     Type *LoadTy =
7121         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7122     if (LoadVT.isVector())
7123       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7124 
7125     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7126                                          PointerType::getUnqual(LoadTy));
7127 
7128     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7129             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7130       return Builder.getValue(LoadCst);
7131   }
7132 
7133   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7134   // still constant memory, the input chain can be the entry node.
7135   SDValue Root;
7136   bool ConstantMemory = false;
7137 
7138   // Do not serialize (non-volatile) loads of constant memory with anything.
7139   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7140     Root = Builder.DAG.getEntryNode();
7141     ConstantMemory = true;
7142   } else {
7143     // Do not serialize non-volatile loads against each other.
7144     Root = Builder.DAG.getRoot();
7145   }
7146 
7147   SDValue Ptr = Builder.getValue(PtrVal);
7148   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7149                                         Ptr, MachinePointerInfo(PtrVal),
7150                                         /* Alignment = */ 1);
7151 
7152   if (!ConstantMemory)
7153     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7154   return LoadVal;
7155 }
7156 
7157 /// Record the value for an instruction that produces an integer result,
7158 /// converting the type where necessary.
7159 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7160                                                   SDValue Value,
7161                                                   bool IsSigned) {
7162   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7163                                                     I.getType(), true);
7164   if (IsSigned)
7165     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7166   else
7167     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7168   setValue(&I, Value);
7169 }
7170 
7171 /// See if we can lower a memcmp call into an optimized form. If so, return
7172 /// true and lower it. Otherwise return false, and it will be lowered like a
7173 /// normal call.
7174 /// The caller already checked that \p I calls the appropriate LibFunc with a
7175 /// correct prototype.
7176 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7177   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7178   const Value *Size = I.getArgOperand(2);
7179   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7180   if (CSize && CSize->getZExtValue() == 0) {
7181     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7182                                                           I.getType(), true);
7183     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7184     return true;
7185   }
7186 
7187   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7188   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7189       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7190       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7191   if (Res.first.getNode()) {
7192     processIntegerCallValue(I, Res.first, true);
7193     PendingLoads.push_back(Res.second);
7194     return true;
7195   }
7196 
7197   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7198   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7199   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7200     return false;
7201 
7202   // If the target has a fast compare for the given size, it will return a
7203   // preferred load type for that size. Require that the load VT is legal and
7204   // that the target supports unaligned loads of that type. Otherwise, return
7205   // INVALID.
7206   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7207     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7208     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7209     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7210       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7211       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7212       // TODO: Check alignment of src and dest ptrs.
7213       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7214       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7215       if (!TLI.isTypeLegal(LVT) ||
7216           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7217           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7218         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7219     }
7220 
7221     return LVT;
7222   };
7223 
7224   // This turns into unaligned loads. We only do this if the target natively
7225   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7226   // we'll only produce a small number of byte loads.
7227   MVT LoadVT;
7228   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7229   switch (NumBitsToCompare) {
7230   default:
7231     return false;
7232   case 16:
7233     LoadVT = MVT::i16;
7234     break;
7235   case 32:
7236     LoadVT = MVT::i32;
7237     break;
7238   case 64:
7239   case 128:
7240   case 256:
7241     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7242     break;
7243   }
7244 
7245   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7246     return false;
7247 
7248   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7249   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7250 
7251   // Bitcast to a wide integer type if the loads are vectors.
7252   if (LoadVT.isVector()) {
7253     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7254     LoadL = DAG.getBitcast(CmpVT, LoadL);
7255     LoadR = DAG.getBitcast(CmpVT, LoadR);
7256   }
7257 
7258   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7259   processIntegerCallValue(I, Cmp, false);
7260   return true;
7261 }
7262 
7263 /// See if we can lower a memchr call into an optimized form. If so, return
7264 /// true and lower it. Otherwise return false, and it will be lowered like a
7265 /// normal call.
7266 /// The caller already checked that \p I calls the appropriate LibFunc with a
7267 /// correct prototype.
7268 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7269   const Value *Src = I.getArgOperand(0);
7270   const Value *Char = I.getArgOperand(1);
7271   const Value *Length = I.getArgOperand(2);
7272 
7273   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7274   std::pair<SDValue, SDValue> Res =
7275     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7276                                 getValue(Src), getValue(Char), getValue(Length),
7277                                 MachinePointerInfo(Src));
7278   if (Res.first.getNode()) {
7279     setValue(&I, Res.first);
7280     PendingLoads.push_back(Res.second);
7281     return true;
7282   }
7283 
7284   return false;
7285 }
7286 
7287 /// See if we can lower a mempcpy call into an optimized form. If so, return
7288 /// true and lower it. Otherwise return false, and it will be lowered like a
7289 /// normal call.
7290 /// The caller already checked that \p I calls the appropriate LibFunc with a
7291 /// correct prototype.
7292 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7293   SDValue Dst = getValue(I.getArgOperand(0));
7294   SDValue Src = getValue(I.getArgOperand(1));
7295   SDValue Size = getValue(I.getArgOperand(2));
7296 
7297   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7298   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7299   unsigned Align = std::min(DstAlign, SrcAlign);
7300   if (Align == 0) // Alignment of one or both could not be inferred.
7301     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7302 
7303   bool isVol = false;
7304   SDLoc sdl = getCurSDLoc();
7305 
7306   // In the mempcpy context we need to pass in a false value for isTailCall
7307   // because the return pointer needs to be adjusted by the size of
7308   // the copied memory.
7309   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7310                              false, /*isTailCall=*/false,
7311                              MachinePointerInfo(I.getArgOperand(0)),
7312                              MachinePointerInfo(I.getArgOperand(1)));
7313   assert(MC.getNode() != nullptr &&
7314          "** memcpy should not be lowered as TailCall in mempcpy context **");
7315   DAG.setRoot(MC);
7316 
7317   // Check if Size needs to be truncated or extended.
7318   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7319 
7320   // Adjust return pointer to point just past the last dst byte.
7321   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7322                                     Dst, Size);
7323   setValue(&I, DstPlusSize);
7324   return true;
7325 }
7326 
7327 /// See if we can lower a strcpy call into an optimized form.  If so, return
7328 /// true and lower it, otherwise return false and it will be lowered like a
7329 /// normal call.
7330 /// The caller already checked that \p I calls the appropriate LibFunc with a
7331 /// correct prototype.
7332 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7333   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7334 
7335   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7336   std::pair<SDValue, SDValue> Res =
7337     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7338                                 getValue(Arg0), getValue(Arg1),
7339                                 MachinePointerInfo(Arg0),
7340                                 MachinePointerInfo(Arg1), isStpcpy);
7341   if (Res.first.getNode()) {
7342     setValue(&I, Res.first);
7343     DAG.setRoot(Res.second);
7344     return true;
7345   }
7346 
7347   return false;
7348 }
7349 
7350 /// See if we can lower a strcmp call into an optimized form.  If so, return
7351 /// true and lower it, otherwise return false and it will be lowered like a
7352 /// normal call.
7353 /// The caller already checked that \p I calls the appropriate LibFunc with a
7354 /// correct prototype.
7355 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7356   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7357 
7358   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7359   std::pair<SDValue, SDValue> Res =
7360     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7361                                 getValue(Arg0), getValue(Arg1),
7362                                 MachinePointerInfo(Arg0),
7363                                 MachinePointerInfo(Arg1));
7364   if (Res.first.getNode()) {
7365     processIntegerCallValue(I, Res.first, true);
7366     PendingLoads.push_back(Res.second);
7367     return true;
7368   }
7369 
7370   return false;
7371 }
7372 
7373 /// See if we can lower a strlen call into an optimized form.  If so, return
7374 /// true and lower it, otherwise return false and it will be lowered like a
7375 /// normal call.
7376 /// The caller already checked that \p I calls the appropriate LibFunc with a
7377 /// correct prototype.
7378 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7379   const Value *Arg0 = I.getArgOperand(0);
7380 
7381   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7382   std::pair<SDValue, SDValue> Res =
7383     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7384                                 getValue(Arg0), MachinePointerInfo(Arg0));
7385   if (Res.first.getNode()) {
7386     processIntegerCallValue(I, Res.first, false);
7387     PendingLoads.push_back(Res.second);
7388     return true;
7389   }
7390 
7391   return false;
7392 }
7393 
7394 /// See if we can lower a strnlen call into an optimized form.  If so, return
7395 /// true and lower it, otherwise return false and it will be lowered like a
7396 /// normal call.
7397 /// The caller already checked that \p I calls the appropriate LibFunc with a
7398 /// correct prototype.
7399 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7400   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7401 
7402   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7403   std::pair<SDValue, SDValue> Res =
7404     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7405                                  getValue(Arg0), getValue(Arg1),
7406                                  MachinePointerInfo(Arg0));
7407   if (Res.first.getNode()) {
7408     processIntegerCallValue(I, Res.first, false);
7409     PendingLoads.push_back(Res.second);
7410     return true;
7411   }
7412 
7413   return false;
7414 }
7415 
7416 /// See if we can lower a unary floating-point operation into an SDNode with
7417 /// the specified Opcode.  If so, return true and lower it, otherwise return
7418 /// false and it will be lowered like a normal call.
7419 /// The caller already checked that \p I calls the appropriate LibFunc with a
7420 /// correct prototype.
7421 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7422                                               unsigned Opcode) {
7423   // We already checked this call's prototype; verify it doesn't modify errno.
7424   if (!I.onlyReadsMemory())
7425     return false;
7426 
7427   SDValue Tmp = getValue(I.getArgOperand(0));
7428   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7429   return true;
7430 }
7431 
7432 /// See if we can lower a binary floating-point operation into an SDNode with
7433 /// the specified Opcode. If so, return true and lower it. Otherwise return
7434 /// false, and it will be lowered like a normal call.
7435 /// The caller already checked that \p I calls the appropriate LibFunc with a
7436 /// correct prototype.
7437 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7438                                                unsigned Opcode) {
7439   // We already checked this call's prototype; verify it doesn't modify errno.
7440   if (!I.onlyReadsMemory())
7441     return false;
7442 
7443   SDValue Tmp0 = getValue(I.getArgOperand(0));
7444   SDValue Tmp1 = getValue(I.getArgOperand(1));
7445   EVT VT = Tmp0.getValueType();
7446   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7447   return true;
7448 }
7449 
7450 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7451   // Handle inline assembly differently.
7452   if (isa<InlineAsm>(I.getCalledValue())) {
7453     visitInlineAsm(&I);
7454     return;
7455   }
7456 
7457   if (Function *F = I.getCalledFunction()) {
7458     if (F->isDeclaration()) {
7459       // Is this an LLVM intrinsic or a target-specific intrinsic?
7460       unsigned IID = F->getIntrinsicID();
7461       if (!IID)
7462         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7463           IID = II->getIntrinsicID(F);
7464 
7465       if (IID) {
7466         visitIntrinsicCall(I, IID);
7467         return;
7468       }
7469     }
7470 
7471     // Check for well-known libc/libm calls.  If the function is internal, it
7472     // can't be a library call.  Don't do the check if marked as nobuiltin for
7473     // some reason or the call site requires strict floating point semantics.
7474     LibFunc Func;
7475     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7476         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7477         LibInfo->hasOptimizedCodeGen(Func)) {
7478       switch (Func) {
7479       default: break;
7480       case LibFunc_copysign:
7481       case LibFunc_copysignf:
7482       case LibFunc_copysignl:
7483         // We already checked this call's prototype; verify it doesn't modify
7484         // errno.
7485         if (I.onlyReadsMemory()) {
7486           SDValue LHS = getValue(I.getArgOperand(0));
7487           SDValue RHS = getValue(I.getArgOperand(1));
7488           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7489                                    LHS.getValueType(), LHS, RHS));
7490           return;
7491         }
7492         break;
7493       case LibFunc_fabs:
7494       case LibFunc_fabsf:
7495       case LibFunc_fabsl:
7496         if (visitUnaryFloatCall(I, ISD::FABS))
7497           return;
7498         break;
7499       case LibFunc_fmin:
7500       case LibFunc_fminf:
7501       case LibFunc_fminl:
7502         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7503           return;
7504         break;
7505       case LibFunc_fmax:
7506       case LibFunc_fmaxf:
7507       case LibFunc_fmaxl:
7508         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7509           return;
7510         break;
7511       case LibFunc_sin:
7512       case LibFunc_sinf:
7513       case LibFunc_sinl:
7514         if (visitUnaryFloatCall(I, ISD::FSIN))
7515           return;
7516         break;
7517       case LibFunc_cos:
7518       case LibFunc_cosf:
7519       case LibFunc_cosl:
7520         if (visitUnaryFloatCall(I, ISD::FCOS))
7521           return;
7522         break;
7523       case LibFunc_sqrt:
7524       case LibFunc_sqrtf:
7525       case LibFunc_sqrtl:
7526       case LibFunc_sqrt_finite:
7527       case LibFunc_sqrtf_finite:
7528       case LibFunc_sqrtl_finite:
7529         if (visitUnaryFloatCall(I, ISD::FSQRT))
7530           return;
7531         break;
7532       case LibFunc_floor:
7533       case LibFunc_floorf:
7534       case LibFunc_floorl:
7535         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7536           return;
7537         break;
7538       case LibFunc_nearbyint:
7539       case LibFunc_nearbyintf:
7540       case LibFunc_nearbyintl:
7541         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7542           return;
7543         break;
7544       case LibFunc_ceil:
7545       case LibFunc_ceilf:
7546       case LibFunc_ceill:
7547         if (visitUnaryFloatCall(I, ISD::FCEIL))
7548           return;
7549         break;
7550       case LibFunc_rint:
7551       case LibFunc_rintf:
7552       case LibFunc_rintl:
7553         if (visitUnaryFloatCall(I, ISD::FRINT))
7554           return;
7555         break;
7556       case LibFunc_round:
7557       case LibFunc_roundf:
7558       case LibFunc_roundl:
7559         if (visitUnaryFloatCall(I, ISD::FROUND))
7560           return;
7561         break;
7562       case LibFunc_trunc:
7563       case LibFunc_truncf:
7564       case LibFunc_truncl:
7565         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7566           return;
7567         break;
7568       case LibFunc_log2:
7569       case LibFunc_log2f:
7570       case LibFunc_log2l:
7571         if (visitUnaryFloatCall(I, ISD::FLOG2))
7572           return;
7573         break;
7574       case LibFunc_exp2:
7575       case LibFunc_exp2f:
7576       case LibFunc_exp2l:
7577         if (visitUnaryFloatCall(I, ISD::FEXP2))
7578           return;
7579         break;
7580       case LibFunc_memcmp:
7581         if (visitMemCmpCall(I))
7582           return;
7583         break;
7584       case LibFunc_mempcpy:
7585         if (visitMemPCpyCall(I))
7586           return;
7587         break;
7588       case LibFunc_memchr:
7589         if (visitMemChrCall(I))
7590           return;
7591         break;
7592       case LibFunc_strcpy:
7593         if (visitStrCpyCall(I, false))
7594           return;
7595         break;
7596       case LibFunc_stpcpy:
7597         if (visitStrCpyCall(I, true))
7598           return;
7599         break;
7600       case LibFunc_strcmp:
7601         if (visitStrCmpCall(I))
7602           return;
7603         break;
7604       case LibFunc_strlen:
7605         if (visitStrLenCall(I))
7606           return;
7607         break;
7608       case LibFunc_strnlen:
7609         if (visitStrNLenCall(I))
7610           return;
7611         break;
7612       }
7613     }
7614   }
7615 
7616   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7617   // have to do anything here to lower funclet bundles.
7618   // CFGuardTarget bundles are lowered in LowerCallTo.
7619   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7620                                         LLVMContext::OB_funclet,
7621                                         LLVMContext::OB_cfguardtarget}) &&
7622          "Cannot lower calls with arbitrary operand bundles!");
7623 
7624   SDValue Callee = getValue(I.getCalledValue());
7625 
7626   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7627     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7628   else
7629     // Check if we can potentially perform a tail call. More detailed checking
7630     // is be done within LowerCallTo, after more information about the call is
7631     // known.
7632     LowerCallTo(&I, Callee, I.isTailCall());
7633 }
7634 
7635 namespace {
7636 
7637 /// AsmOperandInfo - This contains information for each constraint that we are
7638 /// lowering.
7639 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7640 public:
7641   /// CallOperand - If this is the result output operand or a clobber
7642   /// this is null, otherwise it is the incoming operand to the CallInst.
7643   /// This gets modified as the asm is processed.
7644   SDValue CallOperand;
7645 
7646   /// AssignedRegs - If this is a register or register class operand, this
7647   /// contains the set of register corresponding to the operand.
7648   RegsForValue AssignedRegs;
7649 
7650   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7651     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7652   }
7653 
7654   /// Whether or not this operand accesses memory
7655   bool hasMemory(const TargetLowering &TLI) const {
7656     // Indirect operand accesses access memory.
7657     if (isIndirect)
7658       return true;
7659 
7660     for (const auto &Code : Codes)
7661       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7662         return true;
7663 
7664     return false;
7665   }
7666 
7667   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7668   /// corresponds to.  If there is no Value* for this operand, it returns
7669   /// MVT::Other.
7670   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7671                            const DataLayout &DL) const {
7672     if (!CallOperandVal) return MVT::Other;
7673 
7674     if (isa<BasicBlock>(CallOperandVal))
7675       return TLI.getPointerTy(DL);
7676 
7677     llvm::Type *OpTy = CallOperandVal->getType();
7678 
7679     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7680     // If this is an indirect operand, the operand is a pointer to the
7681     // accessed type.
7682     if (isIndirect) {
7683       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7684       if (!PtrTy)
7685         report_fatal_error("Indirect operand for inline asm not a pointer!");
7686       OpTy = PtrTy->getElementType();
7687     }
7688 
7689     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7690     if (StructType *STy = dyn_cast<StructType>(OpTy))
7691       if (STy->getNumElements() == 1)
7692         OpTy = STy->getElementType(0);
7693 
7694     // If OpTy is not a single value, it may be a struct/union that we
7695     // can tile with integers.
7696     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7697       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7698       switch (BitSize) {
7699       default: break;
7700       case 1:
7701       case 8:
7702       case 16:
7703       case 32:
7704       case 64:
7705       case 128:
7706         OpTy = IntegerType::get(Context, BitSize);
7707         break;
7708       }
7709     }
7710 
7711     return TLI.getValueType(DL, OpTy, true);
7712   }
7713 };
7714 
7715 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7716 
7717 } // end anonymous namespace
7718 
7719 /// Make sure that the output operand \p OpInfo and its corresponding input
7720 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7721 /// out).
7722 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7723                                SDISelAsmOperandInfo &MatchingOpInfo,
7724                                SelectionDAG &DAG) {
7725   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7726     return;
7727 
7728   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7729   const auto &TLI = DAG.getTargetLoweringInfo();
7730 
7731   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7732       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7733                                        OpInfo.ConstraintVT);
7734   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7735       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7736                                        MatchingOpInfo.ConstraintVT);
7737   if ((OpInfo.ConstraintVT.isInteger() !=
7738        MatchingOpInfo.ConstraintVT.isInteger()) ||
7739       (MatchRC.second != InputRC.second)) {
7740     // FIXME: error out in a more elegant fashion
7741     report_fatal_error("Unsupported asm: input constraint"
7742                        " with a matching output constraint of"
7743                        " incompatible type!");
7744   }
7745   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7746 }
7747 
7748 /// Get a direct memory input to behave well as an indirect operand.
7749 /// This may introduce stores, hence the need for a \p Chain.
7750 /// \return The (possibly updated) chain.
7751 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7752                                         SDISelAsmOperandInfo &OpInfo,
7753                                         SelectionDAG &DAG) {
7754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7755 
7756   // If we don't have an indirect input, put it in the constpool if we can,
7757   // otherwise spill it to a stack slot.
7758   // TODO: This isn't quite right. We need to handle these according to
7759   // the addressing mode that the constraint wants. Also, this may take
7760   // an additional register for the computation and we don't want that
7761   // either.
7762 
7763   // If the operand is a float, integer, or vector constant, spill to a
7764   // constant pool entry to get its address.
7765   const Value *OpVal = OpInfo.CallOperandVal;
7766   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7767       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7768     OpInfo.CallOperand = DAG.getConstantPool(
7769         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7770     return Chain;
7771   }
7772 
7773   // Otherwise, create a stack slot and emit a store to it before the asm.
7774   Type *Ty = OpVal->getType();
7775   auto &DL = DAG.getDataLayout();
7776   uint64_t TySize = DL.getTypeAllocSize(Ty);
7777   unsigned Align = DL.getPrefTypeAlignment(Ty);
7778   MachineFunction &MF = DAG.getMachineFunction();
7779   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7780   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7781   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7782                             MachinePointerInfo::getFixedStack(MF, SSFI),
7783                             TLI.getMemValueType(DL, Ty));
7784   OpInfo.CallOperand = StackSlot;
7785 
7786   return Chain;
7787 }
7788 
7789 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7790 /// specified operand.  We prefer to assign virtual registers, to allow the
7791 /// register allocator to handle the assignment process.  However, if the asm
7792 /// uses features that we can't model on machineinstrs, we have SDISel do the
7793 /// allocation.  This produces generally horrible, but correct, code.
7794 ///
7795 ///   OpInfo describes the operand
7796 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7797 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7798                                  SDISelAsmOperandInfo &OpInfo,
7799                                  SDISelAsmOperandInfo &RefOpInfo) {
7800   LLVMContext &Context = *DAG.getContext();
7801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7802 
7803   MachineFunction &MF = DAG.getMachineFunction();
7804   SmallVector<unsigned, 4> Regs;
7805   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7806 
7807   // No work to do for memory operations.
7808   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7809     return;
7810 
7811   // If this is a constraint for a single physreg, or a constraint for a
7812   // register class, find it.
7813   unsigned AssignedReg;
7814   const TargetRegisterClass *RC;
7815   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7816       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7817   // RC is unset only on failure. Return immediately.
7818   if (!RC)
7819     return;
7820 
7821   // Get the actual register value type.  This is important, because the user
7822   // may have asked for (e.g.) the AX register in i32 type.  We need to
7823   // remember that AX is actually i16 to get the right extension.
7824   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7825 
7826   if (OpInfo.ConstraintVT != MVT::Other) {
7827     // If this is an FP operand in an integer register (or visa versa), or more
7828     // generally if the operand value disagrees with the register class we plan
7829     // to stick it in, fix the operand type.
7830     //
7831     // If this is an input value, the bitcast to the new type is done now.
7832     // Bitcast for output value is done at the end of visitInlineAsm().
7833     if ((OpInfo.Type == InlineAsm::isOutput ||
7834          OpInfo.Type == InlineAsm::isInput) &&
7835         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7836       // Try to convert to the first EVT that the reg class contains.  If the
7837       // types are identical size, use a bitcast to convert (e.g. two differing
7838       // vector types).  Note: output bitcast is done at the end of
7839       // visitInlineAsm().
7840       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7841         // Exclude indirect inputs while they are unsupported because the code
7842         // to perform the load is missing and thus OpInfo.CallOperand still
7843         // refers to the input address rather than the pointed-to value.
7844         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7845           OpInfo.CallOperand =
7846               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7847         OpInfo.ConstraintVT = RegVT;
7848         // If the operand is an FP value and we want it in integer registers,
7849         // use the corresponding integer type. This turns an f64 value into
7850         // i64, which can be passed with two i32 values on a 32-bit machine.
7851       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7852         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7853         if (OpInfo.Type == InlineAsm::isInput)
7854           OpInfo.CallOperand =
7855               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7856         OpInfo.ConstraintVT = VT;
7857       }
7858     }
7859   }
7860 
7861   // No need to allocate a matching input constraint since the constraint it's
7862   // matching to has already been allocated.
7863   if (OpInfo.isMatchingInputConstraint())
7864     return;
7865 
7866   EVT ValueVT = OpInfo.ConstraintVT;
7867   if (OpInfo.ConstraintVT == MVT::Other)
7868     ValueVT = RegVT;
7869 
7870   // Initialize NumRegs.
7871   unsigned NumRegs = 1;
7872   if (OpInfo.ConstraintVT != MVT::Other)
7873     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7874 
7875   // If this is a constraint for a specific physical register, like {r17},
7876   // assign it now.
7877 
7878   // If this associated to a specific register, initialize iterator to correct
7879   // place. If virtual, make sure we have enough registers
7880 
7881   // Initialize iterator if necessary
7882   TargetRegisterClass::iterator I = RC->begin();
7883   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7884 
7885   // Do not check for single registers.
7886   if (AssignedReg) {
7887       for (; *I != AssignedReg; ++I)
7888         assert(I != RC->end() && "AssignedReg should be member of RC");
7889   }
7890 
7891   for (; NumRegs; --NumRegs, ++I) {
7892     assert(I != RC->end() && "Ran out of registers to allocate!");
7893     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7894     Regs.push_back(R);
7895   }
7896 
7897   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7898 }
7899 
7900 static unsigned
7901 findMatchingInlineAsmOperand(unsigned OperandNo,
7902                              const std::vector<SDValue> &AsmNodeOperands) {
7903   // Scan until we find the definition we already emitted of this operand.
7904   unsigned CurOp = InlineAsm::Op_FirstOperand;
7905   for (; OperandNo; --OperandNo) {
7906     // Advance to the next operand.
7907     unsigned OpFlag =
7908         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7909     assert((InlineAsm::isRegDefKind(OpFlag) ||
7910             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7911             InlineAsm::isMemKind(OpFlag)) &&
7912            "Skipped past definitions?");
7913     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7914   }
7915   return CurOp;
7916 }
7917 
7918 namespace {
7919 
7920 class ExtraFlags {
7921   unsigned Flags = 0;
7922 
7923 public:
7924   explicit ExtraFlags(ImmutableCallSite CS) {
7925     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7926     if (IA->hasSideEffects())
7927       Flags |= InlineAsm::Extra_HasSideEffects;
7928     if (IA->isAlignStack())
7929       Flags |= InlineAsm::Extra_IsAlignStack;
7930     if (CS.isConvergent())
7931       Flags |= InlineAsm::Extra_IsConvergent;
7932     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7933   }
7934 
7935   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7936     // Ideally, we would only check against memory constraints.  However, the
7937     // meaning of an Other constraint can be target-specific and we can't easily
7938     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7939     // for Other constraints as well.
7940     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7941         OpInfo.ConstraintType == TargetLowering::C_Other) {
7942       if (OpInfo.Type == InlineAsm::isInput)
7943         Flags |= InlineAsm::Extra_MayLoad;
7944       else if (OpInfo.Type == InlineAsm::isOutput)
7945         Flags |= InlineAsm::Extra_MayStore;
7946       else if (OpInfo.Type == InlineAsm::isClobber)
7947         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7948     }
7949   }
7950 
7951   unsigned get() const { return Flags; }
7952 };
7953 
7954 } // end anonymous namespace
7955 
7956 /// visitInlineAsm - Handle a call to an InlineAsm object.
7957 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7958   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7959 
7960   /// ConstraintOperands - Information about all of the constraints.
7961   SDISelAsmOperandInfoVector ConstraintOperands;
7962 
7963   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7964   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7965       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7966 
7967   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7968   // AsmDialect, MayLoad, MayStore).
7969   bool HasSideEffect = IA->hasSideEffects();
7970   ExtraFlags ExtraInfo(CS);
7971 
7972   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7973   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7974   for (auto &T : TargetConstraints) {
7975     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7976     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7977 
7978     // Compute the value type for each operand.
7979     if (OpInfo.Type == InlineAsm::isInput ||
7980         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7981       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7982 
7983       // Process the call argument. BasicBlocks are labels, currently appearing
7984       // only in asm's.
7985       const Instruction *I = CS.getInstruction();
7986       if (isa<CallBrInst>(I) &&
7987           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7988                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7989         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7990         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7991         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7992       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7993         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7994       } else {
7995         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7996       }
7997 
7998       OpInfo.ConstraintVT =
7999           OpInfo
8000               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8001               .getSimpleVT();
8002     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8003       // The return value of the call is this value.  As such, there is no
8004       // corresponding argument.
8005       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8006       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8007         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8008             DAG.getDataLayout(), STy->getElementType(ResNo));
8009       } else {
8010         assert(ResNo == 0 && "Asm only has one result!");
8011         OpInfo.ConstraintVT =
8012             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8013       }
8014       ++ResNo;
8015     } else {
8016       OpInfo.ConstraintVT = MVT::Other;
8017     }
8018 
8019     if (!HasSideEffect)
8020       HasSideEffect = OpInfo.hasMemory(TLI);
8021 
8022     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8023     // FIXME: Could we compute this on OpInfo rather than T?
8024 
8025     // Compute the constraint code and ConstraintType to use.
8026     TLI.ComputeConstraintToUse(T, SDValue());
8027 
8028     if (T.ConstraintType == TargetLowering::C_Immediate &&
8029         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8030       // We've delayed emitting a diagnostic like the "n" constraint because
8031       // inlining could cause an integer showing up.
8032       return emitInlineAsmError(
8033           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8034                   "integer constant expression");
8035 
8036     ExtraInfo.update(T);
8037   }
8038 
8039 
8040   // We won't need to flush pending loads if this asm doesn't touch
8041   // memory and is nonvolatile.
8042   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8043 
8044   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8045   if (IsCallBr) {
8046     // If this is a callbr we need to flush pending exports since inlineasm_br
8047     // is a terminator. We need to do this before nodes are glued to
8048     // the inlineasm_br node.
8049     Chain = getControlRoot();
8050   }
8051 
8052   // Second pass over the constraints: compute which constraint option to use.
8053   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8054     // If this is an output operand with a matching input operand, look up the
8055     // matching input. If their types mismatch, e.g. one is an integer, the
8056     // other is floating point, or their sizes are different, flag it as an
8057     // error.
8058     if (OpInfo.hasMatchingInput()) {
8059       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8060       patchMatchingInput(OpInfo, Input, DAG);
8061     }
8062 
8063     // Compute the constraint code and ConstraintType to use.
8064     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8065 
8066     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8067         OpInfo.Type == InlineAsm::isClobber)
8068       continue;
8069 
8070     // If this is a memory input, and if the operand is not indirect, do what we
8071     // need to provide an address for the memory input.
8072     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8073         !OpInfo.isIndirect) {
8074       assert((OpInfo.isMultipleAlternative ||
8075               (OpInfo.Type == InlineAsm::isInput)) &&
8076              "Can only indirectify direct input operands!");
8077 
8078       // Memory operands really want the address of the value.
8079       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8080 
8081       // There is no longer a Value* corresponding to this operand.
8082       OpInfo.CallOperandVal = nullptr;
8083 
8084       // It is now an indirect operand.
8085       OpInfo.isIndirect = true;
8086     }
8087 
8088   }
8089 
8090   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8091   std::vector<SDValue> AsmNodeOperands;
8092   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8093   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8094       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8095 
8096   // If we have a !srcloc metadata node associated with it, we want to attach
8097   // this to the ultimately generated inline asm machineinstr.  To do this, we
8098   // pass in the third operand as this (potentially null) inline asm MDNode.
8099   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8100   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8101 
8102   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8103   // bits as operand 3.
8104   AsmNodeOperands.push_back(DAG.getTargetConstant(
8105       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8106 
8107   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8108   // this, assign virtual and physical registers for inputs and otput.
8109   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8110     // Assign Registers.
8111     SDISelAsmOperandInfo &RefOpInfo =
8112         OpInfo.isMatchingInputConstraint()
8113             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8114             : OpInfo;
8115     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8116 
8117     switch (OpInfo.Type) {
8118     case InlineAsm::isOutput:
8119       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8120           ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8121             OpInfo.ConstraintType == TargetLowering::C_Other) &&
8122            OpInfo.isIndirect)) {
8123         unsigned ConstraintID =
8124             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8125         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8126                "Failed to convert memory constraint code to constraint id.");
8127 
8128         // Add information to the INLINEASM node to know about this output.
8129         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8130         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8131         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8132                                                         MVT::i32));
8133         AsmNodeOperands.push_back(OpInfo.CallOperand);
8134         break;
8135       } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8136                    OpInfo.ConstraintType == TargetLowering::C_Other) &&
8137                   !OpInfo.isIndirect) ||
8138                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8139                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8140         // Otherwise, this outputs to a register (directly for C_Register /
8141         // C_RegisterClass, and a target-defined fashion for
8142         // C_Immediate/C_Other). Find a register that we can use.
8143         if (OpInfo.AssignedRegs.Regs.empty()) {
8144           emitInlineAsmError(
8145               CS, "couldn't allocate output register for constraint '" +
8146                       Twine(OpInfo.ConstraintCode) + "'");
8147           return;
8148         }
8149 
8150         // Add information to the INLINEASM node to know that this register is
8151         // set.
8152         OpInfo.AssignedRegs.AddInlineAsmOperands(
8153             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8154                                   : InlineAsm::Kind_RegDef,
8155             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8156       }
8157       break;
8158 
8159     case InlineAsm::isInput: {
8160       SDValue InOperandVal = OpInfo.CallOperand;
8161 
8162       if (OpInfo.isMatchingInputConstraint()) {
8163         // If this is required to match an output register we have already set,
8164         // just use its register.
8165         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8166                                                   AsmNodeOperands);
8167         unsigned OpFlag =
8168           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8169         if (InlineAsm::isRegDefKind(OpFlag) ||
8170             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8171           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8172           if (OpInfo.isIndirect) {
8173             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8174             emitInlineAsmError(CS, "inline asm not supported yet:"
8175                                    " don't know how to handle tied "
8176                                    "indirect register inputs");
8177             return;
8178           }
8179 
8180           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8181           SmallVector<unsigned, 4> Regs;
8182 
8183           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8184             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8185             MachineRegisterInfo &RegInfo =
8186                 DAG.getMachineFunction().getRegInfo();
8187             for (unsigned i = 0; i != NumRegs; ++i)
8188               Regs.push_back(RegInfo.createVirtualRegister(RC));
8189           } else {
8190             emitInlineAsmError(CS, "inline asm error: This value type register "
8191                                    "class is not natively supported!");
8192             return;
8193           }
8194 
8195           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8196 
8197           SDLoc dl = getCurSDLoc();
8198           // Use the produced MatchedRegs object to
8199           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8200                                     CS.getInstruction());
8201           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8202                                            true, OpInfo.getMatchedOperand(), dl,
8203                                            DAG, AsmNodeOperands);
8204           break;
8205         }
8206 
8207         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8208         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8209                "Unexpected number of operands");
8210         // Add information to the INLINEASM node to know about this input.
8211         // See InlineAsm.h isUseOperandTiedToDef.
8212         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8213         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8214                                                     OpInfo.getMatchedOperand());
8215         AsmNodeOperands.push_back(DAG.getTargetConstant(
8216             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8217         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8218         break;
8219       }
8220 
8221       // Treat indirect 'X' constraint as memory.
8222       if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8223            OpInfo.ConstraintType == TargetLowering::C_Other) &&
8224           OpInfo.isIndirect)
8225         OpInfo.ConstraintType = TargetLowering::C_Memory;
8226 
8227       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8228           OpInfo.ConstraintType == TargetLowering::C_Other) {
8229         std::vector<SDValue> Ops;
8230         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8231                                           Ops, DAG);
8232         if (Ops.empty()) {
8233           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8234             if (isa<ConstantSDNode>(InOperandVal)) {
8235               emitInlineAsmError(CS, "value out of range for constraint '" +
8236                                  Twine(OpInfo.ConstraintCode) + "'");
8237               return;
8238             }
8239 
8240           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8241                                      Twine(OpInfo.ConstraintCode) + "'");
8242           return;
8243         }
8244 
8245         // Add information to the INLINEASM node to know about this input.
8246         unsigned ResOpType =
8247           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8248         AsmNodeOperands.push_back(DAG.getTargetConstant(
8249             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8250         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8251         break;
8252       }
8253 
8254       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8255         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8256         assert(InOperandVal.getValueType() ==
8257                    TLI.getPointerTy(DAG.getDataLayout()) &&
8258                "Memory operands expect pointer values");
8259 
8260         unsigned ConstraintID =
8261             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8262         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8263                "Failed to convert memory constraint code to constraint id.");
8264 
8265         // Add information to the INLINEASM node to know about this input.
8266         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8267         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8268         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8269                                                         getCurSDLoc(),
8270                                                         MVT::i32));
8271         AsmNodeOperands.push_back(InOperandVal);
8272         break;
8273       }
8274 
8275       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8276               OpInfo.ConstraintType == TargetLowering::C_Register ||
8277               OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8278              "Unknown constraint type!");
8279 
8280       // TODO: Support this.
8281       if (OpInfo.isIndirect) {
8282         emitInlineAsmError(
8283             CS, "Don't know how to handle indirect register inputs yet "
8284                 "for constraint '" +
8285                     Twine(OpInfo.ConstraintCode) + "'");
8286         return;
8287       }
8288 
8289       // Copy the input into the appropriate registers.
8290       if (OpInfo.AssignedRegs.Regs.empty()) {
8291         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8292                                    Twine(OpInfo.ConstraintCode) + "'");
8293         return;
8294       }
8295 
8296       SDLoc dl = getCurSDLoc();
8297 
8298       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8299                                         Chain, &Flag, CS.getInstruction());
8300 
8301       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8302                                                dl, DAG, AsmNodeOperands);
8303       break;
8304     }
8305     case InlineAsm::isClobber:
8306       // Add the clobbered value to the operand list, so that the register
8307       // allocator is aware that the physreg got clobbered.
8308       if (!OpInfo.AssignedRegs.Regs.empty())
8309         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8310                                                  false, 0, getCurSDLoc(), DAG,
8311                                                  AsmNodeOperands);
8312       break;
8313     }
8314   }
8315 
8316   // Finish up input operands.  Set the input chain and add the flag last.
8317   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8318   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8319 
8320   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8321   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8322                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8323   Flag = Chain.getValue(1);
8324 
8325   // Do additional work to generate outputs.
8326 
8327   SmallVector<EVT, 1> ResultVTs;
8328   SmallVector<SDValue, 1> ResultValues;
8329   SmallVector<SDValue, 8> OutChains;
8330 
8331   llvm::Type *CSResultType = CS.getType();
8332   ArrayRef<Type *> ResultTypes;
8333   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8334     ResultTypes = StructResult->elements();
8335   else if (!CSResultType->isVoidTy())
8336     ResultTypes = makeArrayRef(CSResultType);
8337 
8338   auto CurResultType = ResultTypes.begin();
8339   auto handleRegAssign = [&](SDValue V) {
8340     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8341     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8342     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8343     ++CurResultType;
8344     // If the type of the inline asm call site return value is different but has
8345     // same size as the type of the asm output bitcast it.  One example of this
8346     // is for vectors with different width / number of elements.  This can
8347     // happen for register classes that can contain multiple different value
8348     // types.  The preg or vreg allocated may not have the same VT as was
8349     // expected.
8350     //
8351     // This can also happen for a return value that disagrees with the register
8352     // class it is put in, eg. a double in a general-purpose register on a
8353     // 32-bit machine.
8354     if (ResultVT != V.getValueType() &&
8355         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8356       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8357     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8358              V.getValueType().isInteger()) {
8359       // If a result value was tied to an input value, the computed result
8360       // may have a wider width than the expected result.  Extract the
8361       // relevant portion.
8362       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8363     }
8364     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8365     ResultVTs.push_back(ResultVT);
8366     ResultValues.push_back(V);
8367   };
8368 
8369   // Deal with output operands.
8370   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8371     if (OpInfo.Type == InlineAsm::isOutput) {
8372       SDValue Val;
8373       // Skip trivial output operands.
8374       if (OpInfo.AssignedRegs.Regs.empty())
8375         continue;
8376 
8377       switch (OpInfo.ConstraintType) {
8378       case TargetLowering::C_Register:
8379       case TargetLowering::C_RegisterClass:
8380         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8381             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8382         break;
8383       case TargetLowering::C_Immediate:
8384       case TargetLowering::C_Other:
8385         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8386                                               OpInfo, DAG);
8387         break;
8388       case TargetLowering::C_Memory:
8389         break; // Already handled.
8390       case TargetLowering::C_Unknown:
8391         assert(false && "Unexpected unknown constraint");
8392       }
8393 
8394       // Indirect output manifest as stores. Record output chains.
8395       if (OpInfo.isIndirect) {
8396         const Value *Ptr = OpInfo.CallOperandVal;
8397         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8398         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8399                                      MachinePointerInfo(Ptr));
8400         OutChains.push_back(Store);
8401       } else {
8402         // generate CopyFromRegs to associated registers.
8403         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8404         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8405           for (const SDValue &V : Val->op_values())
8406             handleRegAssign(V);
8407         } else
8408           handleRegAssign(Val);
8409       }
8410     }
8411   }
8412 
8413   // Set results.
8414   if (!ResultValues.empty()) {
8415     assert(CurResultType == ResultTypes.end() &&
8416            "Mismatch in number of ResultTypes");
8417     assert(ResultValues.size() == ResultTypes.size() &&
8418            "Mismatch in number of output operands in asm result");
8419 
8420     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8421                             DAG.getVTList(ResultVTs), ResultValues);
8422     setValue(CS.getInstruction(), V);
8423   }
8424 
8425   // Collect store chains.
8426   if (!OutChains.empty())
8427     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8428 
8429   // Only Update Root if inline assembly has a memory effect.
8430   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8431     DAG.setRoot(Chain);
8432 }
8433 
8434 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8435                                              const Twine &Message) {
8436   LLVMContext &Ctx = *DAG.getContext();
8437   Ctx.emitError(CS.getInstruction(), Message);
8438 
8439   // Make sure we leave the DAG in a valid state
8440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8441   SmallVector<EVT, 1> ValueVTs;
8442   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8443 
8444   if (ValueVTs.empty())
8445     return;
8446 
8447   SmallVector<SDValue, 1> Ops;
8448   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8449     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8450 
8451   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8452 }
8453 
8454 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8455   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8456                           MVT::Other, getRoot(),
8457                           getValue(I.getArgOperand(0)),
8458                           DAG.getSrcValue(I.getArgOperand(0))));
8459 }
8460 
8461 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8463   const DataLayout &DL = DAG.getDataLayout();
8464   SDValue V = DAG.getVAArg(
8465       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8466       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8467       DL.getABITypeAlignment(I.getType()));
8468   DAG.setRoot(V.getValue(1));
8469 
8470   if (I.getType()->isPointerTy())
8471     V = DAG.getPtrExtOrTrunc(
8472         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8473   setValue(&I, V);
8474 }
8475 
8476 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8477   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8478                           MVT::Other, getRoot(),
8479                           getValue(I.getArgOperand(0)),
8480                           DAG.getSrcValue(I.getArgOperand(0))));
8481 }
8482 
8483 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8484   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8485                           MVT::Other, getRoot(),
8486                           getValue(I.getArgOperand(0)),
8487                           getValue(I.getArgOperand(1)),
8488                           DAG.getSrcValue(I.getArgOperand(0)),
8489                           DAG.getSrcValue(I.getArgOperand(1))));
8490 }
8491 
8492 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8493                                                     const Instruction &I,
8494                                                     SDValue Op) {
8495   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8496   if (!Range)
8497     return Op;
8498 
8499   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8500   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8501     return Op;
8502 
8503   APInt Lo = CR.getUnsignedMin();
8504   if (!Lo.isMinValue())
8505     return Op;
8506 
8507   APInt Hi = CR.getUnsignedMax();
8508   unsigned Bits = std::max(Hi.getActiveBits(),
8509                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8510 
8511   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8512 
8513   SDLoc SL = getCurSDLoc();
8514 
8515   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8516                              DAG.getValueType(SmallVT));
8517   unsigned NumVals = Op.getNode()->getNumValues();
8518   if (NumVals == 1)
8519     return ZExt;
8520 
8521   SmallVector<SDValue, 4> Ops;
8522 
8523   Ops.push_back(ZExt);
8524   for (unsigned I = 1; I != NumVals; ++I)
8525     Ops.push_back(Op.getValue(I));
8526 
8527   return DAG.getMergeValues(Ops, SL);
8528 }
8529 
8530 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8531 /// the call being lowered.
8532 ///
8533 /// This is a helper for lowering intrinsics that follow a target calling
8534 /// convention or require stack pointer adjustment. Only a subset of the
8535 /// intrinsic's operands need to participate in the calling convention.
8536 void SelectionDAGBuilder::populateCallLoweringInfo(
8537     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8538     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8539     bool IsPatchPoint) {
8540   TargetLowering::ArgListTy Args;
8541   Args.reserve(NumArgs);
8542 
8543   // Populate the argument list.
8544   // Attributes for args start at offset 1, after the return attribute.
8545   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8546        ArgI != ArgE; ++ArgI) {
8547     const Value *V = Call->getOperand(ArgI);
8548 
8549     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8550 
8551     TargetLowering::ArgListEntry Entry;
8552     Entry.Node = getValue(V);
8553     Entry.Ty = V->getType();
8554     Entry.setAttributes(Call, ArgI);
8555     Args.push_back(Entry);
8556   }
8557 
8558   CLI.setDebugLoc(getCurSDLoc())
8559       .setChain(getRoot())
8560       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8561       .setDiscardResult(Call->use_empty())
8562       .setIsPatchPoint(IsPatchPoint);
8563 }
8564 
8565 /// Add a stack map intrinsic call's live variable operands to a stackmap
8566 /// or patchpoint target node's operand list.
8567 ///
8568 /// Constants are converted to TargetConstants purely as an optimization to
8569 /// avoid constant materialization and register allocation.
8570 ///
8571 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8572 /// generate addess computation nodes, and so FinalizeISel can convert the
8573 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8574 /// address materialization and register allocation, but may also be required
8575 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8576 /// alloca in the entry block, then the runtime may assume that the alloca's
8577 /// StackMap location can be read immediately after compilation and that the
8578 /// location is valid at any point during execution (this is similar to the
8579 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8580 /// only available in a register, then the runtime would need to trap when
8581 /// execution reaches the StackMap in order to read the alloca's location.
8582 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8583                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8584                                 SelectionDAGBuilder &Builder) {
8585   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8586     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8588       Ops.push_back(
8589         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8590       Ops.push_back(
8591         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8592     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8593       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8594       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8595           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8596     } else
8597       Ops.push_back(OpVal);
8598   }
8599 }
8600 
8601 /// Lower llvm.experimental.stackmap directly to its target opcode.
8602 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8603   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8604   //                                  [live variables...])
8605 
8606   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8607 
8608   SDValue Chain, InFlag, Callee, NullPtr;
8609   SmallVector<SDValue, 32> Ops;
8610 
8611   SDLoc DL = getCurSDLoc();
8612   Callee = getValue(CI.getCalledValue());
8613   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8614 
8615   // The stackmap intrinsic only records the live variables (the arguments
8616   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8617   // intrinsic, this won't be lowered to a function call. This means we don't
8618   // have to worry about calling conventions and target specific lowering code.
8619   // Instead we perform the call lowering right here.
8620   //
8621   // chain, flag = CALLSEQ_START(chain, 0, 0)
8622   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8623   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8624   //
8625   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8626   InFlag = Chain.getValue(1);
8627 
8628   // Add the <id> and <numBytes> constants.
8629   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8630   Ops.push_back(DAG.getTargetConstant(
8631                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8632   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8633   Ops.push_back(DAG.getTargetConstant(
8634                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8635                   MVT::i32));
8636 
8637   // Push live variables for the stack map.
8638   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8639 
8640   // We are not pushing any register mask info here on the operands list,
8641   // because the stackmap doesn't clobber anything.
8642 
8643   // Push the chain and the glue flag.
8644   Ops.push_back(Chain);
8645   Ops.push_back(InFlag);
8646 
8647   // Create the STACKMAP node.
8648   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8649   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8650   Chain = SDValue(SM, 0);
8651   InFlag = Chain.getValue(1);
8652 
8653   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8654 
8655   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8656 
8657   // Set the root to the target-lowered call chain.
8658   DAG.setRoot(Chain);
8659 
8660   // Inform the Frame Information that we have a stackmap in this function.
8661   FuncInfo.MF->getFrameInfo().setHasStackMap();
8662 }
8663 
8664 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8665 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8666                                           const BasicBlock *EHPadBB) {
8667   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8668   //                                                 i32 <numBytes>,
8669   //                                                 i8* <target>,
8670   //                                                 i32 <numArgs>,
8671   //                                                 [Args...],
8672   //                                                 [live variables...])
8673 
8674   CallingConv::ID CC = CS.getCallingConv();
8675   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8676   bool HasDef = !CS->getType()->isVoidTy();
8677   SDLoc dl = getCurSDLoc();
8678   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8679 
8680   // Handle immediate and symbolic callees.
8681   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8682     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8683                                    /*isTarget=*/true);
8684   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8685     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8686                                          SDLoc(SymbolicCallee),
8687                                          SymbolicCallee->getValueType(0));
8688 
8689   // Get the real number of arguments participating in the call <numArgs>
8690   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8691   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8692 
8693   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8694   // Intrinsics include all meta-operands up to but not including CC.
8695   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8696   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8697          "Not enough arguments provided to the patchpoint intrinsic");
8698 
8699   // For AnyRegCC the arguments are lowered later on manually.
8700   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8701   Type *ReturnTy =
8702     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8703 
8704   TargetLowering::CallLoweringInfo CLI(DAG);
8705   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8706                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8707   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8708 
8709   SDNode *CallEnd = Result.second.getNode();
8710   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8711     CallEnd = CallEnd->getOperand(0).getNode();
8712 
8713   /// Get a call instruction from the call sequence chain.
8714   /// Tail calls are not allowed.
8715   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8716          "Expected a callseq node.");
8717   SDNode *Call = CallEnd->getOperand(0).getNode();
8718   bool HasGlue = Call->getGluedNode();
8719 
8720   // Replace the target specific call node with the patchable intrinsic.
8721   SmallVector<SDValue, 8> Ops;
8722 
8723   // Add the <id> and <numBytes> constants.
8724   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8725   Ops.push_back(DAG.getTargetConstant(
8726                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8727   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8728   Ops.push_back(DAG.getTargetConstant(
8729                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8730                   MVT::i32));
8731 
8732   // Add the callee.
8733   Ops.push_back(Callee);
8734 
8735   // Adjust <numArgs> to account for any arguments that have been passed on the
8736   // stack instead.
8737   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8738   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8739   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8740   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8741 
8742   // Add the calling convention
8743   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8744 
8745   // Add the arguments we omitted previously. The register allocator should
8746   // place these in any free register.
8747   if (IsAnyRegCC)
8748     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8749       Ops.push_back(getValue(CS.getArgument(i)));
8750 
8751   // Push the arguments from the call instruction up to the register mask.
8752   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8753   Ops.append(Call->op_begin() + 2, e);
8754 
8755   // Push live variables for the stack map.
8756   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8757 
8758   // Push the register mask info.
8759   if (HasGlue)
8760     Ops.push_back(*(Call->op_end()-2));
8761   else
8762     Ops.push_back(*(Call->op_end()-1));
8763 
8764   // Push the chain (this is originally the first operand of the call, but
8765   // becomes now the last or second to last operand).
8766   Ops.push_back(*(Call->op_begin()));
8767 
8768   // Push the glue flag (last operand).
8769   if (HasGlue)
8770     Ops.push_back(*(Call->op_end()-1));
8771 
8772   SDVTList NodeTys;
8773   if (IsAnyRegCC && HasDef) {
8774     // Create the return types based on the intrinsic definition
8775     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8776     SmallVector<EVT, 3> ValueVTs;
8777     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8778     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8779 
8780     // There is always a chain and a glue type at the end
8781     ValueVTs.push_back(MVT::Other);
8782     ValueVTs.push_back(MVT::Glue);
8783     NodeTys = DAG.getVTList(ValueVTs);
8784   } else
8785     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8786 
8787   // Replace the target specific call node with a PATCHPOINT node.
8788   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8789                                          dl, NodeTys, Ops);
8790 
8791   // Update the NodeMap.
8792   if (HasDef) {
8793     if (IsAnyRegCC)
8794       setValue(CS.getInstruction(), SDValue(MN, 0));
8795     else
8796       setValue(CS.getInstruction(), Result.first);
8797   }
8798 
8799   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8800   // call sequence. Furthermore the location of the chain and glue can change
8801   // when the AnyReg calling convention is used and the intrinsic returns a
8802   // value.
8803   if (IsAnyRegCC && HasDef) {
8804     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8805     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8806     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8807   } else
8808     DAG.ReplaceAllUsesWith(Call, MN);
8809   DAG.DeleteNode(Call);
8810 
8811   // Inform the Frame Information that we have a patchpoint in this function.
8812   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8813 }
8814 
8815 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8816                                             unsigned Intrinsic) {
8817   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8818   SDValue Op1 = getValue(I.getArgOperand(0));
8819   SDValue Op2;
8820   if (I.getNumArgOperands() > 1)
8821     Op2 = getValue(I.getArgOperand(1));
8822   SDLoc dl = getCurSDLoc();
8823   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8824   SDValue Res;
8825   FastMathFlags FMF;
8826   if (isa<FPMathOperator>(I))
8827     FMF = I.getFastMathFlags();
8828 
8829   switch (Intrinsic) {
8830   case Intrinsic::experimental_vector_reduce_v2_fadd:
8831     if (FMF.allowReassoc())
8832       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8833                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8834     else
8835       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8836     break;
8837   case Intrinsic::experimental_vector_reduce_v2_fmul:
8838     if (FMF.allowReassoc())
8839       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8840                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8841     else
8842       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8843     break;
8844   case Intrinsic::experimental_vector_reduce_add:
8845     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8846     break;
8847   case Intrinsic::experimental_vector_reduce_mul:
8848     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8849     break;
8850   case Intrinsic::experimental_vector_reduce_and:
8851     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8852     break;
8853   case Intrinsic::experimental_vector_reduce_or:
8854     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8855     break;
8856   case Intrinsic::experimental_vector_reduce_xor:
8857     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8858     break;
8859   case Intrinsic::experimental_vector_reduce_smax:
8860     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8861     break;
8862   case Intrinsic::experimental_vector_reduce_smin:
8863     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8864     break;
8865   case Intrinsic::experimental_vector_reduce_umax:
8866     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8867     break;
8868   case Intrinsic::experimental_vector_reduce_umin:
8869     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8870     break;
8871   case Intrinsic::experimental_vector_reduce_fmax:
8872     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8873     break;
8874   case Intrinsic::experimental_vector_reduce_fmin:
8875     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8876     break;
8877   default:
8878     llvm_unreachable("Unhandled vector reduce intrinsic");
8879   }
8880   setValue(&I, Res);
8881 }
8882 
8883 /// Returns an AttributeList representing the attributes applied to the return
8884 /// value of the given call.
8885 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8886   SmallVector<Attribute::AttrKind, 2> Attrs;
8887   if (CLI.RetSExt)
8888     Attrs.push_back(Attribute::SExt);
8889   if (CLI.RetZExt)
8890     Attrs.push_back(Attribute::ZExt);
8891   if (CLI.IsInReg)
8892     Attrs.push_back(Attribute::InReg);
8893 
8894   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8895                             Attrs);
8896 }
8897 
8898 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8899 /// implementation, which just calls LowerCall.
8900 /// FIXME: When all targets are
8901 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8902 std::pair<SDValue, SDValue>
8903 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8904   // Handle the incoming return values from the call.
8905   CLI.Ins.clear();
8906   Type *OrigRetTy = CLI.RetTy;
8907   SmallVector<EVT, 4> RetTys;
8908   SmallVector<uint64_t, 4> Offsets;
8909   auto &DL = CLI.DAG.getDataLayout();
8910   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8911 
8912   if (CLI.IsPostTypeLegalization) {
8913     // If we are lowering a libcall after legalization, split the return type.
8914     SmallVector<EVT, 4> OldRetTys;
8915     SmallVector<uint64_t, 4> OldOffsets;
8916     RetTys.swap(OldRetTys);
8917     Offsets.swap(OldOffsets);
8918 
8919     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8920       EVT RetVT = OldRetTys[i];
8921       uint64_t Offset = OldOffsets[i];
8922       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8923       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8924       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8925       RetTys.append(NumRegs, RegisterVT);
8926       for (unsigned j = 0; j != NumRegs; ++j)
8927         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8928     }
8929   }
8930 
8931   SmallVector<ISD::OutputArg, 4> Outs;
8932   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8933 
8934   bool CanLowerReturn =
8935       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8936                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8937 
8938   SDValue DemoteStackSlot;
8939   int DemoteStackIdx = -100;
8940   if (!CanLowerReturn) {
8941     // FIXME: equivalent assert?
8942     // assert(!CS.hasInAllocaArgument() &&
8943     //        "sret demotion is incompatible with inalloca");
8944     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8945     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8946     MachineFunction &MF = CLI.DAG.getMachineFunction();
8947     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8948     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8949                                               DL.getAllocaAddrSpace());
8950 
8951     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8952     ArgListEntry Entry;
8953     Entry.Node = DemoteStackSlot;
8954     Entry.Ty = StackSlotPtrType;
8955     Entry.IsSExt = false;
8956     Entry.IsZExt = false;
8957     Entry.IsInReg = false;
8958     Entry.IsSRet = true;
8959     Entry.IsNest = false;
8960     Entry.IsByVal = false;
8961     Entry.IsReturned = false;
8962     Entry.IsSwiftSelf = false;
8963     Entry.IsSwiftError = false;
8964     Entry.IsCFGuardTarget = false;
8965     Entry.Alignment = Align;
8966     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8967     CLI.NumFixedArgs += 1;
8968     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8969 
8970     // sret demotion isn't compatible with tail-calls, since the sret argument
8971     // points into the callers stack frame.
8972     CLI.IsTailCall = false;
8973   } else {
8974     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8975         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8976     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8977       ISD::ArgFlagsTy Flags;
8978       if (NeedsRegBlock) {
8979         Flags.setInConsecutiveRegs();
8980         if (I == RetTys.size() - 1)
8981           Flags.setInConsecutiveRegsLast();
8982       }
8983       EVT VT = RetTys[I];
8984       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8985                                                      CLI.CallConv, VT);
8986       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8987                                                        CLI.CallConv, VT);
8988       for (unsigned i = 0; i != NumRegs; ++i) {
8989         ISD::InputArg MyFlags;
8990         MyFlags.Flags = Flags;
8991         MyFlags.VT = RegisterVT;
8992         MyFlags.ArgVT = VT;
8993         MyFlags.Used = CLI.IsReturnValueUsed;
8994         if (CLI.RetTy->isPointerTy()) {
8995           MyFlags.Flags.setPointer();
8996           MyFlags.Flags.setPointerAddrSpace(
8997               cast<PointerType>(CLI.RetTy)->getAddressSpace());
8998         }
8999         if (CLI.RetSExt)
9000           MyFlags.Flags.setSExt();
9001         if (CLI.RetZExt)
9002           MyFlags.Flags.setZExt();
9003         if (CLI.IsInReg)
9004           MyFlags.Flags.setInReg();
9005         CLI.Ins.push_back(MyFlags);
9006       }
9007     }
9008   }
9009 
9010   // We push in swifterror return as the last element of CLI.Ins.
9011   ArgListTy &Args = CLI.getArgs();
9012   if (supportSwiftError()) {
9013     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9014       if (Args[i].IsSwiftError) {
9015         ISD::InputArg MyFlags;
9016         MyFlags.VT = getPointerTy(DL);
9017         MyFlags.ArgVT = EVT(getPointerTy(DL));
9018         MyFlags.Flags.setSwiftError();
9019         CLI.Ins.push_back(MyFlags);
9020       }
9021     }
9022   }
9023 
9024   // Handle all of the outgoing arguments.
9025   CLI.Outs.clear();
9026   CLI.OutVals.clear();
9027   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9028     SmallVector<EVT, 4> ValueVTs;
9029     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9030     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9031     Type *FinalType = Args[i].Ty;
9032     if (Args[i].IsByVal)
9033       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9034     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9035         FinalType, CLI.CallConv, CLI.IsVarArg);
9036     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9037          ++Value) {
9038       EVT VT = ValueVTs[Value];
9039       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9040       SDValue Op = SDValue(Args[i].Node.getNode(),
9041                            Args[i].Node.getResNo() + Value);
9042       ISD::ArgFlagsTy Flags;
9043 
9044       // Certain targets (such as MIPS), may have a different ABI alignment
9045       // for a type depending on the context. Give the target a chance to
9046       // specify the alignment it wants.
9047       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9048 
9049       if (Args[i].Ty->isPointerTy()) {
9050         Flags.setPointer();
9051         Flags.setPointerAddrSpace(
9052             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9053       }
9054       if (Args[i].IsZExt)
9055         Flags.setZExt();
9056       if (Args[i].IsSExt)
9057         Flags.setSExt();
9058       if (Args[i].IsInReg) {
9059         // If we are using vectorcall calling convention, a structure that is
9060         // passed InReg - is surely an HVA
9061         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9062             isa<StructType>(FinalType)) {
9063           // The first value of a structure is marked
9064           if (0 == Value)
9065             Flags.setHvaStart();
9066           Flags.setHva();
9067         }
9068         // Set InReg Flag
9069         Flags.setInReg();
9070       }
9071       if (Args[i].IsSRet)
9072         Flags.setSRet();
9073       if (Args[i].IsSwiftSelf)
9074         Flags.setSwiftSelf();
9075       if (Args[i].IsSwiftError)
9076         Flags.setSwiftError();
9077       if (Args[i].IsCFGuardTarget)
9078         Flags.setCFGuardTarget();
9079       if (Args[i].IsByVal)
9080         Flags.setByVal();
9081       if (Args[i].IsInAlloca) {
9082         Flags.setInAlloca();
9083         // Set the byval flag for CCAssignFn callbacks that don't know about
9084         // inalloca.  This way we can know how many bytes we should've allocated
9085         // and how many bytes a callee cleanup function will pop.  If we port
9086         // inalloca to more targets, we'll have to add custom inalloca handling
9087         // in the various CC lowering callbacks.
9088         Flags.setByVal();
9089       }
9090       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9091         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9092         Type *ElementTy = Ty->getElementType();
9093 
9094         unsigned FrameSize = DL.getTypeAllocSize(
9095             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9096         Flags.setByValSize(FrameSize);
9097 
9098         // info is not there but there are cases it cannot get right.
9099         unsigned FrameAlign;
9100         if (Args[i].Alignment)
9101           FrameAlign = Args[i].Alignment;
9102         else
9103           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9104         Flags.setByValAlign(Align(FrameAlign));
9105       }
9106       if (Args[i].IsNest)
9107         Flags.setNest();
9108       if (NeedsRegBlock)
9109         Flags.setInConsecutiveRegs();
9110       Flags.setOrigAlign(OriginalAlignment);
9111 
9112       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9113                                                  CLI.CallConv, VT);
9114       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9115                                                         CLI.CallConv, VT);
9116       SmallVector<SDValue, 4> Parts(NumParts);
9117       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9118 
9119       if (Args[i].IsSExt)
9120         ExtendKind = ISD::SIGN_EXTEND;
9121       else if (Args[i].IsZExt)
9122         ExtendKind = ISD::ZERO_EXTEND;
9123 
9124       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9125       // for now.
9126       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9127           CanLowerReturn) {
9128         assert((CLI.RetTy == Args[i].Ty ||
9129                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9130                  CLI.RetTy->getPointerAddressSpace() ==
9131                      Args[i].Ty->getPointerAddressSpace())) &&
9132                RetTys.size() == NumValues && "unexpected use of 'returned'");
9133         // Before passing 'returned' to the target lowering code, ensure that
9134         // either the register MVT and the actual EVT are the same size or that
9135         // the return value and argument are extended in the same way; in these
9136         // cases it's safe to pass the argument register value unchanged as the
9137         // return register value (although it's at the target's option whether
9138         // to do so)
9139         // TODO: allow code generation to take advantage of partially preserved
9140         // registers rather than clobbering the entire register when the
9141         // parameter extension method is not compatible with the return
9142         // extension method
9143         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9144             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9145              CLI.RetZExt == Args[i].IsZExt))
9146           Flags.setReturned();
9147       }
9148 
9149       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9150                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9151 
9152       for (unsigned j = 0; j != NumParts; ++j) {
9153         // if it isn't first piece, alignment must be 1
9154         // For scalable vectors the scalable part is currently handled
9155         // by individual targets, so we just use the known minimum size here.
9156         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9157                     i < CLI.NumFixedArgs, i,
9158                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9159         if (NumParts > 1 && j == 0)
9160           MyFlags.Flags.setSplit();
9161         else if (j != 0) {
9162           MyFlags.Flags.setOrigAlign(Align::None());
9163           if (j == NumParts - 1)
9164             MyFlags.Flags.setSplitEnd();
9165         }
9166 
9167         CLI.Outs.push_back(MyFlags);
9168         CLI.OutVals.push_back(Parts[j]);
9169       }
9170 
9171       if (NeedsRegBlock && Value == NumValues - 1)
9172         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9173     }
9174   }
9175 
9176   SmallVector<SDValue, 4> InVals;
9177   CLI.Chain = LowerCall(CLI, InVals);
9178 
9179   // Update CLI.InVals to use outside of this function.
9180   CLI.InVals = InVals;
9181 
9182   // Verify that the target's LowerCall behaved as expected.
9183   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9184          "LowerCall didn't return a valid chain!");
9185   assert((!CLI.IsTailCall || InVals.empty()) &&
9186          "LowerCall emitted a return value for a tail call!");
9187   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9188          "LowerCall didn't emit the correct number of values!");
9189 
9190   // For a tail call, the return value is merely live-out and there aren't
9191   // any nodes in the DAG representing it. Return a special value to
9192   // indicate that a tail call has been emitted and no more Instructions
9193   // should be processed in the current block.
9194   if (CLI.IsTailCall) {
9195     CLI.DAG.setRoot(CLI.Chain);
9196     return std::make_pair(SDValue(), SDValue());
9197   }
9198 
9199 #ifndef NDEBUG
9200   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9201     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9202     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9203            "LowerCall emitted a value with the wrong type!");
9204   }
9205 #endif
9206 
9207   SmallVector<SDValue, 4> ReturnValues;
9208   if (!CanLowerReturn) {
9209     // The instruction result is the result of loading from the
9210     // hidden sret parameter.
9211     SmallVector<EVT, 1> PVTs;
9212     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9213 
9214     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9215     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9216     EVT PtrVT = PVTs[0];
9217 
9218     unsigned NumValues = RetTys.size();
9219     ReturnValues.resize(NumValues);
9220     SmallVector<SDValue, 4> Chains(NumValues);
9221 
9222     // An aggregate return value cannot wrap around the address space, so
9223     // offsets to its parts don't wrap either.
9224     SDNodeFlags Flags;
9225     Flags.setNoUnsignedWrap(true);
9226 
9227     for (unsigned i = 0; i < NumValues; ++i) {
9228       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9229                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9230                                                         PtrVT), Flags);
9231       SDValue L = CLI.DAG.getLoad(
9232           RetTys[i], CLI.DL, CLI.Chain, Add,
9233           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9234                                             DemoteStackIdx, Offsets[i]),
9235           /* Alignment = */ 1);
9236       ReturnValues[i] = L;
9237       Chains[i] = L.getValue(1);
9238     }
9239 
9240     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9241   } else {
9242     // Collect the legal value parts into potentially illegal values
9243     // that correspond to the original function's return values.
9244     Optional<ISD::NodeType> AssertOp;
9245     if (CLI.RetSExt)
9246       AssertOp = ISD::AssertSext;
9247     else if (CLI.RetZExt)
9248       AssertOp = ISD::AssertZext;
9249     unsigned CurReg = 0;
9250     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9251       EVT VT = RetTys[I];
9252       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9253                                                      CLI.CallConv, VT);
9254       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9255                                                        CLI.CallConv, VT);
9256 
9257       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9258                                               NumRegs, RegisterVT, VT, nullptr,
9259                                               CLI.CallConv, AssertOp));
9260       CurReg += NumRegs;
9261     }
9262 
9263     // For a function returning void, there is no return value. We can't create
9264     // such a node, so we just return a null return value in that case. In
9265     // that case, nothing will actually look at the value.
9266     if (ReturnValues.empty())
9267       return std::make_pair(SDValue(), CLI.Chain);
9268   }
9269 
9270   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9271                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9272   return std::make_pair(Res, CLI.Chain);
9273 }
9274 
9275 void TargetLowering::LowerOperationWrapper(SDNode *N,
9276                                            SmallVectorImpl<SDValue> &Results,
9277                                            SelectionDAG &DAG) const {
9278   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9279     Results.push_back(Res);
9280 }
9281 
9282 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9283   llvm_unreachable("LowerOperation not implemented for this target!");
9284 }
9285 
9286 void
9287 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9288   SDValue Op = getNonRegisterValue(V);
9289   assert((Op.getOpcode() != ISD::CopyFromReg ||
9290           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9291          "Copy from a reg to the same reg!");
9292   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9293 
9294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9295   // If this is an InlineAsm we have to match the registers required, not the
9296   // notional registers required by the type.
9297 
9298   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9299                    None); // This is not an ABI copy.
9300   SDValue Chain = DAG.getEntryNode();
9301 
9302   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9303                               FuncInfo.PreferredExtendType.end())
9304                                  ? ISD::ANY_EXTEND
9305                                  : FuncInfo.PreferredExtendType[V];
9306   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9307   PendingExports.push_back(Chain);
9308 }
9309 
9310 #include "llvm/CodeGen/SelectionDAGISel.h"
9311 
9312 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9313 /// entry block, return true.  This includes arguments used by switches, since
9314 /// the switch may expand into multiple basic blocks.
9315 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9316   // With FastISel active, we may be splitting blocks, so force creation
9317   // of virtual registers for all non-dead arguments.
9318   if (FastISel)
9319     return A->use_empty();
9320 
9321   const BasicBlock &Entry = A->getParent()->front();
9322   for (const User *U : A->users())
9323     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9324       return false;  // Use not in entry block.
9325 
9326   return true;
9327 }
9328 
9329 using ArgCopyElisionMapTy =
9330     DenseMap<const Argument *,
9331              std::pair<const AllocaInst *, const StoreInst *>>;
9332 
9333 /// Scan the entry block of the function in FuncInfo for arguments that look
9334 /// like copies into a local alloca. Record any copied arguments in
9335 /// ArgCopyElisionCandidates.
9336 static void
9337 findArgumentCopyElisionCandidates(const DataLayout &DL,
9338                                   FunctionLoweringInfo *FuncInfo,
9339                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9340   // Record the state of every static alloca used in the entry block. Argument
9341   // allocas are all used in the entry block, so we need approximately as many
9342   // entries as we have arguments.
9343   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9344   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9345   unsigned NumArgs = FuncInfo->Fn->arg_size();
9346   StaticAllocas.reserve(NumArgs * 2);
9347 
9348   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9349     if (!V)
9350       return nullptr;
9351     V = V->stripPointerCasts();
9352     const auto *AI = dyn_cast<AllocaInst>(V);
9353     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9354       return nullptr;
9355     auto Iter = StaticAllocas.insert({AI, Unknown});
9356     return &Iter.first->second;
9357   };
9358 
9359   // Look for stores of arguments to static allocas. Look through bitcasts and
9360   // GEPs to handle type coercions, as long as the alloca is fully initialized
9361   // by the store. Any non-store use of an alloca escapes it and any subsequent
9362   // unanalyzed store might write it.
9363   // FIXME: Handle structs initialized with multiple stores.
9364   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9365     // Look for stores, and handle non-store uses conservatively.
9366     const auto *SI = dyn_cast<StoreInst>(&I);
9367     if (!SI) {
9368       // We will look through cast uses, so ignore them completely.
9369       if (I.isCast())
9370         continue;
9371       // Ignore debug info intrinsics, they don't escape or store to allocas.
9372       if (isa<DbgInfoIntrinsic>(I))
9373         continue;
9374       // This is an unknown instruction. Assume it escapes or writes to all
9375       // static alloca operands.
9376       for (const Use &U : I.operands()) {
9377         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9378           *Info = StaticAllocaInfo::Clobbered;
9379       }
9380       continue;
9381     }
9382 
9383     // If the stored value is a static alloca, mark it as escaped.
9384     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9385       *Info = StaticAllocaInfo::Clobbered;
9386 
9387     // Check if the destination is a static alloca.
9388     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9389     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9390     if (!Info)
9391       continue;
9392     const AllocaInst *AI = cast<AllocaInst>(Dst);
9393 
9394     // Skip allocas that have been initialized or clobbered.
9395     if (*Info != StaticAllocaInfo::Unknown)
9396       continue;
9397 
9398     // Check if the stored value is an argument, and that this store fully
9399     // initializes the alloca. Don't elide copies from the same argument twice.
9400     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9401     const auto *Arg = dyn_cast<Argument>(Val);
9402     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9403         Arg->getType()->isEmptyTy() ||
9404         DL.getTypeStoreSize(Arg->getType()) !=
9405             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9406         ArgCopyElisionCandidates.count(Arg)) {
9407       *Info = StaticAllocaInfo::Clobbered;
9408       continue;
9409     }
9410 
9411     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9412                       << '\n');
9413 
9414     // Mark this alloca and store for argument copy elision.
9415     *Info = StaticAllocaInfo::Elidable;
9416     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9417 
9418     // Stop scanning if we've seen all arguments. This will happen early in -O0
9419     // builds, which is useful, because -O0 builds have large entry blocks and
9420     // many allocas.
9421     if (ArgCopyElisionCandidates.size() == NumArgs)
9422       break;
9423   }
9424 }
9425 
9426 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9427 /// ArgVal is a load from a suitable fixed stack object.
9428 static void tryToElideArgumentCopy(
9429     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9430     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9431     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9432     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9433     SDValue ArgVal, bool &ArgHasUses) {
9434   // Check if this is a load from a fixed stack object.
9435   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9436   if (!LNode)
9437     return;
9438   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9439   if (!FINode)
9440     return;
9441 
9442   // Check that the fixed stack object is the right size and alignment.
9443   // Look at the alignment that the user wrote on the alloca instead of looking
9444   // at the stack object.
9445   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9446   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9447   const AllocaInst *AI = ArgCopyIter->second.first;
9448   int FixedIndex = FINode->getIndex();
9449   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9450   int OldIndex = AllocaIndex;
9451   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9452   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9453     LLVM_DEBUG(
9454         dbgs() << "  argument copy elision failed due to bad fixed stack "
9455                   "object size\n");
9456     return;
9457   }
9458   unsigned RequiredAlignment = AI->getAlignment();
9459   if (!RequiredAlignment) {
9460     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9461         AI->getAllocatedType());
9462   }
9463   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9464     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9465                          "greater than stack argument alignment ("
9466                       << RequiredAlignment << " vs "
9467                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9468     return;
9469   }
9470 
9471   // Perform the elision. Delete the old stack object and replace its only use
9472   // in the variable info map. Mark the stack object as mutable.
9473   LLVM_DEBUG({
9474     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9475            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9476            << '\n';
9477   });
9478   MFI.RemoveStackObject(OldIndex);
9479   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9480   AllocaIndex = FixedIndex;
9481   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9482   Chains.push_back(ArgVal.getValue(1));
9483 
9484   // Avoid emitting code for the store implementing the copy.
9485   const StoreInst *SI = ArgCopyIter->second.second;
9486   ElidedArgCopyInstrs.insert(SI);
9487 
9488   // Check for uses of the argument again so that we can avoid exporting ArgVal
9489   // if it is't used by anything other than the store.
9490   for (const Value *U : Arg.users()) {
9491     if (U != SI) {
9492       ArgHasUses = true;
9493       break;
9494     }
9495   }
9496 }
9497 
9498 void SelectionDAGISel::LowerArguments(const Function &F) {
9499   SelectionDAG &DAG = SDB->DAG;
9500   SDLoc dl = SDB->getCurSDLoc();
9501   const DataLayout &DL = DAG.getDataLayout();
9502   SmallVector<ISD::InputArg, 16> Ins;
9503 
9504   if (!FuncInfo->CanLowerReturn) {
9505     // Put in an sret pointer parameter before all the other parameters.
9506     SmallVector<EVT, 1> ValueVTs;
9507     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9508                     F.getReturnType()->getPointerTo(
9509                         DAG.getDataLayout().getAllocaAddrSpace()),
9510                     ValueVTs);
9511 
9512     // NOTE: Assuming that a pointer will never break down to more than one VT
9513     // or one register.
9514     ISD::ArgFlagsTy Flags;
9515     Flags.setSRet();
9516     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9517     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9518                          ISD::InputArg::NoArgIndex, 0);
9519     Ins.push_back(RetArg);
9520   }
9521 
9522   // Look for stores of arguments to static allocas. Mark such arguments with a
9523   // flag to ask the target to give us the memory location of that argument if
9524   // available.
9525   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9526   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9527 
9528   // Set up the incoming argument description vector.
9529   for (const Argument &Arg : F.args()) {
9530     unsigned ArgNo = Arg.getArgNo();
9531     SmallVector<EVT, 4> ValueVTs;
9532     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9533     bool isArgValueUsed = !Arg.use_empty();
9534     unsigned PartBase = 0;
9535     Type *FinalType = Arg.getType();
9536     if (Arg.hasAttribute(Attribute::ByVal))
9537       FinalType = Arg.getParamByValType();
9538     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9539         FinalType, F.getCallingConv(), F.isVarArg());
9540     for (unsigned Value = 0, NumValues = ValueVTs.size();
9541          Value != NumValues; ++Value) {
9542       EVT VT = ValueVTs[Value];
9543       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9544       ISD::ArgFlagsTy Flags;
9545 
9546       // Certain targets (such as MIPS), may have a different ABI alignment
9547       // for a type depending on the context. Give the target a chance to
9548       // specify the alignment it wants.
9549       const Align OriginalAlignment(
9550           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9551 
9552       if (Arg.getType()->isPointerTy()) {
9553         Flags.setPointer();
9554         Flags.setPointerAddrSpace(
9555             cast<PointerType>(Arg.getType())->getAddressSpace());
9556       }
9557       if (Arg.hasAttribute(Attribute::ZExt))
9558         Flags.setZExt();
9559       if (Arg.hasAttribute(Attribute::SExt))
9560         Flags.setSExt();
9561       if (Arg.hasAttribute(Attribute::InReg)) {
9562         // If we are using vectorcall calling convention, a structure that is
9563         // passed InReg - is surely an HVA
9564         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9565             isa<StructType>(Arg.getType())) {
9566           // The first value of a structure is marked
9567           if (0 == Value)
9568             Flags.setHvaStart();
9569           Flags.setHva();
9570         }
9571         // Set InReg Flag
9572         Flags.setInReg();
9573       }
9574       if (Arg.hasAttribute(Attribute::StructRet))
9575         Flags.setSRet();
9576       if (Arg.hasAttribute(Attribute::SwiftSelf))
9577         Flags.setSwiftSelf();
9578       if (Arg.hasAttribute(Attribute::SwiftError))
9579         Flags.setSwiftError();
9580       if (Arg.hasAttribute(Attribute::ByVal))
9581         Flags.setByVal();
9582       if (Arg.hasAttribute(Attribute::InAlloca)) {
9583         Flags.setInAlloca();
9584         // Set the byval flag for CCAssignFn callbacks that don't know about
9585         // inalloca.  This way we can know how many bytes we should've allocated
9586         // and how many bytes a callee cleanup function will pop.  If we port
9587         // inalloca to more targets, we'll have to add custom inalloca handling
9588         // in the various CC lowering callbacks.
9589         Flags.setByVal();
9590       }
9591       if (F.getCallingConv() == CallingConv::X86_INTR) {
9592         // IA Interrupt passes frame (1st parameter) by value in the stack.
9593         if (ArgNo == 0)
9594           Flags.setByVal();
9595       }
9596       if (Flags.isByVal() || Flags.isInAlloca()) {
9597         Type *ElementTy = Arg.getParamByValType();
9598 
9599         // For ByVal, size and alignment should be passed from FE.  BE will
9600         // guess if this info is not there but there are cases it cannot get
9601         // right.
9602         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9603         Flags.setByValSize(FrameSize);
9604 
9605         unsigned FrameAlign;
9606         if (Arg.getParamAlignment())
9607           FrameAlign = Arg.getParamAlignment();
9608         else
9609           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9610         Flags.setByValAlign(Align(FrameAlign));
9611       }
9612       if (Arg.hasAttribute(Attribute::Nest))
9613         Flags.setNest();
9614       if (NeedsRegBlock)
9615         Flags.setInConsecutiveRegs();
9616       Flags.setOrigAlign(OriginalAlignment);
9617       if (ArgCopyElisionCandidates.count(&Arg))
9618         Flags.setCopyElisionCandidate();
9619       if (Arg.hasAttribute(Attribute::Returned))
9620         Flags.setReturned();
9621 
9622       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9623           *CurDAG->getContext(), F.getCallingConv(), VT);
9624       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9625           *CurDAG->getContext(), F.getCallingConv(), VT);
9626       for (unsigned i = 0; i != NumRegs; ++i) {
9627         // For scalable vectors, use the minimum size; individual targets
9628         // are responsible for handling scalable vector arguments and
9629         // return values.
9630         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9631                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9632         if (NumRegs > 1 && i == 0)
9633           MyFlags.Flags.setSplit();
9634         // if it isn't first piece, alignment must be 1
9635         else if (i > 0) {
9636           MyFlags.Flags.setOrigAlign(Align::None());
9637           if (i == NumRegs - 1)
9638             MyFlags.Flags.setSplitEnd();
9639         }
9640         Ins.push_back(MyFlags);
9641       }
9642       if (NeedsRegBlock && Value == NumValues - 1)
9643         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9644       PartBase += VT.getStoreSize().getKnownMinSize();
9645     }
9646   }
9647 
9648   // Call the target to set up the argument values.
9649   SmallVector<SDValue, 8> InVals;
9650   SDValue NewRoot = TLI->LowerFormalArguments(
9651       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9652 
9653   // Verify that the target's LowerFormalArguments behaved as expected.
9654   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9655          "LowerFormalArguments didn't return a valid chain!");
9656   assert(InVals.size() == Ins.size() &&
9657          "LowerFormalArguments didn't emit the correct number of values!");
9658   LLVM_DEBUG({
9659     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9660       assert(InVals[i].getNode() &&
9661              "LowerFormalArguments emitted a null value!");
9662       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9663              "LowerFormalArguments emitted a value with the wrong type!");
9664     }
9665   });
9666 
9667   // Update the DAG with the new chain value resulting from argument lowering.
9668   DAG.setRoot(NewRoot);
9669 
9670   // Set up the argument values.
9671   unsigned i = 0;
9672   if (!FuncInfo->CanLowerReturn) {
9673     // Create a virtual register for the sret pointer, and put in a copy
9674     // from the sret argument into it.
9675     SmallVector<EVT, 1> ValueVTs;
9676     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9677                     F.getReturnType()->getPointerTo(
9678                         DAG.getDataLayout().getAllocaAddrSpace()),
9679                     ValueVTs);
9680     MVT VT = ValueVTs[0].getSimpleVT();
9681     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9682     Optional<ISD::NodeType> AssertOp = None;
9683     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9684                                         nullptr, F.getCallingConv(), AssertOp);
9685 
9686     MachineFunction& MF = SDB->DAG.getMachineFunction();
9687     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9688     Register SRetReg =
9689         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9690     FuncInfo->DemoteRegister = SRetReg;
9691     NewRoot =
9692         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9693     DAG.setRoot(NewRoot);
9694 
9695     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9696     ++i;
9697   }
9698 
9699   SmallVector<SDValue, 4> Chains;
9700   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9701   for (const Argument &Arg : F.args()) {
9702     SmallVector<SDValue, 4> ArgValues;
9703     SmallVector<EVT, 4> ValueVTs;
9704     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9705     unsigned NumValues = ValueVTs.size();
9706     if (NumValues == 0)
9707       continue;
9708 
9709     bool ArgHasUses = !Arg.use_empty();
9710 
9711     // Elide the copying store if the target loaded this argument from a
9712     // suitable fixed stack object.
9713     if (Ins[i].Flags.isCopyElisionCandidate()) {
9714       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9715                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9716                              InVals[i], ArgHasUses);
9717     }
9718 
9719     // If this argument is unused then remember its value. It is used to generate
9720     // debugging information.
9721     bool isSwiftErrorArg =
9722         TLI->supportSwiftError() &&
9723         Arg.hasAttribute(Attribute::SwiftError);
9724     if (!ArgHasUses && !isSwiftErrorArg) {
9725       SDB->setUnusedArgValue(&Arg, InVals[i]);
9726 
9727       // Also remember any frame index for use in FastISel.
9728       if (FrameIndexSDNode *FI =
9729           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9730         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9731     }
9732 
9733     for (unsigned Val = 0; Val != NumValues; ++Val) {
9734       EVT VT = ValueVTs[Val];
9735       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9736                                                       F.getCallingConv(), VT);
9737       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9738           *CurDAG->getContext(), F.getCallingConv(), VT);
9739 
9740       // Even an apparent 'unused' swifterror argument needs to be returned. So
9741       // we do generate a copy for it that can be used on return from the
9742       // function.
9743       if (ArgHasUses || isSwiftErrorArg) {
9744         Optional<ISD::NodeType> AssertOp;
9745         if (Arg.hasAttribute(Attribute::SExt))
9746           AssertOp = ISD::AssertSext;
9747         else if (Arg.hasAttribute(Attribute::ZExt))
9748           AssertOp = ISD::AssertZext;
9749 
9750         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9751                                              PartVT, VT, nullptr,
9752                                              F.getCallingConv(), AssertOp));
9753       }
9754 
9755       i += NumParts;
9756     }
9757 
9758     // We don't need to do anything else for unused arguments.
9759     if (ArgValues.empty())
9760       continue;
9761 
9762     // Note down frame index.
9763     if (FrameIndexSDNode *FI =
9764         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9765       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9766 
9767     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9768                                      SDB->getCurSDLoc());
9769 
9770     SDB->setValue(&Arg, Res);
9771     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9772       // We want to associate the argument with the frame index, among
9773       // involved operands, that correspond to the lowest address. The
9774       // getCopyFromParts function, called earlier, is swapping the order of
9775       // the operands to BUILD_PAIR depending on endianness. The result of
9776       // that swapping is that the least significant bits of the argument will
9777       // be in the first operand of the BUILD_PAIR node, and the most
9778       // significant bits will be in the second operand.
9779       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9780       if (LoadSDNode *LNode =
9781           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9782         if (FrameIndexSDNode *FI =
9783             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9784           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9785     }
9786 
9787     // Analyses past this point are naive and don't expect an assertion.
9788     if (Res.getOpcode() == ISD::AssertZext)
9789       Res = Res.getOperand(0);
9790 
9791     // Update the SwiftErrorVRegDefMap.
9792     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9793       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9794       if (Register::isVirtualRegister(Reg))
9795         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9796                                    Reg);
9797     }
9798 
9799     // If this argument is live outside of the entry block, insert a copy from
9800     // wherever we got it to the vreg that other BB's will reference it as.
9801     if (Res.getOpcode() == ISD::CopyFromReg) {
9802       // If we can, though, try to skip creating an unnecessary vreg.
9803       // FIXME: This isn't very clean... it would be nice to make this more
9804       // general.
9805       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9806       if (Register::isVirtualRegister(Reg)) {
9807         FuncInfo->ValueMap[&Arg] = Reg;
9808         continue;
9809       }
9810     }
9811     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9812       FuncInfo->InitializeRegForValue(&Arg);
9813       SDB->CopyToExportRegsIfNeeded(&Arg);
9814     }
9815   }
9816 
9817   if (!Chains.empty()) {
9818     Chains.push_back(NewRoot);
9819     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9820   }
9821 
9822   DAG.setRoot(NewRoot);
9823 
9824   assert(i == InVals.size() && "Argument register count mismatch!");
9825 
9826   // If any argument copy elisions occurred and we have debug info, update the
9827   // stale frame indices used in the dbg.declare variable info table.
9828   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9829   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9830     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9831       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9832       if (I != ArgCopyElisionFrameIndexMap.end())
9833         VI.Slot = I->second;
9834     }
9835   }
9836 
9837   // Finally, if the target has anything special to do, allow it to do so.
9838   EmitFunctionEntryCode();
9839 }
9840 
9841 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9842 /// ensure constants are generated when needed.  Remember the virtual registers
9843 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9844 /// directly add them, because expansion might result in multiple MBB's for one
9845 /// BB.  As such, the start of the BB might correspond to a different MBB than
9846 /// the end.
9847 void
9848 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9849   const Instruction *TI = LLVMBB->getTerminator();
9850 
9851   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9852 
9853   // Check PHI nodes in successors that expect a value to be available from this
9854   // block.
9855   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9856     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9857     if (!isa<PHINode>(SuccBB->begin())) continue;
9858     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9859 
9860     // If this terminator has multiple identical successors (common for
9861     // switches), only handle each succ once.
9862     if (!SuccsHandled.insert(SuccMBB).second)
9863       continue;
9864 
9865     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9866 
9867     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9868     // nodes and Machine PHI nodes, but the incoming operands have not been
9869     // emitted yet.
9870     for (const PHINode &PN : SuccBB->phis()) {
9871       // Ignore dead phi's.
9872       if (PN.use_empty())
9873         continue;
9874 
9875       // Skip empty types
9876       if (PN.getType()->isEmptyTy())
9877         continue;
9878 
9879       unsigned Reg;
9880       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9881 
9882       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9883         unsigned &RegOut = ConstantsOut[C];
9884         if (RegOut == 0) {
9885           RegOut = FuncInfo.CreateRegs(C);
9886           CopyValueToVirtualRegister(C, RegOut);
9887         }
9888         Reg = RegOut;
9889       } else {
9890         DenseMap<const Value *, unsigned>::iterator I =
9891           FuncInfo.ValueMap.find(PHIOp);
9892         if (I != FuncInfo.ValueMap.end())
9893           Reg = I->second;
9894         else {
9895           assert(isa<AllocaInst>(PHIOp) &&
9896                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9897                  "Didn't codegen value into a register!??");
9898           Reg = FuncInfo.CreateRegs(PHIOp);
9899           CopyValueToVirtualRegister(PHIOp, Reg);
9900         }
9901       }
9902 
9903       // Remember that this register needs to added to the machine PHI node as
9904       // the input for this MBB.
9905       SmallVector<EVT, 4> ValueVTs;
9906       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9907       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9908       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9909         EVT VT = ValueVTs[vti];
9910         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9911         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9912           FuncInfo.PHINodesToUpdate.push_back(
9913               std::make_pair(&*MBBI++, Reg + i));
9914         Reg += NumRegisters;
9915       }
9916     }
9917   }
9918 
9919   ConstantsOut.clear();
9920 }
9921 
9922 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9923 /// is 0.
9924 MachineBasicBlock *
9925 SelectionDAGBuilder::StackProtectorDescriptor::
9926 AddSuccessorMBB(const BasicBlock *BB,
9927                 MachineBasicBlock *ParentMBB,
9928                 bool IsLikely,
9929                 MachineBasicBlock *SuccMBB) {
9930   // If SuccBB has not been created yet, create it.
9931   if (!SuccMBB) {
9932     MachineFunction *MF = ParentMBB->getParent();
9933     MachineFunction::iterator BBI(ParentMBB);
9934     SuccMBB = MF->CreateMachineBasicBlock(BB);
9935     MF->insert(++BBI, SuccMBB);
9936   }
9937   // Add it as a successor of ParentMBB.
9938   ParentMBB->addSuccessor(
9939       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9940   return SuccMBB;
9941 }
9942 
9943 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9944   MachineFunction::iterator I(MBB);
9945   if (++I == FuncInfo.MF->end())
9946     return nullptr;
9947   return &*I;
9948 }
9949 
9950 /// During lowering new call nodes can be created (such as memset, etc.).
9951 /// Those will become new roots of the current DAG, but complications arise
9952 /// when they are tail calls. In such cases, the call lowering will update
9953 /// the root, but the builder still needs to know that a tail call has been
9954 /// lowered in order to avoid generating an additional return.
9955 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9956   // If the node is null, we do have a tail call.
9957   if (MaybeTC.getNode() != nullptr)
9958     DAG.setRoot(MaybeTC);
9959   else
9960     HasTailCall = true;
9961 }
9962 
9963 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9964                                         MachineBasicBlock *SwitchMBB,
9965                                         MachineBasicBlock *DefaultMBB) {
9966   MachineFunction *CurMF = FuncInfo.MF;
9967   MachineBasicBlock *NextMBB = nullptr;
9968   MachineFunction::iterator BBI(W.MBB);
9969   if (++BBI != FuncInfo.MF->end())
9970     NextMBB = &*BBI;
9971 
9972   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9973 
9974   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9975 
9976   if (Size == 2 && W.MBB == SwitchMBB) {
9977     // If any two of the cases has the same destination, and if one value
9978     // is the same as the other, but has one bit unset that the other has set,
9979     // use bit manipulation to do two compares at once.  For example:
9980     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9981     // TODO: This could be extended to merge any 2 cases in switches with 3
9982     // cases.
9983     // TODO: Handle cases where W.CaseBB != SwitchBB.
9984     CaseCluster &Small = *W.FirstCluster;
9985     CaseCluster &Big = *W.LastCluster;
9986 
9987     if (Small.Low == Small.High && Big.Low == Big.High &&
9988         Small.MBB == Big.MBB) {
9989       const APInt &SmallValue = Small.Low->getValue();
9990       const APInt &BigValue = Big.Low->getValue();
9991 
9992       // Check that there is only one bit different.
9993       APInt CommonBit = BigValue ^ SmallValue;
9994       if (CommonBit.isPowerOf2()) {
9995         SDValue CondLHS = getValue(Cond);
9996         EVT VT = CondLHS.getValueType();
9997         SDLoc DL = getCurSDLoc();
9998 
9999         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10000                                  DAG.getConstant(CommonBit, DL, VT));
10001         SDValue Cond = DAG.getSetCC(
10002             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10003             ISD::SETEQ);
10004 
10005         // Update successor info.
10006         // Both Small and Big will jump to Small.BB, so we sum up the
10007         // probabilities.
10008         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10009         if (BPI)
10010           addSuccessorWithProb(
10011               SwitchMBB, DefaultMBB,
10012               // The default destination is the first successor in IR.
10013               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10014         else
10015           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10016 
10017         // Insert the true branch.
10018         SDValue BrCond =
10019             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10020                         DAG.getBasicBlock(Small.MBB));
10021         // Insert the false branch.
10022         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10023                              DAG.getBasicBlock(DefaultMBB));
10024 
10025         DAG.setRoot(BrCond);
10026         return;
10027       }
10028     }
10029   }
10030 
10031   if (TM.getOptLevel() != CodeGenOpt::None) {
10032     // Here, we order cases by probability so the most likely case will be
10033     // checked first. However, two clusters can have the same probability in
10034     // which case their relative ordering is non-deterministic. So we use Low
10035     // as a tie-breaker as clusters are guaranteed to never overlap.
10036     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10037                [](const CaseCluster &a, const CaseCluster &b) {
10038       return a.Prob != b.Prob ?
10039              a.Prob > b.Prob :
10040              a.Low->getValue().slt(b.Low->getValue());
10041     });
10042 
10043     // Rearrange the case blocks so that the last one falls through if possible
10044     // without changing the order of probabilities.
10045     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10046       --I;
10047       if (I->Prob > W.LastCluster->Prob)
10048         break;
10049       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10050         std::swap(*I, *W.LastCluster);
10051         break;
10052       }
10053     }
10054   }
10055 
10056   // Compute total probability.
10057   BranchProbability DefaultProb = W.DefaultProb;
10058   BranchProbability UnhandledProbs = DefaultProb;
10059   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10060     UnhandledProbs += I->Prob;
10061 
10062   MachineBasicBlock *CurMBB = W.MBB;
10063   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10064     bool FallthroughUnreachable = false;
10065     MachineBasicBlock *Fallthrough;
10066     if (I == W.LastCluster) {
10067       // For the last cluster, fall through to the default destination.
10068       Fallthrough = DefaultMBB;
10069       FallthroughUnreachable = isa<UnreachableInst>(
10070           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10071     } else {
10072       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10073       CurMF->insert(BBI, Fallthrough);
10074       // Put Cond in a virtual register to make it available from the new blocks.
10075       ExportFromCurrentBlock(Cond);
10076     }
10077     UnhandledProbs -= I->Prob;
10078 
10079     switch (I->Kind) {
10080       case CC_JumpTable: {
10081         // FIXME: Optimize away range check based on pivot comparisons.
10082         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10083         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10084 
10085         // The jump block hasn't been inserted yet; insert it here.
10086         MachineBasicBlock *JumpMBB = JT->MBB;
10087         CurMF->insert(BBI, JumpMBB);
10088 
10089         auto JumpProb = I->Prob;
10090         auto FallthroughProb = UnhandledProbs;
10091 
10092         // If the default statement is a target of the jump table, we evenly
10093         // distribute the default probability to successors of CurMBB. Also
10094         // update the probability on the edge from JumpMBB to Fallthrough.
10095         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10096                                               SE = JumpMBB->succ_end();
10097              SI != SE; ++SI) {
10098           if (*SI == DefaultMBB) {
10099             JumpProb += DefaultProb / 2;
10100             FallthroughProb -= DefaultProb / 2;
10101             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10102             JumpMBB->normalizeSuccProbs();
10103             break;
10104           }
10105         }
10106 
10107         if (FallthroughUnreachable) {
10108           // Skip the range check if the fallthrough block is unreachable.
10109           JTH->OmitRangeCheck = true;
10110         }
10111 
10112         if (!JTH->OmitRangeCheck)
10113           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10114         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10115         CurMBB->normalizeSuccProbs();
10116 
10117         // The jump table header will be inserted in our current block, do the
10118         // range check, and fall through to our fallthrough block.
10119         JTH->HeaderBB = CurMBB;
10120         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10121 
10122         // If we're in the right place, emit the jump table header right now.
10123         if (CurMBB == SwitchMBB) {
10124           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10125           JTH->Emitted = true;
10126         }
10127         break;
10128       }
10129       case CC_BitTests: {
10130         // FIXME: Optimize away range check based on pivot comparisons.
10131         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10132 
10133         // The bit test blocks haven't been inserted yet; insert them here.
10134         for (BitTestCase &BTC : BTB->Cases)
10135           CurMF->insert(BBI, BTC.ThisBB);
10136 
10137         // Fill in fields of the BitTestBlock.
10138         BTB->Parent = CurMBB;
10139         BTB->Default = Fallthrough;
10140 
10141         BTB->DefaultProb = UnhandledProbs;
10142         // If the cases in bit test don't form a contiguous range, we evenly
10143         // distribute the probability on the edge to Fallthrough to two
10144         // successors of CurMBB.
10145         if (!BTB->ContiguousRange) {
10146           BTB->Prob += DefaultProb / 2;
10147           BTB->DefaultProb -= DefaultProb / 2;
10148         }
10149 
10150         if (FallthroughUnreachable) {
10151           // Skip the range check if the fallthrough block is unreachable.
10152           BTB->OmitRangeCheck = true;
10153         }
10154 
10155         // If we're in the right place, emit the bit test header right now.
10156         if (CurMBB == SwitchMBB) {
10157           visitBitTestHeader(*BTB, SwitchMBB);
10158           BTB->Emitted = true;
10159         }
10160         break;
10161       }
10162       case CC_Range: {
10163         const Value *RHS, *LHS, *MHS;
10164         ISD::CondCode CC;
10165         if (I->Low == I->High) {
10166           // Check Cond == I->Low.
10167           CC = ISD::SETEQ;
10168           LHS = Cond;
10169           RHS=I->Low;
10170           MHS = nullptr;
10171         } else {
10172           // Check I->Low <= Cond <= I->High.
10173           CC = ISD::SETLE;
10174           LHS = I->Low;
10175           MHS = Cond;
10176           RHS = I->High;
10177         }
10178 
10179         // If Fallthrough is unreachable, fold away the comparison.
10180         if (FallthroughUnreachable)
10181           CC = ISD::SETTRUE;
10182 
10183         // The false probability is the sum of all unhandled cases.
10184         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10185                      getCurSDLoc(), I->Prob, UnhandledProbs);
10186 
10187         if (CurMBB == SwitchMBB)
10188           visitSwitchCase(CB, SwitchMBB);
10189         else
10190           SL->SwitchCases.push_back(CB);
10191 
10192         break;
10193       }
10194     }
10195     CurMBB = Fallthrough;
10196   }
10197 }
10198 
10199 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10200                                               CaseClusterIt First,
10201                                               CaseClusterIt Last) {
10202   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10203     if (X.Prob != CC.Prob)
10204       return X.Prob > CC.Prob;
10205 
10206     // Ties are broken by comparing the case value.
10207     return X.Low->getValue().slt(CC.Low->getValue());
10208   });
10209 }
10210 
10211 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10212                                         const SwitchWorkListItem &W,
10213                                         Value *Cond,
10214                                         MachineBasicBlock *SwitchMBB) {
10215   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10216          "Clusters not sorted?");
10217 
10218   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10219 
10220   // Balance the tree based on branch probabilities to create a near-optimal (in
10221   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10222   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10223   CaseClusterIt LastLeft = W.FirstCluster;
10224   CaseClusterIt FirstRight = W.LastCluster;
10225   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10226   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10227 
10228   // Move LastLeft and FirstRight towards each other from opposite directions to
10229   // find a partitioning of the clusters which balances the probability on both
10230   // sides. If LeftProb and RightProb are equal, alternate which side is
10231   // taken to ensure 0-probability nodes are distributed evenly.
10232   unsigned I = 0;
10233   while (LastLeft + 1 < FirstRight) {
10234     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10235       LeftProb += (++LastLeft)->Prob;
10236     else
10237       RightProb += (--FirstRight)->Prob;
10238     I++;
10239   }
10240 
10241   while (true) {
10242     // Our binary search tree differs from a typical BST in that ours can have up
10243     // to three values in each leaf. The pivot selection above doesn't take that
10244     // into account, which means the tree might require more nodes and be less
10245     // efficient. We compensate for this here.
10246 
10247     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10248     unsigned NumRight = W.LastCluster - FirstRight + 1;
10249 
10250     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10251       // If one side has less than 3 clusters, and the other has more than 3,
10252       // consider taking a cluster from the other side.
10253 
10254       if (NumLeft < NumRight) {
10255         // Consider moving the first cluster on the right to the left side.
10256         CaseCluster &CC = *FirstRight;
10257         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10258         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10259         if (LeftSideRank <= RightSideRank) {
10260           // Moving the cluster to the left does not demote it.
10261           ++LastLeft;
10262           ++FirstRight;
10263           continue;
10264         }
10265       } else {
10266         assert(NumRight < NumLeft);
10267         // Consider moving the last element on the left to the right side.
10268         CaseCluster &CC = *LastLeft;
10269         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10270         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10271         if (RightSideRank <= LeftSideRank) {
10272           // Moving the cluster to the right does not demot it.
10273           --LastLeft;
10274           --FirstRight;
10275           continue;
10276         }
10277       }
10278     }
10279     break;
10280   }
10281 
10282   assert(LastLeft + 1 == FirstRight);
10283   assert(LastLeft >= W.FirstCluster);
10284   assert(FirstRight <= W.LastCluster);
10285 
10286   // Use the first element on the right as pivot since we will make less-than
10287   // comparisons against it.
10288   CaseClusterIt PivotCluster = FirstRight;
10289   assert(PivotCluster > W.FirstCluster);
10290   assert(PivotCluster <= W.LastCluster);
10291 
10292   CaseClusterIt FirstLeft = W.FirstCluster;
10293   CaseClusterIt LastRight = W.LastCluster;
10294 
10295   const ConstantInt *Pivot = PivotCluster->Low;
10296 
10297   // New blocks will be inserted immediately after the current one.
10298   MachineFunction::iterator BBI(W.MBB);
10299   ++BBI;
10300 
10301   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10302   // we can branch to its destination directly if it's squeezed exactly in
10303   // between the known lower bound and Pivot - 1.
10304   MachineBasicBlock *LeftMBB;
10305   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10306       FirstLeft->Low == W.GE &&
10307       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10308     LeftMBB = FirstLeft->MBB;
10309   } else {
10310     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10311     FuncInfo.MF->insert(BBI, LeftMBB);
10312     WorkList.push_back(
10313         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10314     // Put Cond in a virtual register to make it available from the new blocks.
10315     ExportFromCurrentBlock(Cond);
10316   }
10317 
10318   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10319   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10320   // directly if RHS.High equals the current upper bound.
10321   MachineBasicBlock *RightMBB;
10322   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10323       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10324     RightMBB = FirstRight->MBB;
10325   } else {
10326     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10327     FuncInfo.MF->insert(BBI, RightMBB);
10328     WorkList.push_back(
10329         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10330     // Put Cond in a virtual register to make it available from the new blocks.
10331     ExportFromCurrentBlock(Cond);
10332   }
10333 
10334   // Create the CaseBlock record that will be used to lower the branch.
10335   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10336                getCurSDLoc(), LeftProb, RightProb);
10337 
10338   if (W.MBB == SwitchMBB)
10339     visitSwitchCase(CB, SwitchMBB);
10340   else
10341     SL->SwitchCases.push_back(CB);
10342 }
10343 
10344 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10345 // from the swith statement.
10346 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10347                                             BranchProbability PeeledCaseProb) {
10348   if (PeeledCaseProb == BranchProbability::getOne())
10349     return BranchProbability::getZero();
10350   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10351 
10352   uint32_t Numerator = CaseProb.getNumerator();
10353   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10354   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10355 }
10356 
10357 // Try to peel the top probability case if it exceeds the threshold.
10358 // Return current MachineBasicBlock for the switch statement if the peeling
10359 // does not occur.
10360 // If the peeling is performed, return the newly created MachineBasicBlock
10361 // for the peeled switch statement. Also update Clusters to remove the peeled
10362 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10363 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10364     const SwitchInst &SI, CaseClusterVector &Clusters,
10365     BranchProbability &PeeledCaseProb) {
10366   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10367   // Don't perform if there is only one cluster or optimizing for size.
10368   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10369       TM.getOptLevel() == CodeGenOpt::None ||
10370       SwitchMBB->getParent()->getFunction().hasMinSize())
10371     return SwitchMBB;
10372 
10373   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10374   unsigned PeeledCaseIndex = 0;
10375   bool SwitchPeeled = false;
10376   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10377     CaseCluster &CC = Clusters[Index];
10378     if (CC.Prob < TopCaseProb)
10379       continue;
10380     TopCaseProb = CC.Prob;
10381     PeeledCaseIndex = Index;
10382     SwitchPeeled = true;
10383   }
10384   if (!SwitchPeeled)
10385     return SwitchMBB;
10386 
10387   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10388                     << TopCaseProb << "\n");
10389 
10390   // Record the MBB for the peeled switch statement.
10391   MachineFunction::iterator BBI(SwitchMBB);
10392   ++BBI;
10393   MachineBasicBlock *PeeledSwitchMBB =
10394       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10395   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10396 
10397   ExportFromCurrentBlock(SI.getCondition());
10398   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10399   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10400                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10401   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10402 
10403   Clusters.erase(PeeledCaseIt);
10404   for (CaseCluster &CC : Clusters) {
10405     LLVM_DEBUG(
10406         dbgs() << "Scale the probablity for one cluster, before scaling: "
10407                << CC.Prob << "\n");
10408     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10409     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10410   }
10411   PeeledCaseProb = TopCaseProb;
10412   return PeeledSwitchMBB;
10413 }
10414 
10415 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10416   // Extract cases from the switch.
10417   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10418   CaseClusterVector Clusters;
10419   Clusters.reserve(SI.getNumCases());
10420   for (auto I : SI.cases()) {
10421     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10422     const ConstantInt *CaseVal = I.getCaseValue();
10423     BranchProbability Prob =
10424         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10425             : BranchProbability(1, SI.getNumCases() + 1);
10426     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10427   }
10428 
10429   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10430 
10431   // Cluster adjacent cases with the same destination. We do this at all
10432   // optimization levels because it's cheap to do and will make codegen faster
10433   // if there are many clusters.
10434   sortAndRangeify(Clusters);
10435 
10436   // The branch probablity of the peeled case.
10437   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10438   MachineBasicBlock *PeeledSwitchMBB =
10439       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10440 
10441   // If there is only the default destination, jump there directly.
10442   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10443   if (Clusters.empty()) {
10444     assert(PeeledSwitchMBB == SwitchMBB);
10445     SwitchMBB->addSuccessor(DefaultMBB);
10446     if (DefaultMBB != NextBlock(SwitchMBB)) {
10447       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10448                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10449     }
10450     return;
10451   }
10452 
10453   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10454   SL->findBitTestClusters(Clusters, &SI);
10455 
10456   LLVM_DEBUG({
10457     dbgs() << "Case clusters: ";
10458     for (const CaseCluster &C : Clusters) {
10459       if (C.Kind == CC_JumpTable)
10460         dbgs() << "JT:";
10461       if (C.Kind == CC_BitTests)
10462         dbgs() << "BT:";
10463 
10464       C.Low->getValue().print(dbgs(), true);
10465       if (C.Low != C.High) {
10466         dbgs() << '-';
10467         C.High->getValue().print(dbgs(), true);
10468       }
10469       dbgs() << ' ';
10470     }
10471     dbgs() << '\n';
10472   });
10473 
10474   assert(!Clusters.empty());
10475   SwitchWorkList WorkList;
10476   CaseClusterIt First = Clusters.begin();
10477   CaseClusterIt Last = Clusters.end() - 1;
10478   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10479   // Scale the branchprobability for DefaultMBB if the peel occurs and
10480   // DefaultMBB is not replaced.
10481   if (PeeledCaseProb != BranchProbability::getZero() &&
10482       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10483     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10484   WorkList.push_back(
10485       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10486 
10487   while (!WorkList.empty()) {
10488     SwitchWorkListItem W = WorkList.back();
10489     WorkList.pop_back();
10490     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10491 
10492     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10493         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10494       // For optimized builds, lower large range as a balanced binary tree.
10495       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10496       continue;
10497     }
10498 
10499     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10500   }
10501 }
10502 
10503 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10504   SDValue N = getValue(I.getOperand(0));
10505   setValue(&I, N);
10506 }
10507