xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision f1c28929125400a1680868f7c6eea720de256779)
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/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include "llvm/Transforms/Utils/Local.h"
113 #include <algorithm>
114 #include <cassert>
115 #include <cstddef>
116 #include <cstdint>
117 #include <cstring>
118 #include <iterator>
119 #include <limits>
120 #include <numeric>
121 #include <tuple>
122 #include <utility>
123 #include <vector>
124 
125 using namespace llvm;
126 using namespace PatternMatch;
127 using namespace SwitchCG;
128 
129 #define DEBUG_TYPE "isel"
130 
131 /// LimitFloatPrecision - Generate low-precision inline sequences for
132 /// some float libcalls (6, 8 or 12 bits).
133 static unsigned LimitFloatPrecision;
134 
135 static cl::opt<unsigned, true>
136     LimitFPPrecision("limit-float-precision",
137                      cl::desc("Generate low-precision inline sequences "
138                               "for some float libcalls"),
139                      cl::location(LimitFloatPrecision), cl::Hidden,
140                      cl::init(0));
141 
142 static cl::opt<unsigned> SwitchPeelThreshold(
143     "switch-peel-threshold", cl::Hidden, cl::init(66),
144     cl::desc("Set the case probability threshold for peeling the case from a "
145              "switch statement. A value greater than 100 will void this "
146              "optimization"));
147 
148 // Limit the width of DAG chains. This is important in general to prevent
149 // DAG-based analysis from blowing up. For example, alias analysis and
150 // load clustering may not complete in reasonable time. It is difficult to
151 // recognize and avoid this situation within each individual analysis, and
152 // future analyses are likely to have the same behavior. Limiting DAG width is
153 // the safe approach and will be especially important with global DAGs.
154 //
155 // MaxParallelChains default is arbitrarily high to avoid affecting
156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
157 // sequence over this should have been converted to llvm.memcpy by the
158 // frontend. It is easy to induce this behavior with .ll code such as:
159 // %buffer = alloca [4096 x i8]
160 // %data = load [4096 x i8]* %argPtr
161 // store [4096 x i8] %data, [4096 x i8]* %buffer
162 static const unsigned MaxParallelChains = 64;
163 
164 // Return the calling convention if the Value passed requires ABI mangling as it
165 // is a parameter to a function or a return value from a function which is not
166 // an intrinsic.
167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
168   if (auto *R = dyn_cast<ReturnInst>(V))
169     return R->getParent()->getParent()->getCallingConv();
170 
171   if (auto *CI = dyn_cast<CallInst>(V)) {
172     const bool IsInlineAsm = CI->isInlineAsm();
173     const bool IsIndirectFunctionCall =
174         !IsInlineAsm && !CI->getCalledFunction();
175 
176     // It is possible that the call instruction is an inline asm statement or an
177     // indirect function call in which case the return value of
178     // getCalledFunction() would be nullptr.
179     const bool IsInstrinsicCall =
180         !IsInlineAsm && !IsIndirectFunctionCall &&
181         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
182 
183     if (!IsInlineAsm && !IsInstrinsicCall)
184       return CI->getCallingConv();
185   }
186 
187   return None;
188 }
189 
190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
191                                       const SDValue *Parts, unsigned NumParts,
192                                       MVT PartVT, EVT ValueVT, const Value *V,
193                                       Optional<CallingConv::ID> CC);
194 
195 /// getCopyFromParts - Create a value that contains the specified legal parts
196 /// combined into the value they represent.  If the parts combine to a type
197 /// larger than ValueVT then AssertOp can be used to specify whether the extra
198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
199 /// (ISD::AssertSext).
200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
201                                 const SDValue *Parts, unsigned NumParts,
202                                 MVT PartVT, EVT ValueVT, const Value *V,
203                                 Optional<CallingConv::ID> CC = None,
204                                 Optional<ISD::NodeType> AssertOp = None) {
205   if (ValueVT.isVector())
206     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
207                                   CC);
208 
209   assert(NumParts > 0 && "No parts to assemble!");
210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
211   SDValue Val = Parts[0];
212 
213   if (NumParts > 1) {
214     // Assemble the value from multiple parts.
215     if (ValueVT.isInteger()) {
216       unsigned PartBits = PartVT.getSizeInBits();
217       unsigned ValueBits = ValueVT.getSizeInBits();
218 
219       // Assemble the power of 2 part.
220       unsigned RoundParts =
221           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
222       unsigned RoundBits = PartBits * RoundParts;
223       EVT RoundVT = RoundBits == ValueBits ?
224         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
225       SDValue Lo, Hi;
226 
227       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
228 
229       if (RoundParts > 2) {
230         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
231                               PartVT, HalfVT, V);
232         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
233                               RoundParts / 2, PartVT, HalfVT, V);
234       } else {
235         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
236         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
237       }
238 
239       if (DAG.getDataLayout().isBigEndian())
240         std::swap(Lo, Hi);
241 
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
243 
244       if (RoundParts < NumParts) {
245         // Assemble the trailing non-power-of-2 part.
246         unsigned OddParts = NumParts - RoundParts;
247         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
248         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
249                               OddVT, V, CC);
250 
251         // Combine the round and odd parts.
252         Lo = Val;
253         if (DAG.getDataLayout().isBigEndian())
254           std::swap(Lo, Hi);
255         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
256         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
257         Hi =
258             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
259                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
260                                         TLI.getPointerTy(DAG.getDataLayout())));
261         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
262         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
263       }
264     } else if (PartVT.isFloatingPoint()) {
265       // FP split into multiple FP parts (for ppcf128)
266       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
267              "Unexpected split");
268       SDValue Lo, Hi;
269       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
270       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
271       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
272         std::swap(Lo, Hi);
273       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
274     } else {
275       // FP split into integer parts (soft fp)
276       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
277              !PartVT.isVector() && "Unexpected split");
278       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
279       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
280     }
281   }
282 
283   // There is now one part, held in Val.  Correct it to match ValueVT.
284   // PartEVT is the type of the register class that holds the value.
285   // ValueVT is the type of the inline asm operation.
286   EVT PartEVT = Val.getValueType();
287 
288   if (PartEVT == ValueVT)
289     return Val;
290 
291   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
292       ValueVT.bitsLT(PartEVT)) {
293     // For an FP value in an integer part, we need to truncate to the right
294     // width first.
295     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
296     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
297   }
298 
299   // Handle types that have the same size.
300   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
301     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
302 
303   // Handle types with different sizes.
304   if (PartEVT.isInteger() && ValueVT.isInteger()) {
305     if (ValueVT.bitsLT(PartEVT)) {
306       // For a truncate, see if we have any information to
307       // indicate whether the truncated bits will always be
308       // zero or sign-extension.
309       if (AssertOp.hasValue())
310         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
311                           DAG.getValueType(ValueVT));
312       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
313     }
314     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
315   }
316 
317   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
318     // FP_ROUND's are always exact here.
319     if (ValueVT.bitsLT(Val.getValueType()))
320       return DAG.getNode(
321           ISD::FP_ROUND, DL, ValueVT, Val,
322           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
323 
324     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
325   }
326 
327   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
328   // then truncating.
329   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
330       ValueVT.bitsLT(PartEVT)) {
331     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
332     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
333   }
334 
335   report_fatal_error("Unknown mismatch in getCopyFromParts!");
336 }
337 
338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
339                                               const Twine &ErrMsg) {
340   const Instruction *I = dyn_cast_or_null<Instruction>(V);
341   if (!V)
342     return Ctx.emitError(ErrMsg);
343 
344   const char *AsmError = ", possible invalid constraint for vector type";
345   if (const CallInst *CI = dyn_cast<CallInst>(I))
346     if (isa<InlineAsm>(CI->getCalledValue()))
347       return Ctx.emitError(I, ErrMsg + AsmError);
348 
349   return Ctx.emitError(I, ErrMsg);
350 }
351 
352 /// getCopyFromPartsVector - Create a value that contains the specified legal
353 /// parts combined into the value they represent.  If the parts combine to a
354 /// type larger than ValueVT then AssertOp can be used to specify whether the
355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
356 /// ValueVT (ISD::AssertSext).
357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
358                                       const SDValue *Parts, unsigned NumParts,
359                                       MVT PartVT, EVT ValueVT, const Value *V,
360                                       Optional<CallingConv::ID> CallConv) {
361   assert(ValueVT.isVector() && "Not a vector value");
362   assert(NumParts > 0 && "No parts to assemble!");
363   const bool IsABIRegCopy = CallConv.hasValue();
364 
365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
366   SDValue Val = Parts[0];
367 
368   // Handle a multi-element vector.
369   if (NumParts > 1) {
370     EVT IntermediateVT;
371     MVT RegisterVT;
372     unsigned NumIntermediates;
373     unsigned NumRegs;
374 
375     if (IsABIRegCopy) {
376       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
377           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
378           NumIntermediates, RegisterVT);
379     } else {
380       NumRegs =
381           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
382                                      NumIntermediates, RegisterVT);
383     }
384 
385     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
386     NumParts = NumRegs; // Silence a compiler warning.
387     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
388     assert(RegisterVT.getSizeInBits() ==
389            Parts[0].getSimpleValueType().getSizeInBits() &&
390            "Part type sizes don't match!");
391 
392     // Assemble the parts into intermediate operands.
393     SmallVector<SDValue, 8> Ops(NumIntermediates);
394     if (NumIntermediates == NumParts) {
395       // If the register was not expanded, truncate or copy the value,
396       // as appropriate.
397       for (unsigned i = 0; i != NumParts; ++i)
398         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
399                                   PartVT, IntermediateVT, V);
400     } else if (NumParts > 0) {
401       // If the intermediate type was expanded, build the intermediate
402       // operands from the parts.
403       assert(NumParts % NumIntermediates == 0 &&
404              "Must expand into a divisible number of parts!");
405       unsigned Factor = NumParts / NumIntermediates;
406       for (unsigned i = 0; i != NumIntermediates; ++i)
407         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
408                                   PartVT, IntermediateVT, V);
409     }
410 
411     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
412     // intermediate operands.
413     EVT BuiltVectorTy =
414         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
415                          (IntermediateVT.isVector()
416                               ? IntermediateVT.getVectorNumElements() * NumParts
417                               : NumIntermediates));
418     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
419                                                 : ISD::BUILD_VECTOR,
420                       DL, BuiltVectorTy, Ops);
421   }
422 
423   // There is now one part, held in Val.  Correct it to match ValueVT.
424   EVT PartEVT = Val.getValueType();
425 
426   if (PartEVT == ValueVT)
427     return Val;
428 
429   if (PartEVT.isVector()) {
430     // If the element type of the source/dest vectors are the same, but the
431     // parts vector has more elements than the value vector, then we have a
432     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
433     // elements we want.
434     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
435       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
436              "Cannot narrow, it would be a lossy transformation");
437       return DAG.getNode(
438           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
439           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
440     }
441 
442     // Vector/Vector bitcast.
443     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
444       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445 
446     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
447       "Cannot handle this kind of promotion");
448     // Promoted vector extract
449     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
450 
451   }
452 
453   // Trivial bitcast if the types are the same size and the destination
454   // vector type is legal.
455   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
456       TLI.isTypeLegal(ValueVT))
457     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458 
459   if (ValueVT.getVectorNumElements() != 1) {
460      // Certain ABIs require that vectors are passed as integers. For vectors
461      // are the same size, this is an obvious bitcast.
462      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
463        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
465        // Bitcast Val back the original type and extract the corresponding
466        // vector we want.
467        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
468        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
469                                            ValueVT.getVectorElementType(), Elts);
470        Val = DAG.getBitcast(WiderVecType, Val);
471        return DAG.getNode(
472            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
473            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
474      }
475 
476      diagnosePossiblyInvalidConstraint(
477          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
478      return DAG.getUNDEF(ValueVT);
479   }
480 
481   // Handle cases such as i8 -> <1 x i1>
482   EVT ValueSVT = ValueVT.getVectorElementType();
483   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
484     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
485                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
486 
487   return DAG.getBuildVector(ValueVT, DL, Val);
488 }
489 
490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
491                                  SDValue Val, SDValue *Parts, unsigned NumParts,
492                                  MVT PartVT, const Value *V,
493                                  Optional<CallingConv::ID> CallConv);
494 
495 /// getCopyToParts - Create a series of nodes that contain the specified value
496 /// split into legal parts.  If the parts contain more bits than Val, then, for
497 /// integers, ExtendKind can be used to specify how to generate the extra bits.
498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
499                            SDValue *Parts, unsigned NumParts, MVT PartVT,
500                            const Value *V,
501                            Optional<CallingConv::ID> CallConv = None,
502                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
503   EVT ValueVT = Val.getValueType();
504 
505   // Handle the vector case separately.
506   if (ValueVT.isVector())
507     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
508                                 CallConv);
509 
510   unsigned PartBits = PartVT.getSizeInBits();
511   unsigned OrigNumParts = NumParts;
512   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
513          "Copying to an illegal type!");
514 
515   if (NumParts == 0)
516     return;
517 
518   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
519   EVT PartEVT = PartVT;
520   if (PartEVT == ValueVT) {
521     assert(NumParts == 1 && "No-op copy with multiple parts!");
522     Parts[0] = Val;
523     return;
524   }
525 
526   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
527     // If the parts cover more bits than the value has, promote the value.
528     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
529       assert(NumParts == 1 && "Do not know what to promote to!");
530       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
531     } else {
532       if (ValueVT.isFloatingPoint()) {
533         // FP values need to be bitcast, then extended if they are being put
534         // into a larger container.
535         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
536         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
537       }
538       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
539              ValueVT.isInteger() &&
540              "Unknown mismatch!");
541       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
542       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
543       if (PartVT == MVT::x86mmx)
544         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
545     }
546   } else if (PartBits == ValueVT.getSizeInBits()) {
547     // Different types of the same size.
548     assert(NumParts == 1 && PartEVT != ValueVT);
549     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
550   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
551     // If the parts cover less bits than value has, truncate the value.
552     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
553            ValueVT.isInteger() &&
554            "Unknown mismatch!");
555     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
556     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
557     if (PartVT == MVT::x86mmx)
558       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559   }
560 
561   // The value may have changed - recompute ValueVT.
562   ValueVT = Val.getValueType();
563   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
564          "Failed to tile the value with PartVT!");
565 
566   if (NumParts == 1) {
567     if (PartEVT != ValueVT) {
568       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
569                                         "scalar-to-vector conversion failed");
570       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571     }
572 
573     Parts[0] = Val;
574     return;
575   }
576 
577   // Expand the value into multiple parts.
578   if (NumParts & (NumParts - 1)) {
579     // The number of parts is not a power of 2.  Split off and copy the tail.
580     assert(PartVT.isInteger() && ValueVT.isInteger() &&
581            "Do not know what to expand to!");
582     unsigned RoundParts = 1 << Log2_32(NumParts);
583     unsigned RoundBits = RoundParts * PartBits;
584     unsigned OddParts = NumParts - RoundParts;
585     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
586       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
587 
588     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
589                    CallConv);
590 
591     if (DAG.getDataLayout().isBigEndian())
592       // The odd parts were reversed by getCopyToParts - unreverse them.
593       std::reverse(Parts + RoundParts, Parts + NumParts);
594 
595     NumParts = RoundParts;
596     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
597     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
598   }
599 
600   // The number of parts is a power of 2.  Repeatedly bisect the value using
601   // EXTRACT_ELEMENT.
602   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
603                          EVT::getIntegerVT(*DAG.getContext(),
604                                            ValueVT.getSizeInBits()),
605                          Val);
606 
607   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
608     for (unsigned i = 0; i < NumParts; i += StepSize) {
609       unsigned ThisBits = StepSize * PartBits / 2;
610       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
611       SDValue &Part0 = Parts[i];
612       SDValue &Part1 = Parts[i+StepSize/2];
613 
614       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
615                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
616       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
618 
619       if (ThisBits == PartBits && ThisVT != PartVT) {
620         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
621         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
622       }
623     }
624   }
625 
626   if (DAG.getDataLayout().isBigEndian())
627     std::reverse(Parts, Parts + OrigNumParts);
628 }
629 
630 static SDValue widenVectorToPartType(SelectionDAG &DAG,
631                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
632   if (!PartVT.isVector())
633     return SDValue();
634 
635   EVT ValueVT = Val.getValueType();
636   unsigned PartNumElts = PartVT.getVectorNumElements();
637   unsigned ValueNumElts = ValueVT.getVectorNumElements();
638   if (PartNumElts > ValueNumElts &&
639       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
640     EVT ElementVT = PartVT.getVectorElementType();
641     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
642     // undef elements.
643     SmallVector<SDValue, 16> Ops;
644     DAG.ExtractVectorElements(Val, Ops);
645     SDValue EltUndef = DAG.getUNDEF(ElementVT);
646     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
647       Ops.push_back(EltUndef);
648 
649     // FIXME: Use CONCAT for 2x -> 4x.
650     return DAG.getBuildVector(PartVT, DL, Ops);
651   }
652 
653   return SDValue();
654 }
655 
656 /// getCopyToPartsVector - Create a series of nodes that contain the specified
657 /// value split into legal parts.
658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
659                                  SDValue Val, SDValue *Parts, unsigned NumParts,
660                                  MVT PartVT, const Value *V,
661                                  Optional<CallingConv::ID> CallConv) {
662   EVT ValueVT = Val.getValueType();
663   assert(ValueVT.isVector() && "Not a vector");
664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
665   const bool IsABIRegCopy = CallConv.hasValue();
666 
667   if (NumParts == 1) {
668     EVT PartEVT = PartVT;
669     if (PartEVT == ValueVT) {
670       // Nothing to do.
671     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
672       // Bitconvert vector->vector case.
673       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
674     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
675       Val = Widened;
676     } else if (PartVT.isVector() &&
677                PartEVT.getVectorElementType().bitsGE(
678                  ValueVT.getVectorElementType()) &&
679                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
680 
681       // Promoted vector extract
682       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683     } else {
684       if (ValueVT.getVectorNumElements() == 1) {
685         Val = DAG.getNode(
686             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
687             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
688       } else {
689         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
690                "lossy conversion of vector to scalar type");
691         EVT IntermediateType =
692             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
693         Val = DAG.getBitcast(IntermediateType, Val);
694         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
695       }
696     }
697 
698     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
699     Parts[0] = Val;
700     return;
701   }
702 
703   // Handle a multi-element vector.
704   EVT IntermediateVT;
705   MVT RegisterVT;
706   unsigned NumIntermediates;
707   unsigned NumRegs;
708   if (IsABIRegCopy) {
709     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
710         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
711         NumIntermediates, RegisterVT);
712   } else {
713     NumRegs =
714         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
715                                    NumIntermediates, RegisterVT);
716   }
717 
718   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719   NumParts = NumRegs; // Silence a compiler warning.
720   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
721 
722   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
723     IntermediateVT.getVectorNumElements() : 1;
724 
725   // Convert the vector to the appropiate type if necessary.
726   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
727 
728   EVT BuiltVectorTy = EVT::getVectorVT(
729       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
730   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
731   if (ValueVT != BuiltVectorTy) {
732     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
733       Val = Widened;
734 
735     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
736   }
737 
738   // Split the vector into intermediate operands.
739   SmallVector<SDValue, 8> Ops(NumIntermediates);
740   for (unsigned i = 0; i != NumIntermediates; ++i) {
741     if (IntermediateVT.isVector()) {
742       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
743                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
744     } else {
745       Ops[i] = DAG.getNode(
746           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
747           DAG.getConstant(i, DL, IdxVT));
748     }
749   }
750 
751   // Split the intermediate operands into legal parts.
752   if (NumParts == NumIntermediates) {
753     // If the register was not expanded, promote or copy the value,
754     // as appropriate.
755     for (unsigned i = 0; i != NumParts; ++i)
756       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
757   } else if (NumParts > 0) {
758     // If the intermediate type was expanded, split each the value into
759     // legal parts.
760     assert(NumIntermediates != 0 && "division by zero");
761     assert(NumParts % NumIntermediates == 0 &&
762            "Must expand into a divisible number of parts!");
763     unsigned Factor = NumParts / NumIntermediates;
764     for (unsigned i = 0; i != NumIntermediates; ++i)
765       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
766                      CallConv);
767   }
768 }
769 
770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
771                            EVT valuevt, Optional<CallingConv::ID> CC)
772     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
773       RegCount(1, regs.size()), CallConv(CC) {}
774 
775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
776                            const DataLayout &DL, unsigned Reg, Type *Ty,
777                            Optional<CallingConv::ID> CC) {
778   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
779 
780   CallConv = CC;
781 
782   for (EVT ValueVT : ValueVTs) {
783     unsigned NumRegs =
784         isABIMangled()
785             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
786             : TLI.getNumRegisters(Context, ValueVT);
787     MVT RegisterVT =
788         isABIMangled()
789             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getRegisterType(Context, ValueVT);
791     for (unsigned i = 0; i != NumRegs; ++i)
792       Regs.push_back(Reg + i);
793     RegVTs.push_back(RegisterVT);
794     RegCount.push_back(NumRegs);
795     Reg += NumRegs;
796   }
797 }
798 
799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
800                                       FunctionLoweringInfo &FuncInfo,
801                                       const SDLoc &dl, SDValue &Chain,
802                                       SDValue *Flag, const Value *V) const {
803   // A Value with type {} or [0 x %t] needs no registers.
804   if (ValueVTs.empty())
805     return SDValue();
806 
807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
808 
809   // Assemble the legal parts into the final values.
810   SmallVector<SDValue, 4> Values(ValueVTs.size());
811   SmallVector<SDValue, 8> Parts;
812   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
813     // Copy the legal parts from the registers.
814     EVT ValueVT = ValueVTs[Value];
815     unsigned NumRegs = RegCount[Value];
816     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
817                                           *DAG.getContext(),
818                                           CallConv.getValue(), RegVTs[Value])
819                                     : RegVTs[Value];
820 
821     Parts.resize(NumRegs);
822     for (unsigned i = 0; i != NumRegs; ++i) {
823       SDValue P;
824       if (!Flag) {
825         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
826       } else {
827         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
828         *Flag = P.getValue(2);
829       }
830 
831       Chain = P.getValue(1);
832       Parts[i] = P;
833 
834       // If the source register was virtual and if we know something about it,
835       // add an assert node.
836       if (!Register::isVirtualRegister(Regs[Part + i]) ||
837           !RegisterVT.isInteger())
838         continue;
839 
840       const FunctionLoweringInfo::LiveOutInfo *LOI =
841         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
842       if (!LOI)
843         continue;
844 
845       unsigned RegSize = RegisterVT.getScalarSizeInBits();
846       unsigned NumSignBits = LOI->NumSignBits;
847       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
848 
849       if (NumZeroBits == RegSize) {
850         // The current value is a zero.
851         // Explicitly express that as it would be easier for
852         // optimizations to kick in.
853         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
854         continue;
855       }
856 
857       // FIXME: We capture more information than the dag can represent.  For
858       // now, just use the tightest assertzext/assertsext possible.
859       bool isSExt;
860       EVT FromVT(MVT::Other);
861       if (NumZeroBits) {
862         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
863         isSExt = false;
864       } else if (NumSignBits > 1) {
865         FromVT =
866             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
867         isSExt = true;
868       } else {
869         continue;
870       }
871       // Add an assertion node.
872       assert(FromVT != MVT::Other);
873       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
874                              RegisterVT, P, DAG.getValueType(FromVT));
875     }
876 
877     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
878                                      RegisterVT, ValueVT, V, CallConv);
879     Part += NumRegs;
880     Parts.clear();
881   }
882 
883   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
884 }
885 
886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
887                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
888                                  const Value *V,
889                                  ISD::NodeType PreferredExtendType) const {
890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
891   ISD::NodeType ExtendKind = PreferredExtendType;
892 
893   // Get the list of the values's legal parts.
894   unsigned NumRegs = Regs.size();
895   SmallVector<SDValue, 8> Parts(NumRegs);
896   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
897     unsigned NumParts = RegCount[Value];
898 
899     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
900                                           *DAG.getContext(),
901                                           CallConv.getValue(), RegVTs[Value])
902                                     : RegVTs[Value];
903 
904     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
905       ExtendKind = ISD::ZERO_EXTEND;
906 
907     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
908                    NumParts, RegisterVT, V, CallConv, ExtendKind);
909     Part += NumParts;
910   }
911 
912   // Copy the parts into the registers.
913   SmallVector<SDValue, 8> Chains(NumRegs);
914   for (unsigned i = 0; i != NumRegs; ++i) {
915     SDValue Part;
916     if (!Flag) {
917       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
918     } else {
919       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
920       *Flag = Part.getValue(1);
921     }
922 
923     Chains[i] = Part.getValue(0);
924   }
925 
926   if (NumRegs == 1 || Flag)
927     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
928     // flagged to it. That is the CopyToReg nodes and the user are considered
929     // a single scheduling unit. If we create a TokenFactor and return it as
930     // chain, then the TokenFactor is both a predecessor (operand) of the
931     // user as well as a successor (the TF operands are flagged to the user).
932     // c1, f1 = CopyToReg
933     // c2, f2 = CopyToReg
934     // c3     = TokenFactor c1, c2
935     // ...
936     //        = op c3, ..., f2
937     Chain = Chains[NumRegs-1];
938   else
939     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
940 }
941 
942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
943                                         unsigned MatchingIdx, const SDLoc &dl,
944                                         SelectionDAG &DAG,
945                                         std::vector<SDValue> &Ops) const {
946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
947 
948   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
949   if (HasMatching)
950     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
951   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
952     // Put the register class of the virtual registers in the flag word.  That
953     // way, later passes can recompute register class constraints for inline
954     // assembly as well as normal instructions.
955     // Don't do this for tied operands that can use the regclass information
956     // from the def.
957     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
958     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
959     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
960   }
961 
962   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
963   Ops.push_back(Res);
964 
965   if (Code == InlineAsm::Kind_Clobber) {
966     // Clobbers should always have a 1:1 mapping with registers, and may
967     // reference registers that have illegal (e.g. vector) types. Hence, we
968     // shouldn't try to apply any sort of splitting logic to them.
969     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
970            "No 1:1 mapping from clobbers to regs?");
971     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
972     (void)SP;
973     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
974       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
975       assert(
976           (Regs[I] != SP ||
977            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
978           "If we clobbered the stack pointer, MFI should know about it.");
979     }
980     return;
981   }
982 
983   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
984     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
985     MVT RegisterVT = RegVTs[Value];
986     for (unsigned i = 0; i != NumRegs; ++i) {
987       assert(Reg < Regs.size() && "Mismatch in # registers expected");
988       unsigned TheReg = Regs[Reg++];
989       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
990     }
991   }
992 }
993 
994 SmallVector<std::pair<unsigned, unsigned>, 4>
995 RegsForValue::getRegsAndSizes() const {
996   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
997   unsigned I = 0;
998   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
999     unsigned RegCount = std::get<0>(CountAndVT);
1000     MVT RegisterVT = std::get<1>(CountAndVT);
1001     unsigned RegisterSize = RegisterVT.getSizeInBits();
1002     for (unsigned E = I + RegCount; I != E; ++I)
1003       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1004   }
1005   return OutVec;
1006 }
1007 
1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1009                                const TargetLibraryInfo *li) {
1010   AA = aa;
1011   GFI = gfi;
1012   LibInfo = li;
1013   DL = &DAG.getDataLayout();
1014   Context = DAG.getContext();
1015   LPadToCallSiteMap.clear();
1016   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1017 }
1018 
1019 void SelectionDAGBuilder::clear() {
1020   NodeMap.clear();
1021   UnusedArgNodeMap.clear();
1022   PendingLoads.clear();
1023   PendingExports.clear();
1024   CurInst = nullptr;
1025   HasTailCall = false;
1026   SDNodeOrder = LowestSDNodeOrder;
1027   StatepointLowering.clear();
1028 }
1029 
1030 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1031   DanglingDebugInfoMap.clear();
1032 }
1033 
1034 SDValue SelectionDAGBuilder::getRoot() {
1035   if (PendingLoads.empty())
1036     return DAG.getRoot();
1037 
1038   if (PendingLoads.size() == 1) {
1039     SDValue Root = PendingLoads[0];
1040     DAG.setRoot(Root);
1041     PendingLoads.clear();
1042     return Root;
1043   }
1044 
1045   // Otherwise, we have to make a token factor node.
1046   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1047   PendingLoads.clear();
1048   DAG.setRoot(Root);
1049   return Root;
1050 }
1051 
1052 SDValue SelectionDAGBuilder::getControlRoot() {
1053   SDValue Root = DAG.getRoot();
1054 
1055   if (PendingExports.empty())
1056     return Root;
1057 
1058   // Turn all of the CopyToReg chains into one factored node.
1059   if (Root.getOpcode() != ISD::EntryToken) {
1060     unsigned i = 0, e = PendingExports.size();
1061     for (; i != e; ++i) {
1062       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1063       if (PendingExports[i].getNode()->getOperand(0) == Root)
1064         break;  // Don't add the root if we already indirectly depend on it.
1065     }
1066 
1067     if (i == e)
1068       PendingExports.push_back(Root);
1069   }
1070 
1071   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1072                      PendingExports);
1073   PendingExports.clear();
1074   DAG.setRoot(Root);
1075   return Root;
1076 }
1077 
1078 void SelectionDAGBuilder::visit(const Instruction &I) {
1079   // Set up outgoing PHI node register values before emitting the terminator.
1080   if (I.isTerminator()) {
1081     HandlePHINodesInSuccessorBlocks(I.getParent());
1082   }
1083 
1084   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1085   if (!isa<DbgInfoIntrinsic>(I))
1086     ++SDNodeOrder;
1087 
1088   CurInst = &I;
1089 
1090   visit(I.getOpcode(), I);
1091 
1092   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1093     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1094     // maps to this instruction.
1095     // TODO: We could handle all flags (nsw, etc) here.
1096     // TODO: If an IR instruction maps to >1 node, only the final node will have
1097     //       flags set.
1098     if (SDNode *Node = getNodeForIRValue(&I)) {
1099       SDNodeFlags IncomingFlags;
1100       IncomingFlags.copyFMF(*FPMO);
1101       if (!Node->getFlags().isDefined())
1102         Node->setFlags(IncomingFlags);
1103       else
1104         Node->intersectFlagsWith(IncomingFlags);
1105     }
1106   }
1107 
1108   if (!I.isTerminator() && !HasTailCall &&
1109       !isStatepoint(&I)) // statepoints handle their exports internally
1110     CopyToExportRegsIfNeeded(&I);
1111 
1112   CurInst = nullptr;
1113 }
1114 
1115 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1116   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1117 }
1118 
1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1120   // Note: this doesn't use InstVisitor, because it has to work with
1121   // ConstantExpr's in addition to instructions.
1122   switch (Opcode) {
1123   default: llvm_unreachable("Unknown instruction type encountered!");
1124     // Build the switch statement using the Instruction.def file.
1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1126     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1127 #include "llvm/IR/Instruction.def"
1128   }
1129 }
1130 
1131 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1132                                                 const DIExpression *Expr) {
1133   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1134     const DbgValueInst *DI = DDI.getDI();
1135     DIVariable *DanglingVariable = DI->getVariable();
1136     DIExpression *DanglingExpr = DI->getExpression();
1137     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1138       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1139       return true;
1140     }
1141     return false;
1142   };
1143 
1144   for (auto &DDIMI : DanglingDebugInfoMap) {
1145     DanglingDebugInfoVector &DDIV = DDIMI.second;
1146 
1147     // If debug info is to be dropped, run it through final checks to see
1148     // whether it can be salvaged.
1149     for (auto &DDI : DDIV)
1150       if (isMatchingDbgValue(DDI))
1151         salvageUnresolvedDbgValue(DDI);
1152 
1153     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1154   }
1155 }
1156 
1157 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1158 // generate the debug data structures now that we've seen its definition.
1159 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1160                                                    SDValue Val) {
1161   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1162   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1163     return;
1164 
1165   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1166   for (auto &DDI : DDIV) {
1167     const DbgValueInst *DI = DDI.getDI();
1168     assert(DI && "Ill-formed DanglingDebugInfo");
1169     DebugLoc dl = DDI.getdl();
1170     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1171     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1172     DILocalVariable *Variable = DI->getVariable();
1173     DIExpression *Expr = DI->getExpression();
1174     assert(Variable->isValidLocationForIntrinsic(dl) &&
1175            "Expected inlined-at fields to agree");
1176     SDDbgValue *SDV;
1177     if (Val.getNode()) {
1178       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1179       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1180       // we couldn't resolve it directly when examining the DbgValue intrinsic
1181       // in the first place we should not be more successful here). Unless we
1182       // have some test case that prove this to be correct we should avoid
1183       // calling EmitFuncArgumentDbgValue here.
1184       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1185         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1186                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1187         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1188         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1189         // inserted after the definition of Val when emitting the instructions
1190         // after ISel. An alternative could be to teach
1191         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1192         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1193                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1194                    << ValSDNodeOrder << "\n");
1195         SDV = getDbgValue(Val, Variable, Expr, dl,
1196                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1197         DAG.AddDbgValue(SDV, Val.getNode(), false);
1198       } else
1199         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1200                           << "in EmitFuncArgumentDbgValue\n");
1201     } else {
1202       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1203       auto Undef =
1204           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1205       auto SDV =
1206           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1207       DAG.AddDbgValue(SDV, nullptr, false);
1208     }
1209   }
1210   DDIV.clear();
1211 }
1212 
1213 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1214   Value *V = DDI.getDI()->getValue();
1215   DILocalVariable *Var = DDI.getDI()->getVariable();
1216   DIExpression *Expr = DDI.getDI()->getExpression();
1217   DebugLoc DL = DDI.getdl();
1218   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1219   unsigned SDOrder = DDI.getSDNodeOrder();
1220 
1221   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1222   // that DW_OP_stack_value is desired.
1223   assert(isa<DbgValueInst>(DDI.getDI()));
1224   bool StackValue = true;
1225 
1226   // Can this Value can be encoded without any further work?
1227   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1228     return;
1229 
1230   // Attempt to salvage back through as many instructions as possible. Bail if
1231   // a non-instruction is seen, such as a constant expression or global
1232   // variable. FIXME: Further work could recover those too.
1233   while (isa<Instruction>(V)) {
1234     Instruction &VAsInst = *cast<Instruction>(V);
1235     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1236 
1237     // If we cannot salvage any further, and haven't yet found a suitable debug
1238     // expression, bail out.
1239     if (!NewExpr)
1240       break;
1241 
1242     // New value and expr now represent this debuginfo.
1243     V = VAsInst.getOperand(0);
1244     Expr = NewExpr;
1245 
1246     // Some kind of simplification occurred: check whether the operand of the
1247     // salvaged debug expression can be encoded in this DAG.
1248     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1249       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1250                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1251       return;
1252     }
1253   }
1254 
1255   // This was the final opportunity to salvage this debug information, and it
1256   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1257   // any earlier variable location.
1258   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1259   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1260   DAG.AddDbgValue(SDV, nullptr, false);
1261 
1262   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1263                     << "\n");
1264   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1265                     << "\n");
1266 }
1267 
1268 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1269                                            DIExpression *Expr, DebugLoc dl,
1270                                            DebugLoc InstDL, unsigned Order) {
1271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1272   SDDbgValue *SDV;
1273   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1274       isa<ConstantPointerNull>(V)) {
1275     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1276     DAG.AddDbgValue(SDV, nullptr, false);
1277     return true;
1278   }
1279 
1280   // If the Value is a frame index, we can create a FrameIndex debug value
1281   // without relying on the DAG at all.
1282   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1283     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1284     if (SI != FuncInfo.StaticAllocaMap.end()) {
1285       auto SDV =
1286           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1287                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1288       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1289       // is still available even if the SDNode gets optimized out.
1290       DAG.AddDbgValue(SDV, nullptr, false);
1291       return true;
1292     }
1293   }
1294 
1295   // Do not use getValue() in here; we don't want to generate code at
1296   // this point if it hasn't been done yet.
1297   SDValue N = NodeMap[V];
1298   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1299     N = UnusedArgNodeMap[V];
1300   if (N.getNode()) {
1301     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1302       return true;
1303     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1304     DAG.AddDbgValue(SDV, N.getNode(), false);
1305     return true;
1306   }
1307 
1308   // Special rules apply for the first dbg.values of parameter variables in a
1309   // function. Identify them by the fact they reference Argument Values, that
1310   // they're parameters, and they are parameters of the current function. We
1311   // need to let them dangle until they get an SDNode.
1312   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1313                        !InstDL.getInlinedAt();
1314   if (!IsParamOfFunc) {
1315     // The value is not used in this block yet (or it would have an SDNode).
1316     // We still want the value to appear for the user if possible -- if it has
1317     // an associated VReg, we can refer to that instead.
1318     auto VMI = FuncInfo.ValueMap.find(V);
1319     if (VMI != FuncInfo.ValueMap.end()) {
1320       unsigned Reg = VMI->second;
1321       // If this is a PHI node, it may be split up into several MI PHI nodes
1322       // (in FunctionLoweringInfo::set).
1323       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1324                        V->getType(), None);
1325       if (RFV.occupiesMultipleRegs()) {
1326         unsigned Offset = 0;
1327         unsigned BitsToDescribe = 0;
1328         if (auto VarSize = Var->getSizeInBits())
1329           BitsToDescribe = *VarSize;
1330         if (auto Fragment = Expr->getFragmentInfo())
1331           BitsToDescribe = Fragment->SizeInBits;
1332         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1333           unsigned RegisterSize = RegAndSize.second;
1334           // Bail out if all bits are described already.
1335           if (Offset >= BitsToDescribe)
1336             break;
1337           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1338               ? BitsToDescribe - Offset
1339               : RegisterSize;
1340           auto FragmentExpr = DIExpression::createFragmentExpression(
1341               Expr, Offset, FragmentSize);
1342           if (!FragmentExpr)
1343               continue;
1344           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1345                                     false, dl, SDNodeOrder);
1346           DAG.AddDbgValue(SDV, nullptr, false);
1347           Offset += RegisterSize;
1348         }
1349       } else {
1350         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1351         DAG.AddDbgValue(SDV, nullptr, false);
1352       }
1353       return true;
1354     }
1355   }
1356 
1357   return false;
1358 }
1359 
1360 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1361   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1362   for (auto &Pair : DanglingDebugInfoMap)
1363     for (auto &DDI : Pair.second)
1364       salvageUnresolvedDbgValue(DDI);
1365   clearDanglingDebugInfo();
1366 }
1367 
1368 /// getCopyFromRegs - If there was virtual register allocated for the value V
1369 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1370 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1371   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1372   SDValue Result;
1373 
1374   if (It != FuncInfo.ValueMap.end()) {
1375     unsigned InReg = It->second;
1376 
1377     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1378                      DAG.getDataLayout(), InReg, Ty,
1379                      None); // This is not an ABI copy.
1380     SDValue Chain = DAG.getEntryNode();
1381     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1382                                  V);
1383     resolveDanglingDebugInfo(V, Result);
1384   }
1385 
1386   return Result;
1387 }
1388 
1389 /// getValue - Return an SDValue for the given Value.
1390 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1391   // If we already have an SDValue for this value, use it. It's important
1392   // to do this first, so that we don't create a CopyFromReg if we already
1393   // have a regular SDValue.
1394   SDValue &N = NodeMap[V];
1395   if (N.getNode()) return N;
1396 
1397   // If there's a virtual register allocated and initialized for this
1398   // value, use it.
1399   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1400     return copyFromReg;
1401 
1402   // Otherwise create a new SDValue and remember it.
1403   SDValue Val = getValueImpl(V);
1404   NodeMap[V] = Val;
1405   resolveDanglingDebugInfo(V, Val);
1406   return Val;
1407 }
1408 
1409 // Return true if SDValue exists for the given Value
1410 bool SelectionDAGBuilder::findValue(const Value *V) const {
1411   return (NodeMap.find(V) != NodeMap.end()) ||
1412     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1413 }
1414 
1415 /// getNonRegisterValue - Return an SDValue for the given Value, but
1416 /// don't look in FuncInfo.ValueMap for a virtual register.
1417 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1418   // If we already have an SDValue for this value, use it.
1419   SDValue &N = NodeMap[V];
1420   if (N.getNode()) {
1421     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1422       // Remove the debug location from the node as the node is about to be used
1423       // in a location which may differ from the original debug location.  This
1424       // is relevant to Constant and ConstantFP nodes because they can appear
1425       // as constant expressions inside PHI nodes.
1426       N->setDebugLoc(DebugLoc());
1427     }
1428     return N;
1429   }
1430 
1431   // Otherwise create a new SDValue and remember it.
1432   SDValue Val = getValueImpl(V);
1433   NodeMap[V] = Val;
1434   resolveDanglingDebugInfo(V, Val);
1435   return Val;
1436 }
1437 
1438 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1439 /// Create an SDValue for the given value.
1440 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1442 
1443   if (const Constant *C = dyn_cast<Constant>(V)) {
1444     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1445 
1446     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1447       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1448 
1449     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1450       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1451 
1452     if (isa<ConstantPointerNull>(C)) {
1453       unsigned AS = V->getType()->getPointerAddressSpace();
1454       return DAG.getConstant(0, getCurSDLoc(),
1455                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1456     }
1457 
1458     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1459       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1460 
1461     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1462       return DAG.getUNDEF(VT);
1463 
1464     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1465       visit(CE->getOpcode(), *CE);
1466       SDValue N1 = NodeMap[V];
1467       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1468       return N1;
1469     }
1470 
1471     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1472       SmallVector<SDValue, 4> Constants;
1473       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1474            OI != OE; ++OI) {
1475         SDNode *Val = getValue(*OI).getNode();
1476         // If the operand is an empty aggregate, there are no values.
1477         if (!Val) continue;
1478         // Add each leaf value from the operand to the Constants list
1479         // to form a flattened list of all the values.
1480         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1481           Constants.push_back(SDValue(Val, i));
1482       }
1483 
1484       return DAG.getMergeValues(Constants, getCurSDLoc());
1485     }
1486 
1487     if (const ConstantDataSequential *CDS =
1488           dyn_cast<ConstantDataSequential>(C)) {
1489       SmallVector<SDValue, 4> Ops;
1490       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1491         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1492         // Add each leaf value from the operand to the Constants list
1493         // to form a flattened list of all the values.
1494         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1495           Ops.push_back(SDValue(Val, i));
1496       }
1497 
1498       if (isa<ArrayType>(CDS->getType()))
1499         return DAG.getMergeValues(Ops, getCurSDLoc());
1500       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1501     }
1502 
1503     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1504       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1505              "Unknown struct or array constant!");
1506 
1507       SmallVector<EVT, 4> ValueVTs;
1508       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1509       unsigned NumElts = ValueVTs.size();
1510       if (NumElts == 0)
1511         return SDValue(); // empty struct
1512       SmallVector<SDValue, 4> Constants(NumElts);
1513       for (unsigned i = 0; i != NumElts; ++i) {
1514         EVT EltVT = ValueVTs[i];
1515         if (isa<UndefValue>(C))
1516           Constants[i] = DAG.getUNDEF(EltVT);
1517         else if (EltVT.isFloatingPoint())
1518           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1519         else
1520           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1521       }
1522 
1523       return DAG.getMergeValues(Constants, getCurSDLoc());
1524     }
1525 
1526     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1527       return DAG.getBlockAddress(BA, VT);
1528 
1529     VectorType *VecTy = cast<VectorType>(V->getType());
1530     unsigned NumElements = VecTy->getNumElements();
1531 
1532     // Now that we know the number and type of the elements, get that number of
1533     // elements into the Ops array based on what kind of constant it is.
1534     SmallVector<SDValue, 16> Ops;
1535     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1536       for (unsigned i = 0; i != NumElements; ++i)
1537         Ops.push_back(getValue(CV->getOperand(i)));
1538     } else {
1539       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1540       EVT EltVT =
1541           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1542 
1543       SDValue Op;
1544       if (EltVT.isFloatingPoint())
1545         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1546       else
1547         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1548       Ops.assign(NumElements, Op);
1549     }
1550 
1551     // Create a BUILD_VECTOR node.
1552     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1553   }
1554 
1555   // If this is a static alloca, generate it as the frameindex instead of
1556   // computation.
1557   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1558     DenseMap<const AllocaInst*, int>::iterator SI =
1559       FuncInfo.StaticAllocaMap.find(AI);
1560     if (SI != FuncInfo.StaticAllocaMap.end())
1561       return DAG.getFrameIndex(SI->second,
1562                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1563   }
1564 
1565   // If this is an instruction which fast-isel has deferred, select it now.
1566   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1567     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1568 
1569     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1570                      Inst->getType(), getABIRegCopyCC(V));
1571     SDValue Chain = DAG.getEntryNode();
1572     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1573   }
1574 
1575   llvm_unreachable("Can't get register for value!");
1576 }
1577 
1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1579   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1580   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1581   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1582   bool IsSEH = isAsynchronousEHPersonality(Pers);
1583   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1584   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1585   if (!IsSEH)
1586     CatchPadMBB->setIsEHScopeEntry();
1587   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1588   if (IsMSVCCXX || IsCoreCLR)
1589     CatchPadMBB->setIsEHFuncletEntry();
1590   // Wasm does not need catchpads anymore
1591   if (!IsWasmCXX)
1592     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1593                             getControlRoot()));
1594 }
1595 
1596 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1597   // Update machine-CFG edge.
1598   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1599   FuncInfo.MBB->addSuccessor(TargetMBB);
1600 
1601   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1602   bool IsSEH = isAsynchronousEHPersonality(Pers);
1603   if (IsSEH) {
1604     // If this is not a fall-through branch or optimizations are switched off,
1605     // emit the branch.
1606     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1607         TM.getOptLevel() == CodeGenOpt::None)
1608       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1609                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1610     return;
1611   }
1612 
1613   // Figure out the funclet membership for the catchret's successor.
1614   // This will be used by the FuncletLayout pass to determine how to order the
1615   // BB's.
1616   // A 'catchret' returns to the outer scope's color.
1617   Value *ParentPad = I.getCatchSwitchParentPad();
1618   const BasicBlock *SuccessorColor;
1619   if (isa<ConstantTokenNone>(ParentPad))
1620     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1621   else
1622     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1623   assert(SuccessorColor && "No parent funclet for catchret!");
1624   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1625   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1626 
1627   // Create the terminator node.
1628   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1629                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1630                             DAG.getBasicBlock(SuccessorColorMBB));
1631   DAG.setRoot(Ret);
1632 }
1633 
1634 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1635   // Don't emit any special code for the cleanuppad instruction. It just marks
1636   // the start of an EH scope/funclet.
1637   FuncInfo.MBB->setIsEHScopeEntry();
1638   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639   if (Pers != EHPersonality::Wasm_CXX) {
1640     FuncInfo.MBB->setIsEHFuncletEntry();
1641     FuncInfo.MBB->setIsCleanupFuncletEntry();
1642   }
1643 }
1644 
1645 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1646 // the control flow always stops at the single catch pad, as it does for a
1647 // cleanup pad. In case the exception caught is not of the types the catch pad
1648 // catches, it will be rethrown by a rethrow.
1649 static void findWasmUnwindDestinations(
1650     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1651     BranchProbability Prob,
1652     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1653         &UnwindDests) {
1654   while (EHPadBB) {
1655     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1656     if (isa<CleanupPadInst>(Pad)) {
1657       // Stop on cleanup pads.
1658       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1659       UnwindDests.back().first->setIsEHScopeEntry();
1660       break;
1661     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1662       // Add the catchpad handlers to the possible destinations. We don't
1663       // continue to the unwind destination of the catchswitch for wasm.
1664       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1665         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1666         UnwindDests.back().first->setIsEHScopeEntry();
1667       }
1668       break;
1669     } else {
1670       continue;
1671     }
1672   }
1673 }
1674 
1675 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1676 /// many places it could ultimately go. In the IR, we have a single unwind
1677 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1678 /// This function skips over imaginary basic blocks that hold catchswitch
1679 /// instructions, and finds all the "real" machine
1680 /// basic block destinations. As those destinations may not be successors of
1681 /// EHPadBB, here we also calculate the edge probability to those destinations.
1682 /// The passed-in Prob is the edge probability to EHPadBB.
1683 static void findUnwindDestinations(
1684     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1685     BranchProbability Prob,
1686     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1687         &UnwindDests) {
1688   EHPersonality Personality =
1689     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1690   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1691   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1692   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1693   bool IsSEH = isAsynchronousEHPersonality(Personality);
1694 
1695   if (IsWasmCXX) {
1696     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1697     assert(UnwindDests.size() <= 1 &&
1698            "There should be at most one unwind destination for wasm");
1699     return;
1700   }
1701 
1702   while (EHPadBB) {
1703     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1704     BasicBlock *NewEHPadBB = nullptr;
1705     if (isa<LandingPadInst>(Pad)) {
1706       // Stop on landingpads. They are not funclets.
1707       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1708       break;
1709     } else if (isa<CleanupPadInst>(Pad)) {
1710       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1711       // personalities.
1712       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1713       UnwindDests.back().first->setIsEHScopeEntry();
1714       UnwindDests.back().first->setIsEHFuncletEntry();
1715       break;
1716     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1717       // Add the catchpad handlers to the possible destinations.
1718       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1719         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1720         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1721         if (IsMSVCCXX || IsCoreCLR)
1722           UnwindDests.back().first->setIsEHFuncletEntry();
1723         if (!IsSEH)
1724           UnwindDests.back().first->setIsEHScopeEntry();
1725       }
1726       NewEHPadBB = CatchSwitch->getUnwindDest();
1727     } else {
1728       continue;
1729     }
1730 
1731     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1732     if (BPI && NewEHPadBB)
1733       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1734     EHPadBB = NewEHPadBB;
1735   }
1736 }
1737 
1738 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1739   // Update successor info.
1740   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1741   auto UnwindDest = I.getUnwindDest();
1742   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1743   BranchProbability UnwindDestProb =
1744       (BPI && UnwindDest)
1745           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1746           : BranchProbability::getZero();
1747   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1748   for (auto &UnwindDest : UnwindDests) {
1749     UnwindDest.first->setIsEHPad();
1750     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1751   }
1752   FuncInfo.MBB->normalizeSuccProbs();
1753 
1754   // Create the terminator node.
1755   SDValue Ret =
1756       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1757   DAG.setRoot(Ret);
1758 }
1759 
1760 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1761   report_fatal_error("visitCatchSwitch not yet implemented!");
1762 }
1763 
1764 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1766   auto &DL = DAG.getDataLayout();
1767   SDValue Chain = getControlRoot();
1768   SmallVector<ISD::OutputArg, 8> Outs;
1769   SmallVector<SDValue, 8> OutVals;
1770 
1771   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1772   // lower
1773   //
1774   //   %val = call <ty> @llvm.experimental.deoptimize()
1775   //   ret <ty> %val
1776   //
1777   // differently.
1778   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1779     LowerDeoptimizingReturn();
1780     return;
1781   }
1782 
1783   if (!FuncInfo.CanLowerReturn) {
1784     unsigned DemoteReg = FuncInfo.DemoteRegister;
1785     const Function *F = I.getParent()->getParent();
1786 
1787     // Emit a store of the return value through the virtual register.
1788     // Leave Outs empty so that LowerReturn won't try to load return
1789     // registers the usual way.
1790     SmallVector<EVT, 1> PtrValueVTs;
1791     ComputeValueVTs(TLI, DL,
1792                     F->getReturnType()->getPointerTo(
1793                         DAG.getDataLayout().getAllocaAddrSpace()),
1794                     PtrValueVTs);
1795 
1796     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1797                                         DemoteReg, PtrValueVTs[0]);
1798     SDValue RetOp = getValue(I.getOperand(0));
1799 
1800     SmallVector<EVT, 4> ValueVTs, MemVTs;
1801     SmallVector<uint64_t, 4> Offsets;
1802     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1803                     &Offsets);
1804     unsigned NumValues = ValueVTs.size();
1805 
1806     SmallVector<SDValue, 4> Chains(NumValues);
1807     for (unsigned i = 0; i != NumValues; ++i) {
1808       // An aggregate return value cannot wrap around the address space, so
1809       // offsets to its parts don't wrap either.
1810       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1811 
1812       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1813       if (MemVTs[i] != ValueVTs[i])
1814         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1815       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1816           // FIXME: better loc info would be nice.
1817           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1818     }
1819 
1820     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1821                         MVT::Other, Chains);
1822   } else if (I.getNumOperands() != 0) {
1823     SmallVector<EVT, 4> ValueVTs;
1824     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1825     unsigned NumValues = ValueVTs.size();
1826     if (NumValues) {
1827       SDValue RetOp = getValue(I.getOperand(0));
1828 
1829       const Function *F = I.getParent()->getParent();
1830 
1831       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1832           I.getOperand(0)->getType(), F->getCallingConv(),
1833           /*IsVarArg*/ false);
1834 
1835       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1836       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1837                                           Attribute::SExt))
1838         ExtendKind = ISD::SIGN_EXTEND;
1839       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1840                                                Attribute::ZExt))
1841         ExtendKind = ISD::ZERO_EXTEND;
1842 
1843       LLVMContext &Context = F->getContext();
1844       bool RetInReg = F->getAttributes().hasAttribute(
1845           AttributeList::ReturnIndex, Attribute::InReg);
1846 
1847       for (unsigned j = 0; j != NumValues; ++j) {
1848         EVT VT = ValueVTs[j];
1849 
1850         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1851           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1852 
1853         CallingConv::ID CC = F->getCallingConv();
1854 
1855         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1856         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1857         SmallVector<SDValue, 4> Parts(NumParts);
1858         getCopyToParts(DAG, getCurSDLoc(),
1859                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1860                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1861 
1862         // 'inreg' on function refers to return value
1863         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1864         if (RetInReg)
1865           Flags.setInReg();
1866 
1867         if (I.getOperand(0)->getType()->isPointerTy()) {
1868           Flags.setPointer();
1869           Flags.setPointerAddrSpace(
1870               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1871         }
1872 
1873         if (NeedsRegBlock) {
1874           Flags.setInConsecutiveRegs();
1875           if (j == NumValues - 1)
1876             Flags.setInConsecutiveRegsLast();
1877         }
1878 
1879         // Propagate extension type if any
1880         if (ExtendKind == ISD::SIGN_EXTEND)
1881           Flags.setSExt();
1882         else if (ExtendKind == ISD::ZERO_EXTEND)
1883           Flags.setZExt();
1884 
1885         for (unsigned i = 0; i < NumParts; ++i) {
1886           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1887                                         VT, /*isfixed=*/true, 0, 0));
1888           OutVals.push_back(Parts[i]);
1889         }
1890       }
1891     }
1892   }
1893 
1894   // Push in swifterror virtual register as the last element of Outs. This makes
1895   // sure swifterror virtual register will be returned in the swifterror
1896   // physical register.
1897   const Function *F = I.getParent()->getParent();
1898   if (TLI.supportSwiftError() &&
1899       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1900     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1901     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1902     Flags.setSwiftError();
1903     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1904                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1905                                   true /*isfixed*/, 1 /*origidx*/,
1906                                   0 /*partOffs*/));
1907     // Create SDNode for the swifterror virtual register.
1908     OutVals.push_back(
1909         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1910                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1911                         EVT(TLI.getPointerTy(DL))));
1912   }
1913 
1914   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1915   CallingConv::ID CallConv =
1916     DAG.getMachineFunction().getFunction().getCallingConv();
1917   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1918       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1919 
1920   // Verify that the target's LowerReturn behaved as expected.
1921   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1922          "LowerReturn didn't return a valid chain!");
1923 
1924   // Update the DAG with the new chain value resulting from return lowering.
1925   DAG.setRoot(Chain);
1926 }
1927 
1928 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1929 /// created for it, emit nodes to copy the value into the virtual
1930 /// registers.
1931 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1932   // Skip empty types
1933   if (V->getType()->isEmptyTy())
1934     return;
1935 
1936   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1937   if (VMI != FuncInfo.ValueMap.end()) {
1938     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1939     CopyValueToVirtualRegister(V, VMI->second);
1940   }
1941 }
1942 
1943 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1944 /// the current basic block, add it to ValueMap now so that we'll get a
1945 /// CopyTo/FromReg.
1946 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1947   // No need to export constants.
1948   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1949 
1950   // Already exported?
1951   if (FuncInfo.isExportedInst(V)) return;
1952 
1953   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1954   CopyValueToVirtualRegister(V, Reg);
1955 }
1956 
1957 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1958                                                      const BasicBlock *FromBB) {
1959   // The operands of the setcc have to be in this block.  We don't know
1960   // how to export them from some other block.
1961   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1962     // Can export from current BB.
1963     if (VI->getParent() == FromBB)
1964       return true;
1965 
1966     // Is already exported, noop.
1967     return FuncInfo.isExportedInst(V);
1968   }
1969 
1970   // If this is an argument, we can export it if the BB is the entry block or
1971   // if it is already exported.
1972   if (isa<Argument>(V)) {
1973     if (FromBB == &FromBB->getParent()->getEntryBlock())
1974       return true;
1975 
1976     // Otherwise, can only export this if it is already exported.
1977     return FuncInfo.isExportedInst(V);
1978   }
1979 
1980   // Otherwise, constants can always be exported.
1981   return true;
1982 }
1983 
1984 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1985 BranchProbability
1986 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1987                                         const MachineBasicBlock *Dst) const {
1988   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1989   const BasicBlock *SrcBB = Src->getBasicBlock();
1990   const BasicBlock *DstBB = Dst->getBasicBlock();
1991   if (!BPI) {
1992     // If BPI is not available, set the default probability as 1 / N, where N is
1993     // the number of successors.
1994     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1995     return BranchProbability(1, SuccSize);
1996   }
1997   return BPI->getEdgeProbability(SrcBB, DstBB);
1998 }
1999 
2000 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2001                                                MachineBasicBlock *Dst,
2002                                                BranchProbability Prob) {
2003   if (!FuncInfo.BPI)
2004     Src->addSuccessorWithoutProb(Dst);
2005   else {
2006     if (Prob.isUnknown())
2007       Prob = getEdgeProbability(Src, Dst);
2008     Src->addSuccessor(Dst, Prob);
2009   }
2010 }
2011 
2012 static bool InBlock(const Value *V, const BasicBlock *BB) {
2013   if (const Instruction *I = dyn_cast<Instruction>(V))
2014     return I->getParent() == BB;
2015   return true;
2016 }
2017 
2018 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2019 /// This function emits a branch and is used at the leaves of an OR or an
2020 /// AND operator tree.
2021 void
2022 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2023                                                   MachineBasicBlock *TBB,
2024                                                   MachineBasicBlock *FBB,
2025                                                   MachineBasicBlock *CurBB,
2026                                                   MachineBasicBlock *SwitchBB,
2027                                                   BranchProbability TProb,
2028                                                   BranchProbability FProb,
2029                                                   bool InvertCond) {
2030   const BasicBlock *BB = CurBB->getBasicBlock();
2031 
2032   // If the leaf of the tree is a comparison, merge the condition into
2033   // the caseblock.
2034   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2035     // The operands of the cmp have to be in this block.  We don't know
2036     // how to export them from some other block.  If this is the first block
2037     // of the sequence, no exporting is needed.
2038     if (CurBB == SwitchBB ||
2039         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2040          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2041       ISD::CondCode Condition;
2042       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2043         ICmpInst::Predicate Pred =
2044             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2045         Condition = getICmpCondCode(Pred);
2046       } else {
2047         const FCmpInst *FC = cast<FCmpInst>(Cond);
2048         FCmpInst::Predicate Pred =
2049             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2050         Condition = getFCmpCondCode(Pred);
2051         if (TM.Options.NoNaNsFPMath)
2052           Condition = getFCmpCodeWithoutNaN(Condition);
2053       }
2054 
2055       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2056                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2057       SL->SwitchCases.push_back(CB);
2058       return;
2059     }
2060   }
2061 
2062   // Create a CaseBlock record representing this branch.
2063   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2064   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2065                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2066   SL->SwitchCases.push_back(CB);
2067 }
2068 
2069 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2070                                                MachineBasicBlock *TBB,
2071                                                MachineBasicBlock *FBB,
2072                                                MachineBasicBlock *CurBB,
2073                                                MachineBasicBlock *SwitchBB,
2074                                                Instruction::BinaryOps Opc,
2075                                                BranchProbability TProb,
2076                                                BranchProbability FProb,
2077                                                bool InvertCond) {
2078   // Skip over not part of the tree and remember to invert op and operands at
2079   // next level.
2080   Value *NotCond;
2081   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2082       InBlock(NotCond, CurBB->getBasicBlock())) {
2083     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2084                          !InvertCond);
2085     return;
2086   }
2087 
2088   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2089   // Compute the effective opcode for Cond, taking into account whether it needs
2090   // to be inverted, e.g.
2091   //   and (not (or A, B)), C
2092   // gets lowered as
2093   //   and (and (not A, not B), C)
2094   unsigned BOpc = 0;
2095   if (BOp) {
2096     BOpc = BOp->getOpcode();
2097     if (InvertCond) {
2098       if (BOpc == Instruction::And)
2099         BOpc = Instruction::Or;
2100       else if (BOpc == Instruction::Or)
2101         BOpc = Instruction::And;
2102     }
2103   }
2104 
2105   // If this node is not part of the or/and tree, emit it as a branch.
2106   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2107       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2108       BOp->getParent() != CurBB->getBasicBlock() ||
2109       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2110       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2111     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2112                                  TProb, FProb, InvertCond);
2113     return;
2114   }
2115 
2116   //  Create TmpBB after CurBB.
2117   MachineFunction::iterator BBI(CurBB);
2118   MachineFunction &MF = DAG.getMachineFunction();
2119   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2120   CurBB->getParent()->insert(++BBI, TmpBB);
2121 
2122   if (Opc == Instruction::Or) {
2123     // Codegen X | Y as:
2124     // BB1:
2125     //   jmp_if_X TBB
2126     //   jmp TmpBB
2127     // TmpBB:
2128     //   jmp_if_Y TBB
2129     //   jmp FBB
2130     //
2131 
2132     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2133     // The requirement is that
2134     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2135     //     = TrueProb for original BB.
2136     // Assuming the original probabilities are A and B, one choice is to set
2137     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2138     // A/(1+B) and 2B/(1+B). This choice assumes that
2139     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2140     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2141     // TmpBB, but the math is more complicated.
2142 
2143     auto NewTrueProb = TProb / 2;
2144     auto NewFalseProb = TProb / 2 + FProb;
2145     // Emit the LHS condition.
2146     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2147                          NewTrueProb, NewFalseProb, InvertCond);
2148 
2149     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2150     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2151     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2152     // Emit the RHS condition into TmpBB.
2153     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2154                          Probs[0], Probs[1], InvertCond);
2155   } else {
2156     assert(Opc == Instruction::And && "Unknown merge op!");
2157     // Codegen X & Y as:
2158     // BB1:
2159     //   jmp_if_X TmpBB
2160     //   jmp FBB
2161     // TmpBB:
2162     //   jmp_if_Y TBB
2163     //   jmp FBB
2164     //
2165     //  This requires creation of TmpBB after CurBB.
2166 
2167     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2168     // The requirement is that
2169     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2170     //     = FalseProb for original BB.
2171     // Assuming the original probabilities are A and B, one choice is to set
2172     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2173     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2174     // TrueProb for BB1 * FalseProb for TmpBB.
2175 
2176     auto NewTrueProb = TProb + FProb / 2;
2177     auto NewFalseProb = FProb / 2;
2178     // Emit the LHS condition.
2179     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2180                          NewTrueProb, NewFalseProb, InvertCond);
2181 
2182     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2183     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2184     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2185     // Emit the RHS condition into TmpBB.
2186     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2187                          Probs[0], Probs[1], InvertCond);
2188   }
2189 }
2190 
2191 /// If the set of cases should be emitted as a series of branches, return true.
2192 /// If we should emit this as a bunch of and/or'd together conditions, return
2193 /// false.
2194 bool
2195 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2196   if (Cases.size() != 2) return true;
2197 
2198   // If this is two comparisons of the same values or'd or and'd together, they
2199   // will get folded into a single comparison, so don't emit two blocks.
2200   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2201        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2202       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2203        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2204     return false;
2205   }
2206 
2207   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2208   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2209   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2210       Cases[0].CC == Cases[1].CC &&
2211       isa<Constant>(Cases[0].CmpRHS) &&
2212       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2213     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2214       return false;
2215     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2216       return false;
2217   }
2218 
2219   return true;
2220 }
2221 
2222 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2223   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2224 
2225   // Update machine-CFG edges.
2226   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2227 
2228   if (I.isUnconditional()) {
2229     // Update machine-CFG edges.
2230     BrMBB->addSuccessor(Succ0MBB);
2231 
2232     // If this is not a fall-through branch or optimizations are switched off,
2233     // emit the branch.
2234     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2235       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2236                               MVT::Other, getControlRoot(),
2237                               DAG.getBasicBlock(Succ0MBB)));
2238 
2239     return;
2240   }
2241 
2242   // If this condition is one of the special cases we handle, do special stuff
2243   // now.
2244   const Value *CondVal = I.getCondition();
2245   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2246 
2247   // If this is a series of conditions that are or'd or and'd together, emit
2248   // this as a sequence of branches instead of setcc's with and/or operations.
2249   // As long as jumps are not expensive, this should improve performance.
2250   // For example, instead of something like:
2251   //     cmp A, B
2252   //     C = seteq
2253   //     cmp D, E
2254   //     F = setle
2255   //     or C, F
2256   //     jnz foo
2257   // Emit:
2258   //     cmp A, B
2259   //     je foo
2260   //     cmp D, E
2261   //     jle foo
2262   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2263     Instruction::BinaryOps Opcode = BOp->getOpcode();
2264     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2265         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2266         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2267       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2268                            Opcode,
2269                            getEdgeProbability(BrMBB, Succ0MBB),
2270                            getEdgeProbability(BrMBB, Succ1MBB),
2271                            /*InvertCond=*/false);
2272       // If the compares in later blocks need to use values not currently
2273       // exported from this block, export them now.  This block should always
2274       // be the first entry.
2275       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2276 
2277       // Allow some cases to be rejected.
2278       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2279         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2280           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2281           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2282         }
2283 
2284         // Emit the branch for this block.
2285         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2286         SL->SwitchCases.erase(SL->SwitchCases.begin());
2287         return;
2288       }
2289 
2290       // Okay, we decided not to do this, remove any inserted MBB's and clear
2291       // SwitchCases.
2292       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2293         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2294 
2295       SL->SwitchCases.clear();
2296     }
2297   }
2298 
2299   // Create a CaseBlock record representing this branch.
2300   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2301                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2302 
2303   // Use visitSwitchCase to actually insert the fast branch sequence for this
2304   // cond branch.
2305   visitSwitchCase(CB, BrMBB);
2306 }
2307 
2308 /// visitSwitchCase - Emits the necessary code to represent a single node in
2309 /// the binary search tree resulting from lowering a switch instruction.
2310 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2311                                           MachineBasicBlock *SwitchBB) {
2312   SDValue Cond;
2313   SDValue CondLHS = getValue(CB.CmpLHS);
2314   SDLoc dl = CB.DL;
2315 
2316   if (CB.CC == ISD::SETTRUE) {
2317     // Branch or fall through to TrueBB.
2318     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2319     SwitchBB->normalizeSuccProbs();
2320     if (CB.TrueBB != NextBlock(SwitchBB)) {
2321       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2322                               DAG.getBasicBlock(CB.TrueBB)));
2323     }
2324     return;
2325   }
2326 
2327   auto &TLI = DAG.getTargetLoweringInfo();
2328   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2329 
2330   // Build the setcc now.
2331   if (!CB.CmpMHS) {
2332     // Fold "(X == true)" to X and "(X == false)" to !X to
2333     // handle common cases produced by branch lowering.
2334     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2335         CB.CC == ISD::SETEQ)
2336       Cond = CondLHS;
2337     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2338              CB.CC == ISD::SETEQ) {
2339       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2340       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2341     } else {
2342       SDValue CondRHS = getValue(CB.CmpRHS);
2343 
2344       // If a pointer's DAG type is larger than its memory type then the DAG
2345       // values are zero-extended. This breaks signed comparisons so truncate
2346       // back to the underlying type before doing the compare.
2347       if (CondLHS.getValueType() != MemVT) {
2348         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2349         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2350       }
2351       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2352     }
2353   } else {
2354     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2355 
2356     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2357     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2358 
2359     SDValue CmpOp = getValue(CB.CmpMHS);
2360     EVT VT = CmpOp.getValueType();
2361 
2362     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2363       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2364                           ISD::SETLE);
2365     } else {
2366       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2367                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2368       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2369                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2370     }
2371   }
2372 
2373   // Update successor info
2374   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2375   // TrueBB and FalseBB are always different unless the incoming IR is
2376   // degenerate. This only happens when running llc on weird IR.
2377   if (CB.TrueBB != CB.FalseBB)
2378     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2379   SwitchBB->normalizeSuccProbs();
2380 
2381   // If the lhs block is the next block, invert the condition so that we can
2382   // fall through to the lhs instead of the rhs block.
2383   if (CB.TrueBB == NextBlock(SwitchBB)) {
2384     std::swap(CB.TrueBB, CB.FalseBB);
2385     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2386     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2387   }
2388 
2389   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2390                                MVT::Other, getControlRoot(), Cond,
2391                                DAG.getBasicBlock(CB.TrueBB));
2392 
2393   // Insert the false branch. Do this even if it's a fall through branch,
2394   // this makes it easier to do DAG optimizations which require inverting
2395   // the branch condition.
2396   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2397                        DAG.getBasicBlock(CB.FalseBB));
2398 
2399   DAG.setRoot(BrCond);
2400 }
2401 
2402 /// visitJumpTable - Emit JumpTable node in the current MBB
2403 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2404   // Emit the code for the jump table
2405   assert(JT.Reg != -1U && "Should lower JT Header first!");
2406   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2407   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2408                                      JT.Reg, PTy);
2409   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2410   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2411                                     MVT::Other, Index.getValue(1),
2412                                     Table, Index);
2413   DAG.setRoot(BrJumpTable);
2414 }
2415 
2416 /// visitJumpTableHeader - This function emits necessary code to produce index
2417 /// in the JumpTable from switch case.
2418 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2419                                                JumpTableHeader &JTH,
2420                                                MachineBasicBlock *SwitchBB) {
2421   SDLoc dl = getCurSDLoc();
2422 
2423   // Subtract the lowest switch case value from the value being switched on.
2424   SDValue SwitchOp = getValue(JTH.SValue);
2425   EVT VT = SwitchOp.getValueType();
2426   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2427                             DAG.getConstant(JTH.First, dl, VT));
2428 
2429   // The SDNode we just created, which holds the value being switched on minus
2430   // the smallest case value, needs to be copied to a virtual register so it
2431   // can be used as an index into the jump table in a subsequent basic block.
2432   // This value may be smaller or larger than the target's pointer type, and
2433   // therefore require extension or truncating.
2434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2435   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2436 
2437   unsigned JumpTableReg =
2438       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2439   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2440                                     JumpTableReg, SwitchOp);
2441   JT.Reg = JumpTableReg;
2442 
2443   if (!JTH.OmitRangeCheck) {
2444     // Emit the range check for the jump table, and branch to the default block
2445     // for the switch statement if the value being switched on exceeds the
2446     // largest case in the switch.
2447     SDValue CMP = DAG.getSetCC(
2448         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2449                                    Sub.getValueType()),
2450         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2451 
2452     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2453                                  MVT::Other, CopyTo, CMP,
2454                                  DAG.getBasicBlock(JT.Default));
2455 
2456     // Avoid emitting unnecessary branches to the next block.
2457     if (JT.MBB != NextBlock(SwitchBB))
2458       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2459                            DAG.getBasicBlock(JT.MBB));
2460 
2461     DAG.setRoot(BrCond);
2462   } else {
2463     // Avoid emitting unnecessary branches to the next block.
2464     if (JT.MBB != NextBlock(SwitchBB))
2465       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2466                               DAG.getBasicBlock(JT.MBB)));
2467     else
2468       DAG.setRoot(CopyTo);
2469   }
2470 }
2471 
2472 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2473 /// variable if there exists one.
2474 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2475                                  SDValue &Chain) {
2476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2477   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2478   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2479   MachineFunction &MF = DAG.getMachineFunction();
2480   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2481   MachineSDNode *Node =
2482       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2483   if (Global) {
2484     MachinePointerInfo MPInfo(Global);
2485     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2486                  MachineMemOperand::MODereferenceable;
2487     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2488         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2489     DAG.setNodeMemRefs(Node, {MemRef});
2490   }
2491   if (PtrTy != PtrMemTy)
2492     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2493   return SDValue(Node, 0);
2494 }
2495 
2496 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2497 /// tail spliced into a stack protector check success bb.
2498 ///
2499 /// For a high level explanation of how this fits into the stack protector
2500 /// generation see the comment on the declaration of class
2501 /// StackProtectorDescriptor.
2502 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2503                                                   MachineBasicBlock *ParentBB) {
2504 
2505   // First create the loads to the guard/stack slot for the comparison.
2506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2508   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2509 
2510   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2511   int FI = MFI.getStackProtectorIndex();
2512 
2513   SDValue Guard;
2514   SDLoc dl = getCurSDLoc();
2515   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2516   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2517   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2518 
2519   // Generate code to load the content of the guard slot.
2520   SDValue GuardVal = DAG.getLoad(
2521       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2522       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2523       MachineMemOperand::MOVolatile);
2524 
2525   if (TLI.useStackGuardXorFP())
2526     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2527 
2528   // Retrieve guard check function, nullptr if instrumentation is inlined.
2529   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2530     // The target provides a guard check function to validate the guard value.
2531     // Generate a call to that function with the content of the guard slot as
2532     // argument.
2533     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2534     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2535 
2536     TargetLowering::ArgListTy Args;
2537     TargetLowering::ArgListEntry Entry;
2538     Entry.Node = GuardVal;
2539     Entry.Ty = FnTy->getParamType(0);
2540     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2541       Entry.IsInReg = true;
2542     Args.push_back(Entry);
2543 
2544     TargetLowering::CallLoweringInfo CLI(DAG);
2545     CLI.setDebugLoc(getCurSDLoc())
2546         .setChain(DAG.getEntryNode())
2547         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2548                    getValue(GuardCheckFn), std::move(Args));
2549 
2550     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2551     DAG.setRoot(Result.second);
2552     return;
2553   }
2554 
2555   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2556   // Otherwise, emit a volatile load to retrieve the stack guard value.
2557   SDValue Chain = DAG.getEntryNode();
2558   if (TLI.useLoadStackGuardNode()) {
2559     Guard = getLoadStackGuard(DAG, dl, Chain);
2560   } else {
2561     const Value *IRGuard = TLI.getSDagStackGuard(M);
2562     SDValue GuardPtr = getValue(IRGuard);
2563 
2564     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2565                         MachinePointerInfo(IRGuard, 0), Align,
2566                         MachineMemOperand::MOVolatile);
2567   }
2568 
2569   // Perform the comparison via a subtract/getsetcc.
2570   EVT VT = Guard.getValueType();
2571   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2572 
2573   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2574                                                         *DAG.getContext(),
2575                                                         Sub.getValueType()),
2576                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2577 
2578   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2579   // branch to failure MBB.
2580   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2581                                MVT::Other, GuardVal.getOperand(0),
2582                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2583   // Otherwise branch to success MBB.
2584   SDValue Br = DAG.getNode(ISD::BR, dl,
2585                            MVT::Other, BrCond,
2586                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2587 
2588   DAG.setRoot(Br);
2589 }
2590 
2591 /// Codegen the failure basic block for a stack protector check.
2592 ///
2593 /// A failure stack protector machine basic block consists simply of a call to
2594 /// __stack_chk_fail().
2595 ///
2596 /// For a high level explanation of how this fits into the stack protector
2597 /// generation see the comment on the declaration of class
2598 /// StackProtectorDescriptor.
2599 void
2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602   TargetLowering::MakeLibCallOptions CallOptions;
2603   CallOptions.setDiscardResult(true);
2604   SDValue Chain =
2605       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2606                       None, CallOptions, getCurSDLoc()).second;
2607   // On PS4, the "return address" must still be within the calling function,
2608   // even if it's at the very end, so emit an explicit TRAP here.
2609   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2610   if (TM.getTargetTriple().isPS4CPU())
2611     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2612 
2613   DAG.setRoot(Chain);
2614 }
2615 
2616 /// visitBitTestHeader - This function emits necessary code to produce value
2617 /// suitable for "bit tests"
2618 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2619                                              MachineBasicBlock *SwitchBB) {
2620   SDLoc dl = getCurSDLoc();
2621 
2622   // Subtract the minimum value
2623   SDValue SwitchOp = getValue(B.SValue);
2624   EVT VT = SwitchOp.getValueType();
2625   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2626                             DAG.getConstant(B.First, dl, VT));
2627 
2628   // Check range
2629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2630   SDValue RangeCmp = DAG.getSetCC(
2631       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2632                                  Sub.getValueType()),
2633       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2634 
2635   // Determine the type of the test operands.
2636   bool UsePtrType = false;
2637   if (!TLI.isTypeLegal(VT))
2638     UsePtrType = true;
2639   else {
2640     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2641       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2642         // Switch table case range are encoded into series of masks.
2643         // Just use pointer type, it's guaranteed to fit.
2644         UsePtrType = true;
2645         break;
2646       }
2647   }
2648   if (UsePtrType) {
2649     VT = TLI.getPointerTy(DAG.getDataLayout());
2650     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2651   }
2652 
2653   B.RegVT = VT.getSimpleVT();
2654   B.Reg = FuncInfo.CreateReg(B.RegVT);
2655   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2656 
2657   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2658 
2659   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2660   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2661   SwitchBB->normalizeSuccProbs();
2662 
2663   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2664                                 MVT::Other, CopyTo, RangeCmp,
2665                                 DAG.getBasicBlock(B.Default));
2666 
2667   // Avoid emitting unnecessary branches to the next block.
2668   if (MBB != NextBlock(SwitchBB))
2669     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2670                           DAG.getBasicBlock(MBB));
2671 
2672   DAG.setRoot(BrRange);
2673 }
2674 
2675 /// visitBitTestCase - this function produces one "bit test"
2676 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2677                                            MachineBasicBlock* NextMBB,
2678                                            BranchProbability BranchProbToNext,
2679                                            unsigned Reg,
2680                                            BitTestCase &B,
2681                                            MachineBasicBlock *SwitchBB) {
2682   SDLoc dl = getCurSDLoc();
2683   MVT VT = BB.RegVT;
2684   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2685   SDValue Cmp;
2686   unsigned PopCount = countPopulation(B.Mask);
2687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2688   if (PopCount == 1) {
2689     // Testing for a single bit; just compare the shift count with what it
2690     // would need to be to shift a 1 bit in that position.
2691     Cmp = DAG.getSetCC(
2692         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2693         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2694         ISD::SETEQ);
2695   } else if (PopCount == BB.Range) {
2696     // There is only one zero bit in the range, test for it directly.
2697     Cmp = DAG.getSetCC(
2698         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2699         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2700         ISD::SETNE);
2701   } else {
2702     // Make desired shift
2703     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2704                                     DAG.getConstant(1, dl, VT), ShiftOp);
2705 
2706     // Emit bit tests and jumps
2707     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2708                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2709     Cmp = DAG.getSetCC(
2710         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2711         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2712   }
2713 
2714   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2715   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2716   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2717   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2718   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2719   // one as they are relative probabilities (and thus work more like weights),
2720   // and hence we need to normalize them to let the sum of them become one.
2721   SwitchBB->normalizeSuccProbs();
2722 
2723   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2724                               MVT::Other, getControlRoot(),
2725                               Cmp, DAG.getBasicBlock(B.TargetBB));
2726 
2727   // Avoid emitting unnecessary branches to the next block.
2728   if (NextMBB != NextBlock(SwitchBB))
2729     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2730                         DAG.getBasicBlock(NextMBB));
2731 
2732   DAG.setRoot(BrAnd);
2733 }
2734 
2735 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2736   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2737 
2738   // Retrieve successors. Look through artificial IR level blocks like
2739   // catchswitch for successors.
2740   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2741   const BasicBlock *EHPadBB = I.getSuccessor(1);
2742 
2743   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2744   // have to do anything here to lower funclet bundles.
2745   assert(!I.hasOperandBundlesOtherThan(
2746              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2747          "Cannot lower invokes with arbitrary operand bundles yet!");
2748 
2749   const Value *Callee(I.getCalledValue());
2750   const Function *Fn = dyn_cast<Function>(Callee);
2751   if (isa<InlineAsm>(Callee))
2752     visitInlineAsm(&I);
2753   else if (Fn && Fn->isIntrinsic()) {
2754     switch (Fn->getIntrinsicID()) {
2755     default:
2756       llvm_unreachable("Cannot invoke this intrinsic");
2757     case Intrinsic::donothing:
2758       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2759       break;
2760     case Intrinsic::experimental_patchpoint_void:
2761     case Intrinsic::experimental_patchpoint_i64:
2762       visitPatchpoint(&I, EHPadBB);
2763       break;
2764     case Intrinsic::experimental_gc_statepoint:
2765       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2766       break;
2767     case Intrinsic::wasm_rethrow_in_catch: {
2768       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2769       // special because it can be invoked, so we manually lower it to a DAG
2770       // node here.
2771       SmallVector<SDValue, 8> Ops;
2772       Ops.push_back(getRoot()); // inchain
2773       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774       Ops.push_back(
2775           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2776                                 TLI.getPointerTy(DAG.getDataLayout())));
2777       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2778       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2779       break;
2780     }
2781     }
2782   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2783     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2784     // Eventually we will support lowering the @llvm.experimental.deoptimize
2785     // intrinsic, and right now there are no plans to support other intrinsics
2786     // with deopt state.
2787     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2788   } else {
2789     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2790   }
2791 
2792   // If the value of the invoke is used outside of its defining block, make it
2793   // available as a virtual register.
2794   // We already took care of the exported value for the statepoint instruction
2795   // during call to the LowerStatepoint.
2796   if (!isStatepoint(I)) {
2797     CopyToExportRegsIfNeeded(&I);
2798   }
2799 
2800   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2801   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2802   BranchProbability EHPadBBProb =
2803       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2804           : BranchProbability::getZero();
2805   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2806 
2807   // Update successor info.
2808   addSuccessorWithProb(InvokeMBB, Return);
2809   for (auto &UnwindDest : UnwindDests) {
2810     UnwindDest.first->setIsEHPad();
2811     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2812   }
2813   InvokeMBB->normalizeSuccProbs();
2814 
2815   // Drop into normal successor.
2816   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2817                           DAG.getBasicBlock(Return)));
2818 }
2819 
2820 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2821   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2822 
2823   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2824   // have to do anything here to lower funclet bundles.
2825   assert(!I.hasOperandBundlesOtherThan(
2826              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2827          "Cannot lower callbrs with arbitrary operand bundles yet!");
2828 
2829   assert(isa<InlineAsm>(I.getCalledValue()) &&
2830          "Only know how to handle inlineasm callbr");
2831   visitInlineAsm(&I);
2832 
2833   // Retrieve successors.
2834   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2835 
2836   // Update successor info.
2837   addSuccessorWithProb(CallBrMBB, Return);
2838   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2839     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2840     addSuccessorWithProb(CallBrMBB, Target);
2841   }
2842   CallBrMBB->normalizeSuccProbs();
2843 
2844   // Drop into default successor.
2845   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2846                           MVT::Other, getControlRoot(),
2847                           DAG.getBasicBlock(Return)));
2848 }
2849 
2850 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2851   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2852 }
2853 
2854 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2855   assert(FuncInfo.MBB->isEHPad() &&
2856          "Call to landingpad not in landing pad!");
2857 
2858   // If there aren't registers to copy the values into (e.g., during SjLj
2859   // exceptions), then don't bother to create these DAG nodes.
2860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2861   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2862   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2863       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2864     return;
2865 
2866   // If landingpad's return type is token type, we don't create DAG nodes
2867   // for its exception pointer and selector value. The extraction of exception
2868   // pointer or selector value from token type landingpads is not currently
2869   // supported.
2870   if (LP.getType()->isTokenTy())
2871     return;
2872 
2873   SmallVector<EVT, 2> ValueVTs;
2874   SDLoc dl = getCurSDLoc();
2875   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2876   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2877 
2878   // Get the two live-in registers as SDValues. The physregs have already been
2879   // copied into virtual registers.
2880   SDValue Ops[2];
2881   if (FuncInfo.ExceptionPointerVirtReg) {
2882     Ops[0] = DAG.getZExtOrTrunc(
2883         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2884                            FuncInfo.ExceptionPointerVirtReg,
2885                            TLI.getPointerTy(DAG.getDataLayout())),
2886         dl, ValueVTs[0]);
2887   } else {
2888     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2889   }
2890   Ops[1] = DAG.getZExtOrTrunc(
2891       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2892                          FuncInfo.ExceptionSelectorVirtReg,
2893                          TLI.getPointerTy(DAG.getDataLayout())),
2894       dl, ValueVTs[1]);
2895 
2896   // Merge into one.
2897   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2898                             DAG.getVTList(ValueVTs), Ops);
2899   setValue(&LP, Res);
2900 }
2901 
2902 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2903                                            MachineBasicBlock *Last) {
2904   // Update JTCases.
2905   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2906     if (SL->JTCases[i].first.HeaderBB == First)
2907       SL->JTCases[i].first.HeaderBB = Last;
2908 
2909   // Update BitTestCases.
2910   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2911     if (SL->BitTestCases[i].Parent == First)
2912       SL->BitTestCases[i].Parent = Last;
2913 }
2914 
2915 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2916   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2917 
2918   // Update machine-CFG edges with unique successors.
2919   SmallSet<BasicBlock*, 32> Done;
2920   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2921     BasicBlock *BB = I.getSuccessor(i);
2922     bool Inserted = Done.insert(BB).second;
2923     if (!Inserted)
2924         continue;
2925 
2926     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2927     addSuccessorWithProb(IndirectBrMBB, Succ);
2928   }
2929   IndirectBrMBB->normalizeSuccProbs();
2930 
2931   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2932                           MVT::Other, getControlRoot(),
2933                           getValue(I.getAddress())));
2934 }
2935 
2936 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2937   if (!DAG.getTarget().Options.TrapUnreachable)
2938     return;
2939 
2940   // We may be able to ignore unreachable behind a noreturn call.
2941   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2942     const BasicBlock &BB = *I.getParent();
2943     if (&I != &BB.front()) {
2944       BasicBlock::const_iterator PredI =
2945         std::prev(BasicBlock::const_iterator(&I));
2946       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2947         if (Call->doesNotReturn())
2948           return;
2949       }
2950     }
2951   }
2952 
2953   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2954 }
2955 
2956 void SelectionDAGBuilder::visitFSub(const User &I) {
2957   // -0.0 - X --> fneg
2958   Type *Ty = I.getType();
2959   if (isa<Constant>(I.getOperand(0)) &&
2960       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2961     SDValue Op2 = getValue(I.getOperand(1));
2962     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2963                              Op2.getValueType(), Op2));
2964     return;
2965   }
2966 
2967   visitBinary(I, ISD::FSUB);
2968 }
2969 
2970 /// Checks if the given instruction performs a vector reduction, in which case
2971 /// we have the freedom to alter the elements in the result as long as the
2972 /// reduction of them stays unchanged.
2973 static bool isVectorReductionOp(const User *I) {
2974   const Instruction *Inst = dyn_cast<Instruction>(I);
2975   if (!Inst || !Inst->getType()->isVectorTy())
2976     return false;
2977 
2978   auto OpCode = Inst->getOpcode();
2979   switch (OpCode) {
2980   case Instruction::Add:
2981   case Instruction::Mul:
2982   case Instruction::And:
2983   case Instruction::Or:
2984   case Instruction::Xor:
2985     break;
2986   case Instruction::FAdd:
2987   case Instruction::FMul:
2988     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2989       if (FPOp->getFastMathFlags().isFast())
2990         break;
2991     LLVM_FALLTHROUGH;
2992   default:
2993     return false;
2994   }
2995 
2996   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2997   // Ensure the reduction size is a power of 2.
2998   if (!isPowerOf2_32(ElemNum))
2999     return false;
3000 
3001   unsigned ElemNumToReduce = ElemNum;
3002 
3003   // Do DFS search on the def-use chain from the given instruction. We only
3004   // allow four kinds of operations during the search until we reach the
3005   // instruction that extracts the first element from the vector:
3006   //
3007   //   1. The reduction operation of the same opcode as the given instruction.
3008   //
3009   //   2. PHI node.
3010   //
3011   //   3. ShuffleVector instruction together with a reduction operation that
3012   //      does a partial reduction.
3013   //
3014   //   4. ExtractElement that extracts the first element from the vector, and we
3015   //      stop searching the def-use chain here.
3016   //
3017   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3018   // from 1-3 to the stack to continue the DFS. The given instruction is not
3019   // a reduction operation if we meet any other instructions other than those
3020   // listed above.
3021 
3022   SmallVector<const User *, 16> UsersToVisit{Inst};
3023   SmallPtrSet<const User *, 16> Visited;
3024   bool ReduxExtracted = false;
3025 
3026   while (!UsersToVisit.empty()) {
3027     auto User = UsersToVisit.back();
3028     UsersToVisit.pop_back();
3029     if (!Visited.insert(User).second)
3030       continue;
3031 
3032     for (const auto &U : User->users()) {
3033       auto Inst = dyn_cast<Instruction>(U);
3034       if (!Inst)
3035         return false;
3036 
3037       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3038         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3039           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3040             return false;
3041         UsersToVisit.push_back(U);
3042       } else if (const ShuffleVectorInst *ShufInst =
3043                      dyn_cast<ShuffleVectorInst>(U)) {
3044         // Detect the following pattern: A ShuffleVector instruction together
3045         // with a reduction that do partial reduction on the first and second
3046         // ElemNumToReduce / 2 elements, and store the result in
3047         // ElemNumToReduce / 2 elements in another vector.
3048 
3049         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3050         if (ResultElements < ElemNum)
3051           return false;
3052 
3053         if (ElemNumToReduce == 1)
3054           return false;
3055         if (!isa<UndefValue>(U->getOperand(1)))
3056           return false;
3057         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3058           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3059             return false;
3060         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3061           if (ShufInst->getMaskValue(i) != -1)
3062             return false;
3063 
3064         // There is only one user of this ShuffleVector instruction, which
3065         // must be a reduction operation.
3066         if (!U->hasOneUse())
3067           return false;
3068 
3069         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3070         if (!U2 || U2->getOpcode() != OpCode)
3071           return false;
3072 
3073         // Check operands of the reduction operation.
3074         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3075             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3076           UsersToVisit.push_back(U2);
3077           ElemNumToReduce /= 2;
3078         } else
3079           return false;
3080       } else if (isa<ExtractElementInst>(U)) {
3081         // At this moment we should have reduced all elements in the vector.
3082         if (ElemNumToReduce != 1)
3083           return false;
3084 
3085         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3086         if (!Val || !Val->isZero())
3087           return false;
3088 
3089         ReduxExtracted = true;
3090       } else
3091         return false;
3092     }
3093   }
3094   return ReduxExtracted;
3095 }
3096 
3097 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3098   SDNodeFlags Flags;
3099 
3100   SDValue Op = getValue(I.getOperand(0));
3101   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3102                                     Op, Flags);
3103   setValue(&I, UnNodeValue);
3104 }
3105 
3106 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3107   SDNodeFlags Flags;
3108   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3109     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3110     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3111   }
3112   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3113     Flags.setExact(ExactOp->isExact());
3114   }
3115   if (isVectorReductionOp(&I)) {
3116     Flags.setVectorReduction(true);
3117     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3118   }
3119 
3120   SDValue Op1 = getValue(I.getOperand(0));
3121   SDValue Op2 = getValue(I.getOperand(1));
3122   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3123                                      Op1, Op2, Flags);
3124   setValue(&I, BinNodeValue);
3125 }
3126 
3127 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3128   SDValue Op1 = getValue(I.getOperand(0));
3129   SDValue Op2 = getValue(I.getOperand(1));
3130 
3131   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3132       Op1.getValueType(), DAG.getDataLayout());
3133 
3134   // Coerce the shift amount to the right type if we can.
3135   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3136     unsigned ShiftSize = ShiftTy.getSizeInBits();
3137     unsigned Op2Size = Op2.getValueSizeInBits();
3138     SDLoc DL = getCurSDLoc();
3139 
3140     // If the operand is smaller than the shift count type, promote it.
3141     if (ShiftSize > Op2Size)
3142       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3143 
3144     // If the operand is larger than the shift count type but the shift
3145     // count type has enough bits to represent any shift value, truncate
3146     // it now. This is a common case and it exposes the truncate to
3147     // optimization early.
3148     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3149       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3150     // Otherwise we'll need to temporarily settle for some other convenient
3151     // type.  Type legalization will make adjustments once the shiftee is split.
3152     else
3153       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3154   }
3155 
3156   bool nuw = false;
3157   bool nsw = false;
3158   bool exact = false;
3159 
3160   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3161 
3162     if (const OverflowingBinaryOperator *OFBinOp =
3163             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3164       nuw = OFBinOp->hasNoUnsignedWrap();
3165       nsw = OFBinOp->hasNoSignedWrap();
3166     }
3167     if (const PossiblyExactOperator *ExactOp =
3168             dyn_cast<const PossiblyExactOperator>(&I))
3169       exact = ExactOp->isExact();
3170   }
3171   SDNodeFlags Flags;
3172   Flags.setExact(exact);
3173   Flags.setNoSignedWrap(nsw);
3174   Flags.setNoUnsignedWrap(nuw);
3175   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3176                             Flags);
3177   setValue(&I, Res);
3178 }
3179 
3180 void SelectionDAGBuilder::visitSDiv(const User &I) {
3181   SDValue Op1 = getValue(I.getOperand(0));
3182   SDValue Op2 = getValue(I.getOperand(1));
3183 
3184   SDNodeFlags Flags;
3185   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3186                  cast<PossiblyExactOperator>(&I)->isExact());
3187   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3188                            Op2, Flags));
3189 }
3190 
3191 void SelectionDAGBuilder::visitICmp(const User &I) {
3192   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3193   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3194     predicate = IC->getPredicate();
3195   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3196     predicate = ICmpInst::Predicate(IC->getPredicate());
3197   SDValue Op1 = getValue(I.getOperand(0));
3198   SDValue Op2 = getValue(I.getOperand(1));
3199   ISD::CondCode Opcode = getICmpCondCode(predicate);
3200 
3201   auto &TLI = DAG.getTargetLoweringInfo();
3202   EVT MemVT =
3203       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3204 
3205   // If a pointer's DAG type is larger than its memory type then the DAG values
3206   // are zero-extended. This breaks signed comparisons so truncate back to the
3207   // underlying type before doing the compare.
3208   if (Op1.getValueType() != MemVT) {
3209     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3210     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3211   }
3212 
3213   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3214                                                         I.getType());
3215   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3216 }
3217 
3218 void SelectionDAGBuilder::visitFCmp(const User &I) {
3219   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3220   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3221     predicate = FC->getPredicate();
3222   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3223     predicate = FCmpInst::Predicate(FC->getPredicate());
3224   SDValue Op1 = getValue(I.getOperand(0));
3225   SDValue Op2 = getValue(I.getOperand(1));
3226 
3227   ISD::CondCode Condition = getFCmpCondCode(predicate);
3228   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3229   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3230     Condition = getFCmpCodeWithoutNaN(Condition);
3231 
3232   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3233                                                         I.getType());
3234   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3235 }
3236 
3237 // Check if the condition of the select has one use or two users that are both
3238 // selects with the same condition.
3239 static bool hasOnlySelectUsers(const Value *Cond) {
3240   return llvm::all_of(Cond->users(), [](const Value *V) {
3241     return isa<SelectInst>(V);
3242   });
3243 }
3244 
3245 void SelectionDAGBuilder::visitSelect(const User &I) {
3246   SmallVector<EVT, 4> ValueVTs;
3247   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3248                   ValueVTs);
3249   unsigned NumValues = ValueVTs.size();
3250   if (NumValues == 0) return;
3251 
3252   SmallVector<SDValue, 4> Values(NumValues);
3253   SDValue Cond     = getValue(I.getOperand(0));
3254   SDValue LHSVal   = getValue(I.getOperand(1));
3255   SDValue RHSVal   = getValue(I.getOperand(2));
3256   auto BaseOps = {Cond};
3257   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3258     ISD::VSELECT : ISD::SELECT;
3259 
3260   bool IsUnaryAbs = false;
3261 
3262   // Min/max matching is only viable if all output VTs are the same.
3263   if (is_splat(ValueVTs)) {
3264     EVT VT = ValueVTs[0];
3265     LLVMContext &Ctx = *DAG.getContext();
3266     auto &TLI = DAG.getTargetLoweringInfo();
3267 
3268     // We care about the legality of the operation after it has been type
3269     // legalized.
3270     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3271            VT != TLI.getTypeToTransformTo(Ctx, VT))
3272       VT = TLI.getTypeToTransformTo(Ctx, VT);
3273 
3274     // If the vselect is legal, assume we want to leave this as a vector setcc +
3275     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3276     // min/max is legal on the scalar type.
3277     bool UseScalarMinMax = VT.isVector() &&
3278       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3279 
3280     Value *LHS, *RHS;
3281     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3282     ISD::NodeType Opc = ISD::DELETED_NODE;
3283     switch (SPR.Flavor) {
3284     case SPF_UMAX:    Opc = ISD::UMAX; break;
3285     case SPF_UMIN:    Opc = ISD::UMIN; break;
3286     case SPF_SMAX:    Opc = ISD::SMAX; break;
3287     case SPF_SMIN:    Opc = ISD::SMIN; break;
3288     case SPF_FMINNUM:
3289       switch (SPR.NaNBehavior) {
3290       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3291       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3292       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3293       case SPNB_RETURNS_ANY: {
3294         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3295           Opc = ISD::FMINNUM;
3296         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3297           Opc = ISD::FMINIMUM;
3298         else if (UseScalarMinMax)
3299           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3300             ISD::FMINNUM : ISD::FMINIMUM;
3301         break;
3302       }
3303       }
3304       break;
3305     case SPF_FMAXNUM:
3306       switch (SPR.NaNBehavior) {
3307       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3308       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3309       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3310       case SPNB_RETURNS_ANY:
3311 
3312         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3313           Opc = ISD::FMAXNUM;
3314         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3315           Opc = ISD::FMAXIMUM;
3316         else if (UseScalarMinMax)
3317           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3318             ISD::FMAXNUM : ISD::FMAXIMUM;
3319         break;
3320       }
3321       break;
3322     case SPF_ABS:
3323       IsUnaryAbs = true;
3324       Opc = ISD::ABS;
3325       break;
3326     case SPF_NABS:
3327       // TODO: we need to produce sub(0, abs(X)).
3328     default: break;
3329     }
3330 
3331     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3332         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3333          (UseScalarMinMax &&
3334           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3335         // If the underlying comparison instruction is used by any other
3336         // instruction, the consumed instructions won't be destroyed, so it is
3337         // not profitable to convert to a min/max.
3338         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3339       OpCode = Opc;
3340       LHSVal = getValue(LHS);
3341       RHSVal = getValue(RHS);
3342       BaseOps = {};
3343     }
3344 
3345     if (IsUnaryAbs) {
3346       OpCode = Opc;
3347       LHSVal = getValue(LHS);
3348       BaseOps = {};
3349     }
3350   }
3351 
3352   if (IsUnaryAbs) {
3353     for (unsigned i = 0; i != NumValues; ++i) {
3354       Values[i] =
3355           DAG.getNode(OpCode, getCurSDLoc(),
3356                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3357                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3358     }
3359   } else {
3360     for (unsigned i = 0; i != NumValues; ++i) {
3361       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3362       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3363       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3364       Values[i] = DAG.getNode(
3365           OpCode, getCurSDLoc(),
3366           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3367     }
3368   }
3369 
3370   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3371                            DAG.getVTList(ValueVTs), Values));
3372 }
3373 
3374 void SelectionDAGBuilder::visitTrunc(const User &I) {
3375   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3376   SDValue N = getValue(I.getOperand(0));
3377   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3378                                                         I.getType());
3379   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3380 }
3381 
3382 void SelectionDAGBuilder::visitZExt(const User &I) {
3383   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3384   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3385   SDValue N = getValue(I.getOperand(0));
3386   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3387                                                         I.getType());
3388   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3389 }
3390 
3391 void SelectionDAGBuilder::visitSExt(const User &I) {
3392   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3393   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3394   SDValue N = getValue(I.getOperand(0));
3395   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3396                                                         I.getType());
3397   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3398 }
3399 
3400 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3401   // FPTrunc is never a no-op cast, no need to check
3402   SDValue N = getValue(I.getOperand(0));
3403   SDLoc dl = getCurSDLoc();
3404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3405   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3406   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3407                            DAG.getTargetConstant(
3408                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3409 }
3410 
3411 void SelectionDAGBuilder::visitFPExt(const User &I) {
3412   // FPExt is never a no-op cast, no need to check
3413   SDValue N = getValue(I.getOperand(0));
3414   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415                                                         I.getType());
3416   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3417 }
3418 
3419 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3420   // FPToUI is never a no-op cast, no need to check
3421   SDValue N = getValue(I.getOperand(0));
3422   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3423                                                         I.getType());
3424   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3425 }
3426 
3427 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3428   // FPToSI is never a no-op cast, no need to check
3429   SDValue N = getValue(I.getOperand(0));
3430   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3431                                                         I.getType());
3432   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3433 }
3434 
3435 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3436   // UIToFP is never a no-op cast, no need to check
3437   SDValue N = getValue(I.getOperand(0));
3438   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3439                                                         I.getType());
3440   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3441 }
3442 
3443 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3444   // SIToFP is never a no-op cast, no need to check
3445   SDValue N = getValue(I.getOperand(0));
3446   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3447                                                         I.getType());
3448   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3449 }
3450 
3451 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3452   // What to do depends on the size of the integer and the size of the pointer.
3453   // We can either truncate, zero extend, or no-op, accordingly.
3454   SDValue N = getValue(I.getOperand(0));
3455   auto &TLI = DAG.getTargetLoweringInfo();
3456   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3457                                                         I.getType());
3458   EVT PtrMemVT =
3459       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3460   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3461   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3462   setValue(&I, N);
3463 }
3464 
3465 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3466   // What to do depends on the size of the integer and the size of the pointer.
3467   // We can either truncate, zero extend, or no-op, accordingly.
3468   SDValue N = getValue(I.getOperand(0));
3469   auto &TLI = DAG.getTargetLoweringInfo();
3470   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3471   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3472   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3473   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3474   setValue(&I, N);
3475 }
3476 
3477 void SelectionDAGBuilder::visitBitCast(const User &I) {
3478   SDValue N = getValue(I.getOperand(0));
3479   SDLoc dl = getCurSDLoc();
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482 
3483   // BitCast assures us that source and destination are the same size so this is
3484   // either a BITCAST or a no-op.
3485   if (DestVT != N.getValueType())
3486     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3487                              DestVT, N)); // convert types.
3488   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3489   // might fold any kind of constant expression to an integer constant and that
3490   // is not what we are looking for. Only recognize a bitcast of a genuine
3491   // constant integer as an opaque constant.
3492   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3493     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3494                                  /*isOpaque*/true));
3495   else
3496     setValue(&I, N);            // noop cast.
3497 }
3498 
3499 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3501   const Value *SV = I.getOperand(0);
3502   SDValue N = getValue(SV);
3503   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3504 
3505   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3506   unsigned DestAS = I.getType()->getPointerAddressSpace();
3507 
3508   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3509     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3510 
3511   setValue(&I, N);
3512 }
3513 
3514 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3516   SDValue InVec = getValue(I.getOperand(0));
3517   SDValue InVal = getValue(I.getOperand(1));
3518   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3519                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3520   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3521                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3522                            InVec, InVal, InIdx));
3523 }
3524 
3525 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3527   SDValue InVec = getValue(I.getOperand(0));
3528   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3529                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3530   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3531                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3532                            InVec, InIdx));
3533 }
3534 
3535 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3536   SDValue Src1 = getValue(I.getOperand(0));
3537   SDValue Src2 = getValue(I.getOperand(1));
3538   SDLoc DL = getCurSDLoc();
3539 
3540   SmallVector<int, 8> Mask;
3541   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3542   unsigned MaskNumElts = Mask.size();
3543 
3544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3545   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3546   EVT SrcVT = Src1.getValueType();
3547   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3548 
3549   if (SrcNumElts == MaskNumElts) {
3550     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3551     return;
3552   }
3553 
3554   // Normalize the shuffle vector since mask and vector length don't match.
3555   if (SrcNumElts < MaskNumElts) {
3556     // Mask is longer than the source vectors. We can use concatenate vector to
3557     // make the mask and vectors lengths match.
3558 
3559     if (MaskNumElts % SrcNumElts == 0) {
3560       // Mask length is a multiple of the source vector length.
3561       // Check if the shuffle is some kind of concatenation of the input
3562       // vectors.
3563       unsigned NumConcat = MaskNumElts / SrcNumElts;
3564       bool IsConcat = true;
3565       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3566       for (unsigned i = 0; i != MaskNumElts; ++i) {
3567         int Idx = Mask[i];
3568         if (Idx < 0)
3569           continue;
3570         // Ensure the indices in each SrcVT sized piece are sequential and that
3571         // the same source is used for the whole piece.
3572         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3573             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3574              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3575           IsConcat = false;
3576           break;
3577         }
3578         // Remember which source this index came from.
3579         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3580       }
3581 
3582       // The shuffle is concatenating multiple vectors together. Just emit
3583       // a CONCAT_VECTORS operation.
3584       if (IsConcat) {
3585         SmallVector<SDValue, 8> ConcatOps;
3586         for (auto Src : ConcatSrcs) {
3587           if (Src < 0)
3588             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3589           else if (Src == 0)
3590             ConcatOps.push_back(Src1);
3591           else
3592             ConcatOps.push_back(Src2);
3593         }
3594         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3595         return;
3596       }
3597     }
3598 
3599     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3600     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3601     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3602                                     PaddedMaskNumElts);
3603 
3604     // Pad both vectors with undefs to make them the same length as the mask.
3605     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3606 
3607     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3608     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3609     MOps1[0] = Src1;
3610     MOps2[0] = Src2;
3611 
3612     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3613     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3614 
3615     // Readjust mask for new input vector length.
3616     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3617     for (unsigned i = 0; i != MaskNumElts; ++i) {
3618       int Idx = Mask[i];
3619       if (Idx >= (int)SrcNumElts)
3620         Idx -= SrcNumElts - PaddedMaskNumElts;
3621       MappedOps[i] = Idx;
3622     }
3623 
3624     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3625 
3626     // If the concatenated vector was padded, extract a subvector with the
3627     // correct number of elements.
3628     if (MaskNumElts != PaddedMaskNumElts)
3629       Result = DAG.getNode(
3630           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3631           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3632 
3633     setValue(&I, Result);
3634     return;
3635   }
3636 
3637   if (SrcNumElts > MaskNumElts) {
3638     // Analyze the access pattern of the vector to see if we can extract
3639     // two subvectors and do the shuffle.
3640     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3641     bool CanExtract = true;
3642     for (int Idx : Mask) {
3643       unsigned Input = 0;
3644       if (Idx < 0)
3645         continue;
3646 
3647       if (Idx >= (int)SrcNumElts) {
3648         Input = 1;
3649         Idx -= SrcNumElts;
3650       }
3651 
3652       // If all the indices come from the same MaskNumElts sized portion of
3653       // the sources we can use extract. Also make sure the extract wouldn't
3654       // extract past the end of the source.
3655       int NewStartIdx = alignDown(Idx, MaskNumElts);
3656       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3657           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3658         CanExtract = false;
3659       // Make sure we always update StartIdx as we use it to track if all
3660       // elements are undef.
3661       StartIdx[Input] = NewStartIdx;
3662     }
3663 
3664     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3665       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3666       return;
3667     }
3668     if (CanExtract) {
3669       // Extract appropriate subvector and generate a vector shuffle
3670       for (unsigned Input = 0; Input < 2; ++Input) {
3671         SDValue &Src = Input == 0 ? Src1 : Src2;
3672         if (StartIdx[Input] < 0)
3673           Src = DAG.getUNDEF(VT);
3674         else {
3675           Src = DAG.getNode(
3676               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3677               DAG.getConstant(StartIdx[Input], DL,
3678                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3679         }
3680       }
3681 
3682       // Calculate new mask.
3683       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3684       for (int &Idx : MappedOps) {
3685         if (Idx >= (int)SrcNumElts)
3686           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3687         else if (Idx >= 0)
3688           Idx -= StartIdx[0];
3689       }
3690 
3691       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3692       return;
3693     }
3694   }
3695 
3696   // We can't use either concat vectors or extract subvectors so fall back to
3697   // replacing the shuffle with extract and build vector.
3698   // to insert and build vector.
3699   EVT EltVT = VT.getVectorElementType();
3700   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3701   SmallVector<SDValue,8> Ops;
3702   for (int Idx : Mask) {
3703     SDValue Res;
3704 
3705     if (Idx < 0) {
3706       Res = DAG.getUNDEF(EltVT);
3707     } else {
3708       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3709       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3710 
3711       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3712                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3713     }
3714 
3715     Ops.push_back(Res);
3716   }
3717 
3718   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3719 }
3720 
3721 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3722   ArrayRef<unsigned> Indices;
3723   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3724     Indices = IV->getIndices();
3725   else
3726     Indices = cast<ConstantExpr>(&I)->getIndices();
3727 
3728   const Value *Op0 = I.getOperand(0);
3729   const Value *Op1 = I.getOperand(1);
3730   Type *AggTy = I.getType();
3731   Type *ValTy = Op1->getType();
3732   bool IntoUndef = isa<UndefValue>(Op0);
3733   bool FromUndef = isa<UndefValue>(Op1);
3734 
3735   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3736 
3737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3738   SmallVector<EVT, 4> AggValueVTs;
3739   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3740   SmallVector<EVT, 4> ValValueVTs;
3741   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3742 
3743   unsigned NumAggValues = AggValueVTs.size();
3744   unsigned NumValValues = ValValueVTs.size();
3745   SmallVector<SDValue, 4> Values(NumAggValues);
3746 
3747   // Ignore an insertvalue that produces an empty object
3748   if (!NumAggValues) {
3749     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3750     return;
3751   }
3752 
3753   SDValue Agg = getValue(Op0);
3754   unsigned i = 0;
3755   // Copy the beginning value(s) from the original aggregate.
3756   for (; i != LinearIndex; ++i)
3757     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3758                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3759   // Copy values from the inserted value(s).
3760   if (NumValValues) {
3761     SDValue Val = getValue(Op1);
3762     for (; i != LinearIndex + NumValValues; ++i)
3763       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3764                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3765   }
3766   // Copy remaining value(s) from the original aggregate.
3767   for (; i != NumAggValues; ++i)
3768     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3769                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3770 
3771   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3772                            DAG.getVTList(AggValueVTs), Values));
3773 }
3774 
3775 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3776   ArrayRef<unsigned> Indices;
3777   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3778     Indices = EV->getIndices();
3779   else
3780     Indices = cast<ConstantExpr>(&I)->getIndices();
3781 
3782   const Value *Op0 = I.getOperand(0);
3783   Type *AggTy = Op0->getType();
3784   Type *ValTy = I.getType();
3785   bool OutOfUndef = isa<UndefValue>(Op0);
3786 
3787   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3788 
3789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3790   SmallVector<EVT, 4> ValValueVTs;
3791   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3792 
3793   unsigned NumValValues = ValValueVTs.size();
3794 
3795   // Ignore a extractvalue that produces an empty object
3796   if (!NumValValues) {
3797     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3798     return;
3799   }
3800 
3801   SmallVector<SDValue, 4> Values(NumValValues);
3802 
3803   SDValue Agg = getValue(Op0);
3804   // Copy out the selected value(s).
3805   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3806     Values[i - LinearIndex] =
3807       OutOfUndef ?
3808         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3809         SDValue(Agg.getNode(), Agg.getResNo() + i);
3810 
3811   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3812                            DAG.getVTList(ValValueVTs), Values));
3813 }
3814 
3815 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3816   Value *Op0 = I.getOperand(0);
3817   // Note that the pointer operand may be a vector of pointers. Take the scalar
3818   // element which holds a pointer.
3819   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3820   SDValue N = getValue(Op0);
3821   SDLoc dl = getCurSDLoc();
3822   auto &TLI = DAG.getTargetLoweringInfo();
3823   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3824   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3825 
3826   // Normalize Vector GEP - all scalar operands should be converted to the
3827   // splat vector.
3828   unsigned VectorWidth = I.getType()->isVectorTy() ?
3829     I.getType()->getVectorNumElements() : 0;
3830 
3831   if (VectorWidth && !N.getValueType().isVector()) {
3832     LLVMContext &Context = *DAG.getContext();
3833     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3834     N = DAG.getSplatBuildVector(VT, dl, N);
3835   }
3836 
3837   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3838        GTI != E; ++GTI) {
3839     const Value *Idx = GTI.getOperand();
3840     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3841       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3842       if (Field) {
3843         // N = N + Offset
3844         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3845 
3846         // In an inbounds GEP with an offset that is nonnegative even when
3847         // interpreted as signed, assume there is no unsigned overflow.
3848         SDNodeFlags Flags;
3849         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3850           Flags.setNoUnsignedWrap(true);
3851 
3852         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3853                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3854       }
3855     } else {
3856       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3857       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3858       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3859 
3860       // If this is a scalar constant or a splat vector of constants,
3861       // handle it quickly.
3862       const auto *C = dyn_cast<Constant>(Idx);
3863       if (C && isa<VectorType>(C->getType()))
3864         C = C->getSplatValue();
3865 
3866       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3867         if (CI->isZero())
3868           continue;
3869         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3870         LLVMContext &Context = *DAG.getContext();
3871         SDValue OffsVal = VectorWidth ?
3872           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3873           DAG.getConstant(Offs, dl, IdxTy);
3874 
3875         // In an inbounds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3882 
3883         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3884         continue;
3885       }
3886 
3887       // N = N + Idx * ElementSize;
3888       SDValue IdxN = getValue(Idx);
3889 
3890       if (!IdxN.getValueType().isVector() && VectorWidth) {
3891         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3892         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3893       }
3894 
3895       // If the index is smaller or larger than intptr_t, truncate or extend
3896       // it.
3897       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3898 
3899       // If this is a multiply by a power of two, turn it into a shl
3900       // immediately.  This is a very common case.
3901       if (ElementSize != 1) {
3902         if (ElementSize.isPowerOf2()) {
3903           unsigned Amt = ElementSize.logBase2();
3904           IdxN = DAG.getNode(ISD::SHL, dl,
3905                              N.getValueType(), IdxN,
3906                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3907         } else {
3908           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3909                                           IdxN.getValueType());
3910           IdxN = DAG.getNode(ISD::MUL, dl,
3911                              N.getValueType(), IdxN, Scale);
3912         }
3913       }
3914 
3915       N = DAG.getNode(ISD::ADD, dl,
3916                       N.getValueType(), N, IdxN);
3917     }
3918   }
3919 
3920   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3921     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3922 
3923   setValue(&I, N);
3924 }
3925 
3926 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3927   // If this is a fixed sized alloca in the entry block of the function,
3928   // allocate it statically on the stack.
3929   if (FuncInfo.StaticAllocaMap.count(&I))
3930     return;   // getValue will auto-populate this.
3931 
3932   SDLoc dl = getCurSDLoc();
3933   Type *Ty = I.getAllocatedType();
3934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3935   auto &DL = DAG.getDataLayout();
3936   uint64_t TySize = DL.getTypeAllocSize(Ty);
3937   unsigned Align =
3938       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3939 
3940   SDValue AllocSize = getValue(I.getArraySize());
3941 
3942   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3943   if (AllocSize.getValueType() != IntPtr)
3944     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3945 
3946   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3947                           AllocSize,
3948                           DAG.getConstant(TySize, dl, IntPtr));
3949 
3950   // Handle alignment.  If the requested alignment is less than or equal to
3951   // the stack alignment, ignore it.  If the size is greater than or equal to
3952   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3953   unsigned StackAlign =
3954       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3955   if (Align <= StackAlign)
3956     Align = 0;
3957 
3958   // Round the size of the allocation up to the stack alignment size
3959   // by add SA-1 to the size. This doesn't overflow because we're computing
3960   // an address inside an alloca.
3961   SDNodeFlags Flags;
3962   Flags.setNoUnsignedWrap(true);
3963   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3964                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3965 
3966   // Mask out the low bits for alignment purposes.
3967   AllocSize =
3968       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3969                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3970 
3971   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3972   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3973   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3974   setValue(&I, DSA);
3975   DAG.setRoot(DSA.getValue(1));
3976 
3977   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3978 }
3979 
3980 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3981   if (I.isAtomic())
3982     return visitAtomicLoad(I);
3983 
3984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985   const Value *SV = I.getOperand(0);
3986   if (TLI.supportSwiftError()) {
3987     // Swifterror values can come from either a function parameter with
3988     // swifterror attribute or an alloca with swifterror attribute.
3989     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3990       if (Arg->hasSwiftErrorAttr())
3991         return visitLoadFromSwiftError(I);
3992     }
3993 
3994     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3995       if (Alloca->isSwiftError())
3996         return visitLoadFromSwiftError(I);
3997     }
3998   }
3999 
4000   SDValue Ptr = getValue(SV);
4001 
4002   Type *Ty = I.getType();
4003 
4004   bool isVolatile = I.isVolatile();
4005   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4006   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4007   bool isDereferenceable =
4008       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4009   unsigned Alignment = I.getAlignment();
4010 
4011   AAMDNodes AAInfo;
4012   I.getAAMetadata(AAInfo);
4013   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4014 
4015   SmallVector<EVT, 4> ValueVTs, MemVTs;
4016   SmallVector<uint64_t, 4> Offsets;
4017   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4018   unsigned NumValues = ValueVTs.size();
4019   if (NumValues == 0)
4020     return;
4021 
4022   SDValue Root;
4023   bool ConstantMemory = false;
4024   if (isVolatile || NumValues > MaxParallelChains)
4025     // Serialize volatile loads with other side effects.
4026     Root = getRoot();
4027   else if (AA &&
4028            AA->pointsToConstantMemory(MemoryLocation(
4029                SV,
4030                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4031                AAInfo))) {
4032     // Do not serialize (non-volatile) loads of constant memory with anything.
4033     Root = DAG.getEntryNode();
4034     ConstantMemory = true;
4035   } else {
4036     // Do not serialize non-volatile loads against each other.
4037     Root = DAG.getRoot();
4038   }
4039 
4040   SDLoc dl = getCurSDLoc();
4041 
4042   if (isVolatile)
4043     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4044 
4045   // An aggregate load cannot wrap around the address space, so offsets to its
4046   // parts don't wrap either.
4047   SDNodeFlags Flags;
4048   Flags.setNoUnsignedWrap(true);
4049 
4050   SmallVector<SDValue, 4> Values(NumValues);
4051   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4052   EVT PtrVT = Ptr.getValueType();
4053   unsigned ChainI = 0;
4054   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4055     // Serializing loads here may result in excessive register pressure, and
4056     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4057     // could recover a bit by hoisting nodes upward in the chain by recognizing
4058     // they are side-effect free or do not alias. The optimizer should really
4059     // avoid this case by converting large object/array copies to llvm.memcpy
4060     // (MaxParallelChains should always remain as failsafe).
4061     if (ChainI == MaxParallelChains) {
4062       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4063       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4064                                   makeArrayRef(Chains.data(), ChainI));
4065       Root = Chain;
4066       ChainI = 0;
4067     }
4068     SDValue A = DAG.getNode(ISD::ADD, dl,
4069                             PtrVT, Ptr,
4070                             DAG.getConstant(Offsets[i], dl, PtrVT),
4071                             Flags);
4072     auto MMOFlags = MachineMemOperand::MONone;
4073     if (isVolatile)
4074       MMOFlags |= MachineMemOperand::MOVolatile;
4075     if (isNonTemporal)
4076       MMOFlags |= MachineMemOperand::MONonTemporal;
4077     if (isInvariant)
4078       MMOFlags |= MachineMemOperand::MOInvariant;
4079     if (isDereferenceable)
4080       MMOFlags |= MachineMemOperand::MODereferenceable;
4081     MMOFlags |= TLI.getMMOFlags(I);
4082 
4083     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4084                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4085                             MMOFlags, AAInfo, Ranges);
4086     Chains[ChainI] = L.getValue(1);
4087 
4088     if (MemVTs[i] != ValueVTs[i])
4089       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4090 
4091     Values[i] = L;
4092   }
4093 
4094   if (!ConstantMemory) {
4095     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4096                                 makeArrayRef(Chains.data(), ChainI));
4097     if (isVolatile)
4098       DAG.setRoot(Chain);
4099     else
4100       PendingLoads.push_back(Chain);
4101   }
4102 
4103   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4104                            DAG.getVTList(ValueVTs), Values));
4105 }
4106 
4107 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4108   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4109          "call visitStoreToSwiftError when backend supports swifterror");
4110 
4111   SmallVector<EVT, 4> ValueVTs;
4112   SmallVector<uint64_t, 4> Offsets;
4113   const Value *SrcV = I.getOperand(0);
4114   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4115                   SrcV->getType(), ValueVTs, &Offsets);
4116   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4117          "expect a single EVT for swifterror");
4118 
4119   SDValue Src = getValue(SrcV);
4120   // Create a virtual register, then update the virtual register.
4121   Register VReg =
4122       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4123   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4124   // Chain can be getRoot or getControlRoot.
4125   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4126                                       SDValue(Src.getNode(), Src.getResNo()));
4127   DAG.setRoot(CopyNode);
4128 }
4129 
4130 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4131   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4132          "call visitLoadFromSwiftError when backend supports swifterror");
4133 
4134   assert(!I.isVolatile() &&
4135          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4136          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4137          "Support volatile, non temporal, invariant for load_from_swift_error");
4138 
4139   const Value *SV = I.getOperand(0);
4140   Type *Ty = I.getType();
4141   AAMDNodes AAInfo;
4142   I.getAAMetadata(AAInfo);
4143   assert(
4144       (!AA ||
4145        !AA->pointsToConstantMemory(MemoryLocation(
4146            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4147            AAInfo))) &&
4148       "load_from_swift_error should not be constant memory");
4149 
4150   SmallVector<EVT, 4> ValueVTs;
4151   SmallVector<uint64_t, 4> Offsets;
4152   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4153                   ValueVTs, &Offsets);
4154   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4155          "expect a single EVT for swifterror");
4156 
4157   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4158   SDValue L = DAG.getCopyFromReg(
4159       getRoot(), getCurSDLoc(),
4160       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4161 
4162   setValue(&I, L);
4163 }
4164 
4165 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4166   if (I.isAtomic())
4167     return visitAtomicStore(I);
4168 
4169   const Value *SrcV = I.getOperand(0);
4170   const Value *PtrV = I.getOperand(1);
4171 
4172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4173   if (TLI.supportSwiftError()) {
4174     // Swifterror values can come from either a function parameter with
4175     // swifterror attribute or an alloca with swifterror attribute.
4176     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4177       if (Arg->hasSwiftErrorAttr())
4178         return visitStoreToSwiftError(I);
4179     }
4180 
4181     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4182       if (Alloca->isSwiftError())
4183         return visitStoreToSwiftError(I);
4184     }
4185   }
4186 
4187   SmallVector<EVT, 4> ValueVTs, MemVTs;
4188   SmallVector<uint64_t, 4> Offsets;
4189   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4190                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4191   unsigned NumValues = ValueVTs.size();
4192   if (NumValues == 0)
4193     return;
4194 
4195   // Get the lowered operands. Note that we do this after
4196   // checking if NumResults is zero, because with zero results
4197   // the operands won't have values in the map.
4198   SDValue Src = getValue(SrcV);
4199   SDValue Ptr = getValue(PtrV);
4200 
4201   SDValue Root = getRoot();
4202   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4203   SDLoc dl = getCurSDLoc();
4204   EVT PtrVT = Ptr.getValueType();
4205   unsigned Alignment = I.getAlignment();
4206   AAMDNodes AAInfo;
4207   I.getAAMetadata(AAInfo);
4208 
4209   auto MMOFlags = MachineMemOperand::MONone;
4210   if (I.isVolatile())
4211     MMOFlags |= MachineMemOperand::MOVolatile;
4212   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4213     MMOFlags |= MachineMemOperand::MONonTemporal;
4214   MMOFlags |= TLI.getMMOFlags(I);
4215 
4216   // An aggregate load cannot wrap around the address space, so offsets to its
4217   // parts don't wrap either.
4218   SDNodeFlags Flags;
4219   Flags.setNoUnsignedWrap(true);
4220 
4221   unsigned ChainI = 0;
4222   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4223     // See visitLoad comments.
4224     if (ChainI == MaxParallelChains) {
4225       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4226                                   makeArrayRef(Chains.data(), ChainI));
4227       Root = Chain;
4228       ChainI = 0;
4229     }
4230     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4231                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4232     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4233     if (MemVTs[i] != ValueVTs[i])
4234       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4235     SDValue St =
4236         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4237                      Alignment, MMOFlags, AAInfo);
4238     Chains[ChainI] = St;
4239   }
4240 
4241   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4242                                   makeArrayRef(Chains.data(), ChainI));
4243   DAG.setRoot(StoreNode);
4244 }
4245 
4246 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4247                                            bool IsCompressing) {
4248   SDLoc sdl = getCurSDLoc();
4249 
4250   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4251                            unsigned& Alignment) {
4252     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4253     Src0 = I.getArgOperand(0);
4254     Ptr = I.getArgOperand(1);
4255     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4256     Mask = I.getArgOperand(3);
4257   };
4258   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4259                            unsigned& Alignment) {
4260     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4261     Src0 = I.getArgOperand(0);
4262     Ptr = I.getArgOperand(1);
4263     Mask = I.getArgOperand(2);
4264     Alignment = 0;
4265   };
4266 
4267   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4268   unsigned Alignment;
4269   if (IsCompressing)
4270     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4271   else
4272     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4273 
4274   SDValue Ptr = getValue(PtrOperand);
4275   SDValue Src0 = getValue(Src0Operand);
4276   SDValue Mask = getValue(MaskOperand);
4277 
4278   EVT VT = Src0.getValueType();
4279   if (!Alignment)
4280     Alignment = DAG.getEVTAlignment(VT);
4281 
4282   AAMDNodes AAInfo;
4283   I.getAAMetadata(AAInfo);
4284 
4285   MachineMemOperand *MMO =
4286     DAG.getMachineFunction().
4287     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4288                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4289                           Alignment, AAInfo);
4290   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4291                                          MMO, false /* Truncating */,
4292                                          IsCompressing);
4293   DAG.setRoot(StoreNode);
4294   setValue(&I, StoreNode);
4295 }
4296 
4297 // Get a uniform base for the Gather/Scatter intrinsic.
4298 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4299 // We try to represent it as a base pointer + vector of indices.
4300 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4301 // The first operand of the GEP may be a single pointer or a vector of pointers
4302 // Example:
4303 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4304 //  or
4305 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4306 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4307 //
4308 // When the first GEP operand is a single pointer - it is the uniform base we
4309 // are looking for. If first operand of the GEP is a splat vector - we
4310 // extract the splat value and use it as a uniform base.
4311 // In all other cases the function returns 'false'.
4312 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4313                            ISD::MemIndexType &IndexType, SDValue &Scale,
4314                            SelectionDAGBuilder *SDB) {
4315   SelectionDAG& DAG = SDB->DAG;
4316   LLVMContext &Context = *DAG.getContext();
4317 
4318   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4319   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4320   if (!GEP)
4321     return false;
4322 
4323   const Value *GEPPtr = GEP->getPointerOperand();
4324   if (!GEPPtr->getType()->isVectorTy())
4325     Ptr = GEPPtr;
4326   else if (!(Ptr = getSplatValue(GEPPtr)))
4327     return false;
4328 
4329   unsigned FinalIndex = GEP->getNumOperands() - 1;
4330   Value *IndexVal = GEP->getOperand(FinalIndex);
4331 
4332   // Ensure all the other indices are 0.
4333   for (unsigned i = 1; i < FinalIndex; ++i) {
4334     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4335     if (!C)
4336       return false;
4337     if (isa<VectorType>(C->getType()))
4338       C = C->getSplatValue();
4339     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4340     if (!CI || !CI->isZero())
4341       return false;
4342   }
4343 
4344   // The operands of the GEP may be defined in another basic block.
4345   // In this case we'll not find nodes for the operands.
4346   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4347     return false;
4348 
4349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4350   const DataLayout &DL = DAG.getDataLayout();
4351   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4352                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4353   Base = SDB->getValue(Ptr);
4354   Index = SDB->getValue(IndexVal);
4355   IndexType = ISD::SIGNED_SCALED;
4356 
4357   if (!Index.getValueType().isVector()) {
4358     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4359     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4360     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4361   }
4362   return true;
4363 }
4364 
4365 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4366   SDLoc sdl = getCurSDLoc();
4367 
4368   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4369   const Value *Ptr = I.getArgOperand(1);
4370   SDValue Src0 = getValue(I.getArgOperand(0));
4371   SDValue Mask = getValue(I.getArgOperand(3));
4372   EVT VT = Src0.getValueType();
4373   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4374   if (!Alignment)
4375     Alignment = DAG.getEVTAlignment(VT);
4376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4377 
4378   AAMDNodes AAInfo;
4379   I.getAAMetadata(AAInfo);
4380 
4381   SDValue Base;
4382   SDValue Index;
4383   ISD::MemIndexType IndexType;
4384   SDValue Scale;
4385   const Value *BasePtr = Ptr;
4386   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4387                                     this);
4388 
4389   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4390   MachineMemOperand *MMO = DAG.getMachineFunction().
4391     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4392                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4393                          Alignment, AAInfo);
4394   if (!UniformBase) {
4395     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4396     Index = getValue(Ptr);
4397     IndexType = ISD::SIGNED_SCALED;
4398     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4399   }
4400   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4401   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4402                                          Ops, MMO, IndexType);
4403   DAG.setRoot(Scatter);
4404   setValue(&I, Scatter);
4405 }
4406 
4407 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4408   SDLoc sdl = getCurSDLoc();
4409 
4410   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4411                            unsigned& Alignment) {
4412     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4413     Ptr = I.getArgOperand(0);
4414     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4415     Mask = I.getArgOperand(2);
4416     Src0 = I.getArgOperand(3);
4417   };
4418   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4419                            unsigned& Alignment) {
4420     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4421     Ptr = I.getArgOperand(0);
4422     Alignment = 0;
4423     Mask = I.getArgOperand(1);
4424     Src0 = I.getArgOperand(2);
4425   };
4426 
4427   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4428   unsigned Alignment;
4429   if (IsExpanding)
4430     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4431   else
4432     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4433 
4434   SDValue Ptr = getValue(PtrOperand);
4435   SDValue Src0 = getValue(Src0Operand);
4436   SDValue Mask = getValue(MaskOperand);
4437 
4438   EVT VT = Src0.getValueType();
4439   if (!Alignment)
4440     Alignment = DAG.getEVTAlignment(VT);
4441 
4442   AAMDNodes AAInfo;
4443   I.getAAMetadata(AAInfo);
4444   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4445 
4446   // Do not serialize masked loads of constant memory with anything.
4447   bool AddToChain =
4448       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4449                  PtrOperand,
4450                  LocationSize::precise(
4451                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4452                  AAInfo));
4453   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4454 
4455   MachineMemOperand *MMO =
4456     DAG.getMachineFunction().
4457     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4458                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4459                           Alignment, AAInfo, Ranges);
4460 
4461   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4462                                    ISD::NON_EXTLOAD, IsExpanding);
4463   if (AddToChain)
4464     PendingLoads.push_back(Load.getValue(1));
4465   setValue(&I, Load);
4466 }
4467 
4468 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4469   SDLoc sdl = getCurSDLoc();
4470 
4471   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4472   const Value *Ptr = I.getArgOperand(0);
4473   SDValue Src0 = getValue(I.getArgOperand(3));
4474   SDValue Mask = getValue(I.getArgOperand(2));
4475 
4476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4477   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4478   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4479   if (!Alignment)
4480     Alignment = DAG.getEVTAlignment(VT);
4481 
4482   AAMDNodes AAInfo;
4483   I.getAAMetadata(AAInfo);
4484   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4485 
4486   SDValue Root = DAG.getRoot();
4487   SDValue Base;
4488   SDValue Index;
4489   ISD::MemIndexType IndexType;
4490   SDValue Scale;
4491   const Value *BasePtr = Ptr;
4492   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4493                                     this);
4494   bool ConstantMemory = false;
4495   if (UniformBase && AA &&
4496       AA->pointsToConstantMemory(
4497           MemoryLocation(BasePtr,
4498                          LocationSize::precise(
4499                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4500                          AAInfo))) {
4501     // Do not serialize (non-volatile) loads of constant memory with anything.
4502     Root = DAG.getEntryNode();
4503     ConstantMemory = true;
4504   }
4505 
4506   MachineMemOperand *MMO =
4507     DAG.getMachineFunction().
4508     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4509                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4510                          Alignment, AAInfo, Ranges);
4511 
4512   if (!UniformBase) {
4513     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4514     Index = getValue(Ptr);
4515     IndexType = ISD::SIGNED_SCALED;
4516     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4517   }
4518   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4519   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4520                                        Ops, MMO, IndexType);
4521 
4522   SDValue OutChain = Gather.getValue(1);
4523   if (!ConstantMemory)
4524     PendingLoads.push_back(OutChain);
4525   setValue(&I, Gather);
4526 }
4527 
4528 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4529   SDLoc dl = getCurSDLoc();
4530   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4531   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4532   SyncScope::ID SSID = I.getSyncScopeID();
4533 
4534   SDValue InChain = getRoot();
4535 
4536   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4537   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4538 
4539   auto Alignment = DAG.getEVTAlignment(MemVT);
4540 
4541   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4542   if (I.isVolatile())
4543     Flags |= MachineMemOperand::MOVolatile;
4544   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4545 
4546   MachineFunction &MF = DAG.getMachineFunction();
4547   MachineMemOperand *MMO =
4548     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4549                             Flags, MemVT.getStoreSize(), Alignment,
4550                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4551                             FailureOrdering);
4552 
4553   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4554                                    dl, MemVT, VTs, InChain,
4555                                    getValue(I.getPointerOperand()),
4556                                    getValue(I.getCompareOperand()),
4557                                    getValue(I.getNewValOperand()), MMO);
4558 
4559   SDValue OutChain = L.getValue(2);
4560 
4561   setValue(&I, L);
4562   DAG.setRoot(OutChain);
4563 }
4564 
4565 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4566   SDLoc dl = getCurSDLoc();
4567   ISD::NodeType NT;
4568   switch (I.getOperation()) {
4569   default: llvm_unreachable("Unknown atomicrmw operation");
4570   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4571   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4572   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4573   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4574   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4575   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4576   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4577   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4578   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4579   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4580   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4581   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4582   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4583   }
4584   AtomicOrdering Ordering = I.getOrdering();
4585   SyncScope::ID SSID = I.getSyncScopeID();
4586 
4587   SDValue InChain = getRoot();
4588 
4589   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4590   auto Alignment = DAG.getEVTAlignment(MemVT);
4591 
4592   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4593   if (I.isVolatile())
4594     Flags |= MachineMemOperand::MOVolatile;
4595   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4596 
4597   MachineFunction &MF = DAG.getMachineFunction();
4598   MachineMemOperand *MMO =
4599     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4600                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4601                             nullptr, SSID, Ordering);
4602 
4603   SDValue L =
4604     DAG.getAtomic(NT, dl, MemVT, InChain,
4605                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4606                   MMO);
4607 
4608   SDValue OutChain = L.getValue(1);
4609 
4610   setValue(&I, L);
4611   DAG.setRoot(OutChain);
4612 }
4613 
4614 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4615   SDLoc dl = getCurSDLoc();
4616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4617   SDValue Ops[3];
4618   Ops[0] = getRoot();
4619   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4620                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4621   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4622                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4623   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4624 }
4625 
4626 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4627   SDLoc dl = getCurSDLoc();
4628   AtomicOrdering Order = I.getOrdering();
4629   SyncScope::ID SSID = I.getSyncScopeID();
4630 
4631   SDValue InChain = getRoot();
4632 
4633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4634   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4635   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4636 
4637   if (!TLI.supportsUnalignedAtomics() &&
4638       I.getAlignment() < MemVT.getSizeInBits() / 8)
4639     report_fatal_error("Cannot generate unaligned atomic load");
4640 
4641   auto Flags = MachineMemOperand::MOLoad;
4642   if (I.isVolatile())
4643     Flags |= MachineMemOperand::MOVolatile;
4644   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4645     Flags |= MachineMemOperand::MOInvariant;
4646   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4647                                DAG.getDataLayout()))
4648     Flags |= MachineMemOperand::MODereferenceable;
4649 
4650   Flags |= TLI.getMMOFlags(I);
4651 
4652   MachineMemOperand *MMO =
4653       DAG.getMachineFunction().
4654       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4655                            Flags, MemVT.getStoreSize(),
4656                            I.getAlignment() ? I.getAlignment() :
4657                                               DAG.getEVTAlignment(MemVT),
4658                            AAMDNodes(), nullptr, SSID, Order);
4659 
4660   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4661 
4662   SDValue Ptr = getValue(I.getPointerOperand());
4663 
4664   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4665     // TODO: Once this is better exercised by tests, it should be merged with
4666     // the normal path for loads to prevent future divergence.
4667     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4668     if (MemVT != VT)
4669       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4670 
4671     setValue(&I, L);
4672     if (!I.isUnordered()) {
4673       SDValue OutChain = L.getValue(1);
4674       DAG.setRoot(OutChain);
4675     }
4676     return;
4677   }
4678 
4679   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4680                             Ptr, MMO);
4681 
4682   SDValue OutChain = L.getValue(1);
4683   if (MemVT != VT)
4684     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4685 
4686   setValue(&I, L);
4687   DAG.setRoot(OutChain);
4688 }
4689 
4690 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4691   SDLoc dl = getCurSDLoc();
4692 
4693   AtomicOrdering Ordering = I.getOrdering();
4694   SyncScope::ID SSID = I.getSyncScopeID();
4695 
4696   SDValue InChain = getRoot();
4697 
4698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4699   EVT MemVT =
4700       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4701 
4702   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4703     report_fatal_error("Cannot generate unaligned atomic store");
4704 
4705   auto Flags = MachineMemOperand::MOStore;
4706   if (I.isVolatile())
4707     Flags |= MachineMemOperand::MOVolatile;
4708   Flags |= TLI.getMMOFlags(I);
4709 
4710   MachineFunction &MF = DAG.getMachineFunction();
4711   MachineMemOperand *MMO =
4712     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4713                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4714                             nullptr, SSID, Ordering);
4715 
4716   SDValue Val = getValue(I.getValueOperand());
4717   if (Val.getValueType() != MemVT)
4718     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4719   SDValue Ptr = getValue(I.getPointerOperand());
4720 
4721   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4722     // TODO: Once this is better exercised by tests, it should be merged with
4723     // the normal path for stores to prevent future divergence.
4724     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4725     DAG.setRoot(S);
4726     return;
4727   }
4728   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4729                                    Ptr, Val, MMO);
4730 
4731 
4732   DAG.setRoot(OutChain);
4733 }
4734 
4735 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4736 /// node.
4737 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4738                                                unsigned Intrinsic) {
4739   // Ignore the callsite's attributes. A specific call site may be marked with
4740   // readnone, but the lowering code will expect the chain based on the
4741   // definition.
4742   const Function *F = I.getCalledFunction();
4743   bool HasChain = !F->doesNotAccessMemory();
4744   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4745 
4746   // Build the operand list.
4747   SmallVector<SDValue, 8> Ops;
4748   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4749     if (OnlyLoad) {
4750       // We don't need to serialize loads against other loads.
4751       Ops.push_back(DAG.getRoot());
4752     } else {
4753       Ops.push_back(getRoot());
4754     }
4755   }
4756 
4757   // Info is set by getTgtMemInstrinsic
4758   TargetLowering::IntrinsicInfo Info;
4759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4760   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4761                                                DAG.getMachineFunction(),
4762                                                Intrinsic);
4763 
4764   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4765   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4766       Info.opc == ISD::INTRINSIC_W_CHAIN)
4767     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4768                                         TLI.getPointerTy(DAG.getDataLayout())));
4769 
4770   // Add all operands of the call to the operand list.
4771   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4772     SDValue Op = getValue(I.getArgOperand(i));
4773     Ops.push_back(Op);
4774   }
4775 
4776   SmallVector<EVT, 4> ValueVTs;
4777   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4778 
4779   if (HasChain)
4780     ValueVTs.push_back(MVT::Other);
4781 
4782   SDVTList VTs = DAG.getVTList(ValueVTs);
4783 
4784   // Create the node.
4785   SDValue Result;
4786   if (IsTgtIntrinsic) {
4787     // This is target intrinsic that touches memory
4788     AAMDNodes AAInfo;
4789     I.getAAMetadata(AAInfo);
4790     Result = DAG.getMemIntrinsicNode(
4791         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4792         MachinePointerInfo(Info.ptrVal, Info.offset),
4793         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4794   } else if (!HasChain) {
4795     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4796   } else if (!I.getType()->isVoidTy()) {
4797     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4798   } else {
4799     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4800   }
4801 
4802   if (HasChain) {
4803     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4804     if (OnlyLoad)
4805       PendingLoads.push_back(Chain);
4806     else
4807       DAG.setRoot(Chain);
4808   }
4809 
4810   if (!I.getType()->isVoidTy()) {
4811     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4812       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4813       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4814     } else
4815       Result = lowerRangeToAssertZExt(DAG, I, Result);
4816 
4817     setValue(&I, Result);
4818   }
4819 }
4820 
4821 /// GetSignificand - Get the significand and build it into a floating-point
4822 /// number with exponent of 1:
4823 ///
4824 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4825 ///
4826 /// where Op is the hexadecimal representation of floating point value.
4827 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4828   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4829                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4830   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4831                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4832   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4833 }
4834 
4835 /// GetExponent - Get the exponent:
4836 ///
4837 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4838 ///
4839 /// where Op is the hexadecimal representation of floating point value.
4840 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4841                            const TargetLowering &TLI, const SDLoc &dl) {
4842   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4843                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4844   SDValue t1 = DAG.getNode(
4845       ISD::SRL, dl, MVT::i32, t0,
4846       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4847   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4848                            DAG.getConstant(127, dl, MVT::i32));
4849   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4850 }
4851 
4852 /// getF32Constant - Get 32-bit floating point constant.
4853 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4854                               const SDLoc &dl) {
4855   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4856                            MVT::f32);
4857 }
4858 
4859 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4860                                        SelectionDAG &DAG) {
4861   // TODO: What fast-math-flags should be set on the floating-point nodes?
4862 
4863   //   IntegerPartOfX = ((int32_t)(t0);
4864   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4865 
4866   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4867   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4868   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4869 
4870   //   IntegerPartOfX <<= 23;
4871   IntegerPartOfX = DAG.getNode(
4872       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4873       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4874                                   DAG.getDataLayout())));
4875 
4876   SDValue TwoToFractionalPartOfX;
4877   if (LimitFloatPrecision <= 6) {
4878     // For floating-point precision of 6:
4879     //
4880     //   TwoToFractionalPartOfX =
4881     //     0.997535578f +
4882     //       (0.735607626f + 0.252464424f * x) * x;
4883     //
4884     // error 0.0144103317, which is 6 bits
4885     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4886                              getF32Constant(DAG, 0x3e814304, dl));
4887     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4888                              getF32Constant(DAG, 0x3f3c50c8, dl));
4889     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4890     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4891                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4892   } else if (LimitFloatPrecision <= 12) {
4893     // For floating-point precision of 12:
4894     //
4895     //   TwoToFractionalPartOfX =
4896     //     0.999892986f +
4897     //       (0.696457318f +
4898     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4899     //
4900     // error 0.000107046256, which is 13 to 14 bits
4901     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4902                              getF32Constant(DAG, 0x3da235e3, dl));
4903     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4904                              getF32Constant(DAG, 0x3e65b8f3, dl));
4905     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4906     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4907                              getF32Constant(DAG, 0x3f324b07, dl));
4908     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4909     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4910                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4911   } else { // LimitFloatPrecision <= 18
4912     // For floating-point precision of 18:
4913     //
4914     //   TwoToFractionalPartOfX =
4915     //     0.999999982f +
4916     //       (0.693148872f +
4917     //         (0.240227044f +
4918     //           (0.554906021e-1f +
4919     //             (0.961591928e-2f +
4920     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4921     // error 2.47208000*10^(-7), which is better than 18 bits
4922     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4923                              getF32Constant(DAG, 0x3924b03e, dl));
4924     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4925                              getF32Constant(DAG, 0x3ab24b87, dl));
4926     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4927     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4928                              getF32Constant(DAG, 0x3c1d8c17, dl));
4929     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4930     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4931                              getF32Constant(DAG, 0x3d634a1d, dl));
4932     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4933     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4934                              getF32Constant(DAG, 0x3e75fe14, dl));
4935     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4936     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4937                               getF32Constant(DAG, 0x3f317234, dl));
4938     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4939     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4940                                          getF32Constant(DAG, 0x3f800000, dl));
4941   }
4942 
4943   // Add the exponent into the result in integer domain.
4944   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4945   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4946                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4947 }
4948 
4949 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4950 /// limited-precision mode.
4951 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4952                          const TargetLowering &TLI) {
4953   if (Op.getValueType() == MVT::f32 &&
4954       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4955 
4956     // Put the exponent in the right bit position for later addition to the
4957     // final result:
4958     //
4959     //   #define LOG2OFe 1.4426950f
4960     //   t0 = Op * LOG2OFe
4961 
4962     // TODO: What fast-math-flags should be set here?
4963     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4964                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4965     return getLimitedPrecisionExp2(t0, dl, DAG);
4966   }
4967 
4968   // No special expansion.
4969   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4970 }
4971 
4972 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4973 /// limited-precision mode.
4974 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4975                          const TargetLowering &TLI) {
4976   // TODO: What fast-math-flags should be set on the floating-point nodes?
4977 
4978   if (Op.getValueType() == MVT::f32 &&
4979       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4980     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4981 
4982     // Scale the exponent by log(2) [0.69314718f].
4983     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4984     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4985                                         getF32Constant(DAG, 0x3f317218, dl));
4986 
4987     // Get the significand and build it into a floating-point number with
4988     // exponent of 1.
4989     SDValue X = GetSignificand(DAG, Op1, dl);
4990 
4991     SDValue LogOfMantissa;
4992     if (LimitFloatPrecision <= 6) {
4993       // For floating-point precision of 6:
4994       //
4995       //   LogofMantissa =
4996       //     -1.1609546f +
4997       //       (1.4034025f - 0.23903021f * x) * x;
4998       //
4999       // error 0.0034276066, which is better than 8 bits
5000       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5001                                getF32Constant(DAG, 0xbe74c456, dl));
5002       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5003                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5004       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5005       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5006                                   getF32Constant(DAG, 0x3f949a29, dl));
5007     } else if (LimitFloatPrecision <= 12) {
5008       // For floating-point precision of 12:
5009       //
5010       //   LogOfMantissa =
5011       //     -1.7417939f +
5012       //       (2.8212026f +
5013       //         (-1.4699568f +
5014       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5015       //
5016       // error 0.000061011436, which is 14 bits
5017       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5018                                getF32Constant(DAG, 0xbd67b6d6, dl));
5019       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5020                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5021       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5022       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5023                                getF32Constant(DAG, 0x3fbc278b, dl));
5024       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5025       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5026                                getF32Constant(DAG, 0x40348e95, dl));
5027       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5028       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5029                                   getF32Constant(DAG, 0x3fdef31a, dl));
5030     } else { // LimitFloatPrecision <= 18
5031       // For floating-point precision of 18:
5032       //
5033       //   LogOfMantissa =
5034       //     -2.1072184f +
5035       //       (4.2372794f +
5036       //         (-3.7029485f +
5037       //           (2.2781945f +
5038       //             (-0.87823314f +
5039       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5040       //
5041       // error 0.0000023660568, which is better than 18 bits
5042       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5043                                getF32Constant(DAG, 0xbc91e5ac, dl));
5044       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5045                                getF32Constant(DAG, 0x3e4350aa, dl));
5046       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5047       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5048                                getF32Constant(DAG, 0x3f60d3e3, dl));
5049       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5050       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5051                                getF32Constant(DAG, 0x4011cdf0, dl));
5052       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5053       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5054                                getF32Constant(DAG, 0x406cfd1c, dl));
5055       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5056       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5057                                getF32Constant(DAG, 0x408797cb, dl));
5058       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5059       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5060                                   getF32Constant(DAG, 0x4006dcab, dl));
5061     }
5062 
5063     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5064   }
5065 
5066   // No special expansion.
5067   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5068 }
5069 
5070 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5071 /// limited-precision mode.
5072 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5073                           const TargetLowering &TLI) {
5074   // TODO: What fast-math-flags should be set on the floating-point nodes?
5075 
5076   if (Op.getValueType() == MVT::f32 &&
5077       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5078     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5079 
5080     // Get the exponent.
5081     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5082 
5083     // Get the significand and build it into a floating-point number with
5084     // exponent of 1.
5085     SDValue X = GetSignificand(DAG, Op1, dl);
5086 
5087     // Different possible minimax approximations of significand in
5088     // floating-point for various degrees of accuracy over [1,2].
5089     SDValue Log2ofMantissa;
5090     if (LimitFloatPrecision <= 6) {
5091       // For floating-point precision of 6:
5092       //
5093       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5094       //
5095       // error 0.0049451742, which is more than 7 bits
5096       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5097                                getF32Constant(DAG, 0xbeb08fe0, dl));
5098       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5099                                getF32Constant(DAG, 0x40019463, dl));
5100       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5101       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5102                                    getF32Constant(DAG, 0x3fd6633d, dl));
5103     } else if (LimitFloatPrecision <= 12) {
5104       // For floating-point precision of 12:
5105       //
5106       //   Log2ofMantissa =
5107       //     -2.51285454f +
5108       //       (4.07009056f +
5109       //         (-2.12067489f +
5110       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5111       //
5112       // error 0.0000876136000, which is better than 13 bits
5113       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5114                                getF32Constant(DAG, 0xbda7262e, dl));
5115       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5116                                getF32Constant(DAG, 0x3f25280b, dl));
5117       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5118       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5119                                getF32Constant(DAG, 0x4007b923, dl));
5120       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5121       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5122                                getF32Constant(DAG, 0x40823e2f, dl));
5123       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5124       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5125                                    getF32Constant(DAG, 0x4020d29c, dl));
5126     } else { // LimitFloatPrecision <= 18
5127       // For floating-point precision of 18:
5128       //
5129       //   Log2ofMantissa =
5130       //     -3.0400495f +
5131       //       (6.1129976f +
5132       //         (-5.3420409f +
5133       //           (3.2865683f +
5134       //             (-1.2669343f +
5135       //               (0.27515199f -
5136       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5137       //
5138       // error 0.0000018516, which is better than 18 bits
5139       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5140                                getF32Constant(DAG, 0xbcd2769e, dl));
5141       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5142                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5143       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5144       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5145                                getF32Constant(DAG, 0x3fa22ae7, dl));
5146       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5147       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5148                                getF32Constant(DAG, 0x40525723, dl));
5149       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5150       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5151                                getF32Constant(DAG, 0x40aaf200, dl));
5152       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5153       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5154                                getF32Constant(DAG, 0x40c39dad, dl));
5155       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5156       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5157                                    getF32Constant(DAG, 0x4042902c, dl));
5158     }
5159 
5160     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5161   }
5162 
5163   // No special expansion.
5164   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5165 }
5166 
5167 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5168 /// limited-precision mode.
5169 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5170                            const TargetLowering &TLI) {
5171   // TODO: What fast-math-flags should be set on the floating-point nodes?
5172 
5173   if (Op.getValueType() == MVT::f32 &&
5174       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5175     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5176 
5177     // Scale the exponent by log10(2) [0.30102999f].
5178     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5179     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5180                                         getF32Constant(DAG, 0x3e9a209a, dl));
5181 
5182     // Get the significand and build it into a floating-point number with
5183     // exponent of 1.
5184     SDValue X = GetSignificand(DAG, Op1, dl);
5185 
5186     SDValue Log10ofMantissa;
5187     if (LimitFloatPrecision <= 6) {
5188       // For floating-point precision of 6:
5189       //
5190       //   Log10ofMantissa =
5191       //     -0.50419619f +
5192       //       (0.60948995f - 0.10380950f * x) * x;
5193       //
5194       // error 0.0014886165, which is 6 bits
5195       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5196                                getF32Constant(DAG, 0xbdd49a13, dl));
5197       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5198                                getF32Constant(DAG, 0x3f1c0789, dl));
5199       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5200       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5201                                     getF32Constant(DAG, 0x3f011300, dl));
5202     } else if (LimitFloatPrecision <= 12) {
5203       // For floating-point precision of 12:
5204       //
5205       //   Log10ofMantissa =
5206       //     -0.64831180f +
5207       //       (0.91751397f +
5208       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5209       //
5210       // error 0.00019228036, which is better than 12 bits
5211       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5212                                getF32Constant(DAG, 0x3d431f31, dl));
5213       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5214                                getF32Constant(DAG, 0x3ea21fb2, dl));
5215       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5216       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5217                                getF32Constant(DAG, 0x3f6ae232, dl));
5218       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5219       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5220                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5221     } else { // LimitFloatPrecision <= 18
5222       // For floating-point precision of 18:
5223       //
5224       //   Log10ofMantissa =
5225       //     -0.84299375f +
5226       //       (1.5327582f +
5227       //         (-1.0688956f +
5228       //           (0.49102474f +
5229       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5230       //
5231       // error 0.0000037995730, which is better than 18 bits
5232       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5233                                getF32Constant(DAG, 0x3c5d51ce, dl));
5234       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5235                                getF32Constant(DAG, 0x3e00685a, dl));
5236       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5237       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5238                                getF32Constant(DAG, 0x3efb6798, dl));
5239       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5240       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5241                                getF32Constant(DAG, 0x3f88d192, dl));
5242       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5243       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5244                                getF32Constant(DAG, 0x3fc4316c, dl));
5245       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5246       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5247                                     getF32Constant(DAG, 0x3f57ce70, dl));
5248     }
5249 
5250     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5251   }
5252 
5253   // No special expansion.
5254   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5255 }
5256 
5257 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5258 /// limited-precision mode.
5259 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5260                           const TargetLowering &TLI) {
5261   if (Op.getValueType() == MVT::f32 &&
5262       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5263     return getLimitedPrecisionExp2(Op, dl, DAG);
5264 
5265   // No special expansion.
5266   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5267 }
5268 
5269 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5270 /// limited-precision mode with x == 10.0f.
5271 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5272                          SelectionDAG &DAG, const TargetLowering &TLI) {
5273   bool IsExp10 = false;
5274   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5275       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5276     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5277       APFloat Ten(10.0f);
5278       IsExp10 = LHSC->isExactlyValue(Ten);
5279     }
5280   }
5281 
5282   // TODO: What fast-math-flags should be set on the FMUL node?
5283   if (IsExp10) {
5284     // Put the exponent in the right bit position for later addition to the
5285     // final result:
5286     //
5287     //   #define LOG2OF10 3.3219281f
5288     //   t0 = Op * LOG2OF10;
5289     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5290                              getF32Constant(DAG, 0x40549a78, dl));
5291     return getLimitedPrecisionExp2(t0, dl, DAG);
5292   }
5293 
5294   // No special expansion.
5295   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5296 }
5297 
5298 /// ExpandPowI - Expand a llvm.powi intrinsic.
5299 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5300                           SelectionDAG &DAG) {
5301   // If RHS is a constant, we can expand this out to a multiplication tree,
5302   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5303   // optimizing for size, we only want to do this if the expansion would produce
5304   // a small number of multiplies, otherwise we do the full expansion.
5305   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5306     // Get the exponent as a positive value.
5307     unsigned Val = RHSC->getSExtValue();
5308     if ((int)Val < 0) Val = -Val;
5309 
5310     // powi(x, 0) -> 1.0
5311     if (Val == 0)
5312       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5313 
5314     const Function &F = DAG.getMachineFunction().getFunction();
5315     if (!F.hasOptSize() ||
5316         // If optimizing for size, don't insert too many multiplies.
5317         // This inserts up to 5 multiplies.
5318         countPopulation(Val) + Log2_32(Val) < 7) {
5319       // We use the simple binary decomposition method to generate the multiply
5320       // sequence.  There are more optimal ways to do this (for example,
5321       // powi(x,15) generates one more multiply than it should), but this has
5322       // the benefit of being both really simple and much better than a libcall.
5323       SDValue Res;  // Logically starts equal to 1.0
5324       SDValue CurSquare = LHS;
5325       // TODO: Intrinsics should have fast-math-flags that propagate to these
5326       // nodes.
5327       while (Val) {
5328         if (Val & 1) {
5329           if (Res.getNode())
5330             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5331           else
5332             Res = CurSquare;  // 1.0*CurSquare.
5333         }
5334 
5335         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5336                                 CurSquare, CurSquare);
5337         Val >>= 1;
5338       }
5339 
5340       // If the original was negative, invert the result, producing 1/(x*x*x).
5341       if (RHSC->getSExtValue() < 0)
5342         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5343                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5344       return Res;
5345     }
5346   }
5347 
5348   // Otherwise, expand to a libcall.
5349   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5350 }
5351 
5352 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5353 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5354 static void
5355 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5356                      const SDValue &N) {
5357   switch (N.getOpcode()) {
5358   case ISD::CopyFromReg: {
5359     SDValue Op = N.getOperand(1);
5360     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5361                       Op.getValueType().getSizeInBits());
5362     return;
5363   }
5364   case ISD::BITCAST:
5365   case ISD::AssertZext:
5366   case ISD::AssertSext:
5367   case ISD::TRUNCATE:
5368     getUnderlyingArgRegs(Regs, N.getOperand(0));
5369     return;
5370   case ISD::BUILD_PAIR:
5371   case ISD::BUILD_VECTOR:
5372   case ISD::CONCAT_VECTORS:
5373     for (SDValue Op : N->op_values())
5374       getUnderlyingArgRegs(Regs, Op);
5375     return;
5376   default:
5377     return;
5378   }
5379 }
5380 
5381 /// If the DbgValueInst is a dbg_value of a function argument, create the
5382 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5383 /// instruction selection, they will be inserted to the entry BB.
5384 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5385     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5386     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5387   const Argument *Arg = dyn_cast<Argument>(V);
5388   if (!Arg)
5389     return false;
5390 
5391   if (!IsDbgDeclare) {
5392     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5393     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5394     // the entry block.
5395     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5396     if (!IsInEntryBlock)
5397       return false;
5398 
5399     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5400     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5401     // variable that also is a param.
5402     //
5403     // Although, if we are at the top of the entry block already, we can still
5404     // emit using ArgDbgValue. This might catch some situations when the
5405     // dbg.value refers to an argument that isn't used in the entry block, so
5406     // any CopyToReg node would be optimized out and the only way to express
5407     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5408     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5409     // we should only emit as ArgDbgValue if the Variable is an argument to the
5410     // current function, and the dbg.value intrinsic is found in the entry
5411     // block.
5412     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5413         !DL->getInlinedAt();
5414     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5415     if (!IsInPrologue && !VariableIsFunctionInputArg)
5416       return false;
5417 
5418     // Here we assume that a function argument on IR level only can be used to
5419     // describe one input parameter on source level. If we for example have
5420     // source code like this
5421     //
5422     //    struct A { long x, y; };
5423     //    void foo(struct A a, long b) {
5424     //      ...
5425     //      b = a.x;
5426     //      ...
5427     //    }
5428     //
5429     // and IR like this
5430     //
5431     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5432     //  entry:
5433     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5434     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5435     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5436     //    ...
5437     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5438     //    ...
5439     //
5440     // then the last dbg.value is describing a parameter "b" using a value that
5441     // is an argument. But since we already has used %a1 to describe a parameter
5442     // we should not handle that last dbg.value here (that would result in an
5443     // incorrect hoisting of the DBG_VALUE to the function entry).
5444     // Notice that we allow one dbg.value per IR level argument, to accomodate
5445     // for the situation with fragments above.
5446     if (VariableIsFunctionInputArg) {
5447       unsigned ArgNo = Arg->getArgNo();
5448       if (ArgNo >= FuncInfo.DescribedArgs.size())
5449         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5450       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5451         return false;
5452       FuncInfo.DescribedArgs.set(ArgNo);
5453     }
5454   }
5455 
5456   MachineFunction &MF = DAG.getMachineFunction();
5457   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5458 
5459   bool IsIndirect = false;
5460   Optional<MachineOperand> Op;
5461   // Some arguments' frame index is recorded during argument lowering.
5462   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5463   if (FI != std::numeric_limits<int>::max())
5464     Op = MachineOperand::CreateFI(FI);
5465 
5466   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5467   if (!Op && N.getNode()) {
5468     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5469     Register Reg;
5470     if (ArgRegsAndSizes.size() == 1)
5471       Reg = ArgRegsAndSizes.front().first;
5472 
5473     if (Reg && Reg.isVirtual()) {
5474       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5475       Register PR = RegInfo.getLiveInPhysReg(Reg);
5476       if (PR)
5477         Reg = PR;
5478     }
5479     if (Reg) {
5480       Op = MachineOperand::CreateReg(Reg, false);
5481       IsIndirect = IsDbgDeclare;
5482     }
5483   }
5484 
5485   if (!Op && N.getNode()) {
5486     // Check if frame index is available.
5487     SDValue LCandidate = peekThroughBitcasts(N);
5488     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5489       if (FrameIndexSDNode *FINode =
5490           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5491         Op = MachineOperand::CreateFI(FINode->getIndex());
5492   }
5493 
5494   if (!Op) {
5495     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5496     auto splitMultiRegDbgValue
5497       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5498       unsigned Offset = 0;
5499       for (auto RegAndSize : SplitRegs) {
5500         auto FragmentExpr = DIExpression::createFragmentExpression(
5501           Expr, Offset, RegAndSize.second);
5502         if (!FragmentExpr)
5503           continue;
5504         FuncInfo.ArgDbgValues.push_back(
5505           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5506                   RegAndSize.first, Variable, *FragmentExpr));
5507         Offset += RegAndSize.second;
5508       }
5509     };
5510 
5511     // Check if ValueMap has reg number.
5512     DenseMap<const Value *, unsigned>::const_iterator
5513       VMI = FuncInfo.ValueMap.find(V);
5514     if (VMI != FuncInfo.ValueMap.end()) {
5515       const auto &TLI = DAG.getTargetLoweringInfo();
5516       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5517                        V->getType(), getABIRegCopyCC(V));
5518       if (RFV.occupiesMultipleRegs()) {
5519         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5520         return true;
5521       }
5522 
5523       Op = MachineOperand::CreateReg(VMI->second, false);
5524       IsIndirect = IsDbgDeclare;
5525     } else if (ArgRegsAndSizes.size() > 1) {
5526       // This was split due to the calling convention, and no virtual register
5527       // mapping exists for the value.
5528       splitMultiRegDbgValue(ArgRegsAndSizes);
5529       return true;
5530     }
5531   }
5532 
5533   if (!Op)
5534     return false;
5535 
5536   assert(Variable->isValidLocationForIntrinsic(DL) &&
5537          "Expected inlined-at fields to agree");
5538   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5539   FuncInfo.ArgDbgValues.push_back(
5540       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5541               *Op, Variable, Expr));
5542 
5543   return true;
5544 }
5545 
5546 /// Return the appropriate SDDbgValue based on N.
5547 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5548                                              DILocalVariable *Variable,
5549                                              DIExpression *Expr,
5550                                              const DebugLoc &dl,
5551                                              unsigned DbgSDNodeOrder) {
5552   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5553     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5554     // stack slot locations.
5555     //
5556     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5557     // debug values here after optimization:
5558     //
5559     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5560     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5561     //
5562     // Both describe the direct values of their associated variables.
5563     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5564                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5565   }
5566   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5567                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5568 }
5569 
5570 // VisualStudio defines setjmp as _setjmp
5571 #if defined(_MSC_VER) && defined(setjmp) && \
5572                          !defined(setjmp_undefined_for_msvc)
5573 #  pragma push_macro("setjmp")
5574 #  undef setjmp
5575 #  define setjmp_undefined_for_msvc
5576 #endif
5577 
5578 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5579   switch (Intrinsic) {
5580   case Intrinsic::smul_fix:
5581     return ISD::SMULFIX;
5582   case Intrinsic::umul_fix:
5583     return ISD::UMULFIX;
5584   default:
5585     llvm_unreachable("Unhandled fixed point intrinsic");
5586   }
5587 }
5588 
5589 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5590                                            const char *FunctionName) {
5591   assert(FunctionName && "FunctionName must not be nullptr");
5592   SDValue Callee = DAG.getExternalSymbol(
5593       FunctionName,
5594       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5595   LowerCallTo(&I, Callee, I.isTailCall());
5596 }
5597 
5598 /// Lower the call to the specified intrinsic function.
5599 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5600                                              unsigned Intrinsic) {
5601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5602   SDLoc sdl = getCurSDLoc();
5603   DebugLoc dl = getCurDebugLoc();
5604   SDValue Res;
5605 
5606   switch (Intrinsic) {
5607   default:
5608     // By default, turn this into a target intrinsic node.
5609     visitTargetIntrinsic(I, Intrinsic);
5610     return;
5611   case Intrinsic::vastart:  visitVAStart(I); return;
5612   case Intrinsic::vaend:    visitVAEnd(I); return;
5613   case Intrinsic::vacopy:   visitVACopy(I); return;
5614   case Intrinsic::returnaddress:
5615     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5616                              TLI.getPointerTy(DAG.getDataLayout()),
5617                              getValue(I.getArgOperand(0))));
5618     return;
5619   case Intrinsic::addressofreturnaddress:
5620     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5621                              TLI.getPointerTy(DAG.getDataLayout())));
5622     return;
5623   case Intrinsic::sponentry:
5624     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5625                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5626     return;
5627   case Intrinsic::frameaddress:
5628     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5629                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5630                              getValue(I.getArgOperand(0))));
5631     return;
5632   case Intrinsic::read_register: {
5633     Value *Reg = I.getArgOperand(0);
5634     SDValue Chain = getRoot();
5635     SDValue RegName =
5636         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5637     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5638     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5639       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5640     setValue(&I, Res);
5641     DAG.setRoot(Res.getValue(1));
5642     return;
5643   }
5644   case Intrinsic::write_register: {
5645     Value *Reg = I.getArgOperand(0);
5646     Value *RegValue = I.getArgOperand(1);
5647     SDValue Chain = getRoot();
5648     SDValue RegName =
5649         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5650     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5651                             RegName, getValue(RegValue)));
5652     return;
5653   }
5654   case Intrinsic::setjmp:
5655     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5656     return;
5657   case Intrinsic::longjmp:
5658     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5659     return;
5660   case Intrinsic::memcpy: {
5661     const auto &MCI = cast<MemCpyInst>(I);
5662     SDValue Op1 = getValue(I.getArgOperand(0));
5663     SDValue Op2 = getValue(I.getArgOperand(1));
5664     SDValue Op3 = getValue(I.getArgOperand(2));
5665     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5666     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5667     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5668     unsigned Align = MinAlign(DstAlign, SrcAlign);
5669     bool isVol = MCI.isVolatile();
5670     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5671     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5672     // node.
5673     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5674                                false, isTC,
5675                                MachinePointerInfo(I.getArgOperand(0)),
5676                                MachinePointerInfo(I.getArgOperand(1)));
5677     updateDAGForMaybeTailCall(MC);
5678     return;
5679   }
5680   case Intrinsic::memset: {
5681     const auto &MSI = cast<MemSetInst>(I);
5682     SDValue Op1 = getValue(I.getArgOperand(0));
5683     SDValue Op2 = getValue(I.getArgOperand(1));
5684     SDValue Op3 = getValue(I.getArgOperand(2));
5685     // @llvm.memset defines 0 and 1 to both mean no alignment.
5686     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5687     bool isVol = MSI.isVolatile();
5688     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5689     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5690                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5691     updateDAGForMaybeTailCall(MS);
5692     return;
5693   }
5694   case Intrinsic::memmove: {
5695     const auto &MMI = cast<MemMoveInst>(I);
5696     SDValue Op1 = getValue(I.getArgOperand(0));
5697     SDValue Op2 = getValue(I.getArgOperand(1));
5698     SDValue Op3 = getValue(I.getArgOperand(2));
5699     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5700     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5701     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5702     unsigned Align = MinAlign(DstAlign, SrcAlign);
5703     bool isVol = MMI.isVolatile();
5704     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5705     // FIXME: Support passing different dest/src alignments to the memmove DAG
5706     // node.
5707     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5708                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5709                                 MachinePointerInfo(I.getArgOperand(1)));
5710     updateDAGForMaybeTailCall(MM);
5711     return;
5712   }
5713   case Intrinsic::memcpy_element_unordered_atomic: {
5714     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5715     SDValue Dst = getValue(MI.getRawDest());
5716     SDValue Src = getValue(MI.getRawSource());
5717     SDValue Length = getValue(MI.getLength());
5718 
5719     unsigned DstAlign = MI.getDestAlignment();
5720     unsigned SrcAlign = MI.getSourceAlignment();
5721     Type *LengthTy = MI.getLength()->getType();
5722     unsigned ElemSz = MI.getElementSizeInBytes();
5723     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5724     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5725                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5726                                      MachinePointerInfo(MI.getRawDest()),
5727                                      MachinePointerInfo(MI.getRawSource()));
5728     updateDAGForMaybeTailCall(MC);
5729     return;
5730   }
5731   case Intrinsic::memmove_element_unordered_atomic: {
5732     auto &MI = cast<AtomicMemMoveInst>(I);
5733     SDValue Dst = getValue(MI.getRawDest());
5734     SDValue Src = getValue(MI.getRawSource());
5735     SDValue Length = getValue(MI.getLength());
5736 
5737     unsigned DstAlign = MI.getDestAlignment();
5738     unsigned SrcAlign = MI.getSourceAlignment();
5739     Type *LengthTy = MI.getLength()->getType();
5740     unsigned ElemSz = MI.getElementSizeInBytes();
5741     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5742     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5743                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5744                                       MachinePointerInfo(MI.getRawDest()),
5745                                       MachinePointerInfo(MI.getRawSource()));
5746     updateDAGForMaybeTailCall(MC);
5747     return;
5748   }
5749   case Intrinsic::memset_element_unordered_atomic: {
5750     auto &MI = cast<AtomicMemSetInst>(I);
5751     SDValue Dst = getValue(MI.getRawDest());
5752     SDValue Val = getValue(MI.getValue());
5753     SDValue Length = getValue(MI.getLength());
5754 
5755     unsigned DstAlign = MI.getDestAlignment();
5756     Type *LengthTy = MI.getLength()->getType();
5757     unsigned ElemSz = MI.getElementSizeInBytes();
5758     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5759     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5760                                      LengthTy, ElemSz, isTC,
5761                                      MachinePointerInfo(MI.getRawDest()));
5762     updateDAGForMaybeTailCall(MC);
5763     return;
5764   }
5765   case Intrinsic::dbg_addr:
5766   case Intrinsic::dbg_declare: {
5767     const auto &DI = cast<DbgVariableIntrinsic>(I);
5768     DILocalVariable *Variable = DI.getVariable();
5769     DIExpression *Expression = DI.getExpression();
5770     dropDanglingDebugInfo(Variable, Expression);
5771     assert(Variable && "Missing variable");
5772 
5773     // Check if address has undef value.
5774     const Value *Address = DI.getVariableLocation();
5775     if (!Address || isa<UndefValue>(Address) ||
5776         (Address->use_empty() && !isa<Argument>(Address))) {
5777       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5778       return;
5779     }
5780 
5781     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5782 
5783     // Check if this variable can be described by a frame index, typically
5784     // either as a static alloca or a byval parameter.
5785     int FI = std::numeric_limits<int>::max();
5786     if (const auto *AI =
5787             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5788       if (AI->isStaticAlloca()) {
5789         auto I = FuncInfo.StaticAllocaMap.find(AI);
5790         if (I != FuncInfo.StaticAllocaMap.end())
5791           FI = I->second;
5792       }
5793     } else if (const auto *Arg = dyn_cast<Argument>(
5794                    Address->stripInBoundsConstantOffsets())) {
5795       FI = FuncInfo.getArgumentFrameIndex(Arg);
5796     }
5797 
5798     // llvm.dbg.addr is control dependent and always generates indirect
5799     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5800     // the MachineFunction variable table.
5801     if (FI != std::numeric_limits<int>::max()) {
5802       if (Intrinsic == Intrinsic::dbg_addr) {
5803         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5804             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5805         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5806       }
5807       return;
5808     }
5809 
5810     SDValue &N = NodeMap[Address];
5811     if (!N.getNode() && isa<Argument>(Address))
5812       // Check unused arguments map.
5813       N = UnusedArgNodeMap[Address];
5814     SDDbgValue *SDV;
5815     if (N.getNode()) {
5816       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5817         Address = BCI->getOperand(0);
5818       // Parameters are handled specially.
5819       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5820       if (isParameter && FINode) {
5821         // Byval parameter. We have a frame index at this point.
5822         SDV =
5823             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5824                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5825       } else if (isa<Argument>(Address)) {
5826         // Address is an argument, so try to emit its dbg value using
5827         // virtual register info from the FuncInfo.ValueMap.
5828         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5829         return;
5830       } else {
5831         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5832                               true, dl, SDNodeOrder);
5833       }
5834       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5835     } else {
5836       // If Address is an argument then try to emit its dbg value using
5837       // virtual register info from the FuncInfo.ValueMap.
5838       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5839                                     N)) {
5840         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5841       }
5842     }
5843     return;
5844   }
5845   case Intrinsic::dbg_label: {
5846     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5847     DILabel *Label = DI.getLabel();
5848     assert(Label && "Missing label");
5849 
5850     SDDbgLabel *SDV;
5851     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5852     DAG.AddDbgLabel(SDV);
5853     return;
5854   }
5855   case Intrinsic::dbg_value: {
5856     const DbgValueInst &DI = cast<DbgValueInst>(I);
5857     assert(DI.getVariable() && "Missing variable");
5858 
5859     DILocalVariable *Variable = DI.getVariable();
5860     DIExpression *Expression = DI.getExpression();
5861     dropDanglingDebugInfo(Variable, Expression);
5862     const Value *V = DI.getValue();
5863     if (!V)
5864       return;
5865 
5866     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5867         SDNodeOrder))
5868       return;
5869 
5870     // TODO: Dangling debug info will eventually either be resolved or produce
5871     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5872     // between the original dbg.value location and its resolved DBG_VALUE, which
5873     // we should ideally fill with an extra Undef DBG_VALUE.
5874 
5875     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5876     return;
5877   }
5878 
5879   case Intrinsic::eh_typeid_for: {
5880     // Find the type id for the given typeinfo.
5881     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5882     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5883     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5884     setValue(&I, Res);
5885     return;
5886   }
5887 
5888   case Intrinsic::eh_return_i32:
5889   case Intrinsic::eh_return_i64:
5890     DAG.getMachineFunction().setCallsEHReturn(true);
5891     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5892                             MVT::Other,
5893                             getControlRoot(),
5894                             getValue(I.getArgOperand(0)),
5895                             getValue(I.getArgOperand(1))));
5896     return;
5897   case Intrinsic::eh_unwind_init:
5898     DAG.getMachineFunction().setCallsUnwindInit(true);
5899     return;
5900   case Intrinsic::eh_dwarf_cfa:
5901     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5902                              TLI.getPointerTy(DAG.getDataLayout()),
5903                              getValue(I.getArgOperand(0))));
5904     return;
5905   case Intrinsic::eh_sjlj_callsite: {
5906     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5907     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5908     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5909     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5910 
5911     MMI.setCurrentCallSite(CI->getZExtValue());
5912     return;
5913   }
5914   case Intrinsic::eh_sjlj_functioncontext: {
5915     // Get and store the index of the function context.
5916     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5917     AllocaInst *FnCtx =
5918       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5919     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5920     MFI.setFunctionContextIndex(FI);
5921     return;
5922   }
5923   case Intrinsic::eh_sjlj_setjmp: {
5924     SDValue Ops[2];
5925     Ops[0] = getRoot();
5926     Ops[1] = getValue(I.getArgOperand(0));
5927     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5928                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5929     setValue(&I, Op.getValue(0));
5930     DAG.setRoot(Op.getValue(1));
5931     return;
5932   }
5933   case Intrinsic::eh_sjlj_longjmp:
5934     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5935                             getRoot(), getValue(I.getArgOperand(0))));
5936     return;
5937   case Intrinsic::eh_sjlj_setup_dispatch:
5938     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5939                             getRoot()));
5940     return;
5941   case Intrinsic::masked_gather:
5942     visitMaskedGather(I);
5943     return;
5944   case Intrinsic::masked_load:
5945     visitMaskedLoad(I);
5946     return;
5947   case Intrinsic::masked_scatter:
5948     visitMaskedScatter(I);
5949     return;
5950   case Intrinsic::masked_store:
5951     visitMaskedStore(I);
5952     return;
5953   case Intrinsic::masked_expandload:
5954     visitMaskedLoad(I, true /* IsExpanding */);
5955     return;
5956   case Intrinsic::masked_compressstore:
5957     visitMaskedStore(I, true /* IsCompressing */);
5958     return;
5959   case Intrinsic::x86_mmx_pslli_w:
5960   case Intrinsic::x86_mmx_pslli_d:
5961   case Intrinsic::x86_mmx_pslli_q:
5962   case Intrinsic::x86_mmx_psrli_w:
5963   case Intrinsic::x86_mmx_psrli_d:
5964   case Intrinsic::x86_mmx_psrli_q:
5965   case Intrinsic::x86_mmx_psrai_w:
5966   case Intrinsic::x86_mmx_psrai_d: {
5967     SDValue ShAmt = getValue(I.getArgOperand(1));
5968     if (isa<ConstantSDNode>(ShAmt)) {
5969       visitTargetIntrinsic(I, Intrinsic);
5970       return;
5971     }
5972     unsigned NewIntrinsic = 0;
5973     EVT ShAmtVT = MVT::v2i32;
5974     switch (Intrinsic) {
5975     case Intrinsic::x86_mmx_pslli_w:
5976       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5977       break;
5978     case Intrinsic::x86_mmx_pslli_d:
5979       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5980       break;
5981     case Intrinsic::x86_mmx_pslli_q:
5982       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5983       break;
5984     case Intrinsic::x86_mmx_psrli_w:
5985       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5986       break;
5987     case Intrinsic::x86_mmx_psrli_d:
5988       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5989       break;
5990     case Intrinsic::x86_mmx_psrli_q:
5991       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5992       break;
5993     case Intrinsic::x86_mmx_psrai_w:
5994       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5995       break;
5996     case Intrinsic::x86_mmx_psrai_d:
5997       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5998       break;
5999     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6000     }
6001 
6002     // The vector shift intrinsics with scalars uses 32b shift amounts but
6003     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6004     // to be zero.
6005     // We must do this early because v2i32 is not a legal type.
6006     SDValue ShOps[2];
6007     ShOps[0] = ShAmt;
6008     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
6009     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
6010     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6011     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
6012     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
6013                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
6014                        getValue(I.getArgOperand(0)), ShAmt);
6015     setValue(&I, Res);
6016     return;
6017   }
6018   case Intrinsic::powi:
6019     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6020                             getValue(I.getArgOperand(1)), DAG));
6021     return;
6022   case Intrinsic::log:
6023     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6024     return;
6025   case Intrinsic::log2:
6026     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6027     return;
6028   case Intrinsic::log10:
6029     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6030     return;
6031   case Intrinsic::exp:
6032     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6033     return;
6034   case Intrinsic::exp2:
6035     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6036     return;
6037   case Intrinsic::pow:
6038     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6039                            getValue(I.getArgOperand(1)), DAG, TLI));
6040     return;
6041   case Intrinsic::sqrt:
6042   case Intrinsic::fabs:
6043   case Intrinsic::sin:
6044   case Intrinsic::cos:
6045   case Intrinsic::floor:
6046   case Intrinsic::ceil:
6047   case Intrinsic::trunc:
6048   case Intrinsic::rint:
6049   case Intrinsic::nearbyint:
6050   case Intrinsic::round:
6051   case Intrinsic::canonicalize: {
6052     unsigned Opcode;
6053     switch (Intrinsic) {
6054     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6055     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6056     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6057     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6058     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6059     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6060     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6061     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6062     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6063     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6064     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6065     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6066     }
6067 
6068     setValue(&I, DAG.getNode(Opcode, sdl,
6069                              getValue(I.getArgOperand(0)).getValueType(),
6070                              getValue(I.getArgOperand(0))));
6071     return;
6072   }
6073   case Intrinsic::lround:
6074   case Intrinsic::llround:
6075   case Intrinsic::lrint:
6076   case Intrinsic::llrint: {
6077     unsigned Opcode;
6078     switch (Intrinsic) {
6079     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6080     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6081     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6082     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6083     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6084     }
6085 
6086     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6087     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6088                              getValue(I.getArgOperand(0))));
6089     return;
6090   }
6091   case Intrinsic::minnum:
6092     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6093                              getValue(I.getArgOperand(0)).getValueType(),
6094                              getValue(I.getArgOperand(0)),
6095                              getValue(I.getArgOperand(1))));
6096     return;
6097   case Intrinsic::maxnum:
6098     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6099                              getValue(I.getArgOperand(0)).getValueType(),
6100                              getValue(I.getArgOperand(0)),
6101                              getValue(I.getArgOperand(1))));
6102     return;
6103   case Intrinsic::minimum:
6104     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6105                              getValue(I.getArgOperand(0)).getValueType(),
6106                              getValue(I.getArgOperand(0)),
6107                              getValue(I.getArgOperand(1))));
6108     return;
6109   case Intrinsic::maximum:
6110     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6111                              getValue(I.getArgOperand(0)).getValueType(),
6112                              getValue(I.getArgOperand(0)),
6113                              getValue(I.getArgOperand(1))));
6114     return;
6115   case Intrinsic::copysign:
6116     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6117                              getValue(I.getArgOperand(0)).getValueType(),
6118                              getValue(I.getArgOperand(0)),
6119                              getValue(I.getArgOperand(1))));
6120     return;
6121   case Intrinsic::fma:
6122     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6123                              getValue(I.getArgOperand(0)).getValueType(),
6124                              getValue(I.getArgOperand(0)),
6125                              getValue(I.getArgOperand(1)),
6126                              getValue(I.getArgOperand(2))));
6127     return;
6128   case Intrinsic::experimental_constrained_fadd:
6129   case Intrinsic::experimental_constrained_fsub:
6130   case Intrinsic::experimental_constrained_fmul:
6131   case Intrinsic::experimental_constrained_fdiv:
6132   case Intrinsic::experimental_constrained_frem:
6133   case Intrinsic::experimental_constrained_fma:
6134   case Intrinsic::experimental_constrained_fptosi:
6135   case Intrinsic::experimental_constrained_fptoui:
6136   case Intrinsic::experimental_constrained_fptrunc:
6137   case Intrinsic::experimental_constrained_fpext:
6138   case Intrinsic::experimental_constrained_sqrt:
6139   case Intrinsic::experimental_constrained_pow:
6140   case Intrinsic::experimental_constrained_powi:
6141   case Intrinsic::experimental_constrained_sin:
6142   case Intrinsic::experimental_constrained_cos:
6143   case Intrinsic::experimental_constrained_exp:
6144   case Intrinsic::experimental_constrained_exp2:
6145   case Intrinsic::experimental_constrained_log:
6146   case Intrinsic::experimental_constrained_log10:
6147   case Intrinsic::experimental_constrained_log2:
6148   case Intrinsic::experimental_constrained_rint:
6149   case Intrinsic::experimental_constrained_nearbyint:
6150   case Intrinsic::experimental_constrained_maxnum:
6151   case Intrinsic::experimental_constrained_minnum:
6152   case Intrinsic::experimental_constrained_ceil:
6153   case Intrinsic::experimental_constrained_floor:
6154   case Intrinsic::experimental_constrained_round:
6155   case Intrinsic::experimental_constrained_trunc:
6156     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6157     return;
6158   case Intrinsic::fmuladd: {
6159     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6160     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6161         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6162       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6163                                getValue(I.getArgOperand(0)).getValueType(),
6164                                getValue(I.getArgOperand(0)),
6165                                getValue(I.getArgOperand(1)),
6166                                getValue(I.getArgOperand(2))));
6167     } else {
6168       // TODO: Intrinsic calls should have fast-math-flags.
6169       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6170                                 getValue(I.getArgOperand(0)).getValueType(),
6171                                 getValue(I.getArgOperand(0)),
6172                                 getValue(I.getArgOperand(1)));
6173       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6174                                 getValue(I.getArgOperand(0)).getValueType(),
6175                                 Mul,
6176                                 getValue(I.getArgOperand(2)));
6177       setValue(&I, Add);
6178     }
6179     return;
6180   }
6181   case Intrinsic::convert_to_fp16:
6182     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6183                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6184                                          getValue(I.getArgOperand(0)),
6185                                          DAG.getTargetConstant(0, sdl,
6186                                                                MVT::i32))));
6187     return;
6188   case Intrinsic::convert_from_fp16:
6189     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6190                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6191                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6192                                          getValue(I.getArgOperand(0)))));
6193     return;
6194   case Intrinsic::pcmarker: {
6195     SDValue Tmp = getValue(I.getArgOperand(0));
6196     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6197     return;
6198   }
6199   case Intrinsic::readcyclecounter: {
6200     SDValue Op = getRoot();
6201     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6202                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6203     setValue(&I, Res);
6204     DAG.setRoot(Res.getValue(1));
6205     return;
6206   }
6207   case Intrinsic::bitreverse:
6208     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6209                              getValue(I.getArgOperand(0)).getValueType(),
6210                              getValue(I.getArgOperand(0))));
6211     return;
6212   case Intrinsic::bswap:
6213     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6214                              getValue(I.getArgOperand(0)).getValueType(),
6215                              getValue(I.getArgOperand(0))));
6216     return;
6217   case Intrinsic::cttz: {
6218     SDValue Arg = getValue(I.getArgOperand(0));
6219     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6220     EVT Ty = Arg.getValueType();
6221     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6222                              sdl, Ty, Arg));
6223     return;
6224   }
6225   case Intrinsic::ctlz: {
6226     SDValue Arg = getValue(I.getArgOperand(0));
6227     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6228     EVT Ty = Arg.getValueType();
6229     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6230                              sdl, Ty, Arg));
6231     return;
6232   }
6233   case Intrinsic::ctpop: {
6234     SDValue Arg = getValue(I.getArgOperand(0));
6235     EVT Ty = Arg.getValueType();
6236     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6237     return;
6238   }
6239   case Intrinsic::fshl:
6240   case Intrinsic::fshr: {
6241     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6242     SDValue X = getValue(I.getArgOperand(0));
6243     SDValue Y = getValue(I.getArgOperand(1));
6244     SDValue Z = getValue(I.getArgOperand(2));
6245     EVT VT = X.getValueType();
6246     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6247     SDValue Zero = DAG.getConstant(0, sdl, VT);
6248     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6249 
6250     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6251     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6252       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6253       return;
6254     }
6255 
6256     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6257     // avoid the select that is necessary in the general case to filter out
6258     // the 0-shift possibility that leads to UB.
6259     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6260       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6261       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6262         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6263         return;
6264       }
6265 
6266       // Some targets only rotate one way. Try the opposite direction.
6267       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6268       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6269         // Negate the shift amount because it is safe to ignore the high bits.
6270         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6271         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6272         return;
6273       }
6274 
6275       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6276       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6277       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6278       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6279       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6280       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6281       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6282       return;
6283     }
6284 
6285     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6286     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6287     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6288     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6289     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6290     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6291 
6292     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6293     // and that is undefined. We must compare and select to avoid UB.
6294     EVT CCVT = MVT::i1;
6295     if (VT.isVector())
6296       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6297 
6298     // For fshl, 0-shift returns the 1st arg (X).
6299     // For fshr, 0-shift returns the 2nd arg (Y).
6300     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6301     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6302     return;
6303   }
6304   case Intrinsic::sadd_sat: {
6305     SDValue Op1 = getValue(I.getArgOperand(0));
6306     SDValue Op2 = getValue(I.getArgOperand(1));
6307     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6308     return;
6309   }
6310   case Intrinsic::uadd_sat: {
6311     SDValue Op1 = getValue(I.getArgOperand(0));
6312     SDValue Op2 = getValue(I.getArgOperand(1));
6313     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6314     return;
6315   }
6316   case Intrinsic::ssub_sat: {
6317     SDValue Op1 = getValue(I.getArgOperand(0));
6318     SDValue Op2 = getValue(I.getArgOperand(1));
6319     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6320     return;
6321   }
6322   case Intrinsic::usub_sat: {
6323     SDValue Op1 = getValue(I.getArgOperand(0));
6324     SDValue Op2 = getValue(I.getArgOperand(1));
6325     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6326     return;
6327   }
6328   case Intrinsic::smul_fix:
6329   case Intrinsic::umul_fix: {
6330     SDValue Op1 = getValue(I.getArgOperand(0));
6331     SDValue Op2 = getValue(I.getArgOperand(1));
6332     SDValue Op3 = getValue(I.getArgOperand(2));
6333     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6334                              Op1.getValueType(), Op1, Op2, Op3));
6335     return;
6336   }
6337   case Intrinsic::smul_fix_sat: {
6338     SDValue Op1 = getValue(I.getArgOperand(0));
6339     SDValue Op2 = getValue(I.getArgOperand(1));
6340     SDValue Op3 = getValue(I.getArgOperand(2));
6341     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6342                              Op3));
6343     return;
6344   }
6345   case Intrinsic::umul_fix_sat: {
6346     SDValue Op1 = getValue(I.getArgOperand(0));
6347     SDValue Op2 = getValue(I.getArgOperand(1));
6348     SDValue Op3 = getValue(I.getArgOperand(2));
6349     setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6350                              Op3));
6351     return;
6352   }
6353   case Intrinsic::stacksave: {
6354     SDValue Op = getRoot();
6355     Res = DAG.getNode(
6356         ISD::STACKSAVE, sdl,
6357         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6358     setValue(&I, Res);
6359     DAG.setRoot(Res.getValue(1));
6360     return;
6361   }
6362   case Intrinsic::stackrestore:
6363     Res = getValue(I.getArgOperand(0));
6364     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6365     return;
6366   case Intrinsic::get_dynamic_area_offset: {
6367     SDValue Op = getRoot();
6368     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6369     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6370     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6371     // target.
6372     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6373       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6374                          " intrinsic!");
6375     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6376                       Op);
6377     DAG.setRoot(Op);
6378     setValue(&I, Res);
6379     return;
6380   }
6381   case Intrinsic::stackguard: {
6382     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6383     MachineFunction &MF = DAG.getMachineFunction();
6384     const Module &M = *MF.getFunction().getParent();
6385     SDValue Chain = getRoot();
6386     if (TLI.useLoadStackGuardNode()) {
6387       Res = getLoadStackGuard(DAG, sdl, Chain);
6388     } else {
6389       const Value *Global = TLI.getSDagStackGuard(M);
6390       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6391       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6392                         MachinePointerInfo(Global, 0), Align,
6393                         MachineMemOperand::MOVolatile);
6394     }
6395     if (TLI.useStackGuardXorFP())
6396       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6397     DAG.setRoot(Chain);
6398     setValue(&I, Res);
6399     return;
6400   }
6401   case Intrinsic::stackprotector: {
6402     // Emit code into the DAG to store the stack guard onto the stack.
6403     MachineFunction &MF = DAG.getMachineFunction();
6404     MachineFrameInfo &MFI = MF.getFrameInfo();
6405     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6406     SDValue Src, Chain = getRoot();
6407 
6408     if (TLI.useLoadStackGuardNode())
6409       Src = getLoadStackGuard(DAG, sdl, Chain);
6410     else
6411       Src = getValue(I.getArgOperand(0));   // The guard's value.
6412 
6413     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6414 
6415     int FI = FuncInfo.StaticAllocaMap[Slot];
6416     MFI.setStackProtectorIndex(FI);
6417 
6418     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6419 
6420     // Store the stack protector onto the stack.
6421     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6422                                                  DAG.getMachineFunction(), FI),
6423                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6424     setValue(&I, Res);
6425     DAG.setRoot(Res);
6426     return;
6427   }
6428   case Intrinsic::objectsize: {
6429     // If we don't know by now, we're never going to know.
6430     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6431 
6432     assert(CI && "Non-constant type in __builtin_object_size?");
6433 
6434     SDValue Arg = getValue(I.getCalledValue());
6435     EVT Ty = Arg.getValueType();
6436 
6437     if (CI->isZero())
6438       Res = DAG.getConstant(-1ULL, sdl, Ty);
6439     else
6440       Res = DAG.getConstant(0, sdl, Ty);
6441 
6442     setValue(&I, Res);
6443     return;
6444   }
6445 
6446   case Intrinsic::is_constant:
6447     // If this wasn't constant-folded away by now, then it's not a
6448     // constant.
6449     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6450     return;
6451 
6452   case Intrinsic::annotation:
6453   case Intrinsic::ptr_annotation:
6454   case Intrinsic::launder_invariant_group:
6455   case Intrinsic::strip_invariant_group:
6456     // Drop the intrinsic, but forward the value
6457     setValue(&I, getValue(I.getOperand(0)));
6458     return;
6459   case Intrinsic::assume:
6460   case Intrinsic::var_annotation:
6461   case Intrinsic::sideeffect:
6462     // Discard annotate attributes, assumptions, and artificial side-effects.
6463     return;
6464 
6465   case Intrinsic::codeview_annotation: {
6466     // Emit a label associated with this metadata.
6467     MachineFunction &MF = DAG.getMachineFunction();
6468     MCSymbol *Label =
6469         MF.getMMI().getContext().createTempSymbol("annotation", true);
6470     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6471     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6472     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6473     DAG.setRoot(Res);
6474     return;
6475   }
6476 
6477   case Intrinsic::init_trampoline: {
6478     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6479 
6480     SDValue Ops[6];
6481     Ops[0] = getRoot();
6482     Ops[1] = getValue(I.getArgOperand(0));
6483     Ops[2] = getValue(I.getArgOperand(1));
6484     Ops[3] = getValue(I.getArgOperand(2));
6485     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6486     Ops[5] = DAG.getSrcValue(F);
6487 
6488     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6489 
6490     DAG.setRoot(Res);
6491     return;
6492   }
6493   case Intrinsic::adjust_trampoline:
6494     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6495                              TLI.getPointerTy(DAG.getDataLayout()),
6496                              getValue(I.getArgOperand(0))));
6497     return;
6498   case Intrinsic::gcroot: {
6499     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6500            "only valid in functions with gc specified, enforced by Verifier");
6501     assert(GFI && "implied by previous");
6502     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6503     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6504 
6505     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6506     GFI->addStackRoot(FI->getIndex(), TypeMap);
6507     return;
6508   }
6509   case Intrinsic::gcread:
6510   case Intrinsic::gcwrite:
6511     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6512   case Intrinsic::flt_rounds:
6513     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6514     return;
6515 
6516   case Intrinsic::expect:
6517     // Just replace __builtin_expect(exp, c) with EXP.
6518     setValue(&I, getValue(I.getArgOperand(0)));
6519     return;
6520 
6521   case Intrinsic::debugtrap:
6522   case Intrinsic::trap: {
6523     StringRef TrapFuncName =
6524         I.getAttributes()
6525             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6526             .getValueAsString();
6527     if (TrapFuncName.empty()) {
6528       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6529         ISD::TRAP : ISD::DEBUGTRAP;
6530       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6531       return;
6532     }
6533     TargetLowering::ArgListTy Args;
6534 
6535     TargetLowering::CallLoweringInfo CLI(DAG);
6536     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6537         CallingConv::C, I.getType(),
6538         DAG.getExternalSymbol(TrapFuncName.data(),
6539                               TLI.getPointerTy(DAG.getDataLayout())),
6540         std::move(Args));
6541 
6542     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6543     DAG.setRoot(Result.second);
6544     return;
6545   }
6546 
6547   case Intrinsic::uadd_with_overflow:
6548   case Intrinsic::sadd_with_overflow:
6549   case Intrinsic::usub_with_overflow:
6550   case Intrinsic::ssub_with_overflow:
6551   case Intrinsic::umul_with_overflow:
6552   case Intrinsic::smul_with_overflow: {
6553     ISD::NodeType Op;
6554     switch (Intrinsic) {
6555     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6556     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6557     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6558     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6559     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6560     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6561     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6562     }
6563     SDValue Op1 = getValue(I.getArgOperand(0));
6564     SDValue Op2 = getValue(I.getArgOperand(1));
6565 
6566     EVT ResultVT = Op1.getValueType();
6567     EVT OverflowVT = MVT::i1;
6568     if (ResultVT.isVector())
6569       OverflowVT = EVT::getVectorVT(
6570           *Context, OverflowVT, ResultVT.getVectorNumElements());
6571 
6572     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6573     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6574     return;
6575   }
6576   case Intrinsic::prefetch: {
6577     SDValue Ops[5];
6578     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6579     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6580     Ops[0] = DAG.getRoot();
6581     Ops[1] = getValue(I.getArgOperand(0));
6582     Ops[2] = getValue(I.getArgOperand(1));
6583     Ops[3] = getValue(I.getArgOperand(2));
6584     Ops[4] = getValue(I.getArgOperand(3));
6585     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6586                                              DAG.getVTList(MVT::Other), Ops,
6587                                              EVT::getIntegerVT(*Context, 8),
6588                                              MachinePointerInfo(I.getArgOperand(0)),
6589                                              0, /* align */
6590                                              Flags);
6591 
6592     // Chain the prefetch in parallell with any pending loads, to stay out of
6593     // the way of later optimizations.
6594     PendingLoads.push_back(Result);
6595     Result = getRoot();
6596     DAG.setRoot(Result);
6597     return;
6598   }
6599   case Intrinsic::lifetime_start:
6600   case Intrinsic::lifetime_end: {
6601     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6602     // Stack coloring is not enabled in O0, discard region information.
6603     if (TM.getOptLevel() == CodeGenOpt::None)
6604       return;
6605 
6606     const int64_t ObjectSize =
6607         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6608     Value *const ObjectPtr = I.getArgOperand(1);
6609     SmallVector<const Value *, 4> Allocas;
6610     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6611 
6612     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6613            E = Allocas.end(); Object != E; ++Object) {
6614       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6615 
6616       // Could not find an Alloca.
6617       if (!LifetimeObject)
6618         continue;
6619 
6620       // First check that the Alloca is static, otherwise it won't have a
6621       // valid frame index.
6622       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6623       if (SI == FuncInfo.StaticAllocaMap.end())
6624         return;
6625 
6626       const int FrameIndex = SI->second;
6627       int64_t Offset;
6628       if (GetPointerBaseWithConstantOffset(
6629               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6630         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6631       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6632                                 Offset);
6633       DAG.setRoot(Res);
6634     }
6635     return;
6636   }
6637   case Intrinsic::invariant_start:
6638     // Discard region information.
6639     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6640     return;
6641   case Intrinsic::invariant_end:
6642     // Discard region information.
6643     return;
6644   case Intrinsic::clear_cache:
6645     /// FunctionName may be null.
6646     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6647       lowerCallToExternalSymbol(I, FunctionName);
6648     return;
6649   case Intrinsic::donothing:
6650     // ignore
6651     return;
6652   case Intrinsic::experimental_stackmap:
6653     visitStackmap(I);
6654     return;
6655   case Intrinsic::experimental_patchpoint_void:
6656   case Intrinsic::experimental_patchpoint_i64:
6657     visitPatchpoint(&I);
6658     return;
6659   case Intrinsic::experimental_gc_statepoint:
6660     LowerStatepoint(ImmutableStatepoint(&I));
6661     return;
6662   case Intrinsic::experimental_gc_result:
6663     visitGCResult(cast<GCResultInst>(I));
6664     return;
6665   case Intrinsic::experimental_gc_relocate:
6666     visitGCRelocate(cast<GCRelocateInst>(I));
6667     return;
6668   case Intrinsic::instrprof_increment:
6669     llvm_unreachable("instrprof failed to lower an increment");
6670   case Intrinsic::instrprof_value_profile:
6671     llvm_unreachable("instrprof failed to lower a value profiling call");
6672   case Intrinsic::localescape: {
6673     MachineFunction &MF = DAG.getMachineFunction();
6674     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6675 
6676     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6677     // is the same on all targets.
6678     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6679       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6680       if (isa<ConstantPointerNull>(Arg))
6681         continue; // Skip null pointers. They represent a hole in index space.
6682       AllocaInst *Slot = cast<AllocaInst>(Arg);
6683       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6684              "can only escape static allocas");
6685       int FI = FuncInfo.StaticAllocaMap[Slot];
6686       MCSymbol *FrameAllocSym =
6687           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6688               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6689       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6690               TII->get(TargetOpcode::LOCAL_ESCAPE))
6691           .addSym(FrameAllocSym)
6692           .addFrameIndex(FI);
6693     }
6694 
6695     return;
6696   }
6697 
6698   case Intrinsic::localrecover: {
6699     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6700     MachineFunction &MF = DAG.getMachineFunction();
6701     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6702 
6703     // Get the symbol that defines the frame offset.
6704     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6705     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6706     unsigned IdxVal =
6707         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6708     MCSymbol *FrameAllocSym =
6709         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6710             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6711 
6712     // Create a MCSymbol for the label to avoid any target lowering
6713     // that would make this PC relative.
6714     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6715     SDValue OffsetVal =
6716         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6717 
6718     // Add the offset to the FP.
6719     Value *FP = I.getArgOperand(1);
6720     SDValue FPVal = getValue(FP);
6721     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6722     setValue(&I, Add);
6723 
6724     return;
6725   }
6726 
6727   case Intrinsic::eh_exceptionpointer:
6728   case Intrinsic::eh_exceptioncode: {
6729     // Get the exception pointer vreg, copy from it, and resize it to fit.
6730     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6731     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6732     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6733     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6734     SDValue N =
6735         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6736     if (Intrinsic == Intrinsic::eh_exceptioncode)
6737       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6738     setValue(&I, N);
6739     return;
6740   }
6741   case Intrinsic::xray_customevent: {
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     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6754     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6755     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6756     SDValue Chain = getRoot();
6757     Ops.push_back(LogEntryVal);
6758     Ops.push_back(StrSizeVal);
6759     Ops.push_back(Chain);
6760 
6761     // We need to enforce the calling convention for the callsite, so that
6762     // argument ordering is enforced correctly, and that register allocation can
6763     // see that some registers may be assumed clobbered and have to preserve
6764     // them across calls to the intrinsic.
6765     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6766                                            DL, NodeTys, Ops);
6767     SDValue patchableNode = SDValue(MN, 0);
6768     DAG.setRoot(patchableNode);
6769     setValue(&I, patchableNode);
6770     return;
6771   }
6772   case Intrinsic::xray_typedevent: {
6773     // Here we want to make sure that the intrinsic behaves as if it has a
6774     // specific calling convention, and only for x86_64.
6775     // FIXME: Support other platforms later.
6776     const auto &Triple = DAG.getTarget().getTargetTriple();
6777     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6778       return;
6779 
6780     SDLoc DL = getCurSDLoc();
6781     SmallVector<SDValue, 8> Ops;
6782 
6783     // We want to say that we always want the arguments in registers.
6784     // It's unclear to me how manipulating the selection DAG here forces callers
6785     // to provide arguments in registers instead of on the stack.
6786     SDValue LogTypeId = getValue(I.getArgOperand(0));
6787     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6788     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6789     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6790     SDValue Chain = getRoot();
6791     Ops.push_back(LogTypeId);
6792     Ops.push_back(LogEntryVal);
6793     Ops.push_back(StrSizeVal);
6794     Ops.push_back(Chain);
6795 
6796     // We need to enforce the calling convention for the callsite, so that
6797     // argument ordering is enforced correctly, and that register allocation can
6798     // see that some registers may be assumed clobbered and have to preserve
6799     // them across calls to the intrinsic.
6800     MachineSDNode *MN = DAG.getMachineNode(
6801         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6802     SDValue patchableNode = SDValue(MN, 0);
6803     DAG.setRoot(patchableNode);
6804     setValue(&I, patchableNode);
6805     return;
6806   }
6807   case Intrinsic::experimental_deoptimize:
6808     LowerDeoptimizeCall(&I);
6809     return;
6810 
6811   case Intrinsic::experimental_vector_reduce_v2_fadd:
6812   case Intrinsic::experimental_vector_reduce_v2_fmul:
6813   case Intrinsic::experimental_vector_reduce_add:
6814   case Intrinsic::experimental_vector_reduce_mul:
6815   case Intrinsic::experimental_vector_reduce_and:
6816   case Intrinsic::experimental_vector_reduce_or:
6817   case Intrinsic::experimental_vector_reduce_xor:
6818   case Intrinsic::experimental_vector_reduce_smax:
6819   case Intrinsic::experimental_vector_reduce_smin:
6820   case Intrinsic::experimental_vector_reduce_umax:
6821   case Intrinsic::experimental_vector_reduce_umin:
6822   case Intrinsic::experimental_vector_reduce_fmax:
6823   case Intrinsic::experimental_vector_reduce_fmin:
6824     visitVectorReduce(I, Intrinsic);
6825     return;
6826 
6827   case Intrinsic::icall_branch_funnel: {
6828     SmallVector<SDValue, 16> Ops;
6829     Ops.push_back(getValue(I.getArgOperand(0)));
6830 
6831     int64_t Offset;
6832     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6833         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6834     if (!Base)
6835       report_fatal_error(
6836           "llvm.icall.branch.funnel operand must be a GlobalValue");
6837     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6838 
6839     struct BranchFunnelTarget {
6840       int64_t Offset;
6841       SDValue Target;
6842     };
6843     SmallVector<BranchFunnelTarget, 8> Targets;
6844 
6845     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6846       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6847           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6848       if (ElemBase != Base)
6849         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6850                            "to the same GlobalValue");
6851 
6852       SDValue Val = getValue(I.getArgOperand(Op + 1));
6853       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6854       if (!GA)
6855         report_fatal_error(
6856             "llvm.icall.branch.funnel operand must be a GlobalValue");
6857       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6858                                      GA->getGlobal(), getCurSDLoc(),
6859                                      Val.getValueType(), GA->getOffset())});
6860     }
6861     llvm::sort(Targets,
6862                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6863                  return T1.Offset < T2.Offset;
6864                });
6865 
6866     for (auto &T : Targets) {
6867       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6868       Ops.push_back(T.Target);
6869     }
6870 
6871     Ops.push_back(DAG.getRoot()); // Chain
6872     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6873                                  getCurSDLoc(), MVT::Other, Ops),
6874               0);
6875     DAG.setRoot(N);
6876     setValue(&I, N);
6877     HasTailCall = true;
6878     return;
6879   }
6880 
6881   case Intrinsic::wasm_landingpad_index:
6882     // Information this intrinsic contained has been transferred to
6883     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6884     // delete it now.
6885     return;
6886 
6887   case Intrinsic::aarch64_settag:
6888   case Intrinsic::aarch64_settag_zero: {
6889     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6890     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6891     SDValue Val = TSI.EmitTargetCodeForSetTag(
6892         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6893         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6894         ZeroMemory);
6895     DAG.setRoot(Val);
6896     setValue(&I, Val);
6897     return;
6898   }
6899   case Intrinsic::ptrmask: {
6900     SDValue Ptr = getValue(I.getOperand(0));
6901     SDValue Const = getValue(I.getOperand(1));
6902 
6903     EVT DestVT =
6904         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6905 
6906     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6907                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6908     return;
6909   }
6910   }
6911 }
6912 
6913 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6914     const ConstrainedFPIntrinsic &FPI) {
6915   SDLoc sdl = getCurSDLoc();
6916   unsigned Opcode;
6917   switch (FPI.getIntrinsicID()) {
6918   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6919   case Intrinsic::experimental_constrained_fadd:
6920     Opcode = ISD::STRICT_FADD;
6921     break;
6922   case Intrinsic::experimental_constrained_fsub:
6923     Opcode = ISD::STRICT_FSUB;
6924     break;
6925   case Intrinsic::experimental_constrained_fmul:
6926     Opcode = ISD::STRICT_FMUL;
6927     break;
6928   case Intrinsic::experimental_constrained_fdiv:
6929     Opcode = ISD::STRICT_FDIV;
6930     break;
6931   case Intrinsic::experimental_constrained_frem:
6932     Opcode = ISD::STRICT_FREM;
6933     break;
6934   case Intrinsic::experimental_constrained_fma:
6935     Opcode = ISD::STRICT_FMA;
6936     break;
6937   case Intrinsic::experimental_constrained_fptosi:
6938     Opcode = ISD::STRICT_FP_TO_SINT;
6939     break;
6940   case Intrinsic::experimental_constrained_fptoui:
6941     Opcode = ISD::STRICT_FP_TO_UINT;
6942     break;
6943   case Intrinsic::experimental_constrained_fptrunc:
6944     Opcode = ISD::STRICT_FP_ROUND;
6945     break;
6946   case Intrinsic::experimental_constrained_fpext:
6947     Opcode = ISD::STRICT_FP_EXTEND;
6948     break;
6949   case Intrinsic::experimental_constrained_sqrt:
6950     Opcode = ISD::STRICT_FSQRT;
6951     break;
6952   case Intrinsic::experimental_constrained_pow:
6953     Opcode = ISD::STRICT_FPOW;
6954     break;
6955   case Intrinsic::experimental_constrained_powi:
6956     Opcode = ISD::STRICT_FPOWI;
6957     break;
6958   case Intrinsic::experimental_constrained_sin:
6959     Opcode = ISD::STRICT_FSIN;
6960     break;
6961   case Intrinsic::experimental_constrained_cos:
6962     Opcode = ISD::STRICT_FCOS;
6963     break;
6964   case Intrinsic::experimental_constrained_exp:
6965     Opcode = ISD::STRICT_FEXP;
6966     break;
6967   case Intrinsic::experimental_constrained_exp2:
6968     Opcode = ISD::STRICT_FEXP2;
6969     break;
6970   case Intrinsic::experimental_constrained_log:
6971     Opcode = ISD::STRICT_FLOG;
6972     break;
6973   case Intrinsic::experimental_constrained_log10:
6974     Opcode = ISD::STRICT_FLOG10;
6975     break;
6976   case Intrinsic::experimental_constrained_log2:
6977     Opcode = ISD::STRICT_FLOG2;
6978     break;
6979   case Intrinsic::experimental_constrained_rint:
6980     Opcode = ISD::STRICT_FRINT;
6981     break;
6982   case Intrinsic::experimental_constrained_nearbyint:
6983     Opcode = ISD::STRICT_FNEARBYINT;
6984     break;
6985   case Intrinsic::experimental_constrained_maxnum:
6986     Opcode = ISD::STRICT_FMAXNUM;
6987     break;
6988   case Intrinsic::experimental_constrained_minnum:
6989     Opcode = ISD::STRICT_FMINNUM;
6990     break;
6991   case Intrinsic::experimental_constrained_ceil:
6992     Opcode = ISD::STRICT_FCEIL;
6993     break;
6994   case Intrinsic::experimental_constrained_floor:
6995     Opcode = ISD::STRICT_FFLOOR;
6996     break;
6997   case Intrinsic::experimental_constrained_round:
6998     Opcode = ISD::STRICT_FROUND;
6999     break;
7000   case Intrinsic::experimental_constrained_trunc:
7001     Opcode = ISD::STRICT_FTRUNC;
7002     break;
7003   }
7004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7005   SDValue Chain = getRoot();
7006   SmallVector<EVT, 4> ValueVTs;
7007   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7008   ValueVTs.push_back(MVT::Other); // Out chain
7009 
7010   SDVTList VTs = DAG.getVTList(ValueVTs);
7011   SDValue Result;
7012   if (Opcode == ISD::STRICT_FP_ROUND)
7013     Result = DAG.getNode(Opcode, sdl, VTs,
7014                           { Chain, getValue(FPI.getArgOperand(0)),
7015                                DAG.getTargetConstant(0, sdl,
7016                                TLI.getPointerTy(DAG.getDataLayout())) });
7017   else if (FPI.isUnaryOp())
7018     Result = DAG.getNode(Opcode, sdl, VTs,
7019                          { Chain, getValue(FPI.getArgOperand(0)) });
7020   else if (FPI.isTernaryOp())
7021     Result = DAG.getNode(Opcode, sdl, VTs,
7022                          { Chain, getValue(FPI.getArgOperand(0)),
7023                                   getValue(FPI.getArgOperand(1)),
7024                                   getValue(FPI.getArgOperand(2)) });
7025   else
7026     Result = DAG.getNode(Opcode, sdl, VTs,
7027                          { Chain, getValue(FPI.getArgOperand(0)),
7028                            getValue(FPI.getArgOperand(1))  });
7029 
7030   if (FPI.getExceptionBehavior() !=
7031       ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
7032     SDNodeFlags Flags;
7033     Flags.setFPExcept(true);
7034     Result->setFlags(Flags);
7035   }
7036 
7037   assert(Result.getNode()->getNumValues() == 2);
7038   SDValue OutChain = Result.getValue(1);
7039   DAG.setRoot(OutChain);
7040   SDValue FPResult = Result.getValue(0);
7041   setValue(&FPI, FPResult);
7042 }
7043 
7044 std::pair<SDValue, SDValue>
7045 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7046                                     const BasicBlock *EHPadBB) {
7047   MachineFunction &MF = DAG.getMachineFunction();
7048   MachineModuleInfo &MMI = MF.getMMI();
7049   MCSymbol *BeginLabel = nullptr;
7050 
7051   if (EHPadBB) {
7052     // Insert a label before the invoke call to mark the try range.  This can be
7053     // used to detect deletion of the invoke via the MachineModuleInfo.
7054     BeginLabel = MMI.getContext().createTempSymbol();
7055 
7056     // For SjLj, keep track of which landing pads go with which invokes
7057     // so as to maintain the ordering of pads in the LSDA.
7058     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7059     if (CallSiteIndex) {
7060       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7061       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7062 
7063       // Now that the call site is handled, stop tracking it.
7064       MMI.setCurrentCallSite(0);
7065     }
7066 
7067     // Both PendingLoads and PendingExports must be flushed here;
7068     // this call might not return.
7069     (void)getRoot();
7070     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7071 
7072     CLI.setChain(getRoot());
7073   }
7074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7075   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7076 
7077   assert((CLI.IsTailCall || Result.second.getNode()) &&
7078          "Non-null chain expected with non-tail call!");
7079   assert((Result.second.getNode() || !Result.first.getNode()) &&
7080          "Null value expected with tail call!");
7081 
7082   if (!Result.second.getNode()) {
7083     // As a special case, a null chain means that a tail call has been emitted
7084     // and the DAG root is already updated.
7085     HasTailCall = true;
7086 
7087     // Since there's no actual continuation from this block, nothing can be
7088     // relying on us setting vregs for them.
7089     PendingExports.clear();
7090   } else {
7091     DAG.setRoot(Result.second);
7092   }
7093 
7094   if (EHPadBB) {
7095     // Insert a label at the end of the invoke call to mark the try range.  This
7096     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7097     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7098     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7099 
7100     // Inform MachineModuleInfo of range.
7101     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7102     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7103     // actually use outlined funclets and their LSDA info style.
7104     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7105       assert(CLI.CS);
7106       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7107       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7108                                 BeginLabel, EndLabel);
7109     } else if (!isScopedEHPersonality(Pers)) {
7110       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7111     }
7112   }
7113 
7114   return Result;
7115 }
7116 
7117 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7118                                       bool isTailCall,
7119                                       const BasicBlock *EHPadBB) {
7120   auto &DL = DAG.getDataLayout();
7121   FunctionType *FTy = CS.getFunctionType();
7122   Type *RetTy = CS.getType();
7123 
7124   TargetLowering::ArgListTy Args;
7125   Args.reserve(CS.arg_size());
7126 
7127   const Value *SwiftErrorVal = nullptr;
7128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7129 
7130   // We can't tail call inside a function with a swifterror argument. Lowering
7131   // does not support this yet. It would have to move into the swifterror
7132   // register before the call.
7133   auto *Caller = CS.getInstruction()->getParent()->getParent();
7134   if (TLI.supportSwiftError() &&
7135       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7136     isTailCall = false;
7137 
7138   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7139        i != e; ++i) {
7140     TargetLowering::ArgListEntry Entry;
7141     const Value *V = *i;
7142 
7143     // Skip empty types
7144     if (V->getType()->isEmptyTy())
7145       continue;
7146 
7147     SDValue ArgNode = getValue(V);
7148     Entry.Node = ArgNode; Entry.Ty = V->getType();
7149 
7150     Entry.setAttributes(&CS, i - CS.arg_begin());
7151 
7152     // Use swifterror virtual register as input to the call.
7153     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7154       SwiftErrorVal = V;
7155       // We find the virtual register for the actual swifterror argument.
7156       // Instead of using the Value, we use the virtual register instead.
7157       Entry.Node = DAG.getRegister(
7158           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7159           EVT(TLI.getPointerTy(DL)));
7160     }
7161 
7162     Args.push_back(Entry);
7163 
7164     // If we have an explicit sret argument that is an Instruction, (i.e., it
7165     // might point to function-local memory), we can't meaningfully tail-call.
7166     if (Entry.IsSRet && isa<Instruction>(V))
7167       isTailCall = false;
7168   }
7169 
7170   // Check if target-independent constraints permit a tail call here.
7171   // Target-dependent constraints are checked within TLI->LowerCallTo.
7172   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7173     isTailCall = false;
7174 
7175   // Disable tail calls if there is an swifterror argument. Targets have not
7176   // been updated to support tail calls.
7177   if (TLI.supportSwiftError() && SwiftErrorVal)
7178     isTailCall = false;
7179 
7180   TargetLowering::CallLoweringInfo CLI(DAG);
7181   CLI.setDebugLoc(getCurSDLoc())
7182       .setChain(getRoot())
7183       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7184       .setTailCall(isTailCall)
7185       .setConvergent(CS.isConvergent());
7186   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7187 
7188   if (Result.first.getNode()) {
7189     const Instruction *Inst = CS.getInstruction();
7190     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7191     setValue(Inst, Result.first);
7192   }
7193 
7194   // The last element of CLI.InVals has the SDValue for swifterror return.
7195   // Here we copy it to a virtual register and update SwiftErrorMap for
7196   // book-keeping.
7197   if (SwiftErrorVal && TLI.supportSwiftError()) {
7198     // Get the last element of InVals.
7199     SDValue Src = CLI.InVals.back();
7200     Register VReg = SwiftError.getOrCreateVRegDefAt(
7201         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7202     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7203     DAG.setRoot(CopyNode);
7204   }
7205 }
7206 
7207 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7208                              SelectionDAGBuilder &Builder) {
7209   // Check to see if this load can be trivially constant folded, e.g. if the
7210   // input is from a string literal.
7211   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7212     // Cast pointer to the type we really want to load.
7213     Type *LoadTy =
7214         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7215     if (LoadVT.isVector())
7216       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7217 
7218     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7219                                          PointerType::getUnqual(LoadTy));
7220 
7221     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7222             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7223       return Builder.getValue(LoadCst);
7224   }
7225 
7226   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7227   // still constant memory, the input chain can be the entry node.
7228   SDValue Root;
7229   bool ConstantMemory = false;
7230 
7231   // Do not serialize (non-volatile) loads of constant memory with anything.
7232   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7233     Root = Builder.DAG.getEntryNode();
7234     ConstantMemory = true;
7235   } else {
7236     // Do not serialize non-volatile loads against each other.
7237     Root = Builder.DAG.getRoot();
7238   }
7239 
7240   SDValue Ptr = Builder.getValue(PtrVal);
7241   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7242                                         Ptr, MachinePointerInfo(PtrVal),
7243                                         /* Alignment = */ 1);
7244 
7245   if (!ConstantMemory)
7246     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7247   return LoadVal;
7248 }
7249 
7250 /// Record the value for an instruction that produces an integer result,
7251 /// converting the type where necessary.
7252 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7253                                                   SDValue Value,
7254                                                   bool IsSigned) {
7255   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7256                                                     I.getType(), true);
7257   if (IsSigned)
7258     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7259   else
7260     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7261   setValue(&I, Value);
7262 }
7263 
7264 /// See if we can lower a memcmp call into an optimized form. If so, return
7265 /// true and lower it. Otherwise return false, and it will be lowered like a
7266 /// normal call.
7267 /// The caller already checked that \p I calls the appropriate LibFunc with a
7268 /// correct prototype.
7269 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7270   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7271   const Value *Size = I.getArgOperand(2);
7272   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7273   if (CSize && CSize->getZExtValue() == 0) {
7274     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7275                                                           I.getType(), true);
7276     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7277     return true;
7278   }
7279 
7280   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7281   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7282       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7283       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7284   if (Res.first.getNode()) {
7285     processIntegerCallValue(I, Res.first, true);
7286     PendingLoads.push_back(Res.second);
7287     return true;
7288   }
7289 
7290   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7291   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7292   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7293     return false;
7294 
7295   // If the target has a fast compare for the given size, it will return a
7296   // preferred load type for that size. Require that the load VT is legal and
7297   // that the target supports unaligned loads of that type. Otherwise, return
7298   // INVALID.
7299   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7300     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7301     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7302     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7303       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7304       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7305       // TODO: Check alignment of src and dest ptrs.
7306       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7307       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7308       if (!TLI.isTypeLegal(LVT) ||
7309           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7310           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7311         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7312     }
7313 
7314     return LVT;
7315   };
7316 
7317   // This turns into unaligned loads. We only do this if the target natively
7318   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7319   // we'll only produce a small number of byte loads.
7320   MVT LoadVT;
7321   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7322   switch (NumBitsToCompare) {
7323   default:
7324     return false;
7325   case 16:
7326     LoadVT = MVT::i16;
7327     break;
7328   case 32:
7329     LoadVT = MVT::i32;
7330     break;
7331   case 64:
7332   case 128:
7333   case 256:
7334     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7335     break;
7336   }
7337 
7338   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7339     return false;
7340 
7341   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7342   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7343 
7344   // Bitcast to a wide integer type if the loads are vectors.
7345   if (LoadVT.isVector()) {
7346     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7347     LoadL = DAG.getBitcast(CmpVT, LoadL);
7348     LoadR = DAG.getBitcast(CmpVT, LoadR);
7349   }
7350 
7351   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7352   processIntegerCallValue(I, Cmp, false);
7353   return true;
7354 }
7355 
7356 /// See if we can lower a memchr call into an optimized form. If so, return
7357 /// true and lower it. Otherwise return false, and it will be lowered like a
7358 /// normal call.
7359 /// The caller already checked that \p I calls the appropriate LibFunc with a
7360 /// correct prototype.
7361 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7362   const Value *Src = I.getArgOperand(0);
7363   const Value *Char = I.getArgOperand(1);
7364   const Value *Length = I.getArgOperand(2);
7365 
7366   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7367   std::pair<SDValue, SDValue> Res =
7368     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7369                                 getValue(Src), getValue(Char), getValue(Length),
7370                                 MachinePointerInfo(Src));
7371   if (Res.first.getNode()) {
7372     setValue(&I, Res.first);
7373     PendingLoads.push_back(Res.second);
7374     return true;
7375   }
7376 
7377   return false;
7378 }
7379 
7380 /// See if we can lower a mempcpy call into an optimized form. If so, return
7381 /// true and lower it. Otherwise return false, and it will be lowered like a
7382 /// normal call.
7383 /// The caller already checked that \p I calls the appropriate LibFunc with a
7384 /// correct prototype.
7385 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7386   SDValue Dst = getValue(I.getArgOperand(0));
7387   SDValue Src = getValue(I.getArgOperand(1));
7388   SDValue Size = getValue(I.getArgOperand(2));
7389 
7390   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7391   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7392   unsigned Align = std::min(DstAlign, SrcAlign);
7393   if (Align == 0) // Alignment of one or both could not be inferred.
7394     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7395 
7396   bool isVol = false;
7397   SDLoc sdl = getCurSDLoc();
7398 
7399   // In the mempcpy context we need to pass in a false value for isTailCall
7400   // because the return pointer needs to be adjusted by the size of
7401   // the copied memory.
7402   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7403                              false, /*isTailCall=*/false,
7404                              MachinePointerInfo(I.getArgOperand(0)),
7405                              MachinePointerInfo(I.getArgOperand(1)));
7406   assert(MC.getNode() != nullptr &&
7407          "** memcpy should not be lowered as TailCall in mempcpy context **");
7408   DAG.setRoot(MC);
7409 
7410   // Check if Size needs to be truncated or extended.
7411   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7412 
7413   // Adjust return pointer to point just past the last dst byte.
7414   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7415                                     Dst, Size);
7416   setValue(&I, DstPlusSize);
7417   return true;
7418 }
7419 
7420 /// See if we can lower a strcpy call into an optimized form.  If so, return
7421 /// true and lower it, otherwise return false and it will be lowered like a
7422 /// normal call.
7423 /// The caller already checked that \p I calls the appropriate LibFunc with a
7424 /// correct prototype.
7425 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7426   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7427 
7428   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7429   std::pair<SDValue, SDValue> Res =
7430     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7431                                 getValue(Arg0), getValue(Arg1),
7432                                 MachinePointerInfo(Arg0),
7433                                 MachinePointerInfo(Arg1), isStpcpy);
7434   if (Res.first.getNode()) {
7435     setValue(&I, Res.first);
7436     DAG.setRoot(Res.second);
7437     return true;
7438   }
7439 
7440   return false;
7441 }
7442 
7443 /// See if we can lower a strcmp call into an optimized form.  If so, return
7444 /// true and lower it, otherwise return false and it will be lowered like a
7445 /// normal call.
7446 /// The caller already checked that \p I calls the appropriate LibFunc with a
7447 /// correct prototype.
7448 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7449   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7450 
7451   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7452   std::pair<SDValue, SDValue> Res =
7453     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7454                                 getValue(Arg0), getValue(Arg1),
7455                                 MachinePointerInfo(Arg0),
7456                                 MachinePointerInfo(Arg1));
7457   if (Res.first.getNode()) {
7458     processIntegerCallValue(I, Res.first, true);
7459     PendingLoads.push_back(Res.second);
7460     return true;
7461   }
7462 
7463   return false;
7464 }
7465 
7466 /// See if we can lower a strlen call into an optimized form.  If so, return
7467 /// true and lower it, otherwise return false and it will be lowered like a
7468 /// normal call.
7469 /// The caller already checked that \p I calls the appropriate LibFunc with a
7470 /// correct prototype.
7471 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7472   const Value *Arg0 = I.getArgOperand(0);
7473 
7474   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7475   std::pair<SDValue, SDValue> Res =
7476     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7477                                 getValue(Arg0), MachinePointerInfo(Arg0));
7478   if (Res.first.getNode()) {
7479     processIntegerCallValue(I, Res.first, false);
7480     PendingLoads.push_back(Res.second);
7481     return true;
7482   }
7483 
7484   return false;
7485 }
7486 
7487 /// See if we can lower a strnlen call into an optimized form.  If so, return
7488 /// true and lower it, otherwise return false and it will be lowered like a
7489 /// normal call.
7490 /// The caller already checked that \p I calls the appropriate LibFunc with a
7491 /// correct prototype.
7492 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7493   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7494 
7495   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7496   std::pair<SDValue, SDValue> Res =
7497     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7498                                  getValue(Arg0), getValue(Arg1),
7499                                  MachinePointerInfo(Arg0));
7500   if (Res.first.getNode()) {
7501     processIntegerCallValue(I, Res.first, false);
7502     PendingLoads.push_back(Res.second);
7503     return true;
7504   }
7505 
7506   return false;
7507 }
7508 
7509 /// See if we can lower a unary floating-point operation into an SDNode with
7510 /// the specified Opcode.  If so, return true and lower it, otherwise return
7511 /// false and it will be lowered like a normal call.
7512 /// The caller already checked that \p I calls the appropriate LibFunc with a
7513 /// correct prototype.
7514 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7515                                               unsigned Opcode) {
7516   // We already checked this call's prototype; verify it doesn't modify errno.
7517   if (!I.onlyReadsMemory())
7518     return false;
7519 
7520   SDValue Tmp = getValue(I.getArgOperand(0));
7521   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7522   return true;
7523 }
7524 
7525 /// See if we can lower a binary floating-point operation into an SDNode with
7526 /// the specified Opcode. If so, return true and lower it. Otherwise return
7527 /// false, and it will be lowered like a normal call.
7528 /// The caller already checked that \p I calls the appropriate LibFunc with a
7529 /// correct prototype.
7530 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7531                                                unsigned Opcode) {
7532   // We already checked this call's prototype; verify it doesn't modify errno.
7533   if (!I.onlyReadsMemory())
7534     return false;
7535 
7536   SDValue Tmp0 = getValue(I.getArgOperand(0));
7537   SDValue Tmp1 = getValue(I.getArgOperand(1));
7538   EVT VT = Tmp0.getValueType();
7539   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7540   return true;
7541 }
7542 
7543 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7544   // Handle inline assembly differently.
7545   if (isa<InlineAsm>(I.getCalledValue())) {
7546     visitInlineAsm(&I);
7547     return;
7548   }
7549 
7550   if (Function *F = I.getCalledFunction()) {
7551     if (F->isDeclaration()) {
7552       // Is this an LLVM intrinsic or a target-specific intrinsic?
7553       unsigned IID = F->getIntrinsicID();
7554       if (!IID)
7555         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7556           IID = II->getIntrinsicID(F);
7557 
7558       if (IID) {
7559         visitIntrinsicCall(I, IID);
7560         return;
7561       }
7562     }
7563 
7564     // Check for well-known libc/libm calls.  If the function is internal, it
7565     // can't be a library call.  Don't do the check if marked as nobuiltin for
7566     // some reason or the call site requires strict floating point semantics.
7567     LibFunc Func;
7568     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7569         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7570         LibInfo->hasOptimizedCodeGen(Func)) {
7571       switch (Func) {
7572       default: break;
7573       case LibFunc_copysign:
7574       case LibFunc_copysignf:
7575       case LibFunc_copysignl:
7576         // We already checked this call's prototype; verify it doesn't modify
7577         // errno.
7578         if (I.onlyReadsMemory()) {
7579           SDValue LHS = getValue(I.getArgOperand(0));
7580           SDValue RHS = getValue(I.getArgOperand(1));
7581           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7582                                    LHS.getValueType(), LHS, RHS));
7583           return;
7584         }
7585         break;
7586       case LibFunc_fabs:
7587       case LibFunc_fabsf:
7588       case LibFunc_fabsl:
7589         if (visitUnaryFloatCall(I, ISD::FABS))
7590           return;
7591         break;
7592       case LibFunc_fmin:
7593       case LibFunc_fminf:
7594       case LibFunc_fminl:
7595         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7596           return;
7597         break;
7598       case LibFunc_fmax:
7599       case LibFunc_fmaxf:
7600       case LibFunc_fmaxl:
7601         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7602           return;
7603         break;
7604       case LibFunc_sin:
7605       case LibFunc_sinf:
7606       case LibFunc_sinl:
7607         if (visitUnaryFloatCall(I, ISD::FSIN))
7608           return;
7609         break;
7610       case LibFunc_cos:
7611       case LibFunc_cosf:
7612       case LibFunc_cosl:
7613         if (visitUnaryFloatCall(I, ISD::FCOS))
7614           return;
7615         break;
7616       case LibFunc_sqrt:
7617       case LibFunc_sqrtf:
7618       case LibFunc_sqrtl:
7619       case LibFunc_sqrt_finite:
7620       case LibFunc_sqrtf_finite:
7621       case LibFunc_sqrtl_finite:
7622         if (visitUnaryFloatCall(I, ISD::FSQRT))
7623           return;
7624         break;
7625       case LibFunc_floor:
7626       case LibFunc_floorf:
7627       case LibFunc_floorl:
7628         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7629           return;
7630         break;
7631       case LibFunc_nearbyint:
7632       case LibFunc_nearbyintf:
7633       case LibFunc_nearbyintl:
7634         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7635           return;
7636         break;
7637       case LibFunc_ceil:
7638       case LibFunc_ceilf:
7639       case LibFunc_ceill:
7640         if (visitUnaryFloatCall(I, ISD::FCEIL))
7641           return;
7642         break;
7643       case LibFunc_rint:
7644       case LibFunc_rintf:
7645       case LibFunc_rintl:
7646         if (visitUnaryFloatCall(I, ISD::FRINT))
7647           return;
7648         break;
7649       case LibFunc_round:
7650       case LibFunc_roundf:
7651       case LibFunc_roundl:
7652         if (visitUnaryFloatCall(I, ISD::FROUND))
7653           return;
7654         break;
7655       case LibFunc_trunc:
7656       case LibFunc_truncf:
7657       case LibFunc_truncl:
7658         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7659           return;
7660         break;
7661       case LibFunc_log2:
7662       case LibFunc_log2f:
7663       case LibFunc_log2l:
7664         if (visitUnaryFloatCall(I, ISD::FLOG2))
7665           return;
7666         break;
7667       case LibFunc_exp2:
7668       case LibFunc_exp2f:
7669       case LibFunc_exp2l:
7670         if (visitUnaryFloatCall(I, ISD::FEXP2))
7671           return;
7672         break;
7673       case LibFunc_memcmp:
7674         if (visitMemCmpCall(I))
7675           return;
7676         break;
7677       case LibFunc_mempcpy:
7678         if (visitMemPCpyCall(I))
7679           return;
7680         break;
7681       case LibFunc_memchr:
7682         if (visitMemChrCall(I))
7683           return;
7684         break;
7685       case LibFunc_strcpy:
7686         if (visitStrCpyCall(I, false))
7687           return;
7688         break;
7689       case LibFunc_stpcpy:
7690         if (visitStrCpyCall(I, true))
7691           return;
7692         break;
7693       case LibFunc_strcmp:
7694         if (visitStrCmpCall(I))
7695           return;
7696         break;
7697       case LibFunc_strlen:
7698         if (visitStrLenCall(I))
7699           return;
7700         break;
7701       case LibFunc_strnlen:
7702         if (visitStrNLenCall(I))
7703           return;
7704         break;
7705       }
7706     }
7707   }
7708 
7709   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7710   // have to do anything here to lower funclet bundles.
7711   assert(!I.hasOperandBundlesOtherThan(
7712              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7713          "Cannot lower calls with arbitrary operand bundles!");
7714 
7715   SDValue Callee = getValue(I.getCalledValue());
7716 
7717   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7718     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7719   else
7720     // Check if we can potentially perform a tail call. More detailed checking
7721     // is be done within LowerCallTo, after more information about the call is
7722     // known.
7723     LowerCallTo(&I, Callee, I.isTailCall());
7724 }
7725 
7726 namespace {
7727 
7728 /// AsmOperandInfo - This contains information for each constraint that we are
7729 /// lowering.
7730 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7731 public:
7732   /// CallOperand - If this is the result output operand or a clobber
7733   /// this is null, otherwise it is the incoming operand to the CallInst.
7734   /// This gets modified as the asm is processed.
7735   SDValue CallOperand;
7736 
7737   /// AssignedRegs - If this is a register or register class operand, this
7738   /// contains the set of register corresponding to the operand.
7739   RegsForValue AssignedRegs;
7740 
7741   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7742     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7743   }
7744 
7745   /// Whether or not this operand accesses memory
7746   bool hasMemory(const TargetLowering &TLI) const {
7747     // Indirect operand accesses access memory.
7748     if (isIndirect)
7749       return true;
7750 
7751     for (const auto &Code : Codes)
7752       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7753         return true;
7754 
7755     return false;
7756   }
7757 
7758   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7759   /// corresponds to.  If there is no Value* for this operand, it returns
7760   /// MVT::Other.
7761   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7762                            const DataLayout &DL) const {
7763     if (!CallOperandVal) return MVT::Other;
7764 
7765     if (isa<BasicBlock>(CallOperandVal))
7766       return TLI.getPointerTy(DL);
7767 
7768     llvm::Type *OpTy = CallOperandVal->getType();
7769 
7770     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7771     // If this is an indirect operand, the operand is a pointer to the
7772     // accessed type.
7773     if (isIndirect) {
7774       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7775       if (!PtrTy)
7776         report_fatal_error("Indirect operand for inline asm not a pointer!");
7777       OpTy = PtrTy->getElementType();
7778     }
7779 
7780     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7781     if (StructType *STy = dyn_cast<StructType>(OpTy))
7782       if (STy->getNumElements() == 1)
7783         OpTy = STy->getElementType(0);
7784 
7785     // If OpTy is not a single value, it may be a struct/union that we
7786     // can tile with integers.
7787     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7788       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7789       switch (BitSize) {
7790       default: break;
7791       case 1:
7792       case 8:
7793       case 16:
7794       case 32:
7795       case 64:
7796       case 128:
7797         OpTy = IntegerType::get(Context, BitSize);
7798         break;
7799       }
7800     }
7801 
7802     return TLI.getValueType(DL, OpTy, true);
7803   }
7804 };
7805 
7806 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7807 
7808 } // end anonymous namespace
7809 
7810 /// Make sure that the output operand \p OpInfo and its corresponding input
7811 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7812 /// out).
7813 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7814                                SDISelAsmOperandInfo &MatchingOpInfo,
7815                                SelectionDAG &DAG) {
7816   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7817     return;
7818 
7819   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7820   const auto &TLI = DAG.getTargetLoweringInfo();
7821 
7822   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7823       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7824                                        OpInfo.ConstraintVT);
7825   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7826       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7827                                        MatchingOpInfo.ConstraintVT);
7828   if ((OpInfo.ConstraintVT.isInteger() !=
7829        MatchingOpInfo.ConstraintVT.isInteger()) ||
7830       (MatchRC.second != InputRC.second)) {
7831     // FIXME: error out in a more elegant fashion
7832     report_fatal_error("Unsupported asm: input constraint"
7833                        " with a matching output constraint of"
7834                        " incompatible type!");
7835   }
7836   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7837 }
7838 
7839 /// Get a direct memory input to behave well as an indirect operand.
7840 /// This may introduce stores, hence the need for a \p Chain.
7841 /// \return The (possibly updated) chain.
7842 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7843                                         SDISelAsmOperandInfo &OpInfo,
7844                                         SelectionDAG &DAG) {
7845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7846 
7847   // If we don't have an indirect input, put it in the constpool if we can,
7848   // otherwise spill it to a stack slot.
7849   // TODO: This isn't quite right. We need to handle these according to
7850   // the addressing mode that the constraint wants. Also, this may take
7851   // an additional register for the computation and we don't want that
7852   // either.
7853 
7854   // If the operand is a float, integer, or vector constant, spill to a
7855   // constant pool entry to get its address.
7856   const Value *OpVal = OpInfo.CallOperandVal;
7857   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7858       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7859     OpInfo.CallOperand = DAG.getConstantPool(
7860         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7861     return Chain;
7862   }
7863 
7864   // Otherwise, create a stack slot and emit a store to it before the asm.
7865   Type *Ty = OpVal->getType();
7866   auto &DL = DAG.getDataLayout();
7867   uint64_t TySize = DL.getTypeAllocSize(Ty);
7868   unsigned Align = DL.getPrefTypeAlignment(Ty);
7869   MachineFunction &MF = DAG.getMachineFunction();
7870   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7871   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7872   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7873                             MachinePointerInfo::getFixedStack(MF, SSFI),
7874                             TLI.getMemValueType(DL, Ty));
7875   OpInfo.CallOperand = StackSlot;
7876 
7877   return Chain;
7878 }
7879 
7880 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7881 /// specified operand.  We prefer to assign virtual registers, to allow the
7882 /// register allocator to handle the assignment process.  However, if the asm
7883 /// uses features that we can't model on machineinstrs, we have SDISel do the
7884 /// allocation.  This produces generally horrible, but correct, code.
7885 ///
7886 ///   OpInfo describes the operand
7887 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7888 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7889                                  SDISelAsmOperandInfo &OpInfo,
7890                                  SDISelAsmOperandInfo &RefOpInfo) {
7891   LLVMContext &Context = *DAG.getContext();
7892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7893 
7894   MachineFunction &MF = DAG.getMachineFunction();
7895   SmallVector<unsigned, 4> Regs;
7896   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7897 
7898   // No work to do for memory operations.
7899   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7900     return;
7901 
7902   // If this is a constraint for a single physreg, or a constraint for a
7903   // register class, find it.
7904   unsigned AssignedReg;
7905   const TargetRegisterClass *RC;
7906   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7907       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7908   // RC is unset only on failure. Return immediately.
7909   if (!RC)
7910     return;
7911 
7912   // Get the actual register value type.  This is important, because the user
7913   // may have asked for (e.g.) the AX register in i32 type.  We need to
7914   // remember that AX is actually i16 to get the right extension.
7915   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7916 
7917   if (OpInfo.ConstraintVT != MVT::Other) {
7918     // If this is an FP operand in an integer register (or visa versa), or more
7919     // generally if the operand value disagrees with the register class we plan
7920     // to stick it in, fix the operand type.
7921     //
7922     // If this is an input value, the bitcast to the new type is done now.
7923     // Bitcast for output value is done at the end of visitInlineAsm().
7924     if ((OpInfo.Type == InlineAsm::isOutput ||
7925          OpInfo.Type == InlineAsm::isInput) &&
7926         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7927       // Try to convert to the first EVT that the reg class contains.  If the
7928       // types are identical size, use a bitcast to convert (e.g. two differing
7929       // vector types).  Note: output bitcast is done at the end of
7930       // visitInlineAsm().
7931       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7932         // Exclude indirect inputs while they are unsupported because the code
7933         // to perform the load is missing and thus OpInfo.CallOperand still
7934         // refers to the input address rather than the pointed-to value.
7935         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7936           OpInfo.CallOperand =
7937               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7938         OpInfo.ConstraintVT = RegVT;
7939         // If the operand is an FP value and we want it in integer registers,
7940         // use the corresponding integer type. This turns an f64 value into
7941         // i64, which can be passed with two i32 values on a 32-bit machine.
7942       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7943         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7944         if (OpInfo.Type == InlineAsm::isInput)
7945           OpInfo.CallOperand =
7946               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7947         OpInfo.ConstraintVT = VT;
7948       }
7949     }
7950   }
7951 
7952   // No need to allocate a matching input constraint since the constraint it's
7953   // matching to has already been allocated.
7954   if (OpInfo.isMatchingInputConstraint())
7955     return;
7956 
7957   EVT ValueVT = OpInfo.ConstraintVT;
7958   if (OpInfo.ConstraintVT == MVT::Other)
7959     ValueVT = RegVT;
7960 
7961   // Initialize NumRegs.
7962   unsigned NumRegs = 1;
7963   if (OpInfo.ConstraintVT != MVT::Other)
7964     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7965 
7966   // If this is a constraint for a specific physical register, like {r17},
7967   // assign it now.
7968 
7969   // If this associated to a specific register, initialize iterator to correct
7970   // place. If virtual, make sure we have enough registers
7971 
7972   // Initialize iterator if necessary
7973   TargetRegisterClass::iterator I = RC->begin();
7974   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7975 
7976   // Do not check for single registers.
7977   if (AssignedReg) {
7978       for (; *I != AssignedReg; ++I)
7979         assert(I != RC->end() && "AssignedReg should be member of RC");
7980   }
7981 
7982   for (; NumRegs; --NumRegs, ++I) {
7983     assert(I != RC->end() && "Ran out of registers to allocate!");
7984     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7985     Regs.push_back(R);
7986   }
7987 
7988   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7989 }
7990 
7991 static unsigned
7992 findMatchingInlineAsmOperand(unsigned OperandNo,
7993                              const std::vector<SDValue> &AsmNodeOperands) {
7994   // Scan until we find the definition we already emitted of this operand.
7995   unsigned CurOp = InlineAsm::Op_FirstOperand;
7996   for (; OperandNo; --OperandNo) {
7997     // Advance to the next operand.
7998     unsigned OpFlag =
7999         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8000     assert((InlineAsm::isRegDefKind(OpFlag) ||
8001             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8002             InlineAsm::isMemKind(OpFlag)) &&
8003            "Skipped past definitions?");
8004     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8005   }
8006   return CurOp;
8007 }
8008 
8009 namespace {
8010 
8011 class ExtraFlags {
8012   unsigned Flags = 0;
8013 
8014 public:
8015   explicit ExtraFlags(ImmutableCallSite CS) {
8016     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8017     if (IA->hasSideEffects())
8018       Flags |= InlineAsm::Extra_HasSideEffects;
8019     if (IA->isAlignStack())
8020       Flags |= InlineAsm::Extra_IsAlignStack;
8021     if (CS.isConvergent())
8022       Flags |= InlineAsm::Extra_IsConvergent;
8023     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8024   }
8025 
8026   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8027     // Ideally, we would only check against memory constraints.  However, the
8028     // meaning of an Other constraint can be target-specific and we can't easily
8029     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8030     // for Other constraints as well.
8031     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8032         OpInfo.ConstraintType == TargetLowering::C_Other) {
8033       if (OpInfo.Type == InlineAsm::isInput)
8034         Flags |= InlineAsm::Extra_MayLoad;
8035       else if (OpInfo.Type == InlineAsm::isOutput)
8036         Flags |= InlineAsm::Extra_MayStore;
8037       else if (OpInfo.Type == InlineAsm::isClobber)
8038         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8039     }
8040   }
8041 
8042   unsigned get() const { return Flags; }
8043 };
8044 
8045 } // end anonymous namespace
8046 
8047 /// visitInlineAsm - Handle a call to an InlineAsm object.
8048 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8049   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8050 
8051   /// ConstraintOperands - Information about all of the constraints.
8052   SDISelAsmOperandInfoVector ConstraintOperands;
8053 
8054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8055   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8056       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8057 
8058   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8059   // AsmDialect, MayLoad, MayStore).
8060   bool HasSideEffect = IA->hasSideEffects();
8061   ExtraFlags ExtraInfo(CS);
8062 
8063   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8064   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8065   for (auto &T : TargetConstraints) {
8066     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8067     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8068 
8069     // Compute the value type for each operand.
8070     if (OpInfo.Type == InlineAsm::isInput ||
8071         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8072       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8073 
8074       // Process the call argument. BasicBlocks are labels, currently appearing
8075       // only in asm's.
8076       const Instruction *I = CS.getInstruction();
8077       if (isa<CallBrInst>(I) &&
8078           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8079                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8080         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8081         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8082         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8083       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8084         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8085       } else {
8086         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8087       }
8088 
8089       OpInfo.ConstraintVT =
8090           OpInfo
8091               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8092               .getSimpleVT();
8093     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8094       // The return value of the call is this value.  As such, there is no
8095       // corresponding argument.
8096       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8097       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8098         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8099             DAG.getDataLayout(), STy->getElementType(ResNo));
8100       } else {
8101         assert(ResNo == 0 && "Asm only has one result!");
8102         OpInfo.ConstraintVT =
8103             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8104       }
8105       ++ResNo;
8106     } else {
8107       OpInfo.ConstraintVT = MVT::Other;
8108     }
8109 
8110     if (!HasSideEffect)
8111       HasSideEffect = OpInfo.hasMemory(TLI);
8112 
8113     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8114     // FIXME: Could we compute this on OpInfo rather than T?
8115 
8116     // Compute the constraint code and ConstraintType to use.
8117     TLI.ComputeConstraintToUse(T, SDValue());
8118 
8119     if (T.ConstraintType == TargetLowering::C_Immediate &&
8120         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8121       // We've delayed emitting a diagnostic like the "n" constraint because
8122       // inlining could cause an integer showing up.
8123       return emitInlineAsmError(
8124           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8125                   "integer constant expression");
8126 
8127     ExtraInfo.update(T);
8128   }
8129 
8130 
8131   // We won't need to flush pending loads if this asm doesn't touch
8132   // memory and is nonvolatile.
8133   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8134 
8135   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8136   if (IsCallBr) {
8137     // If this is a callbr we need to flush pending exports since inlineasm_br
8138     // is a terminator. We need to do this before nodes are glued to
8139     // the inlineasm_br node.
8140     Chain = getControlRoot();
8141   }
8142 
8143   // Second pass over the constraints: compute which constraint option to use.
8144   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8145     // If this is an output operand with a matching input operand, look up the
8146     // matching input. If their types mismatch, e.g. one is an integer, the
8147     // other is floating point, or their sizes are different, flag it as an
8148     // error.
8149     if (OpInfo.hasMatchingInput()) {
8150       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8151       patchMatchingInput(OpInfo, Input, DAG);
8152     }
8153 
8154     // Compute the constraint code and ConstraintType to use.
8155     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8156 
8157     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8158         OpInfo.Type == InlineAsm::isClobber)
8159       continue;
8160 
8161     // If this is a memory input, and if the operand is not indirect, do what we
8162     // need to provide an address for the memory input.
8163     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8164         !OpInfo.isIndirect) {
8165       assert((OpInfo.isMultipleAlternative ||
8166               (OpInfo.Type == InlineAsm::isInput)) &&
8167              "Can only indirectify direct input operands!");
8168 
8169       // Memory operands really want the address of the value.
8170       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8171 
8172       // There is no longer a Value* corresponding to this operand.
8173       OpInfo.CallOperandVal = nullptr;
8174 
8175       // It is now an indirect operand.
8176       OpInfo.isIndirect = true;
8177     }
8178 
8179   }
8180 
8181   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8182   std::vector<SDValue> AsmNodeOperands;
8183   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8184   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8185       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8186 
8187   // If we have a !srcloc metadata node associated with it, we want to attach
8188   // this to the ultimately generated inline asm machineinstr.  To do this, we
8189   // pass in the third operand as this (potentially null) inline asm MDNode.
8190   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8191   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8192 
8193   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8194   // bits as operand 3.
8195   AsmNodeOperands.push_back(DAG.getTargetConstant(
8196       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8197 
8198   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8199   // this, assign virtual and physical registers for inputs and otput.
8200   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8201     // Assign Registers.
8202     SDISelAsmOperandInfo &RefOpInfo =
8203         OpInfo.isMatchingInputConstraint()
8204             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8205             : OpInfo;
8206     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8207 
8208     switch (OpInfo.Type) {
8209     case InlineAsm::isOutput:
8210       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8211           ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8212             OpInfo.ConstraintType == TargetLowering::C_Other) &&
8213            OpInfo.isIndirect)) {
8214         unsigned ConstraintID =
8215             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8216         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8217                "Failed to convert memory constraint code to constraint id.");
8218 
8219         // Add information to the INLINEASM node to know about this output.
8220         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8221         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8222         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8223                                                         MVT::i32));
8224         AsmNodeOperands.push_back(OpInfo.CallOperand);
8225         break;
8226       } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8227                    OpInfo.ConstraintType == TargetLowering::C_Other) &&
8228                   !OpInfo.isIndirect) ||
8229                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8230                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8231         // Otherwise, this outputs to a register (directly for C_Register /
8232         // C_RegisterClass, and a target-defined fashion for
8233         // C_Immediate/C_Other). Find a register that we can use.
8234         if (OpInfo.AssignedRegs.Regs.empty()) {
8235           emitInlineAsmError(
8236               CS, "couldn't allocate output register for constraint '" +
8237                       Twine(OpInfo.ConstraintCode) + "'");
8238           return;
8239         }
8240 
8241         // Add information to the INLINEASM node to know that this register is
8242         // set.
8243         OpInfo.AssignedRegs.AddInlineAsmOperands(
8244             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8245                                   : InlineAsm::Kind_RegDef,
8246             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8247       }
8248       break;
8249 
8250     case InlineAsm::isInput: {
8251       SDValue InOperandVal = OpInfo.CallOperand;
8252 
8253       if (OpInfo.isMatchingInputConstraint()) {
8254         // If this is required to match an output register we have already set,
8255         // just use its register.
8256         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8257                                                   AsmNodeOperands);
8258         unsigned OpFlag =
8259           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8260         if (InlineAsm::isRegDefKind(OpFlag) ||
8261             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8262           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8263           if (OpInfo.isIndirect) {
8264             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8265             emitInlineAsmError(CS, "inline asm not supported yet:"
8266                                    " don't know how to handle tied "
8267                                    "indirect register inputs");
8268             return;
8269           }
8270 
8271           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8272           SmallVector<unsigned, 4> Regs;
8273 
8274           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8275             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8276             MachineRegisterInfo &RegInfo =
8277                 DAG.getMachineFunction().getRegInfo();
8278             for (unsigned i = 0; i != NumRegs; ++i)
8279               Regs.push_back(RegInfo.createVirtualRegister(RC));
8280           } else {
8281             emitInlineAsmError(CS, "inline asm error: This value type register "
8282                                    "class is not natively supported!");
8283             return;
8284           }
8285 
8286           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8287 
8288           SDLoc dl = getCurSDLoc();
8289           // Use the produced MatchedRegs object to
8290           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8291                                     CS.getInstruction());
8292           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8293                                            true, OpInfo.getMatchedOperand(), dl,
8294                                            DAG, AsmNodeOperands);
8295           break;
8296         }
8297 
8298         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8299         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8300                "Unexpected number of operands");
8301         // Add information to the INLINEASM node to know about this input.
8302         // See InlineAsm.h isUseOperandTiedToDef.
8303         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8304         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8305                                                     OpInfo.getMatchedOperand());
8306         AsmNodeOperands.push_back(DAG.getTargetConstant(
8307             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8308         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8309         break;
8310       }
8311 
8312       // Treat indirect 'X' constraint as memory.
8313       if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8314            OpInfo.ConstraintType == TargetLowering::C_Other) &&
8315           OpInfo.isIndirect)
8316         OpInfo.ConstraintType = TargetLowering::C_Memory;
8317 
8318       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8319           OpInfo.ConstraintType == TargetLowering::C_Other) {
8320         std::vector<SDValue> Ops;
8321         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8322                                           Ops, DAG);
8323         if (Ops.empty()) {
8324           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8325             if (isa<ConstantSDNode>(InOperandVal)) {
8326               emitInlineAsmError(CS, "value out of range for constraint '" +
8327                                  Twine(OpInfo.ConstraintCode) + "'");
8328               return;
8329             }
8330 
8331           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8332                                      Twine(OpInfo.ConstraintCode) + "'");
8333           return;
8334         }
8335 
8336         // Add information to the INLINEASM node to know about this input.
8337         unsigned ResOpType =
8338           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8339         AsmNodeOperands.push_back(DAG.getTargetConstant(
8340             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8341         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8342         break;
8343       }
8344 
8345       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8346         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8347         assert(InOperandVal.getValueType() ==
8348                    TLI.getPointerTy(DAG.getDataLayout()) &&
8349                "Memory operands expect pointer values");
8350 
8351         unsigned ConstraintID =
8352             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8353         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8354                "Failed to convert memory constraint code to constraint id.");
8355 
8356         // Add information to the INLINEASM node to know about this input.
8357         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8358         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8359         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8360                                                         getCurSDLoc(),
8361                                                         MVT::i32));
8362         AsmNodeOperands.push_back(InOperandVal);
8363         break;
8364       }
8365 
8366       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8367               OpInfo.ConstraintType == TargetLowering::C_Register ||
8368               OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8369              "Unknown constraint type!");
8370 
8371       // TODO: Support this.
8372       if (OpInfo.isIndirect) {
8373         emitInlineAsmError(
8374             CS, "Don't know how to handle indirect register inputs yet "
8375                 "for constraint '" +
8376                     Twine(OpInfo.ConstraintCode) + "'");
8377         return;
8378       }
8379 
8380       // Copy the input into the appropriate registers.
8381       if (OpInfo.AssignedRegs.Regs.empty()) {
8382         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8383                                    Twine(OpInfo.ConstraintCode) + "'");
8384         return;
8385       }
8386 
8387       SDLoc dl = getCurSDLoc();
8388 
8389       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8390                                         Chain, &Flag, CS.getInstruction());
8391 
8392       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8393                                                dl, DAG, AsmNodeOperands);
8394       break;
8395     }
8396     case InlineAsm::isClobber:
8397       // Add the clobbered value to the operand list, so that the register
8398       // allocator is aware that the physreg got clobbered.
8399       if (!OpInfo.AssignedRegs.Regs.empty())
8400         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8401                                                  false, 0, getCurSDLoc(), DAG,
8402                                                  AsmNodeOperands);
8403       break;
8404     }
8405   }
8406 
8407   // Finish up input operands.  Set the input chain and add the flag last.
8408   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8409   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8410 
8411   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8412   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8413                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8414   Flag = Chain.getValue(1);
8415 
8416   // Do additional work to generate outputs.
8417 
8418   SmallVector<EVT, 1> ResultVTs;
8419   SmallVector<SDValue, 1> ResultValues;
8420   SmallVector<SDValue, 8> OutChains;
8421 
8422   llvm::Type *CSResultType = CS.getType();
8423   ArrayRef<Type *> ResultTypes;
8424   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8425     ResultTypes = StructResult->elements();
8426   else if (!CSResultType->isVoidTy())
8427     ResultTypes = makeArrayRef(CSResultType);
8428 
8429   auto CurResultType = ResultTypes.begin();
8430   auto handleRegAssign = [&](SDValue V) {
8431     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8432     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8433     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8434     ++CurResultType;
8435     // If the type of the inline asm call site return value is different but has
8436     // same size as the type of the asm output bitcast it.  One example of this
8437     // is for vectors with different width / number of elements.  This can
8438     // happen for register classes that can contain multiple different value
8439     // types.  The preg or vreg allocated may not have the same VT as was
8440     // expected.
8441     //
8442     // This can also happen for a return value that disagrees with the register
8443     // class it is put in, eg. a double in a general-purpose register on a
8444     // 32-bit machine.
8445     if (ResultVT != V.getValueType() &&
8446         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8447       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8448     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8449              V.getValueType().isInteger()) {
8450       // If a result value was tied to an input value, the computed result
8451       // may have a wider width than the expected result.  Extract the
8452       // relevant portion.
8453       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8454     }
8455     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8456     ResultVTs.push_back(ResultVT);
8457     ResultValues.push_back(V);
8458   };
8459 
8460   // Deal with output operands.
8461   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8462     if (OpInfo.Type == InlineAsm::isOutput) {
8463       SDValue Val;
8464       // Skip trivial output operands.
8465       if (OpInfo.AssignedRegs.Regs.empty())
8466         continue;
8467 
8468       switch (OpInfo.ConstraintType) {
8469       case TargetLowering::C_Register:
8470       case TargetLowering::C_RegisterClass:
8471         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8472             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8473         break;
8474       case TargetLowering::C_Immediate:
8475       case TargetLowering::C_Other:
8476         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8477                                               OpInfo, DAG);
8478         break;
8479       case TargetLowering::C_Memory:
8480         break; // Already handled.
8481       case TargetLowering::C_Unknown:
8482         assert(false && "Unexpected unknown constraint");
8483       }
8484 
8485       // Indirect output manifest as stores. Record output chains.
8486       if (OpInfo.isIndirect) {
8487         const Value *Ptr = OpInfo.CallOperandVal;
8488         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8489         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8490                                      MachinePointerInfo(Ptr));
8491         OutChains.push_back(Store);
8492       } else {
8493         // generate CopyFromRegs to associated registers.
8494         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8495         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8496           for (const SDValue &V : Val->op_values())
8497             handleRegAssign(V);
8498         } else
8499           handleRegAssign(Val);
8500       }
8501     }
8502   }
8503 
8504   // Set results.
8505   if (!ResultValues.empty()) {
8506     assert(CurResultType == ResultTypes.end() &&
8507            "Mismatch in number of ResultTypes");
8508     assert(ResultValues.size() == ResultTypes.size() &&
8509            "Mismatch in number of output operands in asm result");
8510 
8511     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8512                             DAG.getVTList(ResultVTs), ResultValues);
8513     setValue(CS.getInstruction(), V);
8514   }
8515 
8516   // Collect store chains.
8517   if (!OutChains.empty())
8518     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8519 
8520   // Only Update Root if inline assembly has a memory effect.
8521   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8522     DAG.setRoot(Chain);
8523 }
8524 
8525 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8526                                              const Twine &Message) {
8527   LLVMContext &Ctx = *DAG.getContext();
8528   Ctx.emitError(CS.getInstruction(), Message);
8529 
8530   // Make sure we leave the DAG in a valid state
8531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8532   SmallVector<EVT, 1> ValueVTs;
8533   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8534 
8535   if (ValueVTs.empty())
8536     return;
8537 
8538   SmallVector<SDValue, 1> Ops;
8539   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8540     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8541 
8542   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8543 }
8544 
8545 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8546   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8547                           MVT::Other, getRoot(),
8548                           getValue(I.getArgOperand(0)),
8549                           DAG.getSrcValue(I.getArgOperand(0))));
8550 }
8551 
8552 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8554   const DataLayout &DL = DAG.getDataLayout();
8555   SDValue V = DAG.getVAArg(
8556       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8557       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8558       DL.getABITypeAlignment(I.getType()));
8559   DAG.setRoot(V.getValue(1));
8560 
8561   if (I.getType()->isPointerTy())
8562     V = DAG.getPtrExtOrTrunc(
8563         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8564   setValue(&I, V);
8565 }
8566 
8567 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8568   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8569                           MVT::Other, getRoot(),
8570                           getValue(I.getArgOperand(0)),
8571                           DAG.getSrcValue(I.getArgOperand(0))));
8572 }
8573 
8574 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8575   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8576                           MVT::Other, getRoot(),
8577                           getValue(I.getArgOperand(0)),
8578                           getValue(I.getArgOperand(1)),
8579                           DAG.getSrcValue(I.getArgOperand(0)),
8580                           DAG.getSrcValue(I.getArgOperand(1))));
8581 }
8582 
8583 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8584                                                     const Instruction &I,
8585                                                     SDValue Op) {
8586   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8587   if (!Range)
8588     return Op;
8589 
8590   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8591   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8592     return Op;
8593 
8594   APInt Lo = CR.getUnsignedMin();
8595   if (!Lo.isMinValue())
8596     return Op;
8597 
8598   APInt Hi = CR.getUnsignedMax();
8599   unsigned Bits = std::max(Hi.getActiveBits(),
8600                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8601 
8602   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8603 
8604   SDLoc SL = getCurSDLoc();
8605 
8606   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8607                              DAG.getValueType(SmallVT));
8608   unsigned NumVals = Op.getNode()->getNumValues();
8609   if (NumVals == 1)
8610     return ZExt;
8611 
8612   SmallVector<SDValue, 4> Ops;
8613 
8614   Ops.push_back(ZExt);
8615   for (unsigned I = 1; I != NumVals; ++I)
8616     Ops.push_back(Op.getValue(I));
8617 
8618   return DAG.getMergeValues(Ops, SL);
8619 }
8620 
8621 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8622 /// the call being lowered.
8623 ///
8624 /// This is a helper for lowering intrinsics that follow a target calling
8625 /// convention or require stack pointer adjustment. Only a subset of the
8626 /// intrinsic's operands need to participate in the calling convention.
8627 void SelectionDAGBuilder::populateCallLoweringInfo(
8628     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8629     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8630     bool IsPatchPoint) {
8631   TargetLowering::ArgListTy Args;
8632   Args.reserve(NumArgs);
8633 
8634   // Populate the argument list.
8635   // Attributes for args start at offset 1, after the return attribute.
8636   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8637        ArgI != ArgE; ++ArgI) {
8638     const Value *V = Call->getOperand(ArgI);
8639 
8640     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8641 
8642     TargetLowering::ArgListEntry Entry;
8643     Entry.Node = getValue(V);
8644     Entry.Ty = V->getType();
8645     Entry.setAttributes(Call, ArgI);
8646     Args.push_back(Entry);
8647   }
8648 
8649   CLI.setDebugLoc(getCurSDLoc())
8650       .setChain(getRoot())
8651       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8652       .setDiscardResult(Call->use_empty())
8653       .setIsPatchPoint(IsPatchPoint);
8654 }
8655 
8656 /// Add a stack map intrinsic call's live variable operands to a stackmap
8657 /// or patchpoint target node's operand list.
8658 ///
8659 /// Constants are converted to TargetConstants purely as an optimization to
8660 /// avoid constant materialization and register allocation.
8661 ///
8662 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8663 /// generate addess computation nodes, and so FinalizeISel can convert the
8664 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8665 /// address materialization and register allocation, but may also be required
8666 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8667 /// alloca in the entry block, then the runtime may assume that the alloca's
8668 /// StackMap location can be read immediately after compilation and that the
8669 /// location is valid at any point during execution (this is similar to the
8670 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8671 /// only available in a register, then the runtime would need to trap when
8672 /// execution reaches the StackMap in order to read the alloca's location.
8673 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8674                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8675                                 SelectionDAGBuilder &Builder) {
8676   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8677     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8679       Ops.push_back(
8680         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8681       Ops.push_back(
8682         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8683     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8684       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8685       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8686           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8687     } else
8688       Ops.push_back(OpVal);
8689   }
8690 }
8691 
8692 /// Lower llvm.experimental.stackmap directly to its target opcode.
8693 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8694   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8695   //                                  [live variables...])
8696 
8697   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8698 
8699   SDValue Chain, InFlag, Callee, NullPtr;
8700   SmallVector<SDValue, 32> Ops;
8701 
8702   SDLoc DL = getCurSDLoc();
8703   Callee = getValue(CI.getCalledValue());
8704   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8705 
8706   // The stackmap intrinsic only records the live variables (the arguemnts
8707   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8708   // intrinsic, this won't be lowered to a function call. This means we don't
8709   // have to worry about calling conventions and target specific lowering code.
8710   // Instead we perform the call lowering right here.
8711   //
8712   // chain, flag = CALLSEQ_START(chain, 0, 0)
8713   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8714   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8715   //
8716   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8717   InFlag = Chain.getValue(1);
8718 
8719   // Add the <id> and <numBytes> constants.
8720   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8721   Ops.push_back(DAG.getTargetConstant(
8722                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8723   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8724   Ops.push_back(DAG.getTargetConstant(
8725                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8726                   MVT::i32));
8727 
8728   // Push live variables for the stack map.
8729   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8730 
8731   // We are not pushing any register mask info here on the operands list,
8732   // because the stackmap doesn't clobber anything.
8733 
8734   // Push the chain and the glue flag.
8735   Ops.push_back(Chain);
8736   Ops.push_back(InFlag);
8737 
8738   // Create the STACKMAP node.
8739   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8740   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8741   Chain = SDValue(SM, 0);
8742   InFlag = Chain.getValue(1);
8743 
8744   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8745 
8746   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8747 
8748   // Set the root to the target-lowered call chain.
8749   DAG.setRoot(Chain);
8750 
8751   // Inform the Frame Information that we have a stackmap in this function.
8752   FuncInfo.MF->getFrameInfo().setHasStackMap();
8753 }
8754 
8755 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8756 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8757                                           const BasicBlock *EHPadBB) {
8758   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8759   //                                                 i32 <numBytes>,
8760   //                                                 i8* <target>,
8761   //                                                 i32 <numArgs>,
8762   //                                                 [Args...],
8763   //                                                 [live variables...])
8764 
8765   CallingConv::ID CC = CS.getCallingConv();
8766   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8767   bool HasDef = !CS->getType()->isVoidTy();
8768   SDLoc dl = getCurSDLoc();
8769   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8770 
8771   // Handle immediate and symbolic callees.
8772   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8773     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8774                                    /*isTarget=*/true);
8775   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8776     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8777                                          SDLoc(SymbolicCallee),
8778                                          SymbolicCallee->getValueType(0));
8779 
8780   // Get the real number of arguments participating in the call <numArgs>
8781   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8782   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8783 
8784   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8785   // Intrinsics include all meta-operands up to but not including CC.
8786   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8787   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8788          "Not enough arguments provided to the patchpoint intrinsic");
8789 
8790   // For AnyRegCC the arguments are lowered later on manually.
8791   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8792   Type *ReturnTy =
8793     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8794 
8795   TargetLowering::CallLoweringInfo CLI(DAG);
8796   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8797                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8798   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8799 
8800   SDNode *CallEnd = Result.second.getNode();
8801   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8802     CallEnd = CallEnd->getOperand(0).getNode();
8803 
8804   /// Get a call instruction from the call sequence chain.
8805   /// Tail calls are not allowed.
8806   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8807          "Expected a callseq node.");
8808   SDNode *Call = CallEnd->getOperand(0).getNode();
8809   bool HasGlue = Call->getGluedNode();
8810 
8811   // Replace the target specific call node with the patchable intrinsic.
8812   SmallVector<SDValue, 8> Ops;
8813 
8814   // Add the <id> and <numBytes> constants.
8815   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8816   Ops.push_back(DAG.getTargetConstant(
8817                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8818   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8819   Ops.push_back(DAG.getTargetConstant(
8820                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8821                   MVT::i32));
8822 
8823   // Add the callee.
8824   Ops.push_back(Callee);
8825 
8826   // Adjust <numArgs> to account for any arguments that have been passed on the
8827   // stack instead.
8828   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8829   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8830   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8831   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8832 
8833   // Add the calling convention
8834   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8835 
8836   // Add the arguments we omitted previously. The register allocator should
8837   // place these in any free register.
8838   if (IsAnyRegCC)
8839     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8840       Ops.push_back(getValue(CS.getArgument(i)));
8841 
8842   // Push the arguments from the call instruction up to the register mask.
8843   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8844   Ops.append(Call->op_begin() + 2, e);
8845 
8846   // Push live variables for the stack map.
8847   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8848 
8849   // Push the register mask info.
8850   if (HasGlue)
8851     Ops.push_back(*(Call->op_end()-2));
8852   else
8853     Ops.push_back(*(Call->op_end()-1));
8854 
8855   // Push the chain (this is originally the first operand of the call, but
8856   // becomes now the last or second to last operand).
8857   Ops.push_back(*(Call->op_begin()));
8858 
8859   // Push the glue flag (last operand).
8860   if (HasGlue)
8861     Ops.push_back(*(Call->op_end()-1));
8862 
8863   SDVTList NodeTys;
8864   if (IsAnyRegCC && HasDef) {
8865     // Create the return types based on the intrinsic definition
8866     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8867     SmallVector<EVT, 3> ValueVTs;
8868     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8869     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8870 
8871     // There is always a chain and a glue type at the end
8872     ValueVTs.push_back(MVT::Other);
8873     ValueVTs.push_back(MVT::Glue);
8874     NodeTys = DAG.getVTList(ValueVTs);
8875   } else
8876     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8877 
8878   // Replace the target specific call node with a PATCHPOINT node.
8879   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8880                                          dl, NodeTys, Ops);
8881 
8882   // Update the NodeMap.
8883   if (HasDef) {
8884     if (IsAnyRegCC)
8885       setValue(CS.getInstruction(), SDValue(MN, 0));
8886     else
8887       setValue(CS.getInstruction(), Result.first);
8888   }
8889 
8890   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8891   // call sequence. Furthermore the location of the chain and glue can change
8892   // when the AnyReg calling convention is used and the intrinsic returns a
8893   // value.
8894   if (IsAnyRegCC && HasDef) {
8895     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8896     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8897     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8898   } else
8899     DAG.ReplaceAllUsesWith(Call, MN);
8900   DAG.DeleteNode(Call);
8901 
8902   // Inform the Frame Information that we have a patchpoint in this function.
8903   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8904 }
8905 
8906 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8907                                             unsigned Intrinsic) {
8908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8909   SDValue Op1 = getValue(I.getArgOperand(0));
8910   SDValue Op2;
8911   if (I.getNumArgOperands() > 1)
8912     Op2 = getValue(I.getArgOperand(1));
8913   SDLoc dl = getCurSDLoc();
8914   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8915   SDValue Res;
8916   FastMathFlags FMF;
8917   if (isa<FPMathOperator>(I))
8918     FMF = I.getFastMathFlags();
8919 
8920   switch (Intrinsic) {
8921   case Intrinsic::experimental_vector_reduce_v2_fadd:
8922     if (FMF.allowReassoc())
8923       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8924                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8925     else
8926       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8927     break;
8928   case Intrinsic::experimental_vector_reduce_v2_fmul:
8929     if (FMF.allowReassoc())
8930       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8931                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8932     else
8933       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8934     break;
8935   case Intrinsic::experimental_vector_reduce_add:
8936     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8937     break;
8938   case Intrinsic::experimental_vector_reduce_mul:
8939     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8940     break;
8941   case Intrinsic::experimental_vector_reduce_and:
8942     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8943     break;
8944   case Intrinsic::experimental_vector_reduce_or:
8945     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8946     break;
8947   case Intrinsic::experimental_vector_reduce_xor:
8948     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8949     break;
8950   case Intrinsic::experimental_vector_reduce_smax:
8951     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8952     break;
8953   case Intrinsic::experimental_vector_reduce_smin:
8954     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8955     break;
8956   case Intrinsic::experimental_vector_reduce_umax:
8957     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8958     break;
8959   case Intrinsic::experimental_vector_reduce_umin:
8960     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8961     break;
8962   case Intrinsic::experimental_vector_reduce_fmax:
8963     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8964     break;
8965   case Intrinsic::experimental_vector_reduce_fmin:
8966     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8967     break;
8968   default:
8969     llvm_unreachable("Unhandled vector reduce intrinsic");
8970   }
8971   setValue(&I, Res);
8972 }
8973 
8974 /// Returns an AttributeList representing the attributes applied to the return
8975 /// value of the given call.
8976 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8977   SmallVector<Attribute::AttrKind, 2> Attrs;
8978   if (CLI.RetSExt)
8979     Attrs.push_back(Attribute::SExt);
8980   if (CLI.RetZExt)
8981     Attrs.push_back(Attribute::ZExt);
8982   if (CLI.IsInReg)
8983     Attrs.push_back(Attribute::InReg);
8984 
8985   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8986                             Attrs);
8987 }
8988 
8989 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8990 /// implementation, which just calls LowerCall.
8991 /// FIXME: When all targets are
8992 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8993 std::pair<SDValue, SDValue>
8994 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8995   // Handle the incoming return values from the call.
8996   CLI.Ins.clear();
8997   Type *OrigRetTy = CLI.RetTy;
8998   SmallVector<EVT, 4> RetTys;
8999   SmallVector<uint64_t, 4> Offsets;
9000   auto &DL = CLI.DAG.getDataLayout();
9001   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9002 
9003   if (CLI.IsPostTypeLegalization) {
9004     // If we are lowering a libcall after legalization, split the return type.
9005     SmallVector<EVT, 4> OldRetTys;
9006     SmallVector<uint64_t, 4> OldOffsets;
9007     RetTys.swap(OldRetTys);
9008     Offsets.swap(OldOffsets);
9009 
9010     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9011       EVT RetVT = OldRetTys[i];
9012       uint64_t Offset = OldOffsets[i];
9013       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9014       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9015       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9016       RetTys.append(NumRegs, RegisterVT);
9017       for (unsigned j = 0; j != NumRegs; ++j)
9018         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9019     }
9020   }
9021 
9022   SmallVector<ISD::OutputArg, 4> Outs;
9023   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9024 
9025   bool CanLowerReturn =
9026       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9027                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9028 
9029   SDValue DemoteStackSlot;
9030   int DemoteStackIdx = -100;
9031   if (!CanLowerReturn) {
9032     // FIXME: equivalent assert?
9033     // assert(!CS.hasInAllocaArgument() &&
9034     //        "sret demotion is incompatible with inalloca");
9035     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9036     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9037     MachineFunction &MF = CLI.DAG.getMachineFunction();
9038     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9039     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9040                                               DL.getAllocaAddrSpace());
9041 
9042     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9043     ArgListEntry Entry;
9044     Entry.Node = DemoteStackSlot;
9045     Entry.Ty = StackSlotPtrType;
9046     Entry.IsSExt = false;
9047     Entry.IsZExt = false;
9048     Entry.IsInReg = false;
9049     Entry.IsSRet = true;
9050     Entry.IsNest = false;
9051     Entry.IsByVal = false;
9052     Entry.IsReturned = false;
9053     Entry.IsSwiftSelf = false;
9054     Entry.IsSwiftError = false;
9055     Entry.Alignment = Align;
9056     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9057     CLI.NumFixedArgs += 1;
9058     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9059 
9060     // sret demotion isn't compatible with tail-calls, since the sret argument
9061     // points into the callers stack frame.
9062     CLI.IsTailCall = false;
9063   } else {
9064     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9065         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9066     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9067       ISD::ArgFlagsTy Flags;
9068       if (NeedsRegBlock) {
9069         Flags.setInConsecutiveRegs();
9070         if (I == RetTys.size() - 1)
9071           Flags.setInConsecutiveRegsLast();
9072       }
9073       EVT VT = RetTys[I];
9074       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9075                                                      CLI.CallConv, VT);
9076       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9077                                                        CLI.CallConv, VT);
9078       for (unsigned i = 0; i != NumRegs; ++i) {
9079         ISD::InputArg MyFlags;
9080         MyFlags.Flags = Flags;
9081         MyFlags.VT = RegisterVT;
9082         MyFlags.ArgVT = VT;
9083         MyFlags.Used = CLI.IsReturnValueUsed;
9084         if (CLI.RetTy->isPointerTy()) {
9085           MyFlags.Flags.setPointer();
9086           MyFlags.Flags.setPointerAddrSpace(
9087               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9088         }
9089         if (CLI.RetSExt)
9090           MyFlags.Flags.setSExt();
9091         if (CLI.RetZExt)
9092           MyFlags.Flags.setZExt();
9093         if (CLI.IsInReg)
9094           MyFlags.Flags.setInReg();
9095         CLI.Ins.push_back(MyFlags);
9096       }
9097     }
9098   }
9099 
9100   // We push in swifterror return as the last element of CLI.Ins.
9101   ArgListTy &Args = CLI.getArgs();
9102   if (supportSwiftError()) {
9103     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9104       if (Args[i].IsSwiftError) {
9105         ISD::InputArg MyFlags;
9106         MyFlags.VT = getPointerTy(DL);
9107         MyFlags.ArgVT = EVT(getPointerTy(DL));
9108         MyFlags.Flags.setSwiftError();
9109         CLI.Ins.push_back(MyFlags);
9110       }
9111     }
9112   }
9113 
9114   // Handle all of the outgoing arguments.
9115   CLI.Outs.clear();
9116   CLI.OutVals.clear();
9117   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9118     SmallVector<EVT, 4> ValueVTs;
9119     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9120     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9121     Type *FinalType = Args[i].Ty;
9122     if (Args[i].IsByVal)
9123       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9124     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9125         FinalType, CLI.CallConv, CLI.IsVarArg);
9126     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9127          ++Value) {
9128       EVT VT = ValueVTs[Value];
9129       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9130       SDValue Op = SDValue(Args[i].Node.getNode(),
9131                            Args[i].Node.getResNo() + Value);
9132       ISD::ArgFlagsTy Flags;
9133 
9134       // Certain targets (such as MIPS), may have a different ABI alignment
9135       // for a type depending on the context. Give the target a chance to
9136       // specify the alignment it wants.
9137       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
9138 
9139       if (Args[i].Ty->isPointerTy()) {
9140         Flags.setPointer();
9141         Flags.setPointerAddrSpace(
9142             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9143       }
9144       if (Args[i].IsZExt)
9145         Flags.setZExt();
9146       if (Args[i].IsSExt)
9147         Flags.setSExt();
9148       if (Args[i].IsInReg) {
9149         // If we are using vectorcall calling convention, a structure that is
9150         // passed InReg - is surely an HVA
9151         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9152             isa<StructType>(FinalType)) {
9153           // The first value of a structure is marked
9154           if (0 == Value)
9155             Flags.setHvaStart();
9156           Flags.setHva();
9157         }
9158         // Set InReg Flag
9159         Flags.setInReg();
9160       }
9161       if (Args[i].IsSRet)
9162         Flags.setSRet();
9163       if (Args[i].IsSwiftSelf)
9164         Flags.setSwiftSelf();
9165       if (Args[i].IsSwiftError)
9166         Flags.setSwiftError();
9167       if (Args[i].IsByVal)
9168         Flags.setByVal();
9169       if (Args[i].IsInAlloca) {
9170         Flags.setInAlloca();
9171         // Set the byval flag for CCAssignFn callbacks that don't know about
9172         // inalloca.  This way we can know how many bytes we should've allocated
9173         // and how many bytes a callee cleanup function will pop.  If we port
9174         // inalloca to more targets, we'll have to add custom inalloca handling
9175         // in the various CC lowering callbacks.
9176         Flags.setByVal();
9177       }
9178       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9179         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9180         Type *ElementTy = Ty->getElementType();
9181 
9182         unsigned FrameSize = DL.getTypeAllocSize(
9183             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9184         Flags.setByValSize(FrameSize);
9185 
9186         // info is not there but there are cases it cannot get right.
9187         unsigned FrameAlign;
9188         if (Args[i].Alignment)
9189           FrameAlign = Args[i].Alignment;
9190         else
9191           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9192         Flags.setByValAlign(FrameAlign);
9193       }
9194       if (Args[i].IsNest)
9195         Flags.setNest();
9196       if (NeedsRegBlock)
9197         Flags.setInConsecutiveRegs();
9198       Flags.setOrigAlign(OriginalAlignment);
9199 
9200       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9201                                                  CLI.CallConv, VT);
9202       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9203                                                         CLI.CallConv, VT);
9204       SmallVector<SDValue, 4> Parts(NumParts);
9205       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9206 
9207       if (Args[i].IsSExt)
9208         ExtendKind = ISD::SIGN_EXTEND;
9209       else if (Args[i].IsZExt)
9210         ExtendKind = ISD::ZERO_EXTEND;
9211 
9212       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9213       // for now.
9214       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9215           CanLowerReturn) {
9216         assert((CLI.RetTy == Args[i].Ty ||
9217                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9218                  CLI.RetTy->getPointerAddressSpace() ==
9219                      Args[i].Ty->getPointerAddressSpace())) &&
9220                RetTys.size() == NumValues && "unexpected use of 'returned'");
9221         // Before passing 'returned' to the target lowering code, ensure that
9222         // either the register MVT and the actual EVT are the same size or that
9223         // the return value and argument are extended in the same way; in these
9224         // cases it's safe to pass the argument register value unchanged as the
9225         // return register value (although it's at the target's option whether
9226         // to do so)
9227         // TODO: allow code generation to take advantage of partially preserved
9228         // registers rather than clobbering the entire register when the
9229         // parameter extension method is not compatible with the return
9230         // extension method
9231         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9232             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9233              CLI.RetZExt == Args[i].IsZExt))
9234           Flags.setReturned();
9235       }
9236 
9237       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9238                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9239 
9240       for (unsigned j = 0; j != NumParts; ++j) {
9241         // if it isn't first piece, alignment must be 1
9242         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9243                                i < CLI.NumFixedArgs,
9244                                i, j*Parts[j].getValueType().getStoreSize());
9245         if (NumParts > 1 && j == 0)
9246           MyFlags.Flags.setSplit();
9247         else if (j != 0) {
9248           MyFlags.Flags.setOrigAlign(1);
9249           if (j == NumParts - 1)
9250             MyFlags.Flags.setSplitEnd();
9251         }
9252 
9253         CLI.Outs.push_back(MyFlags);
9254         CLI.OutVals.push_back(Parts[j]);
9255       }
9256 
9257       if (NeedsRegBlock && Value == NumValues - 1)
9258         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9259     }
9260   }
9261 
9262   SmallVector<SDValue, 4> InVals;
9263   CLI.Chain = LowerCall(CLI, InVals);
9264 
9265   // Update CLI.InVals to use outside of this function.
9266   CLI.InVals = InVals;
9267 
9268   // Verify that the target's LowerCall behaved as expected.
9269   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9270          "LowerCall didn't return a valid chain!");
9271   assert((!CLI.IsTailCall || InVals.empty()) &&
9272          "LowerCall emitted a return value for a tail call!");
9273   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9274          "LowerCall didn't emit the correct number of values!");
9275 
9276   // For a tail call, the return value is merely live-out and there aren't
9277   // any nodes in the DAG representing it. Return a special value to
9278   // indicate that a tail call has been emitted and no more Instructions
9279   // should be processed in the current block.
9280   if (CLI.IsTailCall) {
9281     CLI.DAG.setRoot(CLI.Chain);
9282     return std::make_pair(SDValue(), SDValue());
9283   }
9284 
9285 #ifndef NDEBUG
9286   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9287     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9288     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9289            "LowerCall emitted a value with the wrong type!");
9290   }
9291 #endif
9292 
9293   SmallVector<SDValue, 4> ReturnValues;
9294   if (!CanLowerReturn) {
9295     // The instruction result is the result of loading from the
9296     // hidden sret parameter.
9297     SmallVector<EVT, 1> PVTs;
9298     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9299 
9300     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9301     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9302     EVT PtrVT = PVTs[0];
9303 
9304     unsigned NumValues = RetTys.size();
9305     ReturnValues.resize(NumValues);
9306     SmallVector<SDValue, 4> Chains(NumValues);
9307 
9308     // An aggregate return value cannot wrap around the address space, so
9309     // offsets to its parts don't wrap either.
9310     SDNodeFlags Flags;
9311     Flags.setNoUnsignedWrap(true);
9312 
9313     for (unsigned i = 0; i < NumValues; ++i) {
9314       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9315                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9316                                                         PtrVT), Flags);
9317       SDValue L = CLI.DAG.getLoad(
9318           RetTys[i], CLI.DL, CLI.Chain, Add,
9319           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9320                                             DemoteStackIdx, Offsets[i]),
9321           /* Alignment = */ 1);
9322       ReturnValues[i] = L;
9323       Chains[i] = L.getValue(1);
9324     }
9325 
9326     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9327   } else {
9328     // Collect the legal value parts into potentially illegal values
9329     // that correspond to the original function's return values.
9330     Optional<ISD::NodeType> AssertOp;
9331     if (CLI.RetSExt)
9332       AssertOp = ISD::AssertSext;
9333     else if (CLI.RetZExt)
9334       AssertOp = ISD::AssertZext;
9335     unsigned CurReg = 0;
9336     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9337       EVT VT = RetTys[I];
9338       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9339                                                      CLI.CallConv, VT);
9340       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9341                                                        CLI.CallConv, VT);
9342 
9343       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9344                                               NumRegs, RegisterVT, VT, nullptr,
9345                                               CLI.CallConv, AssertOp));
9346       CurReg += NumRegs;
9347     }
9348 
9349     // For a function returning void, there is no return value. We can't create
9350     // such a node, so we just return a null return value in that case. In
9351     // that case, nothing will actually look at the value.
9352     if (ReturnValues.empty())
9353       return std::make_pair(SDValue(), CLI.Chain);
9354   }
9355 
9356   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9357                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9358   return std::make_pair(Res, CLI.Chain);
9359 }
9360 
9361 void TargetLowering::LowerOperationWrapper(SDNode *N,
9362                                            SmallVectorImpl<SDValue> &Results,
9363                                            SelectionDAG &DAG) const {
9364   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9365     Results.push_back(Res);
9366 }
9367 
9368 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9369   llvm_unreachable("LowerOperation not implemented for this target!");
9370 }
9371 
9372 void
9373 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9374   SDValue Op = getNonRegisterValue(V);
9375   assert((Op.getOpcode() != ISD::CopyFromReg ||
9376           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9377          "Copy from a reg to the same reg!");
9378   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9379 
9380   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9381   // If this is an InlineAsm we have to match the registers required, not the
9382   // notional registers required by the type.
9383 
9384   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9385                    None); // This is not an ABI copy.
9386   SDValue Chain = DAG.getEntryNode();
9387 
9388   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9389                               FuncInfo.PreferredExtendType.end())
9390                                  ? ISD::ANY_EXTEND
9391                                  : FuncInfo.PreferredExtendType[V];
9392   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9393   PendingExports.push_back(Chain);
9394 }
9395 
9396 #include "llvm/CodeGen/SelectionDAGISel.h"
9397 
9398 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9399 /// entry block, return true.  This includes arguments used by switches, since
9400 /// the switch may expand into multiple basic blocks.
9401 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9402   // With FastISel active, we may be splitting blocks, so force creation
9403   // of virtual registers for all non-dead arguments.
9404   if (FastISel)
9405     return A->use_empty();
9406 
9407   const BasicBlock &Entry = A->getParent()->front();
9408   for (const User *U : A->users())
9409     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9410       return false;  // Use not in entry block.
9411 
9412   return true;
9413 }
9414 
9415 using ArgCopyElisionMapTy =
9416     DenseMap<const Argument *,
9417              std::pair<const AllocaInst *, const StoreInst *>>;
9418 
9419 /// Scan the entry block of the function in FuncInfo for arguments that look
9420 /// like copies into a local alloca. Record any copied arguments in
9421 /// ArgCopyElisionCandidates.
9422 static void
9423 findArgumentCopyElisionCandidates(const DataLayout &DL,
9424                                   FunctionLoweringInfo *FuncInfo,
9425                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9426   // Record the state of every static alloca used in the entry block. Argument
9427   // allocas are all used in the entry block, so we need approximately as many
9428   // entries as we have arguments.
9429   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9430   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9431   unsigned NumArgs = FuncInfo->Fn->arg_size();
9432   StaticAllocas.reserve(NumArgs * 2);
9433 
9434   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9435     if (!V)
9436       return nullptr;
9437     V = V->stripPointerCasts();
9438     const auto *AI = dyn_cast<AllocaInst>(V);
9439     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9440       return nullptr;
9441     auto Iter = StaticAllocas.insert({AI, Unknown});
9442     return &Iter.first->second;
9443   };
9444 
9445   // Look for stores of arguments to static allocas. Look through bitcasts and
9446   // GEPs to handle type coercions, as long as the alloca is fully initialized
9447   // by the store. Any non-store use of an alloca escapes it and any subsequent
9448   // unanalyzed store might write it.
9449   // FIXME: Handle structs initialized with multiple stores.
9450   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9451     // Look for stores, and handle non-store uses conservatively.
9452     const auto *SI = dyn_cast<StoreInst>(&I);
9453     if (!SI) {
9454       // We will look through cast uses, so ignore them completely.
9455       if (I.isCast())
9456         continue;
9457       // Ignore debug info intrinsics, they don't escape or store to allocas.
9458       if (isa<DbgInfoIntrinsic>(I))
9459         continue;
9460       // This is an unknown instruction. Assume it escapes or writes to all
9461       // static alloca operands.
9462       for (const Use &U : I.operands()) {
9463         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9464           *Info = StaticAllocaInfo::Clobbered;
9465       }
9466       continue;
9467     }
9468 
9469     // If the stored value is a static alloca, mark it as escaped.
9470     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9471       *Info = StaticAllocaInfo::Clobbered;
9472 
9473     // Check if the destination is a static alloca.
9474     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9475     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9476     if (!Info)
9477       continue;
9478     const AllocaInst *AI = cast<AllocaInst>(Dst);
9479 
9480     // Skip allocas that have been initialized or clobbered.
9481     if (*Info != StaticAllocaInfo::Unknown)
9482       continue;
9483 
9484     // Check if the stored value is an argument, and that this store fully
9485     // initializes the alloca. Don't elide copies from the same argument twice.
9486     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9487     const auto *Arg = dyn_cast<Argument>(Val);
9488     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9489         Arg->getType()->isEmptyTy() ||
9490         DL.getTypeStoreSize(Arg->getType()) !=
9491             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9492         ArgCopyElisionCandidates.count(Arg)) {
9493       *Info = StaticAllocaInfo::Clobbered;
9494       continue;
9495     }
9496 
9497     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9498                       << '\n');
9499 
9500     // Mark this alloca and store for argument copy elision.
9501     *Info = StaticAllocaInfo::Elidable;
9502     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9503 
9504     // Stop scanning if we've seen all arguments. This will happen early in -O0
9505     // builds, which is useful, because -O0 builds have large entry blocks and
9506     // many allocas.
9507     if (ArgCopyElisionCandidates.size() == NumArgs)
9508       break;
9509   }
9510 }
9511 
9512 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9513 /// ArgVal is a load from a suitable fixed stack object.
9514 static void tryToElideArgumentCopy(
9515     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9516     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9517     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9518     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9519     SDValue ArgVal, bool &ArgHasUses) {
9520   // Check if this is a load from a fixed stack object.
9521   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9522   if (!LNode)
9523     return;
9524   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9525   if (!FINode)
9526     return;
9527 
9528   // Check that the fixed stack object is the right size and alignment.
9529   // Look at the alignment that the user wrote on the alloca instead of looking
9530   // at the stack object.
9531   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9532   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9533   const AllocaInst *AI = ArgCopyIter->second.first;
9534   int FixedIndex = FINode->getIndex();
9535   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9536   int OldIndex = AllocaIndex;
9537   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9538   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9539     LLVM_DEBUG(
9540         dbgs() << "  argument copy elision failed due to bad fixed stack "
9541                   "object size\n");
9542     return;
9543   }
9544   unsigned RequiredAlignment = AI->getAlignment();
9545   if (!RequiredAlignment) {
9546     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9547         AI->getAllocatedType());
9548   }
9549   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9550     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9551                          "greater than stack argument alignment ("
9552                       << RequiredAlignment << " vs "
9553                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9554     return;
9555   }
9556 
9557   // Perform the elision. Delete the old stack object and replace its only use
9558   // in the variable info map. Mark the stack object as mutable.
9559   LLVM_DEBUG({
9560     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9561            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9562            << '\n';
9563   });
9564   MFI.RemoveStackObject(OldIndex);
9565   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9566   AllocaIndex = FixedIndex;
9567   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9568   Chains.push_back(ArgVal.getValue(1));
9569 
9570   // Avoid emitting code for the store implementing the copy.
9571   const StoreInst *SI = ArgCopyIter->second.second;
9572   ElidedArgCopyInstrs.insert(SI);
9573 
9574   // Check for uses of the argument again so that we can avoid exporting ArgVal
9575   // if it is't used by anything other than the store.
9576   for (const Value *U : Arg.users()) {
9577     if (U != SI) {
9578       ArgHasUses = true;
9579       break;
9580     }
9581   }
9582 }
9583 
9584 void SelectionDAGISel::LowerArguments(const Function &F) {
9585   SelectionDAG &DAG = SDB->DAG;
9586   SDLoc dl = SDB->getCurSDLoc();
9587   const DataLayout &DL = DAG.getDataLayout();
9588   SmallVector<ISD::InputArg, 16> Ins;
9589 
9590   if (!FuncInfo->CanLowerReturn) {
9591     // Put in an sret pointer parameter before all the other parameters.
9592     SmallVector<EVT, 1> ValueVTs;
9593     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9594                     F.getReturnType()->getPointerTo(
9595                         DAG.getDataLayout().getAllocaAddrSpace()),
9596                     ValueVTs);
9597 
9598     // NOTE: Assuming that a pointer will never break down to more than one VT
9599     // or one register.
9600     ISD::ArgFlagsTy Flags;
9601     Flags.setSRet();
9602     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9603     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9604                          ISD::InputArg::NoArgIndex, 0);
9605     Ins.push_back(RetArg);
9606   }
9607 
9608   // Look for stores of arguments to static allocas. Mark such arguments with a
9609   // flag to ask the target to give us the memory location of that argument if
9610   // available.
9611   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9612   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9613 
9614   // Set up the incoming argument description vector.
9615   for (const Argument &Arg : F.args()) {
9616     unsigned ArgNo = Arg.getArgNo();
9617     SmallVector<EVT, 4> ValueVTs;
9618     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9619     bool isArgValueUsed = !Arg.use_empty();
9620     unsigned PartBase = 0;
9621     Type *FinalType = Arg.getType();
9622     if (Arg.hasAttribute(Attribute::ByVal))
9623       FinalType = Arg.getParamByValType();
9624     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9625         FinalType, F.getCallingConv(), F.isVarArg());
9626     for (unsigned Value = 0, NumValues = ValueVTs.size();
9627          Value != NumValues; ++Value) {
9628       EVT VT = ValueVTs[Value];
9629       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9630       ISD::ArgFlagsTy Flags;
9631 
9632       // Certain targets (such as MIPS), may have a different ABI alignment
9633       // for a type depending on the context. Give the target a chance to
9634       // specify the alignment it wants.
9635       unsigned OriginalAlignment =
9636           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9637 
9638       if (Arg.getType()->isPointerTy()) {
9639         Flags.setPointer();
9640         Flags.setPointerAddrSpace(
9641             cast<PointerType>(Arg.getType())->getAddressSpace());
9642       }
9643       if (Arg.hasAttribute(Attribute::ZExt))
9644         Flags.setZExt();
9645       if (Arg.hasAttribute(Attribute::SExt))
9646         Flags.setSExt();
9647       if (Arg.hasAttribute(Attribute::InReg)) {
9648         // If we are using vectorcall calling convention, a structure that is
9649         // passed InReg - is surely an HVA
9650         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9651             isa<StructType>(Arg.getType())) {
9652           // The first value of a structure is marked
9653           if (0 == Value)
9654             Flags.setHvaStart();
9655           Flags.setHva();
9656         }
9657         // Set InReg Flag
9658         Flags.setInReg();
9659       }
9660       if (Arg.hasAttribute(Attribute::StructRet))
9661         Flags.setSRet();
9662       if (Arg.hasAttribute(Attribute::SwiftSelf))
9663         Flags.setSwiftSelf();
9664       if (Arg.hasAttribute(Attribute::SwiftError))
9665         Flags.setSwiftError();
9666       if (Arg.hasAttribute(Attribute::ByVal))
9667         Flags.setByVal();
9668       if (Arg.hasAttribute(Attribute::InAlloca)) {
9669         Flags.setInAlloca();
9670         // Set the byval flag for CCAssignFn callbacks that don't know about
9671         // inalloca.  This way we can know how many bytes we should've allocated
9672         // and how many bytes a callee cleanup function will pop.  If we port
9673         // inalloca to more targets, we'll have to add custom inalloca handling
9674         // in the various CC lowering callbacks.
9675         Flags.setByVal();
9676       }
9677       if (F.getCallingConv() == CallingConv::X86_INTR) {
9678         // IA Interrupt passes frame (1st parameter) by value in the stack.
9679         if (ArgNo == 0)
9680           Flags.setByVal();
9681       }
9682       if (Flags.isByVal() || Flags.isInAlloca()) {
9683         Type *ElementTy = Arg.getParamByValType();
9684 
9685         // For ByVal, size and alignment should be passed from FE.  BE will
9686         // guess if this info is not there but there are cases it cannot get
9687         // right.
9688         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9689         Flags.setByValSize(FrameSize);
9690 
9691         unsigned FrameAlign;
9692         if (Arg.getParamAlignment())
9693           FrameAlign = Arg.getParamAlignment();
9694         else
9695           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9696         Flags.setByValAlign(FrameAlign);
9697       }
9698       if (Arg.hasAttribute(Attribute::Nest))
9699         Flags.setNest();
9700       if (NeedsRegBlock)
9701         Flags.setInConsecutiveRegs();
9702       Flags.setOrigAlign(OriginalAlignment);
9703       if (ArgCopyElisionCandidates.count(&Arg))
9704         Flags.setCopyElisionCandidate();
9705       if (Arg.hasAttribute(Attribute::Returned))
9706         Flags.setReturned();
9707 
9708       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9709           *CurDAG->getContext(), F.getCallingConv(), VT);
9710       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9711           *CurDAG->getContext(), F.getCallingConv(), VT);
9712       for (unsigned i = 0; i != NumRegs; ++i) {
9713         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9714                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9715         if (NumRegs > 1 && i == 0)
9716           MyFlags.Flags.setSplit();
9717         // if it isn't first piece, alignment must be 1
9718         else if (i > 0) {
9719           MyFlags.Flags.setOrigAlign(1);
9720           if (i == NumRegs - 1)
9721             MyFlags.Flags.setSplitEnd();
9722         }
9723         Ins.push_back(MyFlags);
9724       }
9725       if (NeedsRegBlock && Value == NumValues - 1)
9726         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9727       PartBase += VT.getStoreSize();
9728     }
9729   }
9730 
9731   // Call the target to set up the argument values.
9732   SmallVector<SDValue, 8> InVals;
9733   SDValue NewRoot = TLI->LowerFormalArguments(
9734       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9735 
9736   // Verify that the target's LowerFormalArguments behaved as expected.
9737   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9738          "LowerFormalArguments didn't return a valid chain!");
9739   assert(InVals.size() == Ins.size() &&
9740          "LowerFormalArguments didn't emit the correct number of values!");
9741   LLVM_DEBUG({
9742     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9743       assert(InVals[i].getNode() &&
9744              "LowerFormalArguments emitted a null value!");
9745       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9746              "LowerFormalArguments emitted a value with the wrong type!");
9747     }
9748   });
9749 
9750   // Update the DAG with the new chain value resulting from argument lowering.
9751   DAG.setRoot(NewRoot);
9752 
9753   // Set up the argument values.
9754   unsigned i = 0;
9755   if (!FuncInfo->CanLowerReturn) {
9756     // Create a virtual register for the sret pointer, and put in a copy
9757     // from the sret argument into it.
9758     SmallVector<EVT, 1> ValueVTs;
9759     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9760                     F.getReturnType()->getPointerTo(
9761                         DAG.getDataLayout().getAllocaAddrSpace()),
9762                     ValueVTs);
9763     MVT VT = ValueVTs[0].getSimpleVT();
9764     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9765     Optional<ISD::NodeType> AssertOp = None;
9766     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9767                                         nullptr, F.getCallingConv(), AssertOp);
9768 
9769     MachineFunction& MF = SDB->DAG.getMachineFunction();
9770     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9771     Register SRetReg =
9772         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9773     FuncInfo->DemoteRegister = SRetReg;
9774     NewRoot =
9775         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9776     DAG.setRoot(NewRoot);
9777 
9778     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9779     ++i;
9780   }
9781 
9782   SmallVector<SDValue, 4> Chains;
9783   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9784   for (const Argument &Arg : F.args()) {
9785     SmallVector<SDValue, 4> ArgValues;
9786     SmallVector<EVT, 4> ValueVTs;
9787     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9788     unsigned NumValues = ValueVTs.size();
9789     if (NumValues == 0)
9790       continue;
9791 
9792     bool ArgHasUses = !Arg.use_empty();
9793 
9794     // Elide the copying store if the target loaded this argument from a
9795     // suitable fixed stack object.
9796     if (Ins[i].Flags.isCopyElisionCandidate()) {
9797       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9798                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9799                              InVals[i], ArgHasUses);
9800     }
9801 
9802     // If this argument is unused then remember its value. It is used to generate
9803     // debugging information.
9804     bool isSwiftErrorArg =
9805         TLI->supportSwiftError() &&
9806         Arg.hasAttribute(Attribute::SwiftError);
9807     if (!ArgHasUses && !isSwiftErrorArg) {
9808       SDB->setUnusedArgValue(&Arg, InVals[i]);
9809 
9810       // Also remember any frame index for use in FastISel.
9811       if (FrameIndexSDNode *FI =
9812           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9813         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9814     }
9815 
9816     for (unsigned Val = 0; Val != NumValues; ++Val) {
9817       EVT VT = ValueVTs[Val];
9818       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9819                                                       F.getCallingConv(), VT);
9820       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9821           *CurDAG->getContext(), F.getCallingConv(), VT);
9822 
9823       // Even an apparant 'unused' swifterror argument needs to be returned. So
9824       // we do generate a copy for it that can be used on return from the
9825       // function.
9826       if (ArgHasUses || isSwiftErrorArg) {
9827         Optional<ISD::NodeType> AssertOp;
9828         if (Arg.hasAttribute(Attribute::SExt))
9829           AssertOp = ISD::AssertSext;
9830         else if (Arg.hasAttribute(Attribute::ZExt))
9831           AssertOp = ISD::AssertZext;
9832 
9833         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9834                                              PartVT, VT, nullptr,
9835                                              F.getCallingConv(), AssertOp));
9836       }
9837 
9838       i += NumParts;
9839     }
9840 
9841     // We don't need to do anything else for unused arguments.
9842     if (ArgValues.empty())
9843       continue;
9844 
9845     // Note down frame index.
9846     if (FrameIndexSDNode *FI =
9847         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9848       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9849 
9850     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9851                                      SDB->getCurSDLoc());
9852 
9853     SDB->setValue(&Arg, Res);
9854     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9855       // We want to associate the argument with the frame index, among
9856       // involved operands, that correspond to the lowest address. The
9857       // getCopyFromParts function, called earlier, is swapping the order of
9858       // the operands to BUILD_PAIR depending on endianness. The result of
9859       // that swapping is that the least significant bits of the argument will
9860       // be in the first operand of the BUILD_PAIR node, and the most
9861       // significant bits will be in the second operand.
9862       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9863       if (LoadSDNode *LNode =
9864           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9865         if (FrameIndexSDNode *FI =
9866             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9867           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9868     }
9869 
9870     // Analyses past this point are naive and don't expect an assertion.
9871     if (Res.getOpcode() == ISD::AssertZext)
9872       Res = Res.getOperand(0);
9873 
9874     // Update the SwiftErrorVRegDefMap.
9875     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9876       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9877       if (Register::isVirtualRegister(Reg))
9878         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9879                                    Reg);
9880     }
9881 
9882     // If this argument is live outside of the entry block, insert a copy from
9883     // wherever we got it to the vreg that other BB's will reference it as.
9884     if (Res.getOpcode() == ISD::CopyFromReg) {
9885       // If we can, though, try to skip creating an unnecessary vreg.
9886       // FIXME: This isn't very clean... it would be nice to make this more
9887       // general.
9888       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9889       if (Register::isVirtualRegister(Reg)) {
9890         FuncInfo->ValueMap[&Arg] = Reg;
9891         continue;
9892       }
9893     }
9894     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9895       FuncInfo->InitializeRegForValue(&Arg);
9896       SDB->CopyToExportRegsIfNeeded(&Arg);
9897     }
9898   }
9899 
9900   if (!Chains.empty()) {
9901     Chains.push_back(NewRoot);
9902     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9903   }
9904 
9905   DAG.setRoot(NewRoot);
9906 
9907   assert(i == InVals.size() && "Argument register count mismatch!");
9908 
9909   // If any argument copy elisions occurred and we have debug info, update the
9910   // stale frame indices used in the dbg.declare variable info table.
9911   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9912   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9913     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9914       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9915       if (I != ArgCopyElisionFrameIndexMap.end())
9916         VI.Slot = I->second;
9917     }
9918   }
9919 
9920   // Finally, if the target has anything special to do, allow it to do so.
9921   EmitFunctionEntryCode();
9922 }
9923 
9924 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9925 /// ensure constants are generated when needed.  Remember the virtual registers
9926 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9927 /// directly add them, because expansion might result in multiple MBB's for one
9928 /// BB.  As such, the start of the BB might correspond to a different MBB than
9929 /// the end.
9930 void
9931 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9932   const Instruction *TI = LLVMBB->getTerminator();
9933 
9934   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9935 
9936   // Check PHI nodes in successors that expect a value to be available from this
9937   // block.
9938   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9939     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9940     if (!isa<PHINode>(SuccBB->begin())) continue;
9941     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9942 
9943     // If this terminator has multiple identical successors (common for
9944     // switches), only handle each succ once.
9945     if (!SuccsHandled.insert(SuccMBB).second)
9946       continue;
9947 
9948     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9949 
9950     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9951     // nodes and Machine PHI nodes, but the incoming operands have not been
9952     // emitted yet.
9953     for (const PHINode &PN : SuccBB->phis()) {
9954       // Ignore dead phi's.
9955       if (PN.use_empty())
9956         continue;
9957 
9958       // Skip empty types
9959       if (PN.getType()->isEmptyTy())
9960         continue;
9961 
9962       unsigned Reg;
9963       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9964 
9965       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9966         unsigned &RegOut = ConstantsOut[C];
9967         if (RegOut == 0) {
9968           RegOut = FuncInfo.CreateRegs(C);
9969           CopyValueToVirtualRegister(C, RegOut);
9970         }
9971         Reg = RegOut;
9972       } else {
9973         DenseMap<const Value *, unsigned>::iterator I =
9974           FuncInfo.ValueMap.find(PHIOp);
9975         if (I != FuncInfo.ValueMap.end())
9976           Reg = I->second;
9977         else {
9978           assert(isa<AllocaInst>(PHIOp) &&
9979                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9980                  "Didn't codegen value into a register!??");
9981           Reg = FuncInfo.CreateRegs(PHIOp);
9982           CopyValueToVirtualRegister(PHIOp, Reg);
9983         }
9984       }
9985 
9986       // Remember that this register needs to added to the machine PHI node as
9987       // the input for this MBB.
9988       SmallVector<EVT, 4> ValueVTs;
9989       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9990       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9991       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9992         EVT VT = ValueVTs[vti];
9993         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9994         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9995           FuncInfo.PHINodesToUpdate.push_back(
9996               std::make_pair(&*MBBI++, Reg + i));
9997         Reg += NumRegisters;
9998       }
9999     }
10000   }
10001 
10002   ConstantsOut.clear();
10003 }
10004 
10005 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10006 /// is 0.
10007 MachineBasicBlock *
10008 SelectionDAGBuilder::StackProtectorDescriptor::
10009 AddSuccessorMBB(const BasicBlock *BB,
10010                 MachineBasicBlock *ParentMBB,
10011                 bool IsLikely,
10012                 MachineBasicBlock *SuccMBB) {
10013   // If SuccBB has not been created yet, create it.
10014   if (!SuccMBB) {
10015     MachineFunction *MF = ParentMBB->getParent();
10016     MachineFunction::iterator BBI(ParentMBB);
10017     SuccMBB = MF->CreateMachineBasicBlock(BB);
10018     MF->insert(++BBI, SuccMBB);
10019   }
10020   // Add it as a successor of ParentMBB.
10021   ParentMBB->addSuccessor(
10022       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10023   return SuccMBB;
10024 }
10025 
10026 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10027   MachineFunction::iterator I(MBB);
10028   if (++I == FuncInfo.MF->end())
10029     return nullptr;
10030   return &*I;
10031 }
10032 
10033 /// During lowering new call nodes can be created (such as memset, etc.).
10034 /// Those will become new roots of the current DAG, but complications arise
10035 /// when they are tail calls. In such cases, the call lowering will update
10036 /// the root, but the builder still needs to know that a tail call has been
10037 /// lowered in order to avoid generating an additional return.
10038 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10039   // If the node is null, we do have a tail call.
10040   if (MaybeTC.getNode() != nullptr)
10041     DAG.setRoot(MaybeTC);
10042   else
10043     HasTailCall = true;
10044 }
10045 
10046 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10047                                         MachineBasicBlock *SwitchMBB,
10048                                         MachineBasicBlock *DefaultMBB) {
10049   MachineFunction *CurMF = FuncInfo.MF;
10050   MachineBasicBlock *NextMBB = nullptr;
10051   MachineFunction::iterator BBI(W.MBB);
10052   if (++BBI != FuncInfo.MF->end())
10053     NextMBB = &*BBI;
10054 
10055   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10056 
10057   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10058 
10059   if (Size == 2 && W.MBB == SwitchMBB) {
10060     // If any two of the cases has the same destination, and if one value
10061     // is the same as the other, but has one bit unset that the other has set,
10062     // use bit manipulation to do two compares at once.  For example:
10063     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10064     // TODO: This could be extended to merge any 2 cases in switches with 3
10065     // cases.
10066     // TODO: Handle cases where W.CaseBB != SwitchBB.
10067     CaseCluster &Small = *W.FirstCluster;
10068     CaseCluster &Big = *W.LastCluster;
10069 
10070     if (Small.Low == Small.High && Big.Low == Big.High &&
10071         Small.MBB == Big.MBB) {
10072       const APInt &SmallValue = Small.Low->getValue();
10073       const APInt &BigValue = Big.Low->getValue();
10074 
10075       // Check that there is only one bit different.
10076       APInt CommonBit = BigValue ^ SmallValue;
10077       if (CommonBit.isPowerOf2()) {
10078         SDValue CondLHS = getValue(Cond);
10079         EVT VT = CondLHS.getValueType();
10080         SDLoc DL = getCurSDLoc();
10081 
10082         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10083                                  DAG.getConstant(CommonBit, DL, VT));
10084         SDValue Cond = DAG.getSetCC(
10085             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10086             ISD::SETEQ);
10087 
10088         // Update successor info.
10089         // Both Small and Big will jump to Small.BB, so we sum up the
10090         // probabilities.
10091         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10092         if (BPI)
10093           addSuccessorWithProb(
10094               SwitchMBB, DefaultMBB,
10095               // The default destination is the first successor in IR.
10096               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10097         else
10098           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10099 
10100         // Insert the true branch.
10101         SDValue BrCond =
10102             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10103                         DAG.getBasicBlock(Small.MBB));
10104         // Insert the false branch.
10105         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10106                              DAG.getBasicBlock(DefaultMBB));
10107 
10108         DAG.setRoot(BrCond);
10109         return;
10110       }
10111     }
10112   }
10113 
10114   if (TM.getOptLevel() != CodeGenOpt::None) {
10115     // Here, we order cases by probability so the most likely case will be
10116     // checked first. However, two clusters can have the same probability in
10117     // which case their relative ordering is non-deterministic. So we use Low
10118     // as a tie-breaker as clusters are guaranteed to never overlap.
10119     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10120                [](const CaseCluster &a, const CaseCluster &b) {
10121       return a.Prob != b.Prob ?
10122              a.Prob > b.Prob :
10123              a.Low->getValue().slt(b.Low->getValue());
10124     });
10125 
10126     // Rearrange the case blocks so that the last one falls through if possible
10127     // without changing the order of probabilities.
10128     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10129       --I;
10130       if (I->Prob > W.LastCluster->Prob)
10131         break;
10132       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10133         std::swap(*I, *W.LastCluster);
10134         break;
10135       }
10136     }
10137   }
10138 
10139   // Compute total probability.
10140   BranchProbability DefaultProb = W.DefaultProb;
10141   BranchProbability UnhandledProbs = DefaultProb;
10142   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10143     UnhandledProbs += I->Prob;
10144 
10145   MachineBasicBlock *CurMBB = W.MBB;
10146   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10147     bool FallthroughUnreachable = false;
10148     MachineBasicBlock *Fallthrough;
10149     if (I == W.LastCluster) {
10150       // For the last cluster, fall through to the default destination.
10151       Fallthrough = DefaultMBB;
10152       FallthroughUnreachable = isa<UnreachableInst>(
10153           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10154     } else {
10155       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10156       CurMF->insert(BBI, Fallthrough);
10157       // Put Cond in a virtual register to make it available from the new blocks.
10158       ExportFromCurrentBlock(Cond);
10159     }
10160     UnhandledProbs -= I->Prob;
10161 
10162     switch (I->Kind) {
10163       case CC_JumpTable: {
10164         // FIXME: Optimize away range check based on pivot comparisons.
10165         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10166         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10167 
10168         // The jump block hasn't been inserted yet; insert it here.
10169         MachineBasicBlock *JumpMBB = JT->MBB;
10170         CurMF->insert(BBI, JumpMBB);
10171 
10172         auto JumpProb = I->Prob;
10173         auto FallthroughProb = UnhandledProbs;
10174 
10175         // If the default statement is a target of the jump table, we evenly
10176         // distribute the default probability to successors of CurMBB. Also
10177         // update the probability on the edge from JumpMBB to Fallthrough.
10178         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10179                                               SE = JumpMBB->succ_end();
10180              SI != SE; ++SI) {
10181           if (*SI == DefaultMBB) {
10182             JumpProb += DefaultProb / 2;
10183             FallthroughProb -= DefaultProb / 2;
10184             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10185             JumpMBB->normalizeSuccProbs();
10186             break;
10187           }
10188         }
10189 
10190         if (FallthroughUnreachable) {
10191           // Skip the range check if the fallthrough block is unreachable.
10192           JTH->OmitRangeCheck = true;
10193         }
10194 
10195         if (!JTH->OmitRangeCheck)
10196           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10197         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10198         CurMBB->normalizeSuccProbs();
10199 
10200         // The jump table header will be inserted in our current block, do the
10201         // range check, and fall through to our fallthrough block.
10202         JTH->HeaderBB = CurMBB;
10203         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10204 
10205         // If we're in the right place, emit the jump table header right now.
10206         if (CurMBB == SwitchMBB) {
10207           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10208           JTH->Emitted = true;
10209         }
10210         break;
10211       }
10212       case CC_BitTests: {
10213         // FIXME: If Fallthrough is unreachable, skip the range check.
10214 
10215         // FIXME: Optimize away range check based on pivot comparisons.
10216         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10217 
10218         // The bit test blocks haven't been inserted yet; insert them here.
10219         for (BitTestCase &BTC : BTB->Cases)
10220           CurMF->insert(BBI, BTC.ThisBB);
10221 
10222         // Fill in fields of the BitTestBlock.
10223         BTB->Parent = CurMBB;
10224         BTB->Default = Fallthrough;
10225 
10226         BTB->DefaultProb = UnhandledProbs;
10227         // If the cases in bit test don't form a contiguous range, we evenly
10228         // distribute the probability on the edge to Fallthrough to two
10229         // successors of CurMBB.
10230         if (!BTB->ContiguousRange) {
10231           BTB->Prob += DefaultProb / 2;
10232           BTB->DefaultProb -= DefaultProb / 2;
10233         }
10234 
10235         // If we're in the right place, emit the bit test header right now.
10236         if (CurMBB == SwitchMBB) {
10237           visitBitTestHeader(*BTB, SwitchMBB);
10238           BTB->Emitted = true;
10239         }
10240         break;
10241       }
10242       case CC_Range: {
10243         const Value *RHS, *LHS, *MHS;
10244         ISD::CondCode CC;
10245         if (I->Low == I->High) {
10246           // Check Cond == I->Low.
10247           CC = ISD::SETEQ;
10248           LHS = Cond;
10249           RHS=I->Low;
10250           MHS = nullptr;
10251         } else {
10252           // Check I->Low <= Cond <= I->High.
10253           CC = ISD::SETLE;
10254           LHS = I->Low;
10255           MHS = Cond;
10256           RHS = I->High;
10257         }
10258 
10259         // If Fallthrough is unreachable, fold away the comparison.
10260         if (FallthroughUnreachable)
10261           CC = ISD::SETTRUE;
10262 
10263         // The false probability is the sum of all unhandled cases.
10264         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10265                      getCurSDLoc(), I->Prob, UnhandledProbs);
10266 
10267         if (CurMBB == SwitchMBB)
10268           visitSwitchCase(CB, SwitchMBB);
10269         else
10270           SL->SwitchCases.push_back(CB);
10271 
10272         break;
10273       }
10274     }
10275     CurMBB = Fallthrough;
10276   }
10277 }
10278 
10279 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10280                                               CaseClusterIt First,
10281                                               CaseClusterIt Last) {
10282   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10283     if (X.Prob != CC.Prob)
10284       return X.Prob > CC.Prob;
10285 
10286     // Ties are broken by comparing the case value.
10287     return X.Low->getValue().slt(CC.Low->getValue());
10288   });
10289 }
10290 
10291 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10292                                         const SwitchWorkListItem &W,
10293                                         Value *Cond,
10294                                         MachineBasicBlock *SwitchMBB) {
10295   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10296          "Clusters not sorted?");
10297 
10298   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10299 
10300   // Balance the tree based on branch probabilities to create a near-optimal (in
10301   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10302   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10303   CaseClusterIt LastLeft = W.FirstCluster;
10304   CaseClusterIt FirstRight = W.LastCluster;
10305   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10306   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10307 
10308   // Move LastLeft and FirstRight towards each other from opposite directions to
10309   // find a partitioning of the clusters which balances the probability on both
10310   // sides. If LeftProb and RightProb are equal, alternate which side is
10311   // taken to ensure 0-probability nodes are distributed evenly.
10312   unsigned I = 0;
10313   while (LastLeft + 1 < FirstRight) {
10314     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10315       LeftProb += (++LastLeft)->Prob;
10316     else
10317       RightProb += (--FirstRight)->Prob;
10318     I++;
10319   }
10320 
10321   while (true) {
10322     // Our binary search tree differs from a typical BST in that ours can have up
10323     // to three values in each leaf. The pivot selection above doesn't take that
10324     // into account, which means the tree might require more nodes and be less
10325     // efficient. We compensate for this here.
10326 
10327     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10328     unsigned NumRight = W.LastCluster - FirstRight + 1;
10329 
10330     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10331       // If one side has less than 3 clusters, and the other has more than 3,
10332       // consider taking a cluster from the other side.
10333 
10334       if (NumLeft < NumRight) {
10335         // Consider moving the first cluster on the right to the left side.
10336         CaseCluster &CC = *FirstRight;
10337         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10338         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10339         if (LeftSideRank <= RightSideRank) {
10340           // Moving the cluster to the left does not demote it.
10341           ++LastLeft;
10342           ++FirstRight;
10343           continue;
10344         }
10345       } else {
10346         assert(NumRight < NumLeft);
10347         // Consider moving the last element on the left to the right side.
10348         CaseCluster &CC = *LastLeft;
10349         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10350         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10351         if (RightSideRank <= LeftSideRank) {
10352           // Moving the cluster to the right does not demot it.
10353           --LastLeft;
10354           --FirstRight;
10355           continue;
10356         }
10357       }
10358     }
10359     break;
10360   }
10361 
10362   assert(LastLeft + 1 == FirstRight);
10363   assert(LastLeft >= W.FirstCluster);
10364   assert(FirstRight <= W.LastCluster);
10365 
10366   // Use the first element on the right as pivot since we will make less-than
10367   // comparisons against it.
10368   CaseClusterIt PivotCluster = FirstRight;
10369   assert(PivotCluster > W.FirstCluster);
10370   assert(PivotCluster <= W.LastCluster);
10371 
10372   CaseClusterIt FirstLeft = W.FirstCluster;
10373   CaseClusterIt LastRight = W.LastCluster;
10374 
10375   const ConstantInt *Pivot = PivotCluster->Low;
10376 
10377   // New blocks will be inserted immediately after the current one.
10378   MachineFunction::iterator BBI(W.MBB);
10379   ++BBI;
10380 
10381   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10382   // we can branch to its destination directly if it's squeezed exactly in
10383   // between the known lower bound and Pivot - 1.
10384   MachineBasicBlock *LeftMBB;
10385   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10386       FirstLeft->Low == W.GE &&
10387       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10388     LeftMBB = FirstLeft->MBB;
10389   } else {
10390     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10391     FuncInfo.MF->insert(BBI, LeftMBB);
10392     WorkList.push_back(
10393         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10394     // Put Cond in a virtual register to make it available from the new blocks.
10395     ExportFromCurrentBlock(Cond);
10396   }
10397 
10398   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10399   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10400   // directly if RHS.High equals the current upper bound.
10401   MachineBasicBlock *RightMBB;
10402   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10403       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10404     RightMBB = FirstRight->MBB;
10405   } else {
10406     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10407     FuncInfo.MF->insert(BBI, RightMBB);
10408     WorkList.push_back(
10409         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10410     // Put Cond in a virtual register to make it available from the new blocks.
10411     ExportFromCurrentBlock(Cond);
10412   }
10413 
10414   // Create the CaseBlock record that will be used to lower the branch.
10415   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10416                getCurSDLoc(), LeftProb, RightProb);
10417 
10418   if (W.MBB == SwitchMBB)
10419     visitSwitchCase(CB, SwitchMBB);
10420   else
10421     SL->SwitchCases.push_back(CB);
10422 }
10423 
10424 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10425 // from the swith statement.
10426 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10427                                             BranchProbability PeeledCaseProb) {
10428   if (PeeledCaseProb == BranchProbability::getOne())
10429     return BranchProbability::getZero();
10430   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10431 
10432   uint32_t Numerator = CaseProb.getNumerator();
10433   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10434   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10435 }
10436 
10437 // Try to peel the top probability case if it exceeds the threshold.
10438 // Return current MachineBasicBlock for the switch statement if the peeling
10439 // does not occur.
10440 // If the peeling is performed, return the newly created MachineBasicBlock
10441 // for the peeled switch statement. Also update Clusters to remove the peeled
10442 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10443 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10444     const SwitchInst &SI, CaseClusterVector &Clusters,
10445     BranchProbability &PeeledCaseProb) {
10446   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10447   // Don't perform if there is only one cluster or optimizing for size.
10448   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10449       TM.getOptLevel() == CodeGenOpt::None ||
10450       SwitchMBB->getParent()->getFunction().hasMinSize())
10451     return SwitchMBB;
10452 
10453   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10454   unsigned PeeledCaseIndex = 0;
10455   bool SwitchPeeled = false;
10456   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10457     CaseCluster &CC = Clusters[Index];
10458     if (CC.Prob < TopCaseProb)
10459       continue;
10460     TopCaseProb = CC.Prob;
10461     PeeledCaseIndex = Index;
10462     SwitchPeeled = true;
10463   }
10464   if (!SwitchPeeled)
10465     return SwitchMBB;
10466 
10467   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10468                     << TopCaseProb << "\n");
10469 
10470   // Record the MBB for the peeled switch statement.
10471   MachineFunction::iterator BBI(SwitchMBB);
10472   ++BBI;
10473   MachineBasicBlock *PeeledSwitchMBB =
10474       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10475   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10476 
10477   ExportFromCurrentBlock(SI.getCondition());
10478   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10479   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10480                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10481   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10482 
10483   Clusters.erase(PeeledCaseIt);
10484   for (CaseCluster &CC : Clusters) {
10485     LLVM_DEBUG(
10486         dbgs() << "Scale the probablity for one cluster, before scaling: "
10487                << CC.Prob << "\n");
10488     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10489     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10490   }
10491   PeeledCaseProb = TopCaseProb;
10492   return PeeledSwitchMBB;
10493 }
10494 
10495 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10496   // Extract cases from the switch.
10497   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10498   CaseClusterVector Clusters;
10499   Clusters.reserve(SI.getNumCases());
10500   for (auto I : SI.cases()) {
10501     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10502     const ConstantInt *CaseVal = I.getCaseValue();
10503     BranchProbability Prob =
10504         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10505             : BranchProbability(1, SI.getNumCases() + 1);
10506     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10507   }
10508 
10509   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10510 
10511   // Cluster adjacent cases with the same destination. We do this at all
10512   // optimization levels because it's cheap to do and will make codegen faster
10513   // if there are many clusters.
10514   sortAndRangeify(Clusters);
10515 
10516   // The branch probablity of the peeled case.
10517   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10518   MachineBasicBlock *PeeledSwitchMBB =
10519       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10520 
10521   // If there is only the default destination, jump there directly.
10522   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10523   if (Clusters.empty()) {
10524     assert(PeeledSwitchMBB == SwitchMBB);
10525     SwitchMBB->addSuccessor(DefaultMBB);
10526     if (DefaultMBB != NextBlock(SwitchMBB)) {
10527       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10528                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10529     }
10530     return;
10531   }
10532 
10533   SL->findJumpTables(Clusters, &SI, DefaultMBB);
10534   SL->findBitTestClusters(Clusters, &SI);
10535 
10536   LLVM_DEBUG({
10537     dbgs() << "Case clusters: ";
10538     for (const CaseCluster &C : Clusters) {
10539       if (C.Kind == CC_JumpTable)
10540         dbgs() << "JT:";
10541       if (C.Kind == CC_BitTests)
10542         dbgs() << "BT:";
10543 
10544       C.Low->getValue().print(dbgs(), true);
10545       if (C.Low != C.High) {
10546         dbgs() << '-';
10547         C.High->getValue().print(dbgs(), true);
10548       }
10549       dbgs() << ' ';
10550     }
10551     dbgs() << '\n';
10552   });
10553 
10554   assert(!Clusters.empty());
10555   SwitchWorkList WorkList;
10556   CaseClusterIt First = Clusters.begin();
10557   CaseClusterIt Last = Clusters.end() - 1;
10558   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10559   // Scale the branchprobability for DefaultMBB if the peel occurs and
10560   // DefaultMBB is not replaced.
10561   if (PeeledCaseProb != BranchProbability::getZero() &&
10562       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10563     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10564   WorkList.push_back(
10565       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10566 
10567   while (!WorkList.empty()) {
10568     SwitchWorkListItem W = WorkList.back();
10569     WorkList.pop_back();
10570     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10571 
10572     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10573         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10574       // For optimized builds, lower large range as a balanced binary tree.
10575       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10576       continue;
10577     }
10578 
10579     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10580   }
10581 }
10582